diff --git a/shared/package-files/0d/0d42d2b355c4b47ac2c8b84dfe0f89f0f8af557b6f4b128dd97cf98116ca9122/__init__.py b/shared/package-files/0d/0d42d2b355c4b47ac2c8b84dfe0f89f0f8af557b6f4b128dd97cf98116ca9122/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4bca8133ac8afd22f12c5560a571f9569b1f3e70 --- /dev/null +++ b/shared/package-files/0d/0d42d2b355c4b47ac2c8b84dfe0f89f0f8af557b6f4b128dd97cf98116ca9122/__init__.py @@ -0,0 +1,42 @@ +# -------------------------------------------------------------------------------------- +# Copyright (c) 2013-2026, Nucleic Development Team. +# +# Distributed under the terms of the Modified BSD License. +# +# The full license is in the file LICENSE, distributed with this software. +# -------------------------------------------------------------------------------------- +from ._cext import ( + Constraint, + Expression, + Solver, + Term, + Variable, + __kiwi_version__, + __version__, + strength, +) +from .exceptions import ( + BadRequiredStrength, + DuplicateConstraint, + DuplicateEditVariable, + UnknownConstraint, + UnknownEditVariable, + UnsatisfiableConstraint, +) + +__all__ = [ + "BadRequiredStrength", + "Constraint", + "DuplicateConstraint", + "DuplicateEditVariable", + "Expression", + "Solver", + "Term", + "UnknownConstraint", + "UnknownEditVariable", + "UnsatisfiableConstraint", + "Variable", + "__kiwi_version__", + "__version__", + "strength", +] diff --git a/shared/package-files/0d/0d85ddbbe8cc487ed7713a216dcf31f0d88a44bb695fd2142df636d288647df0/benchmark.pxi b/shared/package-files/0d/0d85ddbbe8cc487ed7713a216dcf31f0d88a44bb695fd2142df636d288647df0/benchmark.pxi new file mode 100644 index 0000000000000000000000000000000000000000..ab251017db78706c97c7dee8044636c55c80167e --- /dev/null +++ b/shared/package-files/0d/0d85ddbbe8cc487ed7713a216dcf31f0d88a44bb695fd2142df636d288647df0/benchmark.pxi @@ -0,0 +1,20 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + + +def benchmark_PandasObjectIsNull(list obj): + Benchmark_PandasObjectIsNull(obj) diff --git a/shared/package-files/33/3300593114fb9286af9360cc9d871a40e5dcbea4aedc24b832607d1dd71c7b96/two_canvases.py b/shared/package-files/33/3300593114fb9286af9360cc9d871a40e5dcbea4aedc24b832607d1dd71c7b96/two_canvases.py new file mode 100644 index 0000000000000000000000000000000000000000..f3602585ab0592c393fbe9526cb5aae4ae902f6c --- /dev/null +++ b/shared/package-files/33/3300593114fb9286af9360cc9d871a40e5dcbea4aedc24b832607d1dd71c7b96/two_canvases.py @@ -0,0 +1,54 @@ +"""turtledemo.two_canvases + +Use TurtleScreen and RawTurtle to draw on two +distinct canvases in a separate window. The +new window must be separately closed in +addition to pressing the STOP button. +""" + +from turtle import TurtleScreen, RawTurtle, TK + +def main(): + root = TK.Tk() + cv1 = TK.Canvas(root, width=300, height=200, bg="#ddffff") + cv2 = TK.Canvas(root, width=300, height=200, bg="#ffeeee") + cv1.pack() + cv2.pack() + + s1 = TurtleScreen(cv1) + s1.bgcolor(0.85, 0.85, 1) + s2 = TurtleScreen(cv2) + s2.bgcolor(1, 0.85, 0.85) + + p = RawTurtle(s1) + q = RawTurtle(s2) + + p.color("red", (1, 0.85, 0.85)) + p.width(3) + q.color("blue", (0.85, 0.85, 1)) + q.width(3) + + for t in p,q: + t.shape("turtle") + t.lt(36) + + q.lt(180) + + for t in p, q: + t.begin_fill() + for i in range(5): + for t in p, q: + t.fd(50) + t.lt(72) + for t in p,q: + t.end_fill() + t.lt(54) + t.pu() + t.bk(50) + + return "EVENTLOOP" + + +if __name__ == '__main__': + main() + TK.mainloop() # keep window open until user closes it diff --git a/shared/package-files/33/33005b05ab9a5233626a36b6e6864ab7bbc8f5b4465df17994ad69fbc010ebb5/ciphers.py b/shared/package-files/33/33005b05ab9a5233626a36b6e6864ab7bbc8f5b4465df17994ad69fbc010ebb5/ciphers.py new file mode 100644 index 0000000000000000000000000000000000000000..3916b1a510ad6ad96227c7f9bb8bb94471798a53 --- /dev/null +++ b/shared/package-files/33/33005b05ab9a5233626a36b6e6864ab7bbc8f5b4465df17994ad69fbc010ebb5/ciphers.py @@ -0,0 +1,282 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.exceptions import InvalidTag, UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.primitives import ciphers +from cryptography.hazmat.primitives.ciphers import algorithms, modes + +if typing.TYPE_CHECKING: + from cryptography.hazmat.backends.openssl.backend import Backend + + +class _CipherContext: + _ENCRYPT = 1 + _DECRYPT = 0 + _MAX_CHUNK_SIZE = 2**29 + + def __init__(self, backend: Backend, cipher, mode, operation: int) -> None: + self._backend = backend + self._cipher = cipher + self._mode = mode + self._operation = operation + self._tag: bytes | None = None + + if isinstance(self._cipher, ciphers.BlockCipherAlgorithm): + self._block_size_bytes = self._cipher.block_size // 8 + else: + self._block_size_bytes = 1 + + ctx = self._backend._lib.EVP_CIPHER_CTX_new() + ctx = self._backend._ffi.gc( + ctx, self._backend._lib.EVP_CIPHER_CTX_free + ) + + registry = self._backend._cipher_registry + try: + adapter = registry[type(cipher), type(mode)] + except KeyError: + raise UnsupportedAlgorithm( + "cipher {} in {} mode is not supported " + "by this backend.".format( + cipher.name, mode.name if mode else mode + ), + _Reasons.UNSUPPORTED_CIPHER, + ) + + evp_cipher = adapter(self._backend, cipher, mode) + if evp_cipher == self._backend._ffi.NULL: + msg = f"cipher {cipher.name} " + if mode is not None: + msg += f"in {mode.name} mode " + msg += ( + "is not supported by this backend (Your version of OpenSSL " + "may be too old. Current version: {}.)" + ).format(self._backend.openssl_version_text()) + raise UnsupportedAlgorithm(msg, _Reasons.UNSUPPORTED_CIPHER) + + if isinstance(mode, modes.ModeWithInitializationVector): + iv_nonce = self._backend._ffi.from_buffer( + mode.initialization_vector + ) + elif isinstance(mode, modes.ModeWithTweak): + iv_nonce = self._backend._ffi.from_buffer(mode.tweak) + elif isinstance(mode, modes.ModeWithNonce): + iv_nonce = self._backend._ffi.from_buffer(mode.nonce) + elif isinstance(cipher, algorithms.ChaCha20): + iv_nonce = self._backend._ffi.from_buffer(cipher.nonce) + else: + iv_nonce = self._backend._ffi.NULL + # begin init with cipher and operation type + res = self._backend._lib.EVP_CipherInit_ex( + ctx, + evp_cipher, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + operation, + ) + self._backend.openssl_assert(res != 0) + # set the key length to handle variable key ciphers + res = self._backend._lib.EVP_CIPHER_CTX_set_key_length( + ctx, len(cipher.key) + ) + self._backend.openssl_assert(res != 0) + if isinstance(mode, modes.GCM): + res = self._backend._lib.EVP_CIPHER_CTX_ctrl( + ctx, + self._backend._lib.EVP_CTRL_AEAD_SET_IVLEN, + len(iv_nonce), + self._backend._ffi.NULL, + ) + self._backend.openssl_assert(res != 0) + if mode.tag is not None: + res = self._backend._lib.EVP_CIPHER_CTX_ctrl( + ctx, + self._backend._lib.EVP_CTRL_AEAD_SET_TAG, + len(mode.tag), + mode.tag, + ) + self._backend.openssl_assert(res != 0) + self._tag = mode.tag + + # pass key/iv + res = self._backend._lib.EVP_CipherInit_ex( + ctx, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + self._backend._ffi.from_buffer(cipher.key), + iv_nonce, + operation, + ) + + # Check for XTS mode duplicate keys error + errors = self._backend._consume_errors() + lib = self._backend._lib + if res == 0 and ( + ( + not lib.CRYPTOGRAPHY_IS_LIBRESSL + and errors[0]._lib_reason_match( + lib.ERR_LIB_EVP, lib.EVP_R_XTS_DUPLICATED_KEYS + ) + ) + or ( + lib.Cryptography_HAS_PROVIDERS + and errors[0]._lib_reason_match( + lib.ERR_LIB_PROV, lib.PROV_R_XTS_DUPLICATED_KEYS + ) + ) + ): + raise ValueError("In XTS mode duplicated keys are not allowed") + + self._backend.openssl_assert(res != 0, errors=errors) + + # We purposely disable padding here as it's handled higher up in the + # API. + self._backend._lib.EVP_CIPHER_CTX_set_padding(ctx, 0) + self._ctx = ctx + + def update(self, data: bytes) -> bytes: + buf = bytearray(len(data) + self._block_size_bytes - 1) + n = self.update_into(data, buf) + return bytes(buf[:n]) + + def update_into(self, data: bytes, buf: bytes) -> int: + total_data_len = len(data) + if len(buf) < (total_data_len + self._block_size_bytes - 1): + raise ValueError( + "buffer must be at least {} bytes for this payload".format( + len(data) + self._block_size_bytes - 1 + ) + ) + + data_processed = 0 + total_out = 0 + outlen = self._backend._ffi.new("int *") + baseoutbuf = self._backend._ffi.from_buffer(buf, require_writable=True) + baseinbuf = self._backend._ffi.from_buffer(data) + + while data_processed != total_data_len: + outbuf = baseoutbuf + total_out + inbuf = baseinbuf + data_processed + inlen = min(self._MAX_CHUNK_SIZE, total_data_len - data_processed) + + res = self._backend._lib.EVP_CipherUpdate( + self._ctx, outbuf, outlen, inbuf, inlen + ) + if res == 0 and isinstance(self._mode, modes.XTS): + self._backend._consume_errors() + raise ValueError( + "In XTS mode you must supply at least a full block in the " + "first update call. For AES this is 16 bytes." + ) + else: + self._backend.openssl_assert(res != 0) + data_processed += inlen + total_out += outlen[0] + + return total_out + + def finalize(self) -> bytes: + if ( + self._operation == self._DECRYPT + and isinstance(self._mode, modes.ModeWithAuthenticationTag) + and self.tag is None + ): + raise ValueError( + "Authentication tag must be provided when decrypting." + ) + + buf = self._backend._ffi.new("unsigned char[]", self._block_size_bytes) + outlen = self._backend._ffi.new("int *") + res = self._backend._lib.EVP_CipherFinal_ex(self._ctx, buf, outlen) + if res == 0: + errors = self._backend._consume_errors() + + if not errors and isinstance(self._mode, modes.GCM): + raise InvalidTag + + lib = self._backend._lib + self._backend.openssl_assert( + errors[0]._lib_reason_match( + lib.ERR_LIB_EVP, + lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH, + ) + or ( + lib.Cryptography_HAS_PROVIDERS + and errors[0]._lib_reason_match( + lib.ERR_LIB_PROV, + lib.PROV_R_WRONG_FINAL_BLOCK_LENGTH, + ) + ) + or ( + lib.CRYPTOGRAPHY_IS_BORINGSSL + and errors[0].reason + == lib.CIPHER_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH + ), + errors=errors, + ) + raise ValueError( + "The length of the provided data is not a multiple of " + "the block length." + ) + + if ( + isinstance(self._mode, modes.GCM) + and self._operation == self._ENCRYPT + ): + tag_buf = self._backend._ffi.new( + "unsigned char[]", self._block_size_bytes + ) + res = self._backend._lib.EVP_CIPHER_CTX_ctrl( + self._ctx, + self._backend._lib.EVP_CTRL_AEAD_GET_TAG, + self._block_size_bytes, + tag_buf, + ) + self._backend.openssl_assert(res != 0) + self._tag = self._backend._ffi.buffer(tag_buf)[:] + + res = self._backend._lib.EVP_CIPHER_CTX_reset(self._ctx) + self._backend.openssl_assert(res == 1) + return self._backend._ffi.buffer(buf)[: outlen[0]] + + def finalize_with_tag(self, tag: bytes) -> bytes: + tag_len = len(tag) + if tag_len < self._mode._min_tag_length: + raise ValueError( + "Authentication tag must be {} bytes or longer.".format( + self._mode._min_tag_length + ) + ) + elif tag_len > self._block_size_bytes: + raise ValueError( + "Authentication tag cannot be more than {} bytes.".format( + self._block_size_bytes + ) + ) + res = self._backend._lib.EVP_CIPHER_CTX_ctrl( + self._ctx, self._backend._lib.EVP_CTRL_AEAD_SET_TAG, len(tag), tag + ) + self._backend.openssl_assert(res != 0) + self._tag = tag + return self.finalize() + + def authenticate_additional_data(self, data: bytes) -> None: + outlen = self._backend._ffi.new("int *") + res = self._backend._lib.EVP_CipherUpdate( + self._ctx, + self._backend._ffi.NULL, + outlen, + self._backend._ffi.from_buffer(data), + len(data), + ) + self._backend.openssl_assert(res != 0) + + @property + def tag(self) -> bytes | None: + return self._tag diff --git a/shared/package-files/33/33085245aa389b0dcda728610cc30321790a8f619b3eeda03e24f17cccf8fccc/linalg_vander.h b/shared/package-files/33/33085245aa389b0dcda728610cc30321790a8f619b3eeda03e24f17cccf8fccc/linalg_vander.h new file mode 100644 index 0000000000000000000000000000000000000000..9ac4ed5d0c45296d42e9037f1e362d1ea5e9dabc --- /dev/null +++ b/shared/package-files/33/33085245aa389b0dcda728610cc30321790a8f619b3eeda03e24f17cccf8fccc/linalg_vander.h @@ -0,0 +1,47 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::linalg_vander(Tensor x, *, SymInt? N=None) -> Tensor +inline at::Tensor linalg_vander(const at::Tensor & x, c10::optional N=c10::nullopt) { + return at::_ops::linalg_vander::call(x, N.has_value() ? c10::make_optional(c10::SymInt(*N)) : c10::nullopt); +} +namespace symint { + template ::value>> + at::Tensor linalg_vander(const at::Tensor & x, c10::optional N=c10::nullopt) { + return at::_ops::linalg_vander::call(x, N.has_value() ? c10::make_optional(c10::SymInt(*N)) : c10::nullopt); + } +} + +// aten::linalg_vander(Tensor x, *, SymInt? N=None) -> Tensor +inline at::Tensor linalg_vander_symint(const at::Tensor & x, c10::optional N=c10::nullopt) { + return at::_ops::linalg_vander::call(x, N); +} +namespace symint { + template ::value>> + at::Tensor linalg_vander(const at::Tensor & x, c10::optional N=c10::nullopt) { + return at::_ops::linalg_vander::call(x, N); + } +} + +} diff --git a/shared/package-files/33/330fa9d3b183cadb415ca68d0794aee61c34d434176608c465ee4cd5eecf9611/ed448.pyi b/shared/package-files/33/330fa9d3b183cadb415ca68d0794aee61c34d434176608c465ee4cd5eecf9611/ed448.pyi new file mode 100644 index 0000000000000000000000000000000000000000..fa43fc1bc122f2ccf3942ee71791bc49eaced7a4 --- /dev/null +++ b/shared/package-files/33/330fa9d3b183cadb415ca68d0794aee61c34d434176608c465ee4cd5eecf9611/ed448.pyi @@ -0,0 +1,25 @@ +from abc import ABCMeta, abstractmethod + +from cryptography.hazmat.primitives.serialization import Encoding, KeySerializationEncryption, PrivateFormat, PublicFormat + +class Ed448PrivateKey(metaclass=ABCMeta): + @classmethod + def generate(cls) -> Ed448PrivateKey: ... + @classmethod + def from_private_bytes(cls, data: bytes) -> Ed448PrivateKey: ... + @abstractmethod + def private_bytes( + self, encoding: Encoding, format: PrivateFormat, encryption_algorithm: KeySerializationEncryption + ) -> bytes: ... + @abstractmethod + def public_key(self) -> Ed448PublicKey: ... + @abstractmethod + def sign(self, data: bytes) -> bytes: ... + +class Ed448PublicKey(metaclass=ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> Ed448PublicKey: ... + @abstractmethod + def public_bytes(self, encoding: Encoding, format: PublicFormat) -> bytes: ... + @abstractmethod + def verify(self, signature: bytes, data: bytes) -> None: ... diff --git a/shared/package-files/33/3311dac7a97de32aa54d5665780a86efb20b11b5bac14e68b0f707cf127ce67b/multiarray.py b/shared/package-files/33/3311dac7a97de32aa54d5665780a86efb20b11b5bac14e68b0f707cf127ce67b/multiarray.py new file mode 100644 index 0000000000000000000000000000000000000000..26cedfd77566e7b7865345e0775af88153e74ffc --- /dev/null +++ b/shared/package-files/33/3311dac7a97de32aa54d5665780a86efb20b11b5bac14e68b0f707cf127ce67b/multiarray.py @@ -0,0 +1,76 @@ +import numpy as np +import numpy.typing as npt + +AR_f8: npt.NDArray[np.float64] = np.array([1.0]) +AR_i4 = np.array([1], dtype=np.int32) +AR_u1 = np.array([1], dtype=np.uint8) + +AR_LIKE_f = [1.5] +AR_LIKE_i = [1] + +b_f8 = np.broadcast(AR_f8) +b_i4_f8_f8 = np.broadcast(AR_i4, AR_f8, AR_f8) + +next(b_f8) +b_f8.reset() +b_f8.index +b_f8.iters +b_f8.nd +b_f8.ndim +b_f8.numiter +b_f8.shape +b_f8.size + +next(b_i4_f8_f8) +b_i4_f8_f8.reset() +b_i4_f8_f8.ndim +b_i4_f8_f8.index +b_i4_f8_f8.iters +b_i4_f8_f8.nd +b_i4_f8_f8.numiter +b_i4_f8_f8.shape +b_i4_f8_f8.size + +np.inner(AR_f8, AR_i4) + +np.where([True, True, False]) +np.where([True, True, False], 1, 0) + +np.lexsort([0, 1, 2]) + +np.can_cast(np.dtype("i8"), int) +np.can_cast(AR_f8, "f8") +np.can_cast(AR_f8, np.complex128, casting="unsafe") + +np.min_scalar_type([1]) +np.min_scalar_type(AR_f8) + +np.result_type(int, AR_i4) +np.result_type(AR_f8, AR_u1) +np.result_type(AR_f8, np.complex128) + +np.dot(AR_LIKE_f, AR_i4) +np.dot(AR_u1, 1) +np.dot(1.5j, 1) +np.dot(AR_u1, 1, out=AR_f8) + +np.vdot(AR_LIKE_f, AR_i4) +np.vdot(AR_u1, 1) +np.vdot(1.5j, 1) + +np.bincount(AR_i4) + +np.copyto(AR_f8, [1.6]) + +np.putmask(AR_f8, [True], 1.5) + +np.packbits(AR_i4) +np.packbits(AR_u1) + +np.unpackbits(AR_u1) + +np.shares_memory(1, 2) +np.shares_memory(AR_f8, AR_f8, max_work=1) + +np.may_share_memory(1, 2) +np.may_share_memory(AR_f8, AR_f8, max_work=1) diff --git a/shared/package-files/33/331296a1aed4a094512e29b9dc7e8ea3261fcfcecfdfff585171983d39271954/histograms.pyi b/shared/package-files/33/331296a1aed4a094512e29b9dc7e8ea3261fcfcecfdfff585171983d39271954/histograms.pyi new file mode 100644 index 0000000000000000000000000000000000000000..68df0b96f48d80f386bfe68a164bd7320c73fa6e --- /dev/null +++ b/shared/package-files/33/331296a1aed4a094512e29b9dc7e8ea3261fcfcecfdfff585171983d39271954/histograms.pyi @@ -0,0 +1,27 @@ +import sys +from typing import Any + +import numpy as np +import numpy.typing as npt + +if sys.version_info >= (3, 11): + from typing import assert_type +else: + from typing_extensions import assert_type + +AR_i8: npt.NDArray[np.int64] +AR_f8: npt.NDArray[np.float64] + +assert_type(np.histogram_bin_edges(AR_i8, bins="auto"), npt.NDArray[Any]) +assert_type(np.histogram_bin_edges(AR_i8, bins="rice", range=(0, 3)), npt.NDArray[Any]) +assert_type(np.histogram_bin_edges(AR_i8, bins="scott", weights=AR_f8), npt.NDArray[Any]) + +assert_type(np.histogram(AR_i8, bins="auto"), tuple[npt.NDArray[Any], npt.NDArray[Any]]) +assert_type(np.histogram(AR_i8, bins="rice", range=(0, 3)), tuple[npt.NDArray[Any], npt.NDArray[Any]]) +assert_type(np.histogram(AR_i8, bins="scott", weights=AR_f8), tuple[npt.NDArray[Any], npt.NDArray[Any]]) +assert_type(np.histogram(AR_f8, bins=1, density=True), tuple[npt.NDArray[Any], npt.NDArray[Any]]) + +assert_type(np.histogramdd(AR_i8, bins=[1]), tuple[npt.NDArray[Any], list[npt.NDArray[Any]]]) +assert_type(np.histogramdd(AR_i8, range=[(0, 3)]), tuple[npt.NDArray[Any], list[npt.NDArray[Any]]]) +assert_type(np.histogramdd(AR_i8, weights=AR_f8), tuple[npt.NDArray[Any], list[npt.NDArray[Any]]]) +assert_type(np.histogramdd(AR_f8, density=True), tuple[npt.NDArray[Any], list[npt.NDArray[Any]]]) diff --git a/shared/package-files/33/3313b8d0e4e0ff9cff1273326fac1e4078e1b732f55a04b07e3097734ce5f366/parasail.py b/shared/package-files/33/3313b8d0e4e0ff9cff1273326fac1e4078e1b732f55a04b07e3097734ce5f366/parasail.py new file mode 100644 index 0000000000000000000000000000000000000000..5a7238ec7ca89aa55c3b8119b18c4e7c2e1e882e --- /dev/null +++ b/shared/package-files/33/3313b8d0e4e0ff9cff1273326fac1e4078e1b732f55a04b07e3097734ce5f366/parasail.py @@ -0,0 +1,79 @@ +""" + pygments.lexers.parasail + ~~~~~~~~~~~~~~~~~~~~~~~~ + + Lexer for ParaSail. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import re + +from pygments.lexer import RegexLexer, include +from pygments.token import Text, Comment, Operator, Keyword, Name, String, \ + Number, Punctuation, Literal + +__all__ = ['ParaSailLexer'] + + +class ParaSailLexer(RegexLexer): + """ + For ParaSail source code. + + .. versionadded:: 2.1 + """ + + name = 'ParaSail' + url = 'http://www.parasail-lang.org' + aliases = ['parasail'] + filenames = ['*.psi', '*.psl'] + mimetypes = ['text/x-parasail'] + + flags = re.MULTILINE + + tokens = { + 'root': [ + (r'[^\S\n]+', Text), + (r'//.*?\n', Comment.Single), + (r'\b(and|or|xor)=', Operator.Word), + (r'\b(and(\s+then)?|or(\s+else)?|xor|rem|mod|' + r'(is|not)\s+null)\b', + Operator.Word), + # Keywords + (r'\b(abs|abstract|all|block|class|concurrent|const|continue|' + r'each|end|exit|extends|exports|forward|func|global|implements|' + r'import|in|interface|is|lambda|locked|new|not|null|of|op|' + r'optional|private|queued|ref|return|reverse|separate|some|' + r'type|until|var|with|' + # Control flow + r'if|then|else|elsif|case|for|while|loop)\b', + Keyword.Reserved), + (r'(abstract\s+)?(interface|class|op|func|type)', + Keyword.Declaration), + # Literals + (r'"[^"]*"', String), + (r'\\[\'ntrf"0]', String.Escape), + (r'#[a-zA-Z]\w*', Literal), # Enumeration + include('numbers'), + (r"'[^']'", String.Char), + (r'[a-zA-Z]\w*', Name), + # Operators and Punctuation + (r'(<==|==>|<=>|\*\*=|<\|=|<<=|>>=|==|!=|=\?|<=|>=|' + r'\*\*|<<|>>|=>|:=|\+=|-=|\*=|\|=|\||/=|\+|-|\*|/|' + r'\.\.|<\.\.|\.\.<|<\.\.<)', + Operator), + (r'(<|>|\[|\]|\(|\)|\||:|;|,|.|\{|\}|->)', + Punctuation), + (r'\n+', Text), + ], + 'numbers': [ + (r'\d[0-9_]*#[0-9a-fA-F][0-9a-fA-F_]*#', Number.Hex), # any base + (r'0[xX][0-9a-fA-F][0-9a-fA-F_]*', Number.Hex), # C-like hex + (r'0[bB][01][01_]*', Number.Bin), # C-like bin + (r'\d[0-9_]*\.\d[0-9_]*[eE][+-]\d[0-9_]*', # float exp + Number.Float), + (r'\d[0-9_]*\.\d[0-9_]*', Number.Float), # float + (r'\d[0-9_]*', Number.Integer), # integer + ], + } diff --git a/shared/package-files/33/3318448046c83c176f95a97c33b5cd82e0076bee038d72810bef3dac1085e590/tree.py b/shared/package-files/33/3318448046c83c176f95a97c33b5cd82e0076bee038d72810bef3dac1085e590/tree.py new file mode 100644 index 0000000000000000000000000000000000000000..98a20da7f15c11d90a4243b8319131ceed2e8f4c --- /dev/null +++ b/shared/package-files/33/3318448046c83c176f95a97c33b5cd82e0076bee038d72810bef3dac1085e590/tree.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +""" turtle-example-suite: + + tdemo_tree.py + +Displays a 'breadth-first-tree' - in contrast +to the classical Logo tree drawing programs, +which use a depth-first-algorithm. + +Uses: +(1) a tree-generator, where the drawing is +quasi the side-effect, whereas the generator +always yields None. +(2) Turtle-cloning: At each branching point +the current pen is cloned. So in the end +there are 1024 turtles. +""" +from turtle import Turtle, mainloop +from time import perf_counter as clock + +def tree(plist, l, a, f): + """ plist is list of pens + l is length of branch + a is half of the angle between 2 branches + f is factor by which branch is shortened + from level to level.""" + if l > 3: + lst = [] + for p in plist: + p.forward(l) + q = p.clone() + p.left(a) + q.right(a) + lst.append(p) + lst.append(q) + for x in tree(lst, l*f, a, f): + yield None + +def maketree(): + p = Turtle() + p.setundobuffer(None) + p.hideturtle() + p.speed(0) + p.getscreen().tracer(30,0) + p.left(90) + p.penup() + p.forward(-210) + p.pendown() + t = tree([p], 200, 65, 0.6375) + for x in t: + pass + +def main(): + a=clock() + maketree() + b=clock() + return "done: %.2f sec." % (b-a) + +if __name__ == "__main__": + msg = main() + print(msg) + mainloop() diff --git a/shared/package-files/33/331c770f5e07eb18d510cfe34f14da5b2f5620d82b4662d65c9a47e5281797e7/test_base.py b/shared/package-files/33/331c770f5e07eb18d510cfe34f14da5b2f5620d82b4662d65c9a47e5281797e7/test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..27c79e644e34d3e6f88d0329ffc4c8cc3423eba6 --- /dev/null +++ b/shared/package-files/33/331c770f5e07eb18d510cfe34f14da5b2f5620d82b4662d65c9a47e5281797e7/test_base.py @@ -0,0 +1,69 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +import random +import types +import unittest +from contextlib import contextmanager +from unittest import mock + +from conda.exceptions import SpecNotFound +from conda_env import specs + +true_func = mock.Mock(return_value=True) +false_func = mock.Mock(return_value=False) + + +@contextmanager +def patched_specs(*new_specs): + with mock.patch.object(specs, "all_specs") as all_specs: + all_specs.__iter__.return_value = new_specs + yield all_specs + + +def generate_two_specs(): + spec1 = mock.Mock(can_handle=false_func) + spec1.return_value = spec1 + spec2 = mock.Mock(can_handle=true_func) + spec2.return_value = spec2 + return spec1, spec2 + + +class DetectTestCase(unittest.TestCase): + def test_has_detect_function(self): + self.assertTrue(hasattr(specs, "detect")) + self.assertIsInstance(specs.detect, types.FunctionType) + + def test_dispatches_to_registered_specs(self): + spec1, spec2 = generate_two_specs() + with patched_specs(spec1, spec2): + actual = specs.detect(name="foo") + self.assertEqual(actual, spec2) + + def test_passes_kwargs_to_all_specs(self): + random_kwargs = { + "foo": random.randint(100, 200), + "bar%d" % random.randint(100, 200): True, + } + + spec1, spec2 = generate_two_specs() + with patched_specs(spec1, spec2): + specs.detect(**random_kwargs) + spec1.assert_called_with(**random_kwargs) + spec2.assert_called_with(**random_kwargs) + + def test_raises_exception_if_no_detection(self): + spec1 = generate_two_specs()[0] + spec1.msg = "msg" + with patched_specs(spec1): + with self.assertRaises(SpecNotFound): + specs.detect(name="foo") + + def test_has_build_msg_function(self): + self.assertTrue(hasattr(specs, "build_message")) + self.assertIsInstance(specs.build_message, types.FunctionType) + + def test_build_msg(self): + spec3 = mock.Mock(msg="error 3") + spec4 = mock.Mock(msg="error 4") + spec5 = mock.Mock(msg=None) + self.assertEqual(specs.build_message([spec3, spec4, spec5]), "error 3\nerror 4") diff --git a/shared/package-files/33/331ca6c70946040dcfc76145cb321212d027915a317aaf9b24cd5f9368e412db/mpelements.py b/shared/package-files/33/331ca6c70946040dcfc76145cb321212d027915a317aaf9b24cd5f9368e412db/mpelements.py new file mode 100644 index 0000000000000000000000000000000000000000..51208a709effc135c0d05baa56d1313bb76e2892 --- /dev/null +++ b/shared/package-files/33/331ca6c70946040dcfc76145cb321212d027915a317aaf9b24cd5f9368e412db/mpelements.py @@ -0,0 +1,172 @@ +"""Real and complex elements. """ + + +from sympy.polys.domains.domainelement import DomainElement +from sympy.utilities import public + +from mpmath.ctx_mp_python import PythonMPContext, _mpf, _mpc, _constant +from mpmath.libmp import (MPZ_ONE, fzero, fone, finf, fninf, fnan, + round_nearest, mpf_mul, repr_dps, int_types, + from_int, from_float, from_str, to_rational) +from mpmath.rational import mpq + + +@public +class RealElement(_mpf, DomainElement): + """An element of a real domain. """ + + __slots__ = ('__mpf__',) + + def _set_mpf(self, val): + self.__mpf__ = val + + _mpf_ = property(lambda self: self.__mpf__, _set_mpf) + + def parent(self): + return self.context._parent + +@public +class ComplexElement(_mpc, DomainElement): + """An element of a complex domain. """ + + __slots__ = ('__mpc__',) + + def _set_mpc(self, val): + self.__mpc__ = val + + _mpc_ = property(lambda self: self.__mpc__, _set_mpc) + + def parent(self): + return self.context._parent + +new = object.__new__ + +@public +class MPContext(PythonMPContext): + + def __init__(ctx, prec=53, dps=None, tol=None, real=False): + ctx._prec_rounding = [prec, round_nearest] + + if dps is None: + ctx._set_prec(prec) + else: + ctx._set_dps(dps) + + ctx.mpf = RealElement + ctx.mpc = ComplexElement + ctx.mpf._ctxdata = [ctx.mpf, new, ctx._prec_rounding] + ctx.mpc._ctxdata = [ctx.mpc, new, ctx._prec_rounding] + + if real: + ctx.mpf.context = ctx + else: + ctx.mpc.context = ctx + + ctx.constant = _constant + ctx.constant._ctxdata = [ctx.mpf, new, ctx._prec_rounding] + ctx.constant.context = ctx + + ctx.types = [ctx.mpf, ctx.mpc, ctx.constant] + ctx.trap_complex = True + ctx.pretty = True + + if tol is None: + ctx.tol = ctx._make_tol() + elif tol is False: + ctx.tol = fzero + else: + ctx.tol = ctx._convert_tol(tol) + + ctx.tolerance = ctx.make_mpf(ctx.tol) + + if not ctx.tolerance: + ctx.max_denom = 1000000 + else: + ctx.max_denom = int(1/ctx.tolerance) + + ctx.zero = ctx.make_mpf(fzero) + ctx.one = ctx.make_mpf(fone) + ctx.j = ctx.make_mpc((fzero, fone)) + ctx.inf = ctx.make_mpf(finf) + ctx.ninf = ctx.make_mpf(fninf) + ctx.nan = ctx.make_mpf(fnan) + + def _make_tol(ctx): + hundred = (0, 25, 2, 5) + eps = (0, MPZ_ONE, 1-ctx.prec, 1) + return mpf_mul(hundred, eps) + + def make_tol(ctx): + return ctx.make_mpf(ctx._make_tol()) + + def _convert_tol(ctx, tol): + if isinstance(tol, int_types): + return from_int(tol) + if isinstance(tol, float): + return from_float(tol) + if hasattr(tol, "_mpf_"): + return tol._mpf_ + prec, rounding = ctx._prec_rounding + if isinstance(tol, str): + return from_str(tol, prec, rounding) + raise ValueError("expected a real number, got %s" % tol) + + def _convert_fallback(ctx, x, strings): + raise TypeError("cannot create mpf from " + repr(x)) + + @property + def _repr_digits(ctx): + return repr_dps(ctx._prec) + + @property + def _str_digits(ctx): + return ctx._dps + + def to_rational(ctx, s, limit=True): + p, q = to_rational(s._mpf_) + + if not limit or q <= ctx.max_denom: + return p, q + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = p, q + + while True: + a = n//d + q2 = q0 + a*q1 + if q2 > ctx.max_denom: + break + p0, q0, p1, q1 = p1, q1, p0 + a*p1, q2 + n, d = d, n - a*d + + k = (ctx.max_denom - q0)//q1 + + number = mpq(p, q) + bound1 = mpq(p0 + k*p1, q0 + k*q1) + bound2 = mpq(p1, q1) + + if not bound2 or not bound1: + return p, q + elif abs(bound2 - number) <= abs(bound1 - number): + return bound2._mpq_ + else: + return bound1._mpq_ + + def almosteq(ctx, s, t, rel_eps=None, abs_eps=None): + t = ctx.convert(t) + if abs_eps is None and rel_eps is None: + rel_eps = abs_eps = ctx.tolerance or ctx.make_tol() + if abs_eps is None: + abs_eps = ctx.convert(rel_eps) + elif rel_eps is None: + rel_eps = ctx.convert(abs_eps) + diff = abs(s-t) + if diff <= abs_eps: + return True + abss = abs(s) + abst = abs(t) + if abss < abst: + err = diff/abst + else: + err = diff/abss + return err <= rel_eps diff --git a/shared/package-files/33/331f3a5c201fc345c41baedd53bdc68d96598b7f0464c244af0be0ae6efe4e15/test_constrainedlayout.py b/shared/package-files/33/331f3a5c201fc345c41baedd53bdc68d96598b7f0464c244af0be0ae6efe4e15/test_constrainedlayout.py new file mode 100644 index 0000000000000000000000000000000000000000..df2dbd6f43bdb52879893293a222d9e98fcb38b8 --- /dev/null +++ b/shared/package-files/33/331f3a5c201fc345c41baedd53bdc68d96598b7f0464c244af0be0ae6efe4e15/test_constrainedlayout.py @@ -0,0 +1,743 @@ +import gc +import platform + +import numpy as np +import pytest + +import matplotlib as mpl +from matplotlib.testing.decorators import image_comparison +import matplotlib.pyplot as plt +import matplotlib.transforms as mtransforms +from matplotlib import gridspec, ticker + + +pytestmark = [ + pytest.mark.usefixtures('text_placeholders') +] + + +def example_plot(ax, fontsize=12, nodec=False): + ax.plot([1, 2]) + ax.locator_params(nbins=3) + if not nodec: + ax.set_xlabel('x-label', fontsize=fontsize) + ax.set_ylabel('y-label', fontsize=fontsize) + ax.set_title('Title', fontsize=fontsize) + else: + ax.set_xticklabels([]) + ax.set_yticklabels([]) + + +def example_pcolor(ax, fontsize=12): + dx, dy = 0.6, 0.6 + y, x = np.mgrid[slice(-3, 3 + dy, dy), + slice(-3, 3 + dx, dx)] + z = (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) + pcm = ax.pcolormesh(x, y, z[:-1, :-1], cmap='RdBu_r', vmin=-1., vmax=1., + rasterized=True) + ax.set_xlabel('x-label', fontsize=fontsize) + ax.set_ylabel('y-label', fontsize=fontsize) + ax.set_title('Title', fontsize=fontsize) + return pcm + + +@image_comparison(['constrained_layout1.png'], style='mpl20') +def test_constrained_layout1(): + """Test constrained_layout for a single subplot""" + fig = plt.figure(layout="constrained") + ax = fig.add_subplot() + example_plot(ax, fontsize=24) + + +@image_comparison(['constrained_layout2.png'], style='mpl20') +def test_constrained_layout2(): + """Test constrained_layout for 2x2 subplots""" + fig, axs = plt.subplots(2, 2, layout="constrained") + for ax in axs.flat: + example_plot(ax, fontsize=24) + + +@image_comparison(['constrained_layout3.png'], style='mpl20') +def test_constrained_layout3(): + """Test constrained_layout for colorbars with subplots""" + + fig, axs = plt.subplots(2, 2, layout="constrained") + for nn, ax in enumerate(axs.flat): + pcm = example_pcolor(ax, fontsize=24) + if nn == 3: + pad = 0.08 + else: + pad = 0.02 # default + fig.colorbar(pcm, ax=ax, pad=pad) + + +@image_comparison(['constrained_layout4.png'], style='mpl20') +def test_constrained_layout4(): + """Test constrained_layout for a single colorbar with subplots""" + + fig, axs = plt.subplots(2, 2, layout="constrained") + for ax in axs.flat: + pcm = example_pcolor(ax, fontsize=24) + fig.colorbar(pcm, ax=axs, pad=0.01, shrink=0.6) + + +@image_comparison(['constrained_layout5.png'], style='mpl20') +def test_constrained_layout5(): + """ + Test constrained_layout for a single colorbar with subplots, + colorbar bottom + """ + + fig, axs = plt.subplots(2, 2, layout="constrained") + for ax in axs.flat: + pcm = example_pcolor(ax, fontsize=24) + fig.colorbar(pcm, ax=axs, + use_gridspec=False, pad=0.01, shrink=0.6, + location='bottom') + + +@image_comparison(['constrained_layout6.png'], style='mpl20') +def test_constrained_layout6(): + """Test constrained_layout for nested gridspecs""" + fig = plt.figure(layout="constrained") + gs = fig.add_gridspec(1, 2, figure=fig) + gsl = gs[0].subgridspec(2, 2) + gsr = gs[1].subgridspec(1, 2) + axsl = [] + for gs in gsl: + ax = fig.add_subplot(gs) + axsl += [ax] + example_plot(ax, fontsize=12) + ax.set_xlabel('x-label\nMultiLine') + axsr = [] + for gs in gsr: + ax = fig.add_subplot(gs) + axsr += [ax] + pcm = example_pcolor(ax, fontsize=12) + + fig.colorbar(pcm, ax=axsr, + pad=0.01, shrink=0.99, location='bottom', + ticks=ticker.MaxNLocator(nbins=5)) + + +def test_identical_subgridspec(): + + fig = plt.figure(constrained_layout=True) + + GS = fig.add_gridspec(2, 1) + + GSA = GS[0].subgridspec(1, 3) + GSB = GS[1].subgridspec(1, 3) + + axa = [] + axb = [] + for i in range(3): + axa += [fig.add_subplot(GSA[i])] + axb += [fig.add_subplot(GSB[i])] + + fig.draw_without_rendering() + # check first row above second + assert axa[0].get_position().y0 > axb[0].get_position().y1 + + +def test_constrained_layout7(): + """Test for proper warning if fig not set in GridSpec""" + with pytest.warns( + UserWarning, match=('There are no gridspecs with layoutgrids. ' + 'Possibly did not call parent GridSpec with ' + 'the "figure" keyword')): + fig = plt.figure(layout="constrained") + gs = gridspec.GridSpec(1, 2) + gsl = gridspec.GridSpecFromSubplotSpec(2, 2, gs[0]) + gsr = gridspec.GridSpecFromSubplotSpec(1, 2, gs[1]) + for gs in gsl: + fig.add_subplot(gs) + # need to trigger a draw to get warning + fig.draw_without_rendering() + + +@image_comparison(['constrained_layout8.png'], style='mpl20') +def test_constrained_layout8(): + """Test for gridspecs that are not completely full""" + + fig = plt.figure(figsize=(10, 5), layout="constrained") + gs = gridspec.GridSpec(3, 5, figure=fig) + axs = [] + for j in [0, 1]: + if j == 0: + ilist = [1] + else: + ilist = [0, 4] + for i in ilist: + ax = fig.add_subplot(gs[j, i]) + axs += [ax] + example_pcolor(ax, fontsize=9) + if i > 0: + ax.set_ylabel('') + if j < 1: + ax.set_xlabel('') + ax.set_title('') + ax = fig.add_subplot(gs[2, :]) + axs += [ax] + pcm = example_pcolor(ax, fontsize=9) + + fig.colorbar(pcm, ax=axs, pad=0.01, shrink=0.6) + + +@image_comparison(['constrained_layout9.png'], style='mpl20') +def test_constrained_layout9(): + """Test for handling suptitle and for sharex and sharey""" + + fig, axs = plt.subplots(2, 2, layout="constrained", + sharex=False, sharey=False) + for ax in axs.flat: + pcm = example_pcolor(ax, fontsize=24) + ax.set_xlabel('') + ax.set_ylabel('') + ax.set_aspect(2.) + fig.colorbar(pcm, ax=axs, pad=0.01, shrink=0.6) + fig.suptitle('Test Suptitle', fontsize=28) + + +@image_comparison(['constrained_layout10.png'], style='mpl20', + tol=0 if platform.machine() == 'x86_64' else 0.032) +def test_constrained_layout10(): + """Test for handling legend outside axis""" + fig, axs = plt.subplots(2, 2, layout="constrained") + for ax in axs.flat: + ax.plot(np.arange(12), label='This is a label') + ax.legend(loc='center left', bbox_to_anchor=(0.8, 0.5)) + + +@image_comparison(['constrained_layout11.png'], style='mpl20') +def test_constrained_layout11(): + """Test for multiple nested gridspecs""" + + fig = plt.figure(layout="constrained", figsize=(13, 3)) + gs0 = gridspec.GridSpec(1, 2, figure=fig) + gsl = gridspec.GridSpecFromSubplotSpec(1, 2, gs0[0]) + gsl0 = gridspec.GridSpecFromSubplotSpec(2, 2, gsl[1]) + ax = fig.add_subplot(gs0[1]) + example_plot(ax, fontsize=9) + axs = [] + for gs in gsl0: + ax = fig.add_subplot(gs) + axs += [ax] + pcm = example_pcolor(ax, fontsize=9) + fig.colorbar(pcm, ax=axs, shrink=0.6, aspect=70.) + ax = fig.add_subplot(gsl[0]) + example_plot(ax, fontsize=9) + + +@image_comparison(['constrained_layout11rat.png'], style='mpl20') +def test_constrained_layout11rat(): + """Test for multiple nested gridspecs with width_ratios""" + + fig = plt.figure(layout="constrained", figsize=(10, 3)) + gs0 = gridspec.GridSpec(1, 2, figure=fig, width_ratios=[6, 1]) + gsl = gridspec.GridSpecFromSubplotSpec(1, 2, gs0[0]) + gsl0 = gridspec.GridSpecFromSubplotSpec(2, 2, gsl[1], height_ratios=[2, 1]) + ax = fig.add_subplot(gs0[1]) + example_plot(ax, fontsize=9) + axs = [] + for gs in gsl0: + ax = fig.add_subplot(gs) + axs += [ax] + pcm = example_pcolor(ax, fontsize=9) + fig.colorbar(pcm, ax=axs, shrink=0.6, aspect=70.) + ax = fig.add_subplot(gsl[0]) + example_plot(ax, fontsize=9) + + +@image_comparison(['constrained_layout12.png'], style='mpl20') +def test_constrained_layout12(): + """Test that very unbalanced labeling still works.""" + fig = plt.figure(layout="constrained", figsize=(6, 8)) + + gs0 = gridspec.GridSpec(6, 2, figure=fig) + + ax1 = fig.add_subplot(gs0[:3, 1]) + ax2 = fig.add_subplot(gs0[3:, 1]) + + example_plot(ax1, fontsize=18) + example_plot(ax2, fontsize=18) + + ax = fig.add_subplot(gs0[0:2, 0]) + example_plot(ax, nodec=True) + ax = fig.add_subplot(gs0[2:4, 0]) + example_plot(ax, nodec=True) + ax = fig.add_subplot(gs0[4:, 0]) + example_plot(ax, nodec=True) + ax.set_xlabel('x-label') + + +@image_comparison(['constrained_layout13.png'], style='mpl20') +def test_constrained_layout13(): + """Test that padding works.""" + fig, axs = plt.subplots(2, 2, layout="constrained") + for ax in axs.flat: + pcm = example_pcolor(ax, fontsize=12) + fig.colorbar(pcm, ax=ax, shrink=0.6, aspect=20., pad=0.02) + with pytest.raises(TypeError): + fig.get_layout_engine().set(wpad=1, hpad=2) + fig.get_layout_engine().set(w_pad=24./72., h_pad=24./72.) + + +@image_comparison(['constrained_layout14.png'], style='mpl20') +def test_constrained_layout14(): + """Test that padding works.""" + fig, axs = plt.subplots(2, 2, layout="constrained") + for ax in axs.flat: + pcm = example_pcolor(ax, fontsize=12) + fig.colorbar(pcm, ax=ax, shrink=0.6, aspect=20., pad=0.02) + fig.get_layout_engine().set( + w_pad=3./72., h_pad=3./72., + hspace=0.2, wspace=0.2) + + +@image_comparison(['constrained_layout15.png'], style='mpl20') +def test_constrained_layout15(): + """Test that rcparams work.""" + mpl.rcParams['figure.constrained_layout.use'] = True + fig, axs = plt.subplots(2, 2) + for ax in axs.flat: + example_plot(ax, fontsize=12) + + +@image_comparison(['constrained_layout16.png'], style='mpl20') +def test_constrained_layout16(): + """Test ax.set_position.""" + fig, ax = plt.subplots(layout="constrained") + example_plot(ax, fontsize=12) + ax2 = fig.add_axes([0.2, 0.2, 0.4, 0.4]) + + +@image_comparison(['constrained_layout17.png'], style='mpl20') +def test_constrained_layout17(): + """Test uneven gridspecs""" + fig = plt.figure(layout="constrained") + gs = gridspec.GridSpec(3, 3, figure=fig) + + ax1 = fig.add_subplot(gs[0, 0]) + ax2 = fig.add_subplot(gs[0, 1:]) + ax3 = fig.add_subplot(gs[1:, 0:2]) + ax4 = fig.add_subplot(gs[1:, -1]) + + example_plot(ax1) + example_plot(ax2) + example_plot(ax3) + example_plot(ax4) + + +def test_constrained_layout18(): + """Test twinx""" + fig, ax = plt.subplots(layout="constrained") + ax2 = ax.twinx() + example_plot(ax) + example_plot(ax2, fontsize=24) + fig.draw_without_rendering() + assert all(ax.get_position().extents == ax2.get_position().extents) + + +def test_constrained_layout19(): + """Test twiny""" + fig, ax = plt.subplots(layout="constrained") + ax2 = ax.twiny() + example_plot(ax) + example_plot(ax2, fontsize=24) + ax2.set_title('') + ax.set_title('') + fig.draw_without_rendering() + assert all(ax.get_position().extents == ax2.get_position().extents) + + +def test_constrained_layout20(): + """Smoke test cl does not mess up added Axes""" + gx = np.linspace(-5, 5, 4) + img = np.hypot(gx, gx[:, None]) + + fig = plt.figure() + ax = fig.add_axes([0, 0, 1, 1]) + mesh = ax.pcolormesh(gx, gx, img[:-1, :-1]) + fig.colorbar(mesh) + + +def test_constrained_layout21(): + """#11035: repeated calls to suptitle should not alter the layout""" + fig, ax = plt.subplots(layout="constrained") + + fig.suptitle("Suptitle0") + fig.draw_without_rendering() + extents0 = np.copy(ax.get_position().extents) + + fig.suptitle("Suptitle1") + fig.draw_without_rendering() + extents1 = np.copy(ax.get_position().extents) + + np.testing.assert_allclose(extents0, extents1) + + +def test_constrained_layout22(): + """#11035: suptitle should not be include in CL if manually positioned""" + fig, ax = plt.subplots(layout="constrained") + + fig.draw_without_rendering() + extents0 = np.copy(ax.get_position().extents) + + fig.suptitle("Suptitle", y=0.5) + fig.draw_without_rendering() + extents1 = np.copy(ax.get_position().extents) + + np.testing.assert_allclose(extents0, extents1) + + +def test_constrained_layout23(): + """ + Comment in #11035: suptitle used to cause an exception when + reusing a figure w/ CL with ``clear=True``. + """ + + for i in range(2): + fig = plt.figure(layout="constrained", clear=True, num="123") + gs = fig.add_gridspec(1, 2) + sub = gs[0].subgridspec(2, 2) + fig.suptitle(f"Suptitle{i}") + + +@image_comparison(['test_colorbar_location.png'], + remove_text=True, style='mpl20') +def test_colorbar_location(): + """ + Test that colorbar handling is as expected for various complicated + cases... + """ + # Remove this line when this test image is regenerated. + plt.rcParams['pcolormesh.snap'] = False + + fig, axs = plt.subplots(4, 5, layout="constrained") + for ax in axs.flat: + pcm = example_pcolor(ax) + ax.set_xlabel('') + ax.set_ylabel('') + fig.colorbar(pcm, ax=axs[:, 1], shrink=0.4) + fig.colorbar(pcm, ax=axs[-1, :2], shrink=0.5, location='bottom') + fig.colorbar(pcm, ax=axs[0, 2:], shrink=0.5, location='bottom', pad=0.05) + fig.colorbar(pcm, ax=axs[-2, 3:], shrink=0.5, location='top') + fig.colorbar(pcm, ax=axs[0, 0], shrink=0.5, location='left') + fig.colorbar(pcm, ax=axs[1:3, 2], shrink=0.5, location='right') + + +def test_hidden_axes(): + # test that if we make an Axes not visible that constrained_layout + # still works. Note the axes still takes space in the layout + # (as does a gridspec slot that is empty) + fig, axs = plt.subplots(2, 2, layout="constrained") + axs[0, 1].set_visible(False) + fig.draw_without_rendering() + extents1 = np.copy(axs[0, 0].get_position().extents) + + np.testing.assert_allclose( + extents1, [0.046918, 0.541204, 0.477409, 0.980555], rtol=1e-5) + + +def test_colorbar_align(): + for location in ['right', 'left', 'top', 'bottom']: + fig, axs = plt.subplots(2, 2, layout="constrained") + cbs = [] + for nn, ax in enumerate(axs.flat): + ax.tick_params(direction='in') + pc = example_pcolor(ax) + cb = fig.colorbar(pc, ax=ax, location=location, shrink=0.6, + pad=0.04) + cbs += [cb] + cb.ax.tick_params(direction='in') + if nn != 1: + cb.ax.xaxis.set_ticks([]) + cb.ax.yaxis.set_ticks([]) + ax.set_xticklabels([]) + ax.set_yticklabels([]) + fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, + hspace=0.1, wspace=0.1) + + fig.draw_without_rendering() + if location in ['left', 'right']: + np.testing.assert_allclose(cbs[0].ax.get_position().x0, + cbs[2].ax.get_position().x0) + np.testing.assert_allclose(cbs[1].ax.get_position().x0, + cbs[3].ax.get_position().x0) + else: + np.testing.assert_allclose(cbs[0].ax.get_position().y0, + cbs[1].ax.get_position().y0) + np.testing.assert_allclose(cbs[2].ax.get_position().y0, + cbs[3].ax.get_position().y0) + + +@image_comparison(['test_colorbars_no_overlapV.png'], style='mpl20') +def test_colorbars_no_overlapV(): + fig = plt.figure(figsize=(2, 4), layout="constrained") + axs = fig.subplots(2, 1, sharex=True, sharey=True) + for ax in axs: + ax.yaxis.set_major_formatter(ticker.NullFormatter()) + ax.tick_params(axis='both', direction='in') + im = ax.imshow([[1, 2], [3, 4]]) + fig.colorbar(im, ax=ax, orientation="vertical") + fig.suptitle("foo") + + +@image_comparison(['test_colorbars_no_overlapH.png'], style='mpl20') +def test_colorbars_no_overlapH(): + fig = plt.figure(figsize=(4, 2), layout="constrained") + fig.suptitle("foo") + axs = fig.subplots(1, 2, sharex=True, sharey=True) + for ax in axs: + ax.yaxis.set_major_formatter(ticker.NullFormatter()) + ax.tick_params(axis='both', direction='in') + im = ax.imshow([[1, 2], [3, 4]]) + fig.colorbar(im, ax=ax, orientation="horizontal") + + +def test_manually_set_position(): + fig, axs = plt.subplots(1, 2, layout="constrained") + axs[0].set_position([0.2, 0.2, 0.3, 0.3]) + fig.draw_without_rendering() + pp = axs[0].get_position() + np.testing.assert_allclose(pp, [[0.2, 0.2], [0.5, 0.5]]) + + fig, axs = plt.subplots(1, 2, layout="constrained") + axs[0].set_position([0.2, 0.2, 0.3, 0.3]) + pc = axs[0].pcolormesh(np.random.rand(20, 20)) + fig.colorbar(pc, ax=axs[0]) + fig.draw_without_rendering() + pp = axs[0].get_position() + np.testing.assert_allclose(pp, [[0.2, 0.2], [0.44, 0.5]]) + + +@image_comparison(['test_bboxtight.png'], + remove_text=True, style='mpl20', + savefig_kwarg={'bbox_inches': 'tight'}) +def test_bboxtight(): + fig, ax = plt.subplots(layout="constrained") + ax.set_aspect(1.) + + +@image_comparison(['test_bbox.png'], + remove_text=True, style='mpl20', + savefig_kwarg={'bbox_inches': + mtransforms.Bbox([[0.5, 0], [2.5, 2]])}) +def test_bbox(): + fig, ax = plt.subplots(layout="constrained") + ax.set_aspect(1.) + + +def test_align_labels(): + """ + Tests for a bug in which constrained layout and align_ylabels on + three unevenly sized subplots, one of whose y tick labels include + negative numbers, drives the non-negative subplots' y labels off + the edge of the plot + """ + fig, (ax3, ax1, ax2) = plt.subplots(3, 1, layout="constrained", + figsize=(6.4, 8), + gridspec_kw={"height_ratios": (1, 1, + 0.7)}) + + ax1.set_ylim(0, 1) + ax1.set_ylabel("Label") + + ax2.set_ylim(-1.5, 1.5) + ax2.set_ylabel("Label") + + ax3.set_ylim(0, 1) + ax3.set_ylabel("Label") + + fig.align_ylabels(axs=(ax3, ax1, ax2)) + + fig.draw_without_rendering() + after_align = [ax1.yaxis.label.get_window_extent(), + ax2.yaxis.label.get_window_extent(), + ax3.yaxis.label.get_window_extent()] + # ensure labels are approximately aligned + np.testing.assert_allclose([after_align[0].x0, after_align[2].x0], + after_align[1].x0, rtol=0, atol=1e-05) + # ensure labels do not go off the edge + assert after_align[0].x0 >= 1 + + +def test_suplabels(): + fig, ax = plt.subplots(layout="constrained") + fig.draw_without_rendering() + pos0 = ax.get_tightbbox(fig.canvas.get_renderer()) + fig.supxlabel('Boo') + fig.supylabel('Booy') + fig.draw_without_rendering() + pos = ax.get_tightbbox(fig.canvas.get_renderer()) + assert pos.y0 > pos0.y0 + 10.0 + assert pos.x0 > pos0.x0 + 10.0 + + fig, ax = plt.subplots(layout="constrained") + fig.draw_without_rendering() + pos0 = ax.get_tightbbox(fig.canvas.get_renderer()) + # check that specifying x (y) doesn't ruin the layout + fig.supxlabel('Boo', x=0.5) + fig.supylabel('Boo', y=0.5) + fig.draw_without_rendering() + pos = ax.get_tightbbox(fig.canvas.get_renderer()) + assert pos.y0 > pos0.y0 + 10.0 + assert pos.x0 > pos0.x0 + 10.0 + + +def test_gridspec_addressing(): + fig = plt.figure() + gs = fig.add_gridspec(3, 3) + sp = fig.add_subplot(gs[0:, 1:]) + fig.draw_without_rendering() + + +def test_discouraged_api(): + fig, ax = plt.subplots(constrained_layout=True) + fig.draw_without_rendering() + + with pytest.warns(PendingDeprecationWarning, + match="will be deprecated"): + fig, ax = plt.subplots() + fig.set_constrained_layout(True) + fig.draw_without_rendering() + + with pytest.warns(PendingDeprecationWarning, + match="will be deprecated"): + fig, ax = plt.subplots() + fig.set_constrained_layout({'w_pad': 0.02, 'h_pad': 0.02}) + fig.draw_without_rendering() + + +def test_kwargs(): + fig, ax = plt.subplots(constrained_layout={'h_pad': 0.02}) + fig.draw_without_rendering() + + +def test_rect(): + fig, ax = plt.subplots(layout='constrained') + fig.get_layout_engine().set(rect=[0, 0, 0.5, 0.5]) + fig.draw_without_rendering() + ppos = ax.get_position() + assert ppos.x1 < 0.5 + assert ppos.y1 < 0.5 + + fig, ax = plt.subplots(layout='constrained') + fig.get_layout_engine().set(rect=[0.2, 0.2, 0.3, 0.3]) + fig.draw_without_rendering() + ppos = ax.get_position() + assert ppos.x1 < 0.5 + assert ppos.y1 < 0.5 + assert ppos.x0 > 0.2 + assert ppos.y0 > 0.2 + + +def test_compressed1(): + fig, axs = plt.subplots(3, 2, layout='compressed', + sharex=True, sharey=True) + for ax in axs.flat: + pc = ax.imshow(np.random.randn(20, 20)) + + fig.colorbar(pc, ax=axs) + fig.draw_without_rendering() + + pos = axs[0, 0].get_position() + np.testing.assert_allclose(pos.x0, 0.2381, atol=1e-2) + pos = axs[0, 1].get_position() + np.testing.assert_allclose(pos.x1, 0.7024, atol=1e-3) + + # wider than tall + fig, axs = plt.subplots(2, 3, layout='compressed', + sharex=True, sharey=True, figsize=(5, 4)) + for ax in axs.flat: + pc = ax.imshow(np.random.randn(20, 20)) + + fig.colorbar(pc, ax=axs) + fig.draw_without_rendering() + + pos = axs[0, 0].get_position() + np.testing.assert_allclose(pos.x0, 0.05653, atol=1e-3) + np.testing.assert_allclose(pos.y1, 0.8603, atol=1e-2) + pos = axs[1, 2].get_position() + np.testing.assert_allclose(pos.x1, 0.8728, atol=1e-3) + np.testing.assert_allclose(pos.y0, 0.1808, atol=1e-2) + + +def test_compressed_suptitle(): + fig, (ax0, ax1) = plt.subplots( + nrows=2, figsize=(4, 10), layout="compressed", + gridspec_kw={"height_ratios": (1 / 4, 3 / 4), "hspace": 0}) + + ax0.axis("equal") + ax0.set_box_aspect(1/3) + + ax1.axis("equal") + ax1.set_box_aspect(1) + + title = fig.suptitle("Title") + fig.draw_without_rendering() + assert title.get_position()[1] == pytest.approx(0.7491, abs=1e-3) + + title = fig.suptitle("Title", y=0.98) + fig.draw_without_rendering() + assert title.get_position()[1] == 0.98 + + title = fig.suptitle("Title", in_layout=False) + fig.draw_without_rendering() + assert title.get_position()[1] == 0.98 + + +@pytest.mark.parametrize('arg, state', [ + (True, True), + (False, False), + ({}, True), + ({'rect': None}, True) +]) +def test_set_constrained_layout(arg, state): + fig, ax = plt.subplots(constrained_layout=arg) + assert fig.get_constrained_layout() is state + + +def test_constrained_toggle(): + fig, ax = plt.subplots() + with pytest.warns(PendingDeprecationWarning): + fig.set_constrained_layout(True) + assert fig.get_constrained_layout() + fig.set_constrained_layout(False) + assert not fig.get_constrained_layout() + fig.set_constrained_layout(True) + assert fig.get_constrained_layout() + + +def test_layout_leak(): + # Make sure there aren't any cyclic references when using LayoutGrid + # GH #25853 + fig = plt.figure(constrained_layout=True, figsize=(10, 10)) + fig.add_subplot() + fig.draw_without_rendering() + plt.close("all") + del fig + gc.collect() + assert not any(isinstance(obj, mpl._layoutgrid.LayoutGrid) + for obj in gc.get_objects()) + + +def test_submerged_subfig(): + """ + Test that the submerged margin logic does not get called multiple times + on same axes if it is already in a subfigure + """ + fig = plt.figure(figsize=(4, 5), layout='constrained') + figures = fig.subfigures(3, 1) + axs = [] + for f in figures.flatten(): + gs = f.add_gridspec(2, 2) + for i in range(2): + axs += [f.add_subplot(gs[i, 0])] + axs[-1].plot() + f.add_subplot(gs[:, 1]).plot() + fig.draw_without_rendering() + for ax in axs[1:]: + assert np.allclose(ax.get_position().bounds[-1], + axs[0].get_position().bounds[-1], atol=1e-6) diff --git a/shared/package-files/33/331ff95d94552759b94ad3b6a79ad52bd0ffcf2a6b3dbd8e0bc9b6aa5afae36f/fractional_max_pool2d_backward_meta_dispatch.h b/shared/package-files/33/331ff95d94552759b94ad3b6a79ad52bd0ffcf2a6b3dbd8e0bc9b6aa5afae36f/fractional_max_pool2d_backward_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..64561c87b0da88a0458f9b0a07963a82b9da4b23 --- /dev/null +++ b/shared/package-files/33/331ff95d94552759b94ad3b6a79ad52bd0ffcf2a6b3dbd8e0bc9b6aa5afae36f/fractional_max_pool2d_backward_meta_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor fractional_max_pool2d_backward(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices); +TORCH_API at::Tensor & fractional_max_pool2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices); +TORCH_API at::Tensor & fractional_max_pool2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices, at::Tensor & grad_input); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/33/332288615a542442c1306223657cfe72a25c1a86204933385049efc483bd6b70/abstract.py b/shared/package-files/33/332288615a542442c1306223657cfe72a25c1a86204933385049efc483bd6b70/abstract.py new file mode 100644 index 0000000000000000000000000000000000000000..3b5591a6a8d13389a15f1925ed47c95ece86e304 --- /dev/null +++ b/shared/package-files/33/332288615a542442c1306223657cfe72a25c1a86204933385049efc483bd6b70/abstract.py @@ -0,0 +1,516 @@ +from abc import ABCMeta, abstractmethod +from typing import Dict as ptDict, Type as ptType +import itertools +import weakref +from functools import cached_property + +import numpy as np + +from numba.core.utils import get_hashable_key + +# Types are added to a global registry (_typecache) in order to assign +# them unique integer codes for fast matching in _dispatcher.c. +# However, we also want types to be disposable, therefore we ensure +# each type is interned as a weak reference, so that it lives only as +# long as necessary to keep a stable type code. +# NOTE: some types can still be made immortal elsewhere (for example +# in _dispatcher.c's internal caches). +_typecodes = itertools.count() + +def _autoincr(): + n = next(_typecodes) + # 4 billion types should be enough, right? + assert n < 2 ** 32, "Limited to 4 billion types" + return n + +_typecache: ptDict[weakref.ref, weakref.ref] = {} + +def _on_type_disposal(wr, _pop=_typecache.pop): + _pop(wr, None) + + +class _TypeMetaclass(ABCMeta): + """ + A metaclass that will intern instances after they are created. + This is done by first creating a new instance (including calling + __init__, which sets up the required attributes for equality + and hashing), then looking it up in the _typecache registry. + """ + + def __init__(cls, name, bases, orig_vars): + # __init__ is hooked to mark whether a Type class being defined is a + # Numba internal type (one which is defined somewhere under the `numba` + # module) or an external type (one which is defined elsewhere, for + # example a user defined type). + super(_TypeMetaclass, cls).__init__(name, bases, orig_vars) + root = (cls.__module__.split('.'))[0] + cls._is_internal = root == "numba" + + def _intern(cls, inst): + # Try to intern the created instance + wr = weakref.ref(inst, _on_type_disposal) + orig = _typecache.get(wr) + orig = orig and orig() + if orig is not None: + return orig + else: + inst._code = _autoincr() + _typecache[wr] = wr + return inst + + def __call__(cls, *args, **kwargs): + """ + Instantiate *cls* (a Type subclass, presumably) and intern it. + If an interned instance already exists, it is returned, otherwise + the new instance is returned. + """ + inst = type.__call__(cls, *args, **kwargs) + return cls._intern(inst) + + +def _type_reconstructor(reconstructor, reconstructor_args, state): + """ + Rebuild function for unpickling types. + """ + obj = reconstructor(*reconstructor_args) + if state: + obj.__dict__.update(state) + return type(obj)._intern(obj) + + +class Type(metaclass=_TypeMetaclass): + """ + The base class for all Numba types. + It is essential that proper equality comparison is implemented. The + default implementation uses the "key" property (overridable in subclasses) + for both comparison and hashing, to ensure sane behaviour. + """ + + mutable = False + # Rather the type is reflected at the python<->nopython boundary + reflected = False + + def __init__(self, name): + self.name = name + + @property + def key(self): + """ + A property used for __eq__, __ne__ and __hash__. Can be overridden + in subclasses. + """ + return self.name + + @property + def mangling_args(self): + """ + Returns `(basename, args)` where `basename` is the name of the type + and `args` is a sequence of parameters of the type. + + Subclass should override to specialize the behavior. + By default, this returns `(self.name, ())`. + """ + return self.name, () + + def __repr__(self): + return self.name + + def __str__(self): + return self.name + + def __hash__(self): + return hash(self.key) + + def __eq__(self, other): + return self.__class__ is other.__class__ and self.key == other.key + + def __ne__(self, other): + return not (self == other) + + def __reduce__(self): + reconstructor, args, state = super(Type, self).__reduce__() + return (_type_reconstructor, (reconstructor, args, state)) + + def unify(self, typingctx, other): + """ + Try to unify this type with the *other*. A third type must + be returned, or None if unification is not possible. + Only override this if the coercion logic cannot be expressed + as simple casting rules. + """ + return None + + def can_convert_to(self, typingctx, other): + """ + Check whether this type can be converted to the *other*. + If successful, must return a string describing the conversion, e.g. + "exact", "promote", "unsafe", "safe"; otherwise None is returned. + """ + return None + + def can_convert_from(self, typingctx, other): + """ + Similar to *can_convert_to*, but in reverse. Only needed if + the type provides conversion from other types. + """ + return None + + def is_precise(self): + """ + Whether this type is precise, i.e. can be part of a successful + type inference. Default implementation returns True. + """ + return True + + def augment(self, other): + """ + Augment this type with the *other*. Return the augmented type, + or None if not supported. + """ + return None + + # User-facing helpers. These are not part of the core Type API but + # are provided so that users can write e.g. `numba.boolean(1.5)` + # (returns True) or `types.int32(types.int32[:])` (returns something + # usable as a function signature). + + def __call__(self, *args): + from numba.core.typing import signature + if len(args) == 1 and not isinstance(args[0], Type): + return self.cast_python_value(args[0]) + return signature(self, # return_type + *args) + + def __getitem__(self, args, /): + """ + Return an array of this type. + """ + from numba.core.types import Array + ndim, layout = self._determine_array_spec(args) + return Array(dtype=self, ndim=ndim, layout=layout) + + def _determine_array_spec(self, args): + # XXX non-contiguous by default, even for 1d arrays, + # doesn't sound very intuitive + def validate_slice(s): + return isinstance(s, slice) and s.start is None and s.stop is None + + if isinstance(args, (tuple, list)) and all(map(validate_slice, args)): + ndim = len(args) + if args[0].step == 1: + layout = 'F' + elif args[-1].step == 1: + layout = 'C' + else: + layout = 'A' + elif validate_slice(args): + ndim = 1 + if args.step == 1: + layout = 'C' + else: + layout = 'A' + else: + # Raise a KeyError to not be handled by collection constructors (e.g. list). + raise KeyError(f"Can only index numba types with slices with no start or stop, got {args}.") + + return ndim, layout + + def cast_python_value(self, args, /): + raise NotImplementedError + + + @property + def is_internal(self): + """ Returns True if this class is an internally defined Numba type by + virtue of the module in which it is instantiated, False else.""" + return self._is_internal + + def dump(self, tab=''): + print(f'{tab}DUMP {type(self).__name__}[code={self._code}, name={self.name}]') + +# XXX we should distinguish between Dummy (no meaningful +# representation, e.g. None or a builtin function) and Opaque (has a +# meaningful representation, e.g. ExternalFunctionPointer) + +class Dummy(Type): + """ + Base class for types that do not really have a representation and are + compatible with a void*. + """ + + +class Hashable(Type): + """ + Base class for hashable types. + """ + + +class Number(Hashable): + """ + Base class for number types. + """ + + def unify(self, typingctx, other): + """ + Unify the two number types using Numpy's rules. + """ + from numba.np import numpy_support + if isinstance(other, Number): + # XXX: this can produce unsafe conversions, + # e.g. would unify {int64, uint64} to float64 + a = numpy_support.as_dtype(self) + b = numpy_support.as_dtype(other) + sel = np.promote_types(a, b) + return numpy_support.from_dtype(sel) + + +class Callable(Type): + """ + Base class for callables. + """ + + @abstractmethod + def get_call_type(self, context, args, kws): + """ + Using the typing *context*, resolve the callable's signature for + the given arguments. A signature object is returned, or None. + """ + + @abstractmethod + def get_call_signatures(self): + """ + Returns a tuple of (list of signatures, parameterized) + """ + + @abstractmethod + def get_impl_key(self, sig): + """ + Returns the impl key for the given signature + """ + + +class DTypeSpec(Type): + """ + Base class for types usable as "dtype" arguments to various Numpy APIs + (e.g. np.empty()). + """ + + @property + @abstractmethod + def dtype(self): + """ + The actual dtype denoted by this dtype spec (a Type instance). + """ + + +class IterableType(Type): + """ + Base class for iterable types. + """ + + @property + @abstractmethod + def iterator_type(self): + """ + The iterator type obtained when calling iter() (explicitly or implicitly). + """ + + +class Sized(Type): + """ + Base class for objects that support len() + """ + + +class ConstSized(Sized): + """ + For types that have a constant size + """ + @abstractmethod + def __len__(self): + pass + + +class IteratorType(IterableType): + """ + Base class for all iterator types. + Derived classes should implement the *yield_type* attribute. + """ + + def __init__(self, name, **kwargs): + super(IteratorType, self).__init__(name, **kwargs) + + @property + @abstractmethod + def yield_type(self): + """ + The type of values yielded by the iterator. + """ + + # This is a property to avoid recursivity (for pickling) + + @property + def iterator_type(self): + return self + + +class Container(Sized, IterableType): + """ + Base class for container types. + """ + + +class Sequence(Container): + """ + Base class for 1d sequence types. Instances should have the *dtype* + attribute. + """ + + +class MutableSequence(Sequence): + """ + Base class for 1d mutable sequence types. Instances should have the + *dtype* attribute. + """ + + mutable = True + +class ArrayCompatible(Type): + """ + Type class for Numpy array-compatible objects (typically, objects + exposing an __array__ method). + Derived classes should implement the *as_array* attribute. + """ + # If overridden by a subclass, it should also implement typing + # for '__array_wrap__' with arguments (input, formal result). + array_priority = 0.0 + + @property + @abstractmethod + def as_array(self): + """ + The equivalent array type, for operations supporting array-compatible + objects (such as ufuncs). + """ + + # For compatibility with types.Array + + @cached_property + def ndim(self): + return self.as_array.ndim + + @cached_property + def layout(self): + return self.as_array.layout + + @cached_property + def dtype(self): + return self.as_array.dtype + + +class Literal(Type): + """Base class for Literal types. + Literal types contain the original Python value in the type. + + A literal type should always be constructed from the `literal(val)` + function. + """ + + # *ctor_map* is a dictionary mapping Python types to Literal subclasses + # for constructing a numba type for a given Python type. + # It is used in `literal(val)` function. + # To add new Literal subclass, register a new mapping to this dict. + ctor_map: ptDict[type, ptType['Literal']] = {} + + # *_literal_type_cache* is used to cache the numba type of the given value. + _literal_type_cache = None + + def __init__(self, value): + if type(self) is Literal: + raise TypeError( + "Cannot be constructed directly. " + "Use `numba.types.literal(value)` instead", + ) + self._literal_init(value) + fmt = "Literal[{}]({})" + super(Literal, self).__init__(fmt.format(type(value).__name__, value)) + + def _literal_init(self, value): + self._literal_value = value + # We want to support constants of non-hashable values, therefore + # fall back on the value's id() if necessary. + self._key = get_hashable_key(value) + + @property + def literal_value(self): + return self._literal_value + + @property + def literal_type(self): + if self._literal_type_cache is None: + from numba.core import typing + ctx = typing.Context() + try: + res = ctx.resolve_value_type(self.literal_value) + except ValueError as e: + + if "Int value is too large" in str(e): + # If a string literal cannot create an IntegerLiteral + # because of overflow we generate this message. + msg = f"Cannot create literal type. {str(e)}" + raise TypeError(msg) + # Not all literal types have a literal_value that can be + # resolved to a type, for example, LiteralStrKeyDict has a + # literal_value that is a python dict for which there's no + # `typeof` support. + msg = "{} has no attribute 'literal_type'".format(self) + raise AttributeError(msg) + self._literal_type_cache = res + + return self._literal_type_cache + + + +class TypeRef(Dummy): + """Reference to a type. + + Used when a type is passed as a value. + """ + def __init__(self, instance_type): + self.instance_type = instance_type + super(TypeRef, self).__init__('typeref[{}]'.format(self.instance_type)) + + @property + def key(self): + return self.instance_type + + +class InitialValue(object): + """ + Used as a mixin for a type will potentially have an initial value that will + be carried in the .initial_value attribute. + """ + def __init__(self, initial_value): + self._initial_value = initial_value + + @property + def initial_value(self): + return self._initial_value + + +class Poison(Type): + """ + This is the "bottom" type in the type system. It won't unify and it's + unliteral version is Poison of itself. It's advisable for debugging purposes + to call the constructor with the type that's being poisoned (for whatever + reason) but this isn't strictly required. + """ + def __init__(self, ty): + self.ty = ty + super(Poison, self).__init__(name="Poison<%s>" % ty) + + def __unliteral__(self): + return Poison(self) + + def unify(self, typingctx, other): + return None diff --git a/shared/package-files/33/3328083ba04a22cc3e487194398ac0684af6f903c1c40ef827e71e91b324c224/scatter_reduce_cuda_dispatch.h b/shared/package-files/33/3328083ba04a22cc3e487194398ac0684af6f903c1c40ef827e71e91b324c224/scatter_reduce_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..2add648340654ab66e33c3e5775ee3e6a080966b --- /dev/null +++ b/shared/package-files/33/3328083ba04a22cc3e487194398ac0684af6f903c1c40ef827e71e91b324c224/scatter_reduce_cuda_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor scatter_reduce(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self=true); +TORCH_API at::Tensor & scatter_reduce_out(at::Tensor & out, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self=true); +TORCH_API at::Tensor & scatter_reduce_outf(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self, at::Tensor & out); +TORCH_API at::Tensor & scatter_reduce_(at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self=true); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/33/3328cb027cca61175005fa1fd56de4fe17f7d0cbea3a4a8bfff1b6da6439c70c/pzdr.afm b/shared/package-files/33/3328cb027cca61175005fa1fd56de4fe17f7d0cbea3a4a8bfff1b6da6439c70c/pzdr.afm new file mode 100644 index 0000000000000000000000000000000000000000..6b98e8d35f1e257f797d51f51b60fd4f11562e06 --- /dev/null +++ b/shared/package-files/33/3328cb027cca61175005fa1fd56de4fe17f7d0cbea3a4a8bfff1b6da6439c70c/pzdr.afm @@ -0,0 +1,222 @@ +StartFontMetrics 2.0 +Comment Copyright (c) 1985, 1987, 1988, 1989 Adobe Systems Incorporated. All rights reserved. +Comment Creation Date: Fri Dec 1 12:57:42 1989 +Comment UniqueID 26200 +Comment VMusage 39281 49041 +FontName ZapfDingbats +FullName ITC Zapf Dingbats +FamilyName ITC Zapf Dingbats +Weight Medium +ItalicAngle 0 +IsFixedPitch false +FontBBox -1 -143 981 820 +UnderlinePosition -98 +UnderlineThickness 54 +Version 001.004 +Notice Copyright (c) 1985, 1987, 1988, 1989 Adobe Systems Incorporated. All rights reserved.ITC Zapf Dingbats is a registered trademark of International Typeface Corporation. +EncodingScheme FontSpecific +StartCharMetrics 202 +C 32 ; WX 278 ; N space ; B 0 0 0 0 ; +C 33 ; WX 974 ; N a1 ; B 35 72 939 621 ; +C 34 ; WX 961 ; N a2 ; B 35 81 927 611 ; +C 35 ; WX 974 ; N a202 ; B 35 72 939 621 ; +C 36 ; WX 980 ; N a3 ; B 35 0 945 692 ; +C 37 ; WX 719 ; N a4 ; B 34 139 685 566 ; +C 38 ; WX 789 ; N a5 ; B 35 -14 755 705 ; +C 39 ; WX 790 ; N a119 ; B 35 -14 755 705 ; +C 40 ; WX 791 ; N a118 ; B 35 -13 761 705 ; +C 41 ; WX 690 ; N a117 ; B 35 138 655 553 ; +C 42 ; WX 960 ; N a11 ; B 35 123 925 568 ; +C 43 ; WX 939 ; N a12 ; B 35 134 904 559 ; +C 44 ; WX 549 ; N a13 ; B 29 -11 516 705 ; +C 45 ; WX 855 ; N a14 ; B 34 59 820 632 ; +C 46 ; WX 911 ; N a15 ; B 35 50 876 642 ; +C 47 ; WX 933 ; N a16 ; B 35 139 899 550 ; +C 48 ; WX 911 ; N a105 ; B 35 50 876 642 ; +C 49 ; WX 945 ; N a17 ; B 35 139 909 553 ; +C 50 ; WX 974 ; N a18 ; B 35 104 938 587 ; +C 51 ; WX 755 ; N a19 ; B 34 -13 721 705 ; +C 52 ; WX 846 ; N a20 ; B 36 -14 811 705 ; +C 53 ; WX 762 ; N a21 ; B 35 0 727 692 ; +C 54 ; WX 761 ; N a22 ; B 35 0 727 692 ; +C 55 ; WX 571 ; N a23 ; B -1 -68 571 661 ; +C 56 ; WX 677 ; N a24 ; B 36 -13 642 705 ; +C 57 ; WX 763 ; N a25 ; B 35 0 728 692 ; +C 58 ; WX 760 ; N a26 ; B 35 0 726 692 ; +C 59 ; WX 759 ; N a27 ; B 35 0 725 692 ; +C 60 ; WX 754 ; N a28 ; B 35 0 720 692 ; +C 61 ; WX 494 ; N a6 ; B 35 0 460 692 ; +C 62 ; WX 552 ; N a7 ; B 35 0 517 692 ; +C 63 ; WX 537 ; N a8 ; B 35 0 503 692 ; +C 64 ; WX 577 ; N a9 ; B 35 96 542 596 ; +C 65 ; WX 692 ; N a10 ; B 35 -14 657 705 ; +C 66 ; WX 786 ; N a29 ; B 35 -14 751 705 ; +C 67 ; WX 788 ; N a30 ; B 35 -14 752 705 ; +C 68 ; WX 788 ; N a31 ; B 35 -14 753 705 ; +C 69 ; WX 790 ; N a32 ; B 35 -14 756 705 ; +C 70 ; WX 793 ; N a33 ; B 35 -13 759 705 ; +C 71 ; WX 794 ; N a34 ; B 35 -13 759 705 ; +C 72 ; WX 816 ; N a35 ; B 35 -14 782 705 ; +C 73 ; WX 823 ; N a36 ; B 35 -14 787 705 ; +C 74 ; WX 789 ; N a37 ; B 35 -14 754 705 ; +C 75 ; WX 841 ; N a38 ; B 35 -14 807 705 ; +C 76 ; WX 823 ; N a39 ; B 35 -14 789 705 ; +C 77 ; WX 833 ; N a40 ; B 35 -14 798 705 ; +C 78 ; WX 816 ; N a41 ; B 35 -13 782 705 ; +C 79 ; WX 831 ; N a42 ; B 35 -14 796 705 ; +C 80 ; WX 923 ; N a43 ; B 35 -14 888 705 ; +C 81 ; WX 744 ; N a44 ; B 35 0 710 692 ; +C 82 ; WX 723 ; N a45 ; B 35 0 688 692 ; +C 83 ; WX 749 ; N a46 ; B 35 0 714 692 ; +C 84 ; WX 790 ; N a47 ; B 34 -14 756 705 ; +C 85 ; WX 792 ; N a48 ; B 35 -14 758 705 ; +C 86 ; WX 695 ; N a49 ; B 35 -14 661 706 ; +C 87 ; WX 776 ; N a50 ; B 35 -6 741 699 ; +C 88 ; WX 768 ; N a51 ; B 35 -7 734 699 ; +C 89 ; WX 792 ; N a52 ; B 35 -14 757 705 ; +C 90 ; WX 759 ; N a53 ; B 35 0 725 692 ; +C 91 ; WX 707 ; N a54 ; B 35 -13 672 704 ; +C 92 ; WX 708 ; N a55 ; B 35 -14 672 705 ; +C 93 ; WX 682 ; N a56 ; B 35 -14 647 705 ; +C 94 ; WX 701 ; N a57 ; B 35 -14 666 705 ; +C 95 ; WX 826 ; N a58 ; B 35 -14 791 705 ; +C 96 ; WX 815 ; N a59 ; B 35 -14 780 705 ; +C 97 ; WX 789 ; N a60 ; B 35 -14 754 705 ; +C 98 ; WX 789 ; N a61 ; B 35 -14 754 705 ; +C 99 ; WX 707 ; N a62 ; B 34 -14 673 705 ; +C 100 ; WX 687 ; N a63 ; B 36 0 651 692 ; +C 101 ; WX 696 ; N a64 ; B 35 0 661 691 ; +C 102 ; WX 689 ; N a65 ; B 35 0 655 692 ; +C 103 ; WX 786 ; N a66 ; B 34 -14 751 705 ; +C 104 ; WX 787 ; N a67 ; B 35 -14 752 705 ; +C 105 ; WX 713 ; N a68 ; B 35 -14 678 705 ; +C 106 ; WX 791 ; N a69 ; B 35 -14 756 705 ; +C 107 ; WX 785 ; N a70 ; B 36 -14 751 705 ; +C 108 ; WX 791 ; N a71 ; B 35 -14 757 705 ; +C 109 ; WX 873 ; N a72 ; B 35 -14 838 705 ; +C 110 ; WX 761 ; N a73 ; B 35 0 726 692 ; +C 111 ; WX 762 ; N a74 ; B 35 0 727 692 ; +C 112 ; WX 762 ; N a203 ; B 35 0 727 692 ; +C 113 ; WX 759 ; N a75 ; B 35 0 725 692 ; +C 114 ; WX 759 ; N a204 ; B 35 0 725 692 ; +C 115 ; WX 892 ; N a76 ; B 35 0 858 705 ; +C 116 ; WX 892 ; N a77 ; B 35 -14 858 692 ; +C 117 ; WX 788 ; N a78 ; B 35 -14 754 705 ; +C 118 ; WX 784 ; N a79 ; B 35 -14 749 705 ; +C 119 ; WX 438 ; N a81 ; B 35 -14 403 705 ; +C 120 ; WX 138 ; N a82 ; B 35 0 104 692 ; +C 121 ; WX 277 ; N a83 ; B 35 0 242 692 ; +C 122 ; WX 415 ; N a84 ; B 35 0 380 692 ; +C 123 ; WX 392 ; N a97 ; B 35 263 357 705 ; +C 124 ; WX 392 ; N a98 ; B 34 263 357 705 ; +C 125 ; WX 668 ; N a99 ; B 35 263 633 705 ; +C 126 ; WX 668 ; N a100 ; B 36 263 634 705 ; +C 161 ; WX 732 ; N a101 ; B 35 -143 697 806 ; +C 162 ; WX 544 ; N a102 ; B 56 -14 488 706 ; +C 163 ; WX 544 ; N a103 ; B 34 -14 508 705 ; +C 164 ; WX 910 ; N a104 ; B 35 40 875 651 ; +C 165 ; WX 667 ; N a106 ; B 35 -14 633 705 ; +C 166 ; WX 760 ; N a107 ; B 35 -14 726 705 ; +C 167 ; WX 760 ; N a108 ; B 0 121 758 569 ; +C 168 ; WX 776 ; N a112 ; B 35 0 741 705 ; +C 169 ; WX 595 ; N a111 ; B 34 -14 560 705 ; +C 170 ; WX 694 ; N a110 ; B 35 -14 659 705 ; +C 171 ; WX 626 ; N a109 ; B 34 0 591 705 ; +C 172 ; WX 788 ; N a120 ; B 35 -14 754 705 ; +C 173 ; WX 788 ; N a121 ; B 35 -14 754 705 ; +C 174 ; WX 788 ; N a122 ; B 35 -14 754 705 ; +C 175 ; WX 788 ; N a123 ; B 35 -14 754 705 ; +C 176 ; WX 788 ; N a124 ; B 35 -14 754 705 ; +C 177 ; WX 788 ; N a125 ; B 35 -14 754 705 ; +C 178 ; WX 788 ; N a126 ; B 35 -14 754 705 ; +C 179 ; WX 788 ; N a127 ; B 35 -14 754 705 ; +C 180 ; WX 788 ; N a128 ; B 35 -14 754 705 ; +C 181 ; WX 788 ; N a129 ; B 35 -14 754 705 ; +C 182 ; WX 788 ; N a130 ; B 35 -14 754 705 ; +C 183 ; WX 788 ; N a131 ; B 35 -14 754 705 ; +C 184 ; WX 788 ; N a132 ; B 35 -14 754 705 ; +C 185 ; WX 788 ; N a133 ; B 35 -14 754 705 ; +C 186 ; WX 788 ; N a134 ; B 35 -14 754 705 ; +C 187 ; WX 788 ; N a135 ; B 35 -14 754 705 ; +C 188 ; WX 788 ; N a136 ; B 35 -14 754 705 ; +C 189 ; WX 788 ; N a137 ; B 35 -14 754 705 ; +C 190 ; WX 788 ; N a138 ; B 35 -14 754 705 ; +C 191 ; WX 788 ; N a139 ; B 35 -14 754 705 ; +C 192 ; WX 788 ; N a140 ; B 35 -14 754 705 ; +C 193 ; WX 788 ; N a141 ; B 35 -14 754 705 ; +C 194 ; WX 788 ; N a142 ; B 35 -14 754 705 ; +C 195 ; WX 788 ; N a143 ; B 35 -14 754 705 ; +C 196 ; WX 788 ; N a144 ; B 35 -14 754 705 ; +C 197 ; WX 788 ; N a145 ; B 35 -14 754 705 ; +C 198 ; WX 788 ; N a146 ; B 35 -14 754 705 ; +C 199 ; WX 788 ; N a147 ; B 35 -14 754 705 ; +C 200 ; WX 788 ; N a148 ; B 35 -14 754 705 ; +C 201 ; WX 788 ; N a149 ; B 35 -14 754 705 ; +C 202 ; WX 788 ; N a150 ; B 35 -14 754 705 ; +C 203 ; WX 788 ; N a151 ; B 35 -14 754 705 ; +C 204 ; WX 788 ; N a152 ; B 35 -14 754 705 ; +C 205 ; WX 788 ; N a153 ; B 35 -14 754 705 ; +C 206 ; WX 788 ; N a154 ; B 35 -14 754 705 ; +C 207 ; WX 788 ; N a155 ; B 35 -14 754 705 ; +C 208 ; WX 788 ; N a156 ; B 35 -14 754 705 ; +C 209 ; WX 788 ; N a157 ; B 35 -14 754 705 ; +C 210 ; WX 788 ; N a158 ; B 35 -14 754 705 ; +C 211 ; WX 788 ; N a159 ; B 35 -14 754 705 ; +C 212 ; WX 894 ; N a160 ; B 35 58 860 634 ; +C 213 ; WX 838 ; N a161 ; B 35 152 803 540 ; +C 214 ; WX 1016 ; N a163 ; B 34 152 981 540 ; +C 215 ; WX 458 ; N a164 ; B 35 -127 422 820 ; +C 216 ; WX 748 ; N a196 ; B 35 94 698 597 ; +C 217 ; WX 924 ; N a165 ; B 35 140 890 552 ; +C 218 ; WX 748 ; N a192 ; B 35 94 698 597 ; +C 219 ; WX 918 ; N a166 ; B 35 166 884 526 ; +C 220 ; WX 927 ; N a167 ; B 35 32 892 660 ; +C 221 ; WX 928 ; N a168 ; B 35 129 891 562 ; +C 222 ; WX 928 ; N a169 ; B 35 128 893 563 ; +C 223 ; WX 834 ; N a170 ; B 35 155 799 537 ; +C 224 ; WX 873 ; N a171 ; B 35 93 838 599 ; +C 225 ; WX 828 ; N a172 ; B 35 104 791 588 ; +C 226 ; WX 924 ; N a173 ; B 35 98 889 594 ; +C 227 ; WX 924 ; N a162 ; B 35 98 889 594 ; +C 228 ; WX 917 ; N a174 ; B 35 0 882 692 ; +C 229 ; WX 930 ; N a175 ; B 35 84 896 608 ; +C 230 ; WX 931 ; N a176 ; B 35 84 896 608 ; +C 231 ; WX 463 ; N a177 ; B 35 -99 429 791 ; +C 232 ; WX 883 ; N a178 ; B 35 71 848 623 ; +C 233 ; WX 836 ; N a179 ; B 35 44 802 648 ; +C 234 ; WX 836 ; N a193 ; B 35 44 802 648 ; +C 235 ; WX 867 ; N a180 ; B 35 101 832 591 ; +C 236 ; WX 867 ; N a199 ; B 35 101 832 591 ; +C 237 ; WX 696 ; N a181 ; B 35 44 661 648 ; +C 238 ; WX 696 ; N a200 ; B 35 44 661 648 ; +C 239 ; WX 874 ; N a182 ; B 35 77 840 619 ; +C 241 ; WX 874 ; N a201 ; B 35 73 840 615 ; +C 242 ; WX 760 ; N a183 ; B 35 0 725 692 ; +C 243 ; WX 946 ; N a184 ; B 35 160 911 533 ; +C 244 ; WX 771 ; N a197 ; B 34 37 736 655 ; +C 245 ; WX 865 ; N a185 ; B 35 207 830 481 ; +C 246 ; WX 771 ; N a194 ; B 34 37 736 655 ; +C 247 ; WX 888 ; N a198 ; B 34 -19 853 712 ; +C 248 ; WX 967 ; N a186 ; B 35 124 932 568 ; +C 249 ; WX 888 ; N a195 ; B 34 -19 853 712 ; +C 250 ; WX 831 ; N a187 ; B 35 113 796 579 ; +C 251 ; WX 873 ; N a188 ; B 36 118 838 578 ; +C 252 ; WX 927 ; N a189 ; B 35 150 891 542 ; +C 253 ; WX 970 ; N a190 ; B 35 76 931 616 ; +C 254 ; WX 918 ; N a191 ; B 34 99 884 593 ; +C -1 ; WX 410 ; N a86 ; B 35 0 375 692 ; +C -1 ; WX 509 ; N a85 ; B 35 0 475 692 ; +C -1 ; WX 334 ; N a95 ; B 35 0 299 692 ; +C -1 ; WX 509 ; N a205 ; B 35 0 475 692 ; +C -1 ; WX 390 ; N a89 ; B 35 -14 356 705 ; +C -1 ; WX 234 ; N a87 ; B 35 -14 199 705 ; +C -1 ; WX 276 ; N a91 ; B 35 0 242 692 ; +C -1 ; WX 390 ; N a90 ; B 35 -14 355 705 ; +C -1 ; WX 410 ; N a206 ; B 35 0 375 692 ; +C -1 ; WX 317 ; N a94 ; B 35 0 283 692 ; +C -1 ; WX 317 ; N a93 ; B 35 0 283 692 ; +C -1 ; WX 276 ; N a92 ; B 35 0 242 692 ; +C -1 ; WX 334 ; N a96 ; B 35 0 299 692 ; +C -1 ; WX 234 ; N a88 ; B 35 -14 199 705 ; +EndCharMetrics +EndFontMetrics diff --git a/shared/package-files/33/33293b3dd4ae5a2346be22cdad57f7f288da5dd40d34f36ababe8c84cf320264/NativeMetaFunctions.h b/shared/package-files/33/33293b3dd4ae5a2346be22cdad57f7f288da5dd40d34f36ababe8c84cf320264/NativeMetaFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..eabea23f7fbae46c2a291dae90c52067dbdc1e85 --- /dev/null +++ b/shared/package-files/33/33293b3dd4ae5a2346be22cdad57f7f288da5dd40d34f36ababe8c84cf320264/NativeMetaFunctions.h @@ -0,0 +1,1303 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunctions.h + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { + +namespace meta { + + + +} // namespace meta +} // namespace at diff --git a/shared/package-files/33/332cbd2657d64c9dbd27c3b28aafaea6a6a0f957ec3c78378ecbaaec71d4f621/baseconv.pyi b/shared/package-files/33/332cbd2657d64c9dbd27c3b28aafaea6a6a0f957ec3c78378ecbaaec71d4f621/baseconv.pyi new file mode 100644 index 0000000000000000000000000000000000000000..20f65556c733fb41dafe3f93b175dfd31dca7dcb --- /dev/null +++ b/shared/package-files/33/332cbd2657d64c9dbd27c3b28aafaea6a6a0f957ec3c78378ecbaaec71d4f621/baseconv.pyi @@ -0,0 +1,24 @@ +from typing import Any, Tuple, Union + +BASE2_ALPHABET: str +BASE16_ALPHABET: str +BASE56_ALPHABET: str +BASE36_ALPHABET: str +BASE62_ALPHABET: str +BASE64_ALPHABET: Any + +class BaseConverter: + decimal_digits: str = ... + sign: str = ... + digits: str = ... + def __init__(self, digits: str, sign: str = ...) -> None: ... + def encode(self, i: int) -> str: ... + def decode(self, s: str) -> int: ... + def convert(self, number: Union[int, str], from_digits: str, to_digits: str, sign: str) -> Tuple[int, str]: ... + +base2: Any +base16: Any +base36: Any +base56: Any +base62: Any +base64: Any diff --git a/shared/package-files/33/332cea5d4b963f5f8181b6c207327220b892fe389c64ed8b3543148efeef861d/scope.py b/shared/package-files/33/332cea5d4b963f5f8181b6c207327220b892fe389c64ed8b3543148efeef861d/scope.py new file mode 100644 index 0000000000000000000000000000000000000000..976a3ba242e3e9f94e4f6fd07de8a29f837e580d --- /dev/null +++ b/shared/package-files/33/332cea5d4b963f5f8181b6c207327220b892fe389c64ed8b3543148efeef861d/scope.py @@ -0,0 +1,91 @@ +""" +Scope definition and related utilities. + +Those are defined here, instead of in the 'fixtures' module because +their use is spread across many other pytest modules, and centralizing it in 'fixtures' +would cause circular references. + +Also this makes the module light to import, as it should. +""" + +from __future__ import annotations + +from enum import Enum +from functools import total_ordering +from typing import Literal + + +_ScopeName = Literal["session", "package", "module", "class", "function"] + + +@total_ordering +class Scope(Enum): + """ + Represents one of the possible fixture scopes in pytest. + + Scopes are ordered from lower to higher, that is: + + ->>> higher ->>> + + Function < Class < Module < Package < Session + + <<<- lower <<<- + """ + + # Scopes need to be listed from lower to higher. + Function: _ScopeName = "function" + Class: _ScopeName = "class" + Module: _ScopeName = "module" + Package: _ScopeName = "package" + Session: _ScopeName = "session" + + def next_lower(self) -> Scope: + """Return the next lower scope.""" + index = _SCOPE_INDICES[self] + if index == 0: + raise ValueError(f"{self} is the lower-most scope") + return _ALL_SCOPES[index - 1] + + def next_higher(self) -> Scope: + """Return the next higher scope.""" + index = _SCOPE_INDICES[self] + if index == len(_SCOPE_INDICES) - 1: + raise ValueError(f"{self} is the upper-most scope") + return _ALL_SCOPES[index + 1] + + def __lt__(self, other: Scope) -> bool: + self_index = _SCOPE_INDICES[self] + other_index = _SCOPE_INDICES[other] + return self_index < other_index + + @classmethod + def from_user( + cls, scope_name: _ScopeName, descr: str, where: str | None = None + ) -> Scope: + """ + Given a scope name from the user, return the equivalent Scope enum. Should be used + whenever we want to convert a user provided scope name to its enum object. + + If the scope name is invalid, construct a user friendly message and call pytest.fail. + """ + from _pytest.outcomes import fail + + try: + # Holding this reference is necessary for mypy at the moment. + scope = Scope(scope_name) + except ValueError: + fail( + "{} {}got an unexpected scope value '{}'".format( + descr, f"from {where} " if where else "", scope_name + ), + pytrace=False, + ) + return scope + + +_ALL_SCOPES = list(Scope) +_SCOPE_INDICES = {scope: index for index, scope in enumerate(_ALL_SCOPES)} + + +# Ordered list of scopes which can contain many tests (in practice all except Function). +HIGH_SCOPES = [x for x in Scope if x is not Scope.Function] diff --git a/shared/package-files/33/332e5db8799453cbb47dadc745a0693bfb78cb9b190bc01ec503b8981ea82623/slow_conv_transpose2d_meta.h b/shared/package-files/33/332e5db8799453cbb47dadc745a0693bfb78cb9b190bc01ec503b8981ea82623/slow_conv_transpose2d_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..404b5a485c15dcd972c9271caf6e4e0871f4d15e --- /dev/null +++ b/shared/package-files/33/332e5db8799453cbb47dadc745a0693bfb78cb9b190bc01ec503b8981ea82623/slow_conv_transpose2d_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_slow_conv_transpose2d : public at::impl::MetaBase { + + + void meta(const at::Tensor & self, const at::Tensor & weight, at::ArrayRef kernel_size, at::OptionalTensorRef bias, at::ArrayRef stride, at::ArrayRef padding, at::ArrayRef output_padding, at::ArrayRef dilation); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/33/333231626133ad5f4d3f3559893f5fcd756b564fbd83564997ad3757ee28159f/_make_per_tensor_quantized_tensor_ops.h b/shared/package-files/33/333231626133ad5f4d3f3559893f5fcd756b564fbd83564997ad3757ee28159f/_make_per_tensor_quantized_tensor_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..c817e7547dbbccd3e6c165f24cb25583e4e1c406 --- /dev/null +++ b/shared/package-files/33/333231626133ad5f4d3f3559893f5fcd756b564fbd83564997ad3757ee28159f/_make_per_tensor_quantized_tensor_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _make_per_tensor_quantized_tensor { + using schema = at::Tensor (const at::Tensor &, double, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_make_per_tensor_quantized_tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_make_per_tensor_quantized_tensor(Tensor self, float scale, int zero_point) -> Tensor") + static at::Tensor call(const at::Tensor & self, double scale, int64_t zero_point); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, double scale, int64_t zero_point); +}; + +struct TORCH_API _make_per_tensor_quantized_tensor_out { + using schema = at::Tensor & (const at::Tensor &, double, int64_t, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_make_per_tensor_quantized_tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_make_per_tensor_quantized_tensor.out(Tensor self, float scale, int zero_point, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, double scale, int64_t zero_point, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, double scale, int64_t zero_point, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/33/3333f5c213bd28025dfac3d303ed03990166e2773bc2e7615787c4ae2826e114/digamma_cpu_dispatch.h b/shared/package-files/33/3333f5c213bd28025dfac3d303ed03990166e2773bc2e7615787c4ae2826e114/digamma_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1474453f1644deb4f2c42ebe05c3db4c7693e814 --- /dev/null +++ b/shared/package-files/33/3333f5c213bd28025dfac3d303ed03990166e2773bc2e7615787c4ae2826e114/digamma_cpu_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor digamma(const at::Tensor & self); +TORCH_API at::Tensor & digamma_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & digamma_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & digamma_(at::Tensor & self); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/33/33347744575c5b047abf7344e1ae392834abd33659ea190eba92109525d32de4/_monitoring.py b/shared/package-files/33/33347744575c5b047abf7344e1ae392834abd33659ea190eba92109525d32de4/_monitoring.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc0daddc1c0ecb26d8337dc11e77cc1ff2fb2dd --- /dev/null +++ b/shared/package-files/33/33347744575c5b047abf7344e1ae392834abd33659ea190eba92109525d32de4/_monitoring.py @@ -0,0 +1,81 @@ +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import scipy.stats + +from . import colors +from ._labels import labels + + +def truncate_text(text, max_len): + if len(text) > max_len: + return text[: int(max_len / 2) - 2] + "..." + text[-int(max_len / 2) + 1 :] + else: + return text + + +def monitoring(ind, shap_values, features, feature_names=None, show=True): + """Create a SHAP monitoring plot. + + (Note this function is preliminary and subject to change!!) + A SHAP monitoring plot is meant to display the behavior of a model + over time. Often the shap_values given to this plot explain the loss + of a model, so changes in a feature's impact on the model's loss over + time can help in monitoring the model's performance. + + Parameters + ---------- + ind : int + Index of the feature to plot. + + shap_values : numpy.array + Matrix of SHAP values (# samples x # features) + + features : numpy.array or pandas.DataFrame + Matrix of feature values (# samples x # features) + + feature_names : list + Names of the features (length # features) + + """ + if isinstance(features, pd.DataFrame): + if feature_names is None: + feature_names = features.columns + features = features.values + + num_features = shap_values.shape[1] + + if feature_names is None: + feature_names = np.array([labels["FEATURE"] % str(i) for i in range(num_features)]) + + plt.figure(figsize=(10, 3)) + ys = shap_values[:, ind] + xs = np.arange(len(ys)) # np.linspace(0, 12*2, len(ys)) + + pvals = [] + inc = 50 + for i in range(inc, len(ys) - inc, inc): + # stat, pval = scipy.stats.mannwhitneyu(v[:i], v[i:], alternative="two-sided") + _, pval = scipy.stats.ttest_ind(ys[:i], ys[i:]) + pvals.append(pval) + min_pval = np.min(pvals) + min_pval_ind = float(np.argmin(pvals) * inc + inc) + + if min_pval < 0.05 / shap_values.shape[1]: + plt.axvline(min_pval_ind, linestyle="dashed", color="#666666", alpha=0.2) + + plt.scatter(xs, ys, s=10, c=features[:, ind], cmap=colors.red_blue) + + plt.xlabel("Sample index") + plt.ylabel(truncate_text(feature_names[ind], 30) + "\nSHAP value", size=13) + plt.gca().xaxis.set_ticks_position("bottom") + plt.gca().yaxis.set_ticks_position("left") + plt.gca().spines["right"].set_visible(False) + plt.gca().spines["top"].set_visible(False) + cb = plt.colorbar() + cb.outline.set_visible(False) # type: ignore + bbox = cb.ax.get_window_extent().transformed(plt.gcf().dpi_scale_trans.inverted()) + cb.ax.set_aspect((bbox.height - 0.7) * 20) + cb.set_label(truncate_text(feature_names[ind], 30), size=13) + if show: + plt.show() diff --git a/shared/package-files/33/3334dd5e9e21c3a272819e5db1b49137efc74076d129087d390b8941855b1ec7/compat.py b/shared/package-files/33/3334dd5e9e21c3a272819e5db1b49137efc74076d129087d390b8941855b1ec7/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..5d56d228d7b48282f662d4c1e9ed2052aaf135da --- /dev/null +++ b/shared/package-files/33/3334dd5e9e21c3a272819e5db1b49137efc74076d129087d390b8941855b1ec7/compat.py @@ -0,0 +1,43 @@ +# This file is part of Patsy +# Copyright (C) 2012 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file contains compatibility code for supporting old versions of Python +# and numpy. (If we can concentrate it here, hopefully it'll make it easier to +# get rid of weird hacks once we drop support for old versions). + +##### Numpy + +import os + +# To force use of the compat code, set this env var to a non-empty value: +optional_dep_ok = not os.environ.get("PATSY_AVOID_OPTIONAL_DEPENDENCIES") + +##### Python standard library + +# The Python license requires that all derivative works contain a "brief +# summary of the changes made to Python". Both for license compliance, and for +# our own sanity, therefore, please add a note at the top of any snippets you +# add here explaining their provenance, any changes made, and what versions of +# Python require them: + +# OrderedDict is only available in Python 2.7+. compat_ordereddict.py has +# comments at the top. +import collections + +if optional_dep_ok and hasattr(collections, "OrderedDict"): + from collections import OrderedDict +else: + from patsy.compat_ordereddict import OrderedDict + +# 'raise from' available in Python 3+ +import sys +from patsy import PatsyError + + +def call_and_wrap_exc(msg, origin, f, *args, **kwargs): + try: + return f(*args, **kwargs) + except Exception as e: + new_exc = PatsyError("%s: %s: %s" % (msg, e.__class__.__name__, e), origin) + raise new_exc from e diff --git a/shared/package-files/33/3334fb3983c45171d834f06b564c8a11a1b909ab3668e034c6faceee5e184eb4/testdouble_4.2c_SOL2.mat b/shared/package-files/33/3334fb3983c45171d834f06b564c8a11a1b909ab3668e034c6faceee5e184eb4/testdouble_4.2c_SOL2.mat new file mode 100644 index 0000000000000000000000000000000000000000..5dbfcf17dd0e01dc0325dd009340291158906e8d Binary files /dev/null and b/shared/package-files/33/3334fb3983c45171d834f06b564c8a11a1b909ab3668e034c6faceee5e184eb4/testdouble_4.2c_SOL2.mat differ diff --git a/shared/package-files/33/333555ba99cb1c4beec255429fa991ecb43da4b78d896336956c0d948c28a3df/test_shift.py b/shared/package-files/33/333555ba99cb1c4beec255429fa991ecb43da4b78d896336956c0d948c28a3df/test_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..a0986d1496881a2061ac8306d0a064f4393cd4e9 --- /dev/null +++ b/shared/package-files/33/333555ba99cb1c4beec255429fa991ecb43da4b78d896336956c0d948c28a3df/test_shift.py @@ -0,0 +1,76 @@ +import pytest + +from pandas.errors import NullFrequencyError + +import pandas as pd +from pandas import TimedeltaIndex +import pandas._testing as tm + + +class TestTimedeltaIndexShift: + # ------------------------------------------------------------- + # TimedeltaIndex.shift is used by __add__/__sub__ + + def test_tdi_shift_empty(self): + # GH#9903 + idx = TimedeltaIndex([], name="xxx") + tm.assert_index_equal(idx.shift(0, freq="h"), idx) + tm.assert_index_equal(idx.shift(3, freq="h"), idx) + + def test_tdi_shift_hours(self): + # GH#9903 + idx = TimedeltaIndex(["5 hours", "6 hours", "9 hours"], name="xxx") + tm.assert_index_equal(idx.shift(0, freq="h"), idx) + exp = TimedeltaIndex(["8 hours", "9 hours", "12 hours"], name="xxx") + tm.assert_index_equal(idx.shift(3, freq="h"), exp) + exp = TimedeltaIndex(["2 hours", "3 hours", "6 hours"], name="xxx") + tm.assert_index_equal(idx.shift(-3, freq="h"), exp) + + def test_tdi_shift_minutes(self): + # GH#9903 + idx = TimedeltaIndex(["5 hours", "6 hours", "9 hours"], name="xxx") + tm.assert_index_equal(idx.shift(0, freq="min"), idx) + exp = TimedeltaIndex(["05:03:00", "06:03:00", "9:03:00"], name="xxx") + tm.assert_index_equal(idx.shift(3, freq="min"), exp) + exp = TimedeltaIndex(["04:57:00", "05:57:00", "8:57:00"], name="xxx") + tm.assert_index_equal(idx.shift(-3, freq="min"), exp) + + def test_tdi_shift_int(self): + # GH#8083 + tdi = pd.to_timedelta(range(5), unit="d") + trange = tdi._with_freq("infer") + pd.offsets.Hour(1) + result = trange.shift(1) + expected = TimedeltaIndex( + [ + "1 days 01:00:00", + "2 days 01:00:00", + "3 days 01:00:00", + "4 days 01:00:00", + "5 days 01:00:00", + ], + freq="D", + ) + tm.assert_index_equal(result, expected) + + def test_tdi_shift_nonstandard_freq(self): + # GH#8083 + tdi = pd.to_timedelta(range(5), unit="d") + trange = tdi._with_freq("infer") + pd.offsets.Hour(1) + result = trange.shift(3, freq="2D 1s") + expected = TimedeltaIndex( + [ + "6 days 01:00:03", + "7 days 01:00:03", + "8 days 01:00:03", + "9 days 01:00:03", + "10 days 01:00:03", + ], + freq="D", + ) + tm.assert_index_equal(result, expected) + + def test_shift_no_freq(self): + # GH#19147 + tdi = TimedeltaIndex(["1 days 01:00:00", "2 days 01:00:00"], freq=None) + with pytest.raises(NullFrequencyError, match="Cannot shift with no freq"): + tdi.shift(2) diff --git a/shared/package-files/33/3339f39dd38edd0a1c71c20cc9d74eeefd7211c0804be1cb6cb42a026adfcd67/_kalman_filter.pxd b/shared/package-files/33/3339f39dd38edd0a1c71c20cc9d74eeefd7211c0804be1cb6cb42a026adfcd67/_kalman_filter.pxd new file mode 100644 index 0000000000000000000000000000000000000000..4f967c753d20c73bd4d617bd0e015469a955a4c7 --- /dev/null +++ b/shared/package-files/33/3339f39dd38edd0a1c71c20cc9d74eeefd7211c0804be1cb6cb42a026adfcd67/_kalman_filter.pxd @@ -0,0 +1,690 @@ +#cython: boundscheck=False +#cython: wraparound=False +#cython: cdivision=False +""" +Kalman Filter declarations + +Author: Chad Fulton +License: Simplified-BSD +""" + +include "statsmodels/tsa/statespace/_blas_int.pxi" + +# ## Constants + +# ### Filters +cdef int FILTER_CONVENTIONAL # Durbin and Koopman (2012), Chapter 4 +cdef int FILTER_EXACT_INITIAL # ibid., Chapter 5.6 +cdef int FILTER_AUGMENTED # ibid., Chapter 5.7 +cdef int FILTER_SQUARE_ROOT # ibid., Chapter 6.3 +cdef int FILTER_UNIVARIATE # ibid., Chapter 6.4 +cdef int FILTER_COLLAPSED # ibid., Chapter 6.5 +cdef int FILTER_EXTENDED # ibid., Chapter 10.2 +cdef int FILTER_UNSCENTED # ibid., Chapter 10.3 +cdef int FILTER_CONCENTRATED # Harvey (1989), Chapter 3.4 +cdef int FILTER_CHANDRASEKHAR # Herbst (2015) + +# ### Inversion methods +# Methods by which the terms using the inverse of the forecast error +# covariance matrix are solved. +cdef int INVERT_UNIVARIATE +cdef int SOLVE_LU +cdef int INVERT_LU +cdef int SOLVE_CHOLESKY +cdef int INVERT_CHOLESKY + +# ### Numerical Stability methods +# Methods to improve numerical stability +cdef int STABILITY_FORCE_SYMMETRY + +# ### Memory conservation options +cdef int MEMORY_STORE_ALL +cdef int MEMORY_NO_FORECAST_MEAN +cdef int MEMORY_NO_FORECAST_COV +cdef int MEMORY_NO_FORECAST +cdef int MEMORY_NO_PREDICTED_MEAN +cdef int MEMORY_NO_PREDICTED_COV +cdef int MEMORY_NO_PREDICTED +cdef int MEMORY_NO_FILTERED_MEAN +cdef int MEMORY_NO_FILTERED_COV +cdef int MEMORY_NO_FILTERED +cdef int MEMORY_NO_LIKELIHOOD +cdef int MEMORY_NO_GAIN +cdef int MEMORY_NO_SMOOTHING +cdef int MEMORY_NO_STD_FORECAST +cdef int MEMORY_CONSERVE + +# ### Timing options +cdef int TIMING_INIT_FILTERED +cdef int TIMING_INIT_PREDICTED + +# Typical imports + +cimport numpy as np + +from statsmodels.tsa.statespace._representation cimport ( + cStatespace, + dStatespace, + sStatespace, + zStatespace, +) + + +# Single precision +cdef class sKalmanFilter(object): + # Statespace object + cdef readonly sStatespace model + + # ### Filter parameters + cdef readonly int t + cdef public np.float64_t tolerance, tolerance_diffuse + cdef readonly int nobs_diffuse + cdef readonly int nobs_kendog_diffuse_nonsingular + cdef readonly int nobs_kendog_univariate_singular + cdef readonly int converged + cdef readonly int period_converged + cdef readonly int time_invariant + cdef readonly int filter_method + cdef public int inversion_method + cdef public int stability_method + cdef readonly int conserve_memory + cdef public int filter_timing + cdef readonly int loglikelihood_burn + + cdef public int [:] univariate_filter + + # ### Kalman filter properties + cdef readonly np.float32_t [:] loglikelihood, scale + cdef readonly np.float32_t [::1,:] filtered_state, predicted_state, forecast, forecast_error, standardized_forecast_error + cdef readonly np.float32_t [::1,:,:] filtered_state_cov, predicted_state_cov, forecast_error_cov, predicted_diffuse_state_cov, forecast_error_diffuse_cov, M, M_inf + cdef readonly np.float32_t [::1,:,:] kalman_gain + + # ### Steady State Values + cdef readonly np.float32_t [::1,:] converged_forecast_error_cov + cdef readonly np.float32_t [::1,:] converged_filtered_state_cov + cdef readonly np.float32_t [::1,:] converged_predicted_state_cov + cdef readonly np.float32_t [::1,:] converged_kalman_gain + cdef readonly np.float32_t [::1,:] converged_M + cdef readonly np.float32_t converged_determinant + + # ### Temporary arrays + cdef readonly np.float32_t [::1,:] forecast_error_fac + cdef readonly blas_int [:] forecast_error_ipiv + cdef readonly np.float32_t [::1,:] forecast_error_work + cdef readonly np.float32_t [::1,:] tmp0, tmp00 + cdef readonly np.float32_t [::1,:] tmp2 + cdef readonly np.float32_t [::1,:,:] tmp1, tmp3, tmp4 + cdef readonly np.float32_t [:] tmpK0, tmpK1 + cdef readonly np.float32_t [::1,:] tmpL0, tmpL1 + + cdef readonly np.float32_t [::1,:] CW, CtmpW, CMW, CM, CprevFiZ, CtmpM, CMWZ + + + cdef readonly np.float32_t determinant + + # ### Pointers to current-iteration arrays + # cdef np.float32_t * _obs + # cdef np.float32_t * _design + # cdef np.float32_t * _obs_intercept + # cdef np.float32_t * _obs_cov + # cdef np.float32_t * _transition + # cdef np.float32_t * _state_intercept + # cdef np.float32_t * _selection + # cdef np.float32_t * _state_cov + # cdef np.float32_t * _selected_state_cov + # cdef np.float32_t * _initial_state + # cdef np.float32_t * _initial_state_cov + + cdef np.float32_t * _input_state + cdef np.float32_t * _input_state_cov + cdef np.float32_t * _input_diffuse_state_cov + + cdef np.float32_t * _forecast + cdef np.float32_t * _forecast_error + cdef np.float32_t * _standardized_forecast_error + cdef np.float32_t * _forecast_error_cov + cdef np.float32_t * _filtered_state + cdef np.float32_t * _filtered_state_cov + cdef np.float32_t * _predicted_state + cdef np.float32_t * _predicted_state_cov + + cdef np.float32_t * _forecast_error_diffuse_cov + cdef np.float32_t * _predicted_diffuse_state_cov + cdef np.float32_t * _M + cdef np.float32_t * _M_inf + + cdef np.float32_t * _kalman_gain + cdef np.float32_t * _loglikelihood + cdef np.float32_t * _scale + + cdef np.float32_t * _converged_forecast_error_cov + cdef np.float32_t * _converged_filtered_state_cov + cdef np.float32_t * _converged_predicted_state_cov + cdef np.float32_t * _converged_kalman_gain + cdef np.float32_t * _converged_M + + cdef np.float32_t * _forecast_error_fac + cdef blas_int * _forecast_error_ipiv + cdef np.float32_t * _forecast_error_work + + cdef np.float32_t * _tmp0 + cdef np.float32_t * _tmp00 + cdef np.float32_t * _tmp1 + cdef np.float32_t * _tmp2 + cdef np.float32_t * _tmp3 + cdef np.float32_t * _tmp4 + + cdef np.float32_t * _tmpM_inf + cdef np.float32_t * _tmpK0 + cdef np.float32_t * _tmpK1 + cdef np.float32_t * _tmpL0 + cdef np.float32_t * _tmpL1 + + # ### Pointers to current-iteration Kalman filtering functions + cdef int (*forecasting)( + sKalmanFilter, sStatespace + ) + cdef np.float32_t (*inversion)( + sKalmanFilter, sStatespace, np.float32_t + ) except * + cdef int (*updating)( + sKalmanFilter, sStatespace + ) + cdef np.float32_t (*calculate_loglikelihood)( + sKalmanFilter, sStatespace, np.float32_t + ) + cdef np.float32_t (*calculate_scale)( + sKalmanFilter, sStatespace + ) + cdef int (*prediction)( + sKalmanFilter, sStatespace + ) + + # ### Define some constants + cdef readonly int k_endog, k_states, k_posdef, k_endog2, k_states2, k_posdef2, k_endogstates, k_statesposdef + cdef readonly int ldwork + + cdef allocate_arrays(self) + cdef void set_dimensions(self) + cpdef set_filter_method(self, int filter_method, int force_reset=*) + cpdef seek(self, unsigned int t, int reset=*) + + cdef void initialize_statespace_object_pointers(self) except * + cdef void initialize_filter_object_pointers(self) + cdef void initialize_function_pointers(self) except * + cdef void post_convergence(self) + cdef void numerical_stability(self) + cdef int check_diffuse(self) + cdef void check_convergence(self) + cdef void migrate_storage(self) + cdef void _reinitialize_pointers(self) except * + + cdef void _forecasting(self) + cdef np.float32_t _inversion(self) + cdef void _updating(self) + cdef np.float32_t _calculate_loglikelihood(self) + cdef void _prediction(self) + +# Double precision +cdef class dKalmanFilter(object): + # Statespace object + cdef readonly dStatespace model + + # ### Filter parameters + cdef readonly int t + cdef public np.float64_t tolerance, tolerance_diffuse + cdef readonly int nobs_diffuse + cdef readonly int nobs_kendog_diffuse_nonsingular + cdef readonly int nobs_kendog_univariate_singular + cdef readonly int converged + cdef readonly int period_converged + cdef readonly int time_invariant + cdef readonly int filter_method + cdef public int inversion_method + cdef public int stability_method + cdef readonly int conserve_memory + cdef public int filter_timing + cdef readonly int loglikelihood_burn + + cdef public int [:] univariate_filter + + # ### Kalman filter properties + cdef readonly np.float64_t [:] loglikelihood, scale + cdef readonly np.float64_t [::1,:] filtered_state, predicted_state, forecast, forecast_error, standardized_forecast_error + cdef readonly np.float64_t [::1,:,:] filtered_state_cov, predicted_state_cov, forecast_error_cov, predicted_diffuse_state_cov, forecast_error_diffuse_cov, M, M_inf + cdef readonly np.float64_t [::1,:,:] kalman_gain + + # ### Steady State Values + cdef readonly np.float64_t [::1,:] converged_forecast_error_cov + cdef readonly np.float64_t [::1,:] converged_filtered_state_cov + cdef readonly np.float64_t [::1,:] converged_predicted_state_cov + cdef readonly np.float64_t [::1,:] converged_kalman_gain + cdef readonly np.float64_t [::1,:] converged_M + cdef readonly np.float64_t converged_determinant + + # ### Temporary arrays + cdef readonly np.float64_t [::1,:] forecast_error_fac + cdef readonly blas_int [:] forecast_error_ipiv + cdef readonly np.float64_t [::1,:] forecast_error_work + cdef readonly np.float64_t [::1,:] tmp0, tmp00 + cdef readonly np.float64_t [::1,:] tmp2 + cdef readonly np.float64_t [::1,:,:] tmp1, tmp3, tmp4 + cdef readonly np.float64_t [:] tmpM_inf, tmpK0, tmpK1 + cdef readonly np.float64_t [::1,:] tmpL0, tmpL1 + + cdef readonly np.float64_t [::1,:] CW, CtmpW, CMW, CM, CprevFiZ, CtmpM, CMWZ + + cdef readonly np.float64_t determinant + + # ### Pointers to current-iteration arrays + # cdef np.float64_t * _obs + # cdef np.float64_t * _design + # cdef np.float64_t * _obs_intercept + # cdef np.float64_t * _obs_cov + # cdef np.float64_t * _transition + # cdef np.float64_t * _state_intercept + # cdef np.float64_t * _selection + # cdef np.float64_t * _state_cov + # cdef np.float64_t * _selected_state_cov + # cdef np.float64_t * _initial_state + # cdef np.float64_t * _initial_state_cov + + cdef np.float64_t * _input_state + cdef np.float64_t * _input_state_cov + cdef np.float64_t * _input_diffuse_state_cov + + cdef np.float64_t * _forecast + cdef np.float64_t * _forecast_error + cdef np.float64_t * _standardized_forecast_error + cdef np.float64_t * _forecast_error_cov + cdef np.float64_t * _filtered_state + cdef np.float64_t * _filtered_state_cov + cdef np.float64_t * _predicted_state + cdef np.float64_t * _predicted_state_cov + + cdef np.float64_t * _forecast_error_diffuse_cov + cdef np.float64_t * _predicted_diffuse_state_cov + cdef np.float64_t * _M + cdef np.float64_t * _M_inf + + cdef np.float64_t * _kalman_gain + cdef np.float64_t * _loglikelihood + cdef np.float64_t * _scale + + cdef np.float64_t * _converged_forecast_error_cov + cdef np.float64_t * _converged_filtered_state_cov + cdef np.float64_t * _converged_predicted_state_cov + cdef np.float64_t * _converged_kalman_gain + cdef np.float64_t * _converged_M + + cdef np.float64_t * _forecast_error_fac + cdef blas_int * _forecast_error_ipiv + cdef np.float64_t * _forecast_error_work + + cdef np.float64_t * _tmp0 + cdef np.float64_t * _tmp00 + cdef np.float64_t * _tmp1 + cdef np.float64_t * _tmp2 + cdef np.float64_t * _tmp3 + cdef np.float64_t * _tmp4 + + cdef np.float64_t * _tmpM_inf + cdef np.float64_t * _tmpK0 + cdef np.float64_t * _tmpK1 + cdef np.float64_t * _tmpL0 + cdef np.float64_t * _tmpL1 + + # ### Pointers to current-iteration Kalman filtering functions + cdef int (*forecasting)( + dKalmanFilter, dStatespace + ) + cdef np.float64_t (*inversion)( + dKalmanFilter, dStatespace, np.float64_t + ) except * + cdef int (*updating)( + dKalmanFilter, dStatespace + ) + cdef np.float64_t (*calculate_loglikelihood)( + dKalmanFilter, dStatespace, np.float64_t + ) + cdef np.float64_t (*calculate_scale)( + dKalmanFilter, dStatespace + ) + cdef int (*prediction)( + dKalmanFilter, dStatespace + ) + + # ### Define some constants + cdef readonly int k_endog, k_states, k_posdef, k_endog2, k_states2, k_posdef2, k_endogstates, k_statesposdef + cdef readonly int ldwork + + cdef allocate_arrays(self) + cdef void set_dimensions(self) + cpdef set_filter_method(self, int filter_method, int force_reset=*) + cpdef seek(self, unsigned int t, int reset=*) + + cdef void initialize_statespace_object_pointers(self) except * + cdef void initialize_filter_object_pointers(self) + cdef void initialize_function_pointers(self) except * + cdef void post_convergence(self) + cdef void numerical_stability(self) + cdef int check_diffuse(self) + cdef void check_convergence(self) + cdef void migrate_storage(self) + cdef void _reinitialize_pointers(self) except * + + cdef void _forecasting(self) + cdef np.float64_t _inversion(self) + cdef void _updating(self) + cdef np.float64_t _calculate_loglikelihood(self) + cdef void _prediction(self) + +# Single precision complex +cdef class cKalmanFilter(object): + # Statespace object + cdef readonly cStatespace model + + # ### Filter parameters + cdef readonly int t + cdef public np.float64_t tolerance, tolerance_diffuse + cdef readonly int nobs_diffuse + cdef readonly int nobs_kendog_diffuse_nonsingular + cdef readonly int nobs_kendog_univariate_singular + cdef readonly int converged + cdef readonly int period_converged + cdef readonly int time_invariant + cdef readonly int filter_method + cdef public int inversion_method + cdef public int stability_method + cdef readonly int conserve_memory + cdef public int filter_timing + cdef readonly int loglikelihood_burn + + cdef public int [:] univariate_filter + + # ### Kalman filter properties + cdef readonly np.complex64_t [:] loglikelihood, scale + cdef readonly np.complex64_t [::1,:] filtered_state, predicted_state, forecast, forecast_error, standardized_forecast_error + cdef readonly np.complex64_t [::1,:,:] filtered_state_cov, predicted_state_cov, forecast_error_cov, predicted_diffuse_state_cov, forecast_error_diffuse_cov, M, M_inf + cdef readonly np.complex64_t [::1,:,:] kalman_gain + + # ### Steady State Values + cdef readonly np.complex64_t [::1,:] converged_forecast_error_cov + cdef readonly np.complex64_t [::1,:] converged_filtered_state_cov + cdef readonly np.complex64_t [::1,:] converged_predicted_state_cov + cdef readonly np.complex64_t [::1,:] converged_kalman_gain + cdef readonly np.complex64_t [::1,:] converged_M + cdef readonly np.complex64_t converged_determinant + + # ### Temporary arrays + cdef readonly np.complex64_t [::1,:] forecast_error_fac + cdef readonly blas_int [:] forecast_error_ipiv + cdef readonly np.complex64_t [::1,:] forecast_error_work + cdef readonly np.complex64_t [::1,:] tmp0, tmp00 + cdef readonly np.complex64_t [::1,:] tmp2 + cdef readonly np.complex64_t [::1,:,:] tmp1, tmp3, tmp4 + cdef readonly np.complex64_t [:] tmpM_inf, tmpK0, tmpK1 + cdef readonly np.complex64_t [::1,:] tmpL0, tmpL1 + + cdef readonly np.complex64_t [::1,:] CW, CtmpW, CMW, CM, CprevFiZ, CtmpM, CMWZ + + + cdef readonly np.complex64_t determinant + + # ### Pointers to current-iteration arrays + # cdef np.complex64_t * _obs + # cdef np.complex64_t * _design + # cdef np.complex64_t * _obs_intercept + # cdef np.complex64_t * _obs_cov + # cdef np.complex64_t * _transition + # cdef np.complex64_t * _state_intercept + # cdef np.complex64_t * _selection + # cdef np.complex64_t * _state_cov + # cdef np.complex64_t * _selected_state_cov + # cdef np.complex64_t * _initial_state + # cdef np.complex64_t * _initial_state_cov + + cdef np.complex64_t * _input_state + cdef np.complex64_t * _input_state_cov + cdef np.complex64_t * _input_diffuse_state_cov + + cdef np.complex64_t * _forecast + cdef np.complex64_t * _forecast_error + cdef np.complex64_t * _standardized_forecast_error + cdef np.complex64_t * _forecast_error_cov + cdef np.complex64_t * _filtered_state + cdef np.complex64_t * _filtered_state_cov + cdef np.complex64_t * _predicted_state + cdef np.complex64_t * _predicted_state_cov + + cdef np.complex64_t * _forecast_error_diffuse_cov + cdef np.complex64_t * _predicted_diffuse_state_cov + cdef np.complex64_t * _M + cdef np.complex64_t * _M_inf + + cdef np.complex64_t * _kalman_gain + cdef np.complex64_t * _loglikelihood + cdef np.complex64_t * _scale + + cdef np.complex64_t * _converged_forecast_error_cov + cdef np.complex64_t * _converged_filtered_state_cov + cdef np.complex64_t * _converged_predicted_state_cov + cdef np.complex64_t * _converged_kalman_gain + cdef np.complex64_t * _converged_M + + cdef np.complex64_t * _forecast_error_fac + cdef blas_int * _forecast_error_ipiv + cdef np.complex64_t * _forecast_error_work + + cdef np.complex64_t * _tmp0 + cdef np.complex64_t * _tmp00 + cdef np.complex64_t * _tmp1 + cdef np.complex64_t * _tmp2 + cdef np.complex64_t * _tmp3 + cdef np.complex64_t * _tmp4 + + cdef np.complex64_t * _tmpM_inf + cdef np.complex64_t * _tmpK0 + cdef np.complex64_t * _tmpK1 + cdef np.complex64_t * _tmpL0 + cdef np.complex64_t * _tmpL1 + + # ### Pointers to current-iteration Kalman filtering functions + cdef int (*forecasting)( + cKalmanFilter, cStatespace + ) + cdef np.complex64_t (*inversion)( + cKalmanFilter, cStatespace, np.complex64_t + ) except * + cdef int (*updating)( + cKalmanFilter, cStatespace + ) + cdef np.complex64_t (*calculate_loglikelihood)( + cKalmanFilter, cStatespace, np.complex64_t + ) + cdef np.complex64_t (*calculate_scale)( + cKalmanFilter, cStatespace + ) + cdef int (*prediction)( + cKalmanFilter, cStatespace + ) + + # ### Define some constants + cdef readonly int k_endog, k_states, k_posdef, k_endog2, k_states2, k_posdef2, k_endogstates, k_statesposdef + cdef readonly int ldwork + + cdef allocate_arrays(self) + cdef void set_dimensions(self) + cpdef set_filter_method(self, int filter_method, int force_reset=*) + cpdef seek(self, unsigned int t, int reset=*) + + cdef void initialize_statespace_object_pointers(self) except * + cdef void initialize_filter_object_pointers(self) + cdef void initialize_function_pointers(self) except * + cdef void post_convergence(self) + cdef void numerical_stability(self) + cdef int check_diffuse(self) + cdef void check_convergence(self) + cdef void migrate_storage(self) + cdef void _reinitialize_pointers(self) except * + + cdef void _forecasting(self) + cdef np.complex64_t _inversion(self) + cdef void _updating(self) + cdef np.complex64_t _calculate_loglikelihood(self) + cdef void _prediction(self) + +# Double precision complex +cdef class zKalmanFilter(object): + # Statespace object + cdef readonly zStatespace model + + # ### Filter parameters + cdef readonly int t + cdef public np.float64_t tolerance, tolerance_diffuse + cdef readonly int nobs_diffuse + cdef readonly int nobs_kendog_diffuse_nonsingular + cdef readonly int nobs_kendog_univariate_singular + cdef readonly int converged + cdef readonly int period_converged + cdef readonly int time_invariant + cdef readonly int filter_method + cdef public int inversion_method + cdef public int stability_method + cdef readonly int conserve_memory + cdef public int filter_timing + cdef readonly int loglikelihood_burn + + cdef public int [:] univariate_filter + + # ### Kalman filter properties + cdef readonly np.complex128_t [:] loglikelihood, scale + cdef readonly np.complex128_t [::1,:] filtered_state, predicted_state, forecast, forecast_error, standardized_forecast_error + cdef readonly np.complex128_t [::1,:,:] filtered_state_cov, predicted_state_cov, forecast_error_cov, predicted_diffuse_state_cov, forecast_error_diffuse_cov, M, M_inf + cdef readonly np.complex128_t [::1,:,:] kalman_gain + + # ### Steady State Values + cdef readonly np.complex128_t [::1,:] converged_forecast_error_cov + cdef readonly np.complex128_t [::1,:] converged_filtered_state_cov + cdef readonly np.complex128_t [::1,:] converged_predicted_state_cov + cdef readonly np.complex128_t [::1,:] converged_kalman_gain + cdef readonly np.complex128_t [::1,:] converged_M + cdef readonly np.complex128_t converged_determinant + + # ### Temporary arrays + cdef readonly np.complex128_t [::1,:] forecast_error_fac + cdef readonly blas_int [:] forecast_error_ipiv + cdef readonly np.complex128_t [::1,:] forecast_error_work + cdef readonly np.complex128_t [::1,:] tmp0, tmp00 + cdef readonly np.complex128_t [::1,:] tmp2 + cdef readonly np.complex128_t [::1,:,:] tmp1, tmp3, tmp4 + cdef readonly np.complex128_t [:] tmpM_inf, tmpK0, tmpK1 + cdef readonly np.complex128_t [::1,:] tmpL0, tmpL1 + + cdef readonly np.complex128_t [::1,:] CW, CtmpW, CMW, CM, CprevFiZ, CtmpM, CMWZ + + + cdef readonly np.complex128_t determinant + + # ### Pointers to current-iteration arrays + # cdef np.complex128_t * _obs + # cdef np.complex128_t * _design + # cdef np.complex128_t * _obs_intercept + # cdef np.complex128_t * _obs_cov + # cdef np.complex128_t * _transition + # cdef np.complex128_t * _state_intercept + # cdef np.complex128_t * _selection + # cdef np.complex128_t * _state_cov + # cdef np.complex128_t * _selected_state_cov + # cdef np.complex128_t * _initial_state + # cdef np.complex128_t * _initial_state_cov + + cdef np.complex128_t * _input_state + cdef np.complex128_t * _input_state_cov + cdef np.complex128_t * _input_diffuse_state_cov + + cdef np.complex128_t * _forecast + cdef np.complex128_t * _forecast_error + cdef np.complex128_t * _standardized_forecast_error + cdef np.complex128_t * _forecast_error_cov + cdef np.complex128_t * _filtered_state + cdef np.complex128_t * _filtered_state_cov + cdef np.complex128_t * _predicted_state + cdef np.complex128_t * _predicted_state_cov + + cdef np.complex128_t * _forecast_error_diffuse_cov + cdef np.complex128_t * _predicted_diffuse_state_cov + cdef np.complex128_t * _M + cdef np.complex128_t * _M_inf + + cdef np.complex128_t * _kalman_gain + cdef np.complex128_t * _loglikelihood + cdef np.complex128_t * _scale + + cdef np.complex128_t * _converged_forecast_error_cov + cdef np.complex128_t * _converged_filtered_state_cov + cdef np.complex128_t * _converged_predicted_state_cov + cdef np.complex128_t * _converged_kalman_gain + cdef np.complex128_t * _converged_M + + cdef np.complex128_t * _forecast_error_fac + cdef blas_int * _forecast_error_ipiv + cdef np.complex128_t * _forecast_error_work + + cdef np.complex128_t * _tmp0 + cdef np.complex128_t * _tmp00 + cdef np.complex128_t * _tmp1 + cdef np.complex128_t * _tmp2 + cdef np.complex128_t * _tmp3 + cdef np.complex128_t * _tmp4 + + cdef np.complex128_t * _tmpM_inf + cdef np.complex128_t * _tmpK0 + cdef np.complex128_t * _tmpK1 + cdef np.complex128_t * _tmpL0 + cdef np.complex128_t * _tmpL1 + + # ### Pointers to current-iteration Kalman filtering functions + cdef int (*forecasting)( + zKalmanFilter, zStatespace + ) + cdef np.complex128_t (*inversion)( + zKalmanFilter, zStatespace, np.complex128_t + ) except * + cdef int (*updating)( + zKalmanFilter, zStatespace + ) + cdef np.complex128_t (*calculate_loglikelihood)( + zKalmanFilter, zStatespace, np.complex128_t + ) + cdef np.complex128_t (*calculate_scale)( + zKalmanFilter, zStatespace + ) + cdef int (*prediction)( + zKalmanFilter, zStatespace + ) + + # ### Define some constants + cdef readonly int k_endog, k_states, k_posdef, k_endog2, k_states2, k_posdef2, k_endogstates, k_statesposdef + cdef readonly int ldwork + + cdef allocate_arrays(self) + cdef void set_dimensions(self) + cpdef set_filter_method(self, int filter_method, int force_reset=*) + cpdef seek(self, unsigned int t, int reset=*) + + cdef void initialize_statespace_object_pointers(self) except * + cdef void initialize_filter_object_pointers(self) + cdef void initialize_function_pointers(self) except * + cdef void post_convergence(self) + cdef void numerical_stability(self) + cdef int check_diffuse(self) + cdef void check_convergence(self) + cdef void migrate_storage(self) + cdef void _reinitialize_pointers(self) except * + + cdef void _forecasting(self) + cdef np.complex128_t _inversion(self) + cdef void _updating(self) + cdef np.complex128_t _calculate_loglikelihood(self) + cdef void _prediction(self) diff --git a/shared/package-files/33/333dd019f806e7c875bae091f9bf6bfcfbfc2febc0f281f823834de8bea17c2d/user.pyi b/shared/package-files/33/333dd019f806e7c875bae091f9bf6bfcfbfc2febc0f281f823834de8bea17c2d/user.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9c33922b383d62bef5d05ec54cba170b9a767d90 --- /dev/null +++ b/shared/package-files/33/333dd019f806e7c875bae091f9bf6bfcfbfc2febc0f281f823834de8bea17c2d/user.pyi @@ -0,0 +1,6 @@ +from typing import Any + +def __getattr__(name) -> Any: ... + +home: str +pythonrc: str diff --git a/shared/package-files/33/3341413075b40e3eae33a4254813f8c79a78b7c5261c11ef09667a1e846e2cd5/smooth_l1_loss.h b/shared/package-files/33/3341413075b40e3eae33a4254813f8c79a78b7c5261c11ef09667a1e846e2cd5/smooth_l1_loss.h new file mode 100644 index 0000000000000000000000000000000000000000..f5528ebf38085cc860d814bab0e1cdc28c4f9f7b --- /dev/null +++ b/shared/package-files/33/3341413075b40e3eae33a4254813f8c79a78b7c5261c11ef09667a1e846e2cd5/smooth_l1_loss.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::smooth_l1_loss.out(Tensor self, Tensor target, int reduction=Mean, float beta=1.0, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & smooth_l1_loss_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & target, int64_t reduction=at::Reduction::Mean, double beta=1.0) { + return at::_ops::smooth_l1_loss_out::call(self, target, reduction, beta, out); +} +// aten::smooth_l1_loss.out(Tensor self, Tensor target, int reduction=Mean, float beta=1.0, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & smooth_l1_loss_outf(const at::Tensor & self, const at::Tensor & target, int64_t reduction, double beta, at::Tensor & out) { + return at::_ops::smooth_l1_loss_out::call(self, target, reduction, beta, out); +} + +// aten::smooth_l1_loss(Tensor self, Tensor target, int reduction=Mean, float beta=1.0) -> Tensor +inline at::Tensor smooth_l1_loss(const at::Tensor & self, const at::Tensor & target, int64_t reduction=at::Reduction::Mean, double beta=1.0) { + return at::_ops::smooth_l1_loss::call(self, target, reduction, beta); +} + +} diff --git a/shared/package-files/33/3342d477dc64280b8dc7afc68ee13945b8b72927a8c79ba88b25e11fc72adb85/plotting.py b/shared/package-files/33/3342d477dc64280b8dc7afc68ee13945b8b72927a8c79ba88b25e11fc72adb85/plotting.py new file mode 100644 index 0000000000000000000000000000000000000000..95c64fdbcf40089c383beba2b75f1ec6d2640a04 --- /dev/null +++ b/shared/package-files/33/3342d477dc64280b8dc7afc68ee13945b8b72927a8c79ba88b25e11fc72adb85/plotting.py @@ -0,0 +1,494 @@ +from statsmodels.compat.python import lrange + +import numpy as np + +from statsmodels.graphics.utils import _import_mpl +from statsmodels.tsa.vector_ar import util + + +class MPLConfigurator: + + def __init__(self): + self._inverse_actions = [] + + def revert(self): + for action in self._inverse_actions: + action() + + def set_fontsize(self, size): + import matplotlib as mpl + + old_size = mpl.rcParams["font.size"] + mpl.rcParams["font.size"] = size + + def revert(): + mpl.rcParams["font.size"] = old_size + + self._inverse_actions.append(revert) + + +# +# Plotting functions +# +def plot_mts(Y, names=None, index=None): + """ + Plot multiple time series + + Parameters + ---------- + Y : ndarray + 2-d array of the time series to plot, of shape (nobs, neqs). + names : sequence of str, optional + Titles to use for each subplot. If None, subplots are not + given a title. + index : array_like, optional + Values to use for the x-axis of each subplot. If None, uses + the default integer index. + + Returns + ------- + Figure + The figure containing the grid of time series plots. + """ + plt = _import_mpl() + + k = Y.shape[1] + rows, cols = k, 1 + + fig = plt.figure(figsize=(10, 10)) + + for j in range(k): + ts = Y[:, j] + + ax = fig.add_subplot(rows, cols, j + 1) + if index is not None: + ax.plot(index, ts) + else: + ax.plot(ts) + + if names is not None: + ax.set_title(names[j]) + + return fig + + +def plot_var_forc( + prior, + forc, + err_upper, + err_lower, + index=None, + names=None, + plot_stderr=True, + legend_options=None, +): + """ + Plot a forecast against the observed data, with optional error bands + + Parameters + ---------- + prior : ndarray + 2-d array of the observed data prior to the forecast, of shape + (nobs, neqs). + forc : ndarray + 2-d array of forecast values, of shape (steps, neqs). + err_upper : ndarray + 2-d array of upper confidence interval bounds for the forecast, + of shape (steps, neqs). + err_lower : ndarray + 2-d array of lower confidence interval bounds for the forecast, + of shape (steps, neqs). + index : array_like, optional + Currently unused. + names : sequence of str, optional + Titles to use for each subplot. If None, subplots are not + given a title. + plot_stderr : bool, optional + If True, plot the confidence interval around the forecast. + legend_options : dict, optional + Keyword arguments passed to ``ax.legend``. If None, uses + ``{"loc": "upper right"}``. + + Returns + ------- + Figure + The figure containing the grid of forecast plots. + """ + plt = _import_mpl() + + n, k = prior.shape + rows, cols = k, 1 + + fig = plt.figure(figsize=(10, 10)) + + prange = np.arange(n) + rng_f = np.arange(n - 1, n + len(forc)) + rng_err = np.arange(n, n + len(forc)) + + for j in range(k): + ax = plt.subplot(rows, cols, j + 1) + + ax.plot(prange, prior[:, j], "k", label="Observed") + ax.plot(rng_f, np.r_[prior[-1:, j], forc[:, j]], "k--", label="Forecast") + + if plot_stderr: + ax.plot(rng_err, err_upper[:, j], "k-.", label="Forc 2 STD err") + ax.plot(rng_err, err_lower[:, j], "k-.") + + if names is not None: + ax.set_title(names[j]) + + if legend_options is None: + legend_options = {"loc": "upper right"} + ax.legend(**legend_options) + return fig + + +def plot_with_error( + y, + error, + x=None, + axes=None, + value_fmt="k", + error_fmt="k--", + alpha=0.05, + stderr_type="asym", +): + """ + Make plot with optional error bars + + Parameters + ---------- + y : array_like + The data to plot. + error : array_like, tuple of array_like, or None + The error used to plot error bars around `y`. If `stderr_type` + is "asym", an array the same shape as `y` combined with `alpha` + to compute the bands. If `stderr_type` is one of "mc", "sz1", + "sz2", "sz3", a 2-tuple of arrays giving the lower and upper + bands directly. If None, no error bars are plotted. + x : array_like, optional + The x-axis values to use. If None, uses a range the same length + as `y`. + axes : AxesSubplot, optional + Matplotlib axes to plot on. If None, uses the current axes. + value_fmt : str, optional + Matplotlib format string used to plot `y`. + error_fmt : str, optional + Matplotlib format string used to plot the error bars. + alpha : float, optional + The significance level to use when `stderr_type` is "asym". + stderr_type : {"asym", "mc", "sz1", "sz2", "sz3"}, optional + The kind of error bars being plotted. + """ + plt = _import_mpl() + + if axes is None: + axes = plt.gca() + + x = x if x is not None else lrange(len(y)) + + def plot_action(y, fmt): + return axes.plot(x, y, fmt) + + plot_action(y, value_fmt) + + # changed this + if error is not None: + if stderr_type == "asym": + q = util.norm_signif_level(alpha) + plot_action(y - q * error, error_fmt) + plot_action(y + q * error, error_fmt) + if stderr_type in ("mc", "sz1", "sz2", "sz3"): + plot_action(error[0], error_fmt) + plot_action(error[1], error_fmt) + + +def plot_full_acorr(acorr, fontsize=8, linewidth=8, xlabel=None, err_bound=None): + """ + Plot the autocorrelations of a multivariate time series in a grid + + Parameters + ---------- + acorr : ndarray + Array of autocorrelations, shape (nlags, k, k). + fontsize : int, optional + Font size used for the plot labels. + linewidth : int, optional + Width of the lines used in the autocorrelation plots. + xlabel : array_like, optional + Labels to use for the x-axis of each subplot. If None, uses a + range the same length as `acorr`. + err_bound : float, optional + If provided, draws horizontal reference lines at +/- `err_bound`. + + Returns + ------- + Figure + The figure containing the grid of autocorrelation plots. + """ + plt = _import_mpl() + + config = MPLConfigurator() + config.set_fontsize(fontsize) + + k = acorr.shape[1] + fig, axes = plt.subplots(k, k, figsize=(10, 10), squeeze=False) + + for i in range(k): + for j in range(k): + ax = axes[i][j] + acorr_plot(acorr[:, i, j], linewidth=linewidth, xlabel=xlabel, ax=ax) + + if err_bound is not None: + ax.axhline(err_bound, color="k", linestyle="--") + ax.axhline(-err_bound, color="k", linestyle="--") + + adjust_subplots() + config.revert() + + return fig + + +def acorr_plot(acorr, linewidth=8, xlabel=None, ax=None): + """ + Plot a single autocorrelation function as a stem plot + + Parameters + ---------- + acorr : array_like + 1-d array of autocorrelations to plot. + linewidth : int, optional + Width of the vertical lines used in the plot. + xlabel : array_like, optional + Positions to use for the x-axis. If None, uses a range the + same length as `acorr`. + ax : AxesSubplot, optional + Matplotlib axes to plot on. If None, uses the current axes. + """ + plt = _import_mpl() + + if ax is None: + ax = plt.gca() + + if xlabel is None: + xlabel = np.arange(len(acorr)) + + ax.vlines(xlabel, [0], acorr, lw=linewidth) + + ax.axhline(0, color="k") + ax.set_ylim([-1, 1]) + + # hack? + ax.set_xlim([-1, xlabel[-1] + 1]) + + +def plot_acorr_with_error(): + """Not implemented.""" + raise NotImplementedError + + +def adjust_subplots(**kwds): + """ + Adjust subplot spacing using defaults suitable for the grid plots + + Parameters + ---------- + **kwds + Keyword arguments passed to ``matplotlib.pyplot.subplots_adjust``, + overriding the defaults. + """ + plt = _import_mpl() + + passed_kwds = { + "bottom": 0.05, + "top": 0.925, + "left": 0.05, + "right": 0.95, + "hspace": 0.2, + } + passed_kwds.update(kwds) + plt.subplots_adjust(**passed_kwds) + + +# +# Multiple impulse response (cum_effects, etc.) cplots +# + + +def irf_grid_plot( + values, + stderr, + impcol, + rescol, + names, + title, + signif=0.05, + hlines=None, + subplot_params=None, + plot_params=None, + figsize=(10, 10), + stderr_type="asym", +): + """ + Reusable function to make flexible grid plots of impulse responses and + cumulative effects + + Parameters + ---------- + values : ndarray + Array of values to plot, shape (T, k, k). + stderr : ndarray, tuple of ndarray, or None + Used to plot error bands around `values`. If `stderr_type` is + "asym", an array of shape (T, k ** 2, k ** 2) giving the + covariance matrix of the vectorized values at each period (as + returned by :meth:`~statsmodels.tsa.vector_ar.irf.IRAnalysis.cov`). + If `stderr_type` is one of "mc", "sz1", "sz2", "sz3", a 2-tuple + of arrays of shape (T, k, k) giving the lower and upper error + bands directly. If None, no error bands are plotted. + impcol : int, str, or None + Column of the impulse variable to plot. If None, plots impulses + from all variables. + rescol : int, str, or None + Column of the response variable to plot. If None, plots responses + of all variables. + names : sequence of str + Names of the variables in the system. + title : str + Title to use for the figure. + signif : float, optional + Significance level used when plotting error bands. + hlines : ndarray, optional + Array of horizontal reference lines to draw on each subplot, + shape (k, k). + subplot_params : dict, optional + May contain a "fontsize" key controlling the subplot title font + size. + plot_params : dict, optional + Additional keyword arguments (currently unused). + figsize : tuple of float, optional + The size of the figure to create. + stderr_type : {"asym", "mc", "sz1", "sz2", "sz3"}, optional + The kind of error bars being plotted. + + Returns + ------- + Figure + The figure containing the grid of impulse response plots. + """ + plt = _import_mpl() + + if subplot_params is None: + subplot_params = {} + if plot_params is None: + plot_params = {} + + nrows, ncols, to_plot = _get_irf_plot_config(names, impcol, rescol) + + fig, axes = plt.subplots( + nrows=nrows, ncols=ncols, sharex=True, squeeze=False, figsize=figsize + ) + + # fill out space + adjust_subplots() + + fig.suptitle(title, fontsize=14) + + subtitle_temp = r"%s$\rightarrow$%s" + + k = len(names) + + rng = lrange(len(values)) + for j, i, ai, aj in to_plot: + ax = axes[ai][aj] + + # HACK? + if stderr is not None: + if stderr_type == "asym": + sig = np.sqrt(stderr[:, j * k + i, j * k + i]) + plot_with_error( + values[:, i, j], + sig, + x=rng, + axes=ax, + alpha=signif, + value_fmt="b", + stderr_type=stderr_type, + ) + if stderr_type in ("mc", "sz1", "sz2", "sz3"): + errs = stderr[0][:, i, j], stderr[1][:, i, j] + plot_with_error( + values[:, i, j], + errs, + x=rng, + axes=ax, + alpha=signif, + value_fmt="b", + stderr_type=stderr_type, + ) + else: + plot_with_error(values[:, i, j], None, x=rng, axes=ax, value_fmt="b") + + ax.axhline(0, color="k") + + if hlines is not None: + ax.axhline(hlines[i, j], color="k") + + sz = subplot_params.get("fontsize", 12) + ax.set_title(subtitle_temp % (names[j], names[i]), fontsize=sz) + + return fig + + +def _get_irf_plot_config(names, impcol, rescol): + """ + Determine the subplot grid layout for `irf_grid_plot` + + Parameters + ---------- + names : sequence of str + Names of the variables in the system. + impcol : int, str, or None + Column of the impulse variable to plot. If None, plots impulses + from all variables. + rescol : int, str, or None + Column of the response variable to plot. If None, plots responses + of all variables. + + Returns + ------- + nrows : int + Number of subplot rows. + ncols : int + Number of subplot columns. + to_plot : list of tuple + Each tuple is ``(j, i, ai, aj)`` giving the impulse index `j`, + response index `i`, and the subplot grid position (`ai`, `aj`) + to plot it at. + """ + nrows = ncols = k = len(names) + if impcol is not None and rescol is not None: + # plot one impulse-response pair + nrows = ncols = 1 + j = util.get_index(names, impcol) + i = util.get_index(names, rescol) + to_plot = [(j, i, 0, 0)] + elif impcol is not None: + # plot impacts of impulse in one variable + ncols = 1 + j = util.get_index(names, impcol) + to_plot = [(j, i, i, 0) for i in range(k)] + elif rescol is not None: + # plot only things having impact on particular variable + ncols = 1 + i = util.get_index(names, rescol) + to_plot = [(j, i, j, 0) for j in range(k)] + else: + # plot everything + to_plot = [(j, i, i, j) for i in range(k) for j in range(k)] + + return nrows, ncols, to_plot + + +# +# Forecast error variance decomposition diff --git a/shared/package-files/33/3343d3b7c20e21c557a903d67b6379d2c9b812ad9ba1d457578564774f1cad79/mutable_ndim_array.py b/shared/package-files/33/3343d3b7c20e21c557a903d67b6379d2c9b812ad9ba1d457578564774f1cad79/mutable_ndim_array.py new file mode 100644 index 0000000000000000000000000000000000000000..e1eaaf7241bc3b4a48234178d18da3aa5736e189 --- /dev/null +++ b/shared/package-files/33/3343d3b7c20e21c557a903d67b6379d2c9b812ad9ba1d457578564774f1cad79/mutable_ndim_array.py @@ -0,0 +1,13 @@ +from sympy.tensor.array.ndim_array import NDimArray + + +class MutableNDimArray(NDimArray): + + def as_immutable(self): + raise NotImplementedError("abstract method") + + def as_mutable(self): + return self + + def _sympy_(self): + return self.as_immutable() diff --git a/shared/package-files/33/3344af465d1c008f91cb7852e15960800d16bacb2f764ad8e12e5327aceddb5a/css_parser.py b/shared/package-files/33/3344af465d1c008f91cb7852e15960800d16bacb2f764ad8e12e5327aceddb5a/css_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..14cf54a228119ef942dcd443f96aefd63f40e419 --- /dev/null +++ b/shared/package-files/33/3344af465d1c008f91cb7852e15960800d16bacb2f764ad8e12e5327aceddb5a/css_parser.py @@ -0,0 +1,1280 @@ +"""CSS selector parser.""" +from __future__ import annotations +import re +from functools import lru_cache +from . import util +from . import css_match as cm +from . import css_types as ct +from .util import SelectorSyntaxError +import warnings +from typing import Match, Any, Iterator, cast + +UNICODE_REPLACEMENT_CHAR = 0xFFFD + +# Simple pseudo classes that take no parameters +PSEUDO_SIMPLE = { + ":any-link", + ":empty", + ":first-child", + ":first-of-type", + ":in-range", + ":out-of-range", + ":last-child", + ":last-of-type", + ":link", + ":only-child", + ":only-of-type", + ":root", + ':checked', + ':default', + ':disabled', + ':enabled', + ':indeterminate', + ':optional', + ':placeholder-shown', + ':read-only', + ':read-write', + ':required', + ':scope', + ':defined' +} + +# Supported, simple pseudo classes that match nothing in the Soup Sieve environment +PSEUDO_SIMPLE_NO_MATCH = { + ':active', + ':current', + ':focus', + ':focus-visible', + ':focus-within', + ':future', + ':host', + ':hover', + ':local-link', + ':past', + ':paused', + ':playing', + ':target', + ':target-within', + ':user-invalid', + ':visited' +} + +# Complex pseudo classes that take selector lists +PSEUDO_COMPLEX = { + ':contains', + ':-soup-contains', + ':-soup-contains-own', + ':has', + ':is', + ':matches', + ':not', + ':where' +} + +PSEUDO_COMPLEX_NO_MATCH = { + ':current', + ':host', + ':host-context' +} + +# Complex pseudo classes that take very specific parameters and are handled special +PSEUDO_SPECIAL = { + ':dir', + ':lang', + ':nth-child', + ':nth-last-child', + ':nth-last-of-type', + ':nth-of-type' +} + +PSEUDO_SUPPORTED = PSEUDO_SIMPLE | PSEUDO_SIMPLE_NO_MATCH | PSEUDO_COMPLEX | PSEUDO_COMPLEX_NO_MATCH | PSEUDO_SPECIAL + +# Sub-patterns parts +# Whitespace +NEWLINE = r'(?:\r\n|(?!\r\n)[\n\f\r])' +WS = fr'(?:[ \t]|{NEWLINE})' +# Comments +COMMENTS = r'(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)' +# Whitespace with comments included +WSC = fr'(?:{WS}|{COMMENTS})' +# CSS escapes +CSS_ESCAPES = fr'(?:\\(?:[a-f0-9]{{1,6}}{WS}?|[^\r\n\f]|$))' +CSS_STRING_ESCAPES = fr'(?:\\(?:[a-f0-9]{{1,6}}{WS}?|[^\r\n\f]|$|{NEWLINE}))' +# CSS Identifier +IDENTIFIER = fr''' +(?:(?:-?(?:[^\x00-\x2f\x30-\x40\x5B-\x5E\x60\x7B-\x9f]|{CSS_ESCAPES})+|--) +(?:[^\x00-\x2c\x2e\x2f\x3A-\x40\x5B-\x5E\x60\x7B-\x9f]|{CSS_ESCAPES})*) +''' +# `nth` content +NTH = fr'(?:[-+])?(?:[0-9]+n?|n)(?:(?<=n){WSC}*(?:[-+]){WSC}*(?:[0-9]+))?' +# Value: quoted string or identifier +VALUE = fr'''(?:"(?:\\(?:.|{NEWLINE})|[^\\"\r\n\f]+)*?"|'(?:\\(?:.|{NEWLINE})|[^\\'\r\n\f]+)*?'|{IDENTIFIER}+)''' +# Attribute value comparison. `!=` is handled special as it is non-standard. +ATTR = fr'(?:{WSC}*(?P[!~^|*$]?=){WSC}*(?P{VALUE})(?:{WSC}*(?P[is]))?)?{WSC}*\]' + +# Selector patterns +# IDs (`#id`) +PAT_ID = fr'\#{IDENTIFIER}' +# Classes (`.class`) +PAT_CLASS = fr'\.{IDENTIFIER}' +# Prefix:Tag (`prefix|tag`) +PAT_TAG = fr'(?P(?:{IDENTIFIER}|\*)?\|)?(?P{IDENTIFIER}|\*)' +# Attributes (`[attr]`, `[attr=value]`, etc.) +PAT_ATTR = fr'\[{WSC}*(?P(?:{IDENTIFIER}|\*)?\|)?(?P{IDENTIFIER}){ATTR}' +# Pseudo class (`:pseudo-class`, `:pseudo-class(`) +PAT_PSEUDO_CLASS = fr'(?P:{IDENTIFIER})(?P\({WSC}*)?' +# Pseudo class special patterns. Matches `:pseudo-class(` for special case pseudo classes. +PAT_PSEUDO_CLASS_SPECIAL = fr'(?P:{IDENTIFIER})(?P\({WSC}*)' +# Custom pseudo class (`:--custom-pseudo`) +PAT_PSEUDO_CLASS_CUSTOM = fr'(?P:(?=--){IDENTIFIER})' +# Closing pseudo group (`)`) +PAT_PSEUDO_CLOSE = fr'{WSC}*\)' +# Pseudo element (`::pseudo-element`) +PAT_PSEUDO_ELEMENT = fr':{PAT_PSEUDO_CLASS}' +# At rule (`@page`, etc.) (not supported) +PAT_AT_RULE = fr'@P{IDENTIFIER}' +# Pseudo class `nth-child` (`:nth-child(an+b [of S]?)`, `:first-child`, etc.) +PAT_PSEUDO_NTH_CHILD = fr''' +(?P{PAT_PSEUDO_CLASS_SPECIAL} +(?P{NTH}|even|odd))(?:{WSC}*\)|(?P{COMMENTS}*{WS}{WSC}*of{COMMENTS}*{WS}{WSC}*)) +''' +# Pseudo class `nth-of-type` (`:nth-of-type(an+b)`, `:first-of-type`, etc.) +PAT_PSEUDO_NTH_TYPE = fr''' +(?P{PAT_PSEUDO_CLASS_SPECIAL} +(?P{NTH}|even|odd)){WSC}*\) +''' +# Pseudo class language (`:lang("*-de", en)`) +PAT_PSEUDO_LANG = fr'{PAT_PSEUDO_CLASS_SPECIAL}(?P{VALUE}(?:{WSC}*,{WSC}*{VALUE})*){WSC}*\)' +# Pseudo class direction (`:dir(ltr)`) +PAT_PSEUDO_DIR = fr'{PAT_PSEUDO_CLASS_SPECIAL}(?Pltr|rtl){WSC}*\)' +# Combining characters (`>`, `~`, ` `, `+`, `,`) +PAT_COMBINE = fr'{WSC}*?(?P[,+>~]|{WS}(?![,+>~])){WSC}*' +# Extra: Contains (`:contains(text)`) +PAT_PSEUDO_CONTAINS = fr'{PAT_PSEUDO_CLASS_SPECIAL}(?P{VALUE}(?:{WSC}*,{WSC}*{VALUE})*){WSC}*\)' + +# Regular expressions +# CSS escape pattern +RE_CSS_ESC = re.compile(fr'(?:(\\[a-f0-9]{{1,6}}{WSC}?)|(\\[^\r\n\f])|(\\$))', re.I) +RE_CSS_STR_ESC = re.compile(fr'(?:(\\[a-f0-9]{{1,6}}{WS}?)|(\\[^\r\n\f])|(\\$)|(\\{NEWLINE}))', re.I) +# Pattern to break up `nth` specifiers +RE_NTH = re.compile(fr'(?P[-+])?(?P[0-9]+n?|n)(?:(?<=n){WSC}*(?P[-+]){WSC}*(?P[0-9]+))?', re.I) +# Pattern to iterate multiple values. +RE_VALUES = re.compile(fr'(?:(?P{VALUE})|(?P{WSC}*,{WSC}*))', re.X) +# Whitespace checks +RE_WS = re.compile(WS) +RE_WS_BEGIN = re.compile(fr'^{WSC}*') +RE_WS_END = re.compile(fr'{WSC}*$') +RE_CUSTOM = re.compile(fr'^{PAT_PSEUDO_CLASS_CUSTOM}$', re.X) + +# Constants +# List split token +COMMA_COMBINATOR = ',' +# Relation token for descendant +WS_COMBINATOR = " " + +# Parse flags +FLG_PSEUDO = 0x01 +FLG_NOT = 0x02 +FLG_RELATIVE = 0x04 +FLG_DEFAULT = 0x08 +FLG_HTML = 0x10 +FLG_INDETERMINATE = 0x20 +FLG_OPEN = 0x40 +FLG_IN_RANGE = 0x80 +FLG_OUT_OF_RANGE = 0x100 +FLG_PLACEHOLDER_SHOWN = 0x200 +FLG_FORGIVE = 0x400 + +# Maximum cached patterns to store +_MAXCACHE = 500 + + +@lru_cache(maxsize=_MAXCACHE) +def _cached_css_compile( + pattern: str, + namespaces: ct.Namespaces | None, + custom: ct.CustomSelectors | None, + flags: int +) -> cm.SoupSieve: + """Cached CSS compile.""" + + custom_selectors = process_custom(custom) + return cm.SoupSieve( + pattern, + CSSParser( + pattern, + custom=custom_selectors, + flags=flags + ).process_selectors(), + namespaces, + custom, + flags + ) + + +def _purge_cache() -> None: + """Purge the cache.""" + + _cached_css_compile.cache_clear() + + +def process_custom(custom: ct.CustomSelectors | None) -> dict[str, str | ct.SelectorList]: + """Process custom.""" + + custom_selectors = {} + if custom is not None: + for key, value in custom.items(): + name = util.lower(key) + if RE_CUSTOM.match(name) is None: + raise SelectorSyntaxError(f"The name '{name}' is not a valid custom pseudo-class name") + if name in custom_selectors: + raise KeyError(f"The custom selector '{name}' has already been registered") + custom_selectors[css_unescape(name)] = value + return custom_selectors + + +def css_unescape(content: str, string: bool = False) -> str: + """ + Unescape CSS value. + + Strings allow for spanning the value on multiple strings by escaping a new line. + """ + + def replace(m: Match[str]) -> str: + """Replace with the appropriate substitute.""" + + if m.group(1): + codepoint = int(m.group(1)[1:], 16) + if codepoint == 0: + codepoint = UNICODE_REPLACEMENT_CHAR + value = chr(codepoint) + elif m.group(2): + value = m.group(2)[1:] + elif m.group(3): + value = '\ufffd' + else: + value = '' + + return value + + return (RE_CSS_ESC if not string else RE_CSS_STR_ESC).sub(replace, content) + + +def escape(ident: str) -> str: + """Escape identifier.""" + + string = [] + length = len(ident) + start_dash = length > 0 and ident[0] == '-' + if length == 1 and start_dash: + # Need to escape identifier that is a single `-` with no other characters + string.append(f'\\{ident}') + else: + for index, c in enumerate(ident): + codepoint = ord(c) + if codepoint == 0x00: + string.append('\ufffd') + elif (0x01 <= codepoint <= 0x1F) or codepoint == 0x7F: + string.append(f'\\{codepoint:x} ') + elif (index == 0 or (start_dash and index == 1)) and (0x30 <= codepoint <= 0x39): + string.append(f'\\{codepoint:x} ') + elif ( + codepoint in (0x2D, 0x5F) or codepoint >= 0x80 or (0x30 <= codepoint <= 0x39) or + (0x30 <= codepoint <= 0x39) or (0x41 <= codepoint <= 0x5A) or (0x61 <= codepoint <= 0x7A) + ): + string.append(c) + else: + string.append(f'\\{c}') + return ''.join(string) + + +class SelectorPattern: + """Selector pattern.""" + + def __init__(self, name: str, pattern: str) -> None: + """Initialize.""" + + self.name = name + self.re_pattern = re.compile(pattern, re.I | re.X | re.U) + + def get_name(self) -> str: + """Get name.""" + + return self.name + + def match(self, selector: str, index: int, flags: int) -> Match[str] | None: + """Match the selector.""" + + return self.re_pattern.match(selector, index) + + +class SpecialPseudoPattern(SelectorPattern): + """Selector pattern.""" + + def __init__(self, patterns: tuple[tuple[str, tuple[str, ...], str, type[SelectorPattern]], ...]) -> None: + """Initialize.""" + + self.patterns = {} + for p in patterns: + name = p[0] + pattern = p[3](name, p[2]) + for pseudo in p[1]: + self.patterns[pseudo] = pattern + + self.matched_name = None # type: SelectorPattern | None + self.re_pseudo_name = re.compile(PAT_PSEUDO_CLASS_SPECIAL, re.I | re.X | re.U) + + def get_name(self) -> str: + """Get name.""" + + return '' if self.matched_name is None else self.matched_name.get_name() + + def match(self, selector: str, index: int, flags: int) -> Match[str] | None: + """Match the selector.""" + + pseudo = None + m = self.re_pseudo_name.match(selector, index) + if m: + name = util.lower(css_unescape(m.group('name'))) + pattern = self.patterns.get(name) + if pattern: + pseudo = pattern.match(selector, index, flags) + if pseudo: + self.matched_name = pattern + + return pseudo + + +class _Selector: + """ + Intermediate selector class. + + This stores selector data for a compound selector as we are acquiring them. + Once we are done collecting the data for a compound selector, we freeze + the data in an object that can be pickled and hashed. + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize.""" + + self.tag = kwargs.get('tag', None) # type: ct.SelectorTag | None + self.ids = kwargs.get('ids', []) # type: list[str] + self.classes = kwargs.get('classes', []) # type: list[str] + self.attributes = kwargs.get('attributes', []) # type: list[ct.SelectorAttribute] + self.nth = kwargs.get('nth', []) # type: list[ct.SelectorNth] + self.selectors = kwargs.get('selectors', []) # type: list[ct.SelectorList] + self.relations = kwargs.get('relations', []) # type: list[_Selector] + self.rel_type = kwargs.get('rel_type', None) # type: str | None + self.contains = kwargs.get('contains', []) # type: list[ct.SelectorContains] + self.lang = kwargs.get('lang', []) # type: list[ct.SelectorLang] + self.flags = kwargs.get('flags', 0) # type: int + self.no_match = kwargs.get('no_match', False) # type: bool + + def _freeze_relations(self, relations: list[_Selector]) -> ct.SelectorList: + """Freeze relation.""" + + if relations: + sel = relations[0] + sel.relations.extend(relations[1:]) + return ct.SelectorList([sel.freeze()]) + else: + return ct.SelectorList() + + def freeze(self) -> ct.Selector | ct.SelectorNull: + """Freeze self.""" + + if self.no_match: + return ct.SelectorNull() + else: + return ct.Selector( + self.tag, + tuple(self.ids), + tuple(self.classes), + tuple(self.attributes), + tuple(self.nth), + tuple(self.selectors), + self._freeze_relations(self.relations), + self.rel_type, + tuple(self.contains), + tuple(self.lang), + self.flags + ) + + def __str__(self) -> str: # pragma: no cover + """String representation.""" + + return ( + f'_Selector(tag={self.tag!r}, ids={self.ids!r}, classes={self.classes!r}, attributes={self.attributes!r}, ' + f'nth={self.nth!r}, selectors={self.selectors!r}, relations={self.relations!r}, ' + f'rel_type={self.rel_type!r}, contains={self.contains!r}, lang={self.lang!r}, flags={self.flags!r}, ' + f'no_match={self.no_match!r})' + ) + + __repr__ = __str__ + + +class CSSParser: + """Parse CSS selectors.""" + + css_tokens = ( + SelectorPattern("pseudo_close", PAT_PSEUDO_CLOSE), + SpecialPseudoPattern( + ( + ( + "pseudo_contains", + (':contains', ':-soup-contains', ':-soup-contains-own'), + PAT_PSEUDO_CONTAINS, + SelectorPattern + ), + ("pseudo_nth_child", (':nth-child', ':nth-last-child'), PAT_PSEUDO_NTH_CHILD, SelectorPattern), + ("pseudo_nth_type", (':nth-of-type', ':nth-last-of-type'), PAT_PSEUDO_NTH_TYPE, SelectorPattern), + ("pseudo_lang", (':lang',), PAT_PSEUDO_LANG, SelectorPattern), + ("pseudo_dir", (':dir',), PAT_PSEUDO_DIR, SelectorPattern) + ) + ), + SelectorPattern("pseudo_class_custom", PAT_PSEUDO_CLASS_CUSTOM), + SelectorPattern("pseudo_class", PAT_PSEUDO_CLASS), + SelectorPattern("pseudo_element", PAT_PSEUDO_ELEMENT), + SelectorPattern("at_rule", PAT_AT_RULE), + SelectorPattern("id", PAT_ID), + SelectorPattern("class", PAT_CLASS), + SelectorPattern("tag", PAT_TAG), + SelectorPattern("attribute", PAT_ATTR), + SelectorPattern("combine", PAT_COMBINE) + ) + + def __init__( + self, + selector: str, + custom: dict[str, str | ct.SelectorList] | None = None, + flags: int = 0 + ) -> None: + """Initialize.""" + + self.pattern = selector.replace('\x00', '\ufffd') + self.flags = flags + self.debug = self.flags & util.DEBUG + self.custom = {} if custom is None else custom + + def parse_attribute_selector(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool: + """Create attribute selector from the returned regex match.""" + + inverse = False + op = m.group('cmp') + case = util.lower(m.group('case')) if m.group('case') else None + ns = css_unescape(m.group('attr_ns')[:-1]) if m.group('attr_ns') else '' + attr = css_unescape(m.group('attr_name')) + is_type = False + pattern2 = None + value = '' + + if case: + flags = (re.I if case == 'i' else 0) | re.DOTALL + elif util.lower(attr) == 'type': + flags = re.I | re.DOTALL + is_type = True + else: + flags = re.DOTALL + + if op: + if m.group('value').startswith(('"', "'")): + value = css_unescape(m.group('value')[1:-1], True) + else: + value = css_unescape(m.group('value')) + + if not op: + # Attribute name + pattern = None + elif op.startswith('^'): + # Value start with + pattern = re.compile(r'^%s.*' % re.escape(value), flags) + elif op.startswith('$'): + # Value ends with + pattern = re.compile(r'.*?%s$' % re.escape(value), flags) + elif op.startswith('*'): + # Value contains + pattern = re.compile(r'.*?%s.*' % re.escape(value), flags) + elif op.startswith('~'): + # Value contains word within space separated list + # `~=` should match nothing if it is empty or contains whitespace, + # so if either of these cases is present, use `[^\s\S]` which cannot be matched. + value = r'[^\s\S]' if not value or RE_WS.search(value) else re.escape(value) + pattern = re.compile(r'.*?(?:(?<=^)|(?<=[ \t\r\n\f]))%s(?=(?:[ \t\r\n\f]|$)).*' % value, flags) + elif op.startswith('|'): + # Value starts with word in dash separated list + pattern = re.compile(r'^%s(?:-.*)?$' % re.escape(value), flags) + else: + # Value matches + pattern = re.compile(r'^%s$' % re.escape(value), flags) + if op.startswith('!'): + # Equivalent to `:not([attr=value])` + inverse = True + if is_type and pattern: + pattern2 = re.compile(pattern.pattern) + + # Append the attribute selector + sel_attr = ct.SelectorAttribute(attr, ns, pattern, pattern2) + if inverse: + # If we are using `!=`, we need to nest the pattern under a `:not()`. + sub_sel = _Selector() + sub_sel.attributes.append(sel_attr) + not_list = ct.SelectorList([sub_sel.freeze()], True, False) + sel.selectors.append(not_list) + else: + sel.attributes.append(sel_attr) + + has_selector = True + return has_selector + + def parse_tag_pattern(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool: + """Parse tag pattern from regex match.""" + + prefix = css_unescape(m.group('tag_ns')[:-1]) if m.group('tag_ns') else None + tag = css_unescape(m.group('tag_name')) + sel.tag = ct.SelectorTag(tag, prefix) + has_selector = True + return has_selector + + def parse_pseudo_class_custom(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool: + """ + Parse custom pseudo class alias. + + Compile custom selectors as we need them. When compiling a custom selector, + set it to `None` in the dictionary so we can avoid an infinite loop. + """ + + pseudo = util.lower(css_unescape(m.group('name'))) + selector = self.custom.get(pseudo) + if selector is None: + raise SelectorSyntaxError( + f"Undefined custom selector '{pseudo}' found at position {m.end(0)}", + self.pattern, + m.end(0) + ) + + if not isinstance(selector, ct.SelectorList): + del self.custom[pseudo] + selector = CSSParser( + selector, custom=self.custom, flags=self.flags + ).process_selectors(flags=FLG_PSEUDO) + self.custom[pseudo] = selector + + sel.selectors.append(selector) + has_selector = True + return has_selector + + def parse_pseudo_class( + self, + sel: _Selector, + m: Match[str], + has_selector: bool, + iselector: Iterator[tuple[str, Match[str]]], + is_html: bool + ) -> tuple[bool, bool]: + """Parse pseudo class.""" + + complex_pseudo = False + pseudo = util.lower(css_unescape(m.group('name'))) + if m.group('open'): + complex_pseudo = True + if complex_pseudo and pseudo in PSEUDO_COMPLEX: + has_selector = self.parse_pseudo_open(sel, pseudo, has_selector, iselector, m.end(0)) + elif not complex_pseudo and pseudo in PSEUDO_SIMPLE: + if pseudo == ':root': + sel.flags |= ct.SEL_ROOT + elif pseudo == ':defined': + sel.flags |= ct.SEL_DEFINED + is_html = True + elif pseudo == ':scope': + sel.flags |= ct.SEL_SCOPE + elif pseudo == ':empty': + sel.flags |= ct.SEL_EMPTY + elif pseudo in (':link', ':any-link'): + sel.selectors.append(CSS_LINK) + elif pseudo == ':checked': + sel.selectors.append(CSS_CHECKED) + elif pseudo == ':default': + sel.selectors.append(CSS_DEFAULT) + elif pseudo == ':indeterminate': + sel.selectors.append(CSS_INDETERMINATE) + elif pseudo == ":disabled": + sel.selectors.append(CSS_DISABLED) + elif pseudo == ":enabled": + sel.selectors.append(CSS_ENABLED) + elif pseudo == ":required": + sel.selectors.append(CSS_REQUIRED) + elif pseudo == ":optional": + sel.selectors.append(CSS_OPTIONAL) + elif pseudo == ":read-only": + sel.selectors.append(CSS_READ_ONLY) + elif pseudo == ":read-write": + sel.selectors.append(CSS_READ_WRITE) + elif pseudo == ":in-range": + sel.selectors.append(CSS_IN_RANGE) + elif pseudo == ":out-of-range": + sel.selectors.append(CSS_OUT_OF_RANGE) + elif pseudo == ":placeholder-shown": + sel.selectors.append(CSS_PLACEHOLDER_SHOWN) + elif pseudo == ':first-child': + sel.nth.append(ct.SelectorNth(1, False, 0, False, False, ct.SelectorList())) + elif pseudo == ':last-child': + sel.nth.append(ct.SelectorNth(1, False, 0, False, True, ct.SelectorList())) + elif pseudo == ':first-of-type': + sel.nth.append(ct.SelectorNth(1, False, 0, True, False, ct.SelectorList())) + elif pseudo == ':last-of-type': + sel.nth.append(ct.SelectorNth(1, False, 0, True, True, ct.SelectorList())) + elif pseudo == ':only-child': + sel.nth.extend( + [ + ct.SelectorNth(1, False, 0, False, False, ct.SelectorList()), + ct.SelectorNth(1, False, 0, False, True, ct.SelectorList()) + ] + ) + elif pseudo == ':only-of-type': + sel.nth.extend( + [ + ct.SelectorNth(1, False, 0, True, False, ct.SelectorList()), + ct.SelectorNth(1, False, 0, True, True, ct.SelectorList()) + ] + ) + has_selector = True + elif complex_pseudo and pseudo in PSEUDO_COMPLEX_NO_MATCH: + self.parse_selectors(iselector, m.end(0), FLG_PSEUDO | FLG_OPEN) + sel.no_match = True + has_selector = True + elif not complex_pseudo and pseudo in PSEUDO_SIMPLE_NO_MATCH: + sel.no_match = True + has_selector = True + elif pseudo in PSEUDO_SUPPORTED: + raise SelectorSyntaxError( + f"Invalid syntax for pseudo class '{pseudo}'", + self.pattern, + m.start(0) + ) + else: + raise NotImplementedError( + f"'{pseudo}' pseudo-class is not implemented at this time" + ) + + return has_selector, is_html + + def parse_pseudo_nth( + self, + sel: _Selector, + m: Match[str], + has_selector: bool, + iselector: Iterator[tuple[str, Match[str]]] + ) -> bool: + """Parse `nth` pseudo.""" + + mdict = m.groupdict() + if mdict.get('pseudo_nth_child'): + postfix = '_child' + else: + postfix = '_type' + mdict['name'] = util.lower(css_unescape(mdict['name'])) + content = util.lower(mdict.get('nth' + postfix)) + if content == 'even': + # 2n + s1 = 2 + s2 = 0 + var = True + elif content == 'odd': + # 2n+1 + s1 = 2 + s2 = 1 + var = True + else: + nth_parts = cast(Match[str], RE_NTH.match(content)) + _s1 = '-' if nth_parts.group('s1') and nth_parts.group('s1') == '-' else '' + a = nth_parts.group('a') + var = a.endswith('n') + if a.startswith('n'): + _s1 += '1' + elif var: + _s1 += a[:-1] + else: + _s1 += a + _s2 = '-' if nth_parts.group('s2') and nth_parts.group('s2') == '-' else '' + if nth_parts.group('b'): + _s2 += nth_parts.group('b') + else: + _s2 = '0' + s1 = int(_s1, 10) + s2 = int(_s2, 10) + + pseudo_sel = mdict['name'] + if postfix == '_child': + if m.group('of'): + # Parse the rest of `of S`. + nth_sel = self.parse_selectors(iselector, m.end(0), FLG_PSEUDO | FLG_OPEN) + else: + # Use default `*|*` for `of S`. + nth_sel = CSS_NTH_OF_S_DEFAULT + if pseudo_sel == ':nth-child': + sel.nth.append(ct.SelectorNth(s1, var, s2, False, False, nth_sel)) + elif pseudo_sel == ':nth-last-child': + sel.nth.append(ct.SelectorNth(s1, var, s2, False, True, nth_sel)) + else: + if pseudo_sel == ':nth-of-type': + sel.nth.append(ct.SelectorNth(s1, var, s2, True, False, ct.SelectorList())) + elif pseudo_sel == ':nth-last-of-type': + sel.nth.append(ct.SelectorNth(s1, var, s2, True, True, ct.SelectorList())) + has_selector = True + return has_selector + + def parse_pseudo_open( + self, + sel: _Selector, + name: str, + has_selector: bool, + iselector: Iterator[tuple[str, Match[str]]], + index: int + ) -> bool: + """Parse pseudo with opening bracket.""" + + flags = FLG_PSEUDO | FLG_OPEN + if name == ':not': + flags |= FLG_NOT + elif name == ':has': + flags |= FLG_RELATIVE + elif name in (':where', ':is'): + flags |= FLG_FORGIVE + + sel.selectors.append(self.parse_selectors(iselector, index, flags)) + has_selector = True + + return has_selector + + def parse_has_combinator( + self, + sel: _Selector, + m: Match[str], + has_selector: bool, + selectors: list[_Selector], + rel_type: str, + index: int + ) -> tuple[bool, _Selector, str]: + """Parse combinator tokens.""" + + combinator = m.group('relation').strip() + if not combinator: + combinator = WS_COMBINATOR + if combinator == COMMA_COMBINATOR: + sel.rel_type = rel_type + selectors[-1].relations.append(sel) + rel_type = ":" + WS_COMBINATOR + selectors.append(_Selector()) + else: + if has_selector: + # End the current selector and associate the leading combinator with this selector. + sel.rel_type = rel_type + selectors[-1].relations.append(sel) + elif rel_type[1:] != WS_COMBINATOR: + # It's impossible to have two whitespace combinators after each other as the patterns + # will gobble up trailing whitespace. It is also impossible to have a whitespace + # combinator after any other kind for the same reason. But we could have + # multiple non-whitespace combinators. So if the current combinator is not a whitespace, + # then we've hit the multiple combinator case, so we should fail. + raise SelectorSyntaxError( + f'The multiple combinators at position {index}', + self.pattern, + index + ) + + # Set the leading combinator for the next selector. + rel_type = ':' + combinator + + sel = _Selector() + has_selector = False + return has_selector, sel, rel_type + + def parse_combinator( + self, + sel: _Selector, + m: Match[str], + has_selector: bool, + selectors: list[_Selector], + relations: list[_Selector], + is_pseudo: bool, + is_forgive: bool, + index: int + ) -> tuple[bool, _Selector]: + """Parse combinator tokens.""" + + combinator = m.group('relation').strip() + if not combinator: + combinator = WS_COMBINATOR + if not has_selector: + if not is_forgive or combinator != COMMA_COMBINATOR: + raise SelectorSyntaxError( + f"The combinator '{combinator}' at position {index}, must have a selector before it", + self.pattern, + index + ) + + # If we are in a forgiving pseudo class, just make the selector a "no match" + if combinator == COMMA_COMBINATOR: + sel.no_match = True + del relations[:] + selectors.append(sel) + else: + if combinator == COMMA_COMBINATOR: + if not sel.tag and not is_pseudo: + # Implied `*` + sel.tag = ct.SelectorTag('*', None) + sel.relations.extend(relations) + selectors.append(sel) + del relations[:] + else: + sel.relations.extend(relations) + sel.rel_type = combinator + del relations[:] + relations.append(sel) + + sel = _Selector() + has_selector = False + + return has_selector, sel + + def parse_class_id(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool: + """Parse HTML classes and ids.""" + + selector = m.group(0) + if selector.startswith('.'): + sel.classes.append(css_unescape(selector[1:])) + else: + sel.ids.append(css_unescape(selector[1:])) + has_selector = True + return has_selector + + def parse_pseudo_contains(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool: + """Parse contains.""" + + pseudo = util.lower(css_unescape(m.group('name'))) + if pseudo == ":contains": + warnings.warn( # noqa: B028 + "The pseudo class ':contains' is deprecated, ':-soup-contains' should be used moving forward.", + FutureWarning + ) + contains_own = pseudo == ":-soup-contains-own" + values = css_unescape(m.group('values')) + patterns = [] + for token in RE_VALUES.finditer(values): + if token.group('split'): + continue + value = token.group('value') + if value.startswith(("'", '"')): + value = css_unescape(value[1:-1], True) + else: + value = css_unescape(value) + patterns.append(value) + sel.contains.append(ct.SelectorContains(patterns, contains_own)) + has_selector = True + return has_selector + + def parse_pseudo_lang(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool: + """Parse pseudo language.""" + + values = m.group('values') + patterns = [] + for token in RE_VALUES.finditer(values): + if token.group('split'): + continue + value = token.group('value') + if value.startswith(('"', "'")): + value = css_unescape(value[1:-1], True) + else: + value = css_unescape(value) + + patterns.append(value) + + sel.lang.append(ct.SelectorLang(patterns)) + has_selector = True + + return has_selector + + def parse_pseudo_dir(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool: + """Parse pseudo direction.""" + + value = ct.SEL_DIR_LTR if util.lower(m.group('dir')) == 'ltr' else ct.SEL_DIR_RTL + sel.flags |= value + has_selector = True + return has_selector + + def parse_selectors( + self, + iselector: Iterator[tuple[str, Match[str]]], + index: int = 0, + flags: int = 0 + ) -> ct.SelectorList: + """Parse selectors.""" + + # Initialize important variables + sel = _Selector() + selectors = [] + has_selector = False + closed = False + relations = [] # type: list[_Selector] + rel_type = ":" + WS_COMBINATOR + + # Setup various flags + is_open = bool(flags & FLG_OPEN) + is_pseudo = bool(flags & FLG_PSEUDO) + is_relative = bool(flags & FLG_RELATIVE) + is_not = bool(flags & FLG_NOT) + is_html = bool(flags & FLG_HTML) + is_default = bool(flags & FLG_DEFAULT) + is_indeterminate = bool(flags & FLG_INDETERMINATE) + is_in_range = bool(flags & FLG_IN_RANGE) + is_out_of_range = bool(flags & FLG_OUT_OF_RANGE) + is_placeholder_shown = bool(flags & FLG_PLACEHOLDER_SHOWN) + is_forgive = bool(flags & FLG_FORGIVE) + + # Print out useful debug stuff + if self.debug: # pragma: no cover + if is_pseudo: + print(' is_pseudo: True') + if is_open: + print(' is_open: True') + if is_relative: + print(' is_relative: True') + if is_not: + print(' is_not: True') + if is_html: + print(' is_html: True') + if is_default: + print(' is_default: True') + if is_indeterminate: + print(' is_indeterminate: True') + if is_in_range: + print(' is_in_range: True') + if is_out_of_range: + print(' is_out_of_range: True') + if is_placeholder_shown: + print(' is_placeholder_shown: True') + if is_forgive: + print(' is_forgive: True') + + # The algorithm for relative selectors require an initial selector in the selector list + if is_relative: + selectors.append(_Selector()) + + try: + while True: + key, m = next(iselector) + + # Handle parts + if key == "at_rule": + raise NotImplementedError(f"At-rules found at position {m.start(0)}") + elif key == 'pseudo_class_custom': + has_selector = self.parse_pseudo_class_custom(sel, m, has_selector) + elif key == 'pseudo_class': + has_selector, is_html = self.parse_pseudo_class(sel, m, has_selector, iselector, is_html) + elif key == 'pseudo_element': + raise NotImplementedError(f"Pseudo-element found at position {m.start(0)}") + elif key == 'pseudo_contains': + has_selector = self.parse_pseudo_contains(sel, m, has_selector) + elif key in ('pseudo_nth_type', 'pseudo_nth_child'): + has_selector = self.parse_pseudo_nth(sel, m, has_selector, iselector) + elif key == 'pseudo_lang': + has_selector = self.parse_pseudo_lang(sel, m, has_selector) + elif key == 'pseudo_dir': + has_selector = self.parse_pseudo_dir(sel, m, has_selector) + # Currently only supports HTML + is_html = True + elif key == 'pseudo_close': + if not has_selector: + if not is_forgive: + raise SelectorSyntaxError( + f"Expected a selector at position {m.start(0)}", + self.pattern, + m.start(0) + ) + sel.no_match = True + if is_open: + closed = True + break + else: + raise SelectorSyntaxError( + f"Unmatched pseudo-class close at position {m.start(0)}", + self.pattern, + m.start(0) + ) + elif key == 'combine': + if is_relative: + has_selector, sel, rel_type = self.parse_has_combinator( + sel, m, has_selector, selectors, rel_type, index + ) + else: + has_selector, sel = self.parse_combinator( + sel, m, has_selector, selectors, relations, is_pseudo, is_forgive, index + ) + elif key == 'attribute': + has_selector = self.parse_attribute_selector(sel, m, has_selector) + elif key == 'tag': + if has_selector: + raise SelectorSyntaxError( + f"Tag name found at position {m.start(0)} instead of at the start", + self.pattern, + m.start(0) + ) + has_selector = self.parse_tag_pattern(sel, m, has_selector) + elif key in ('class', 'id'): + has_selector = self.parse_class_id(sel, m, has_selector) + + index = m.end(0) + except StopIteration: + pass + + # Handle selectors that are not closed + if is_open and not closed: + raise SelectorSyntaxError( + f"Unclosed pseudo-class at position {index}", + self.pattern, + index + ) + + # Cleanup completed selector piece + if has_selector: + if not sel.tag and not is_pseudo: + # Implied `*` + sel.tag = ct.SelectorTag('*', None) + if is_relative: + sel.rel_type = rel_type + selectors[-1].relations.append(sel) + else: + sel.relations.extend(relations) + del relations[:] + selectors.append(sel) + + # Forgive empty slots in pseudo-classes that have lists (and are forgiving) + elif is_forgive and (not selectors or not relations): + # Handle normal pseudo-classes with empty slots like `:is()` etc. + sel.no_match = True + del relations[:] + selectors.append(sel) + has_selector = True + + if not has_selector: + # We will always need to finish a selector when `:has()` is used as it leads with combining. + # May apply to others as well. + raise SelectorSyntaxError( + f'Expected a selector at position {index}', + self.pattern, + index + ) + + # Some patterns require additional logic, such as default. We try to make these the + # last pattern, and append the appropriate flag to that selector which communicates + # to the matcher what additional logic is required. + if is_default: + selectors[-1].flags = ct.SEL_DEFAULT + if is_indeterminate: + selectors[-1].flags = ct.SEL_INDETERMINATE + if is_in_range: + selectors[-1].flags = ct.SEL_IN_RANGE + if is_out_of_range: + selectors[-1].flags = ct.SEL_OUT_OF_RANGE + if is_placeholder_shown: + selectors[-1].flags = ct.SEL_PLACEHOLDER_SHOWN + + # Return selector list + return ct.SelectorList([s.freeze() for s in selectors], is_not, is_html) + + def selector_iter(self, pattern: str) -> Iterator[tuple[str, Match[str]]]: + """Iterate selector tokens.""" + + # Ignore whitespace and comments at start and end of pattern + m = RE_WS_BEGIN.search(pattern) + index = m.end(0) if m else 0 + m = RE_WS_END.search(pattern) + end = (m.start(0) - 1) if m else (len(pattern) - 1) + + if self.debug: # pragma: no cover + print(f'## PARSING: {pattern!r}') + while index <= end: + m = None + for v in self.css_tokens: + m = v.match(pattern, index, self.flags) + if m: + name = v.get_name() + if self.debug: # pragma: no cover + print(f"TOKEN: '{name}' --> {m.group(0)!r} at position {m.start(0)}") + index = m.end(0) + yield name, m + break + if m is None: + c = pattern[index] + # If the character represents the start of one of the known selector types, + # throw an exception mentioning that the known selector type is in error; + # otherwise, report the invalid character. + if c == '[': + msg = f"Malformed attribute selector at position {index}" + elif c == '.': + msg = f"Malformed class selector at position {index}" + elif c == '#': + msg = f"Malformed id selector at position {index}" + elif c == ':': + msg = f"Malformed pseudo-class selector at position {index}" + else: + msg = f"Invalid character {c!r} position {index}" + raise SelectorSyntaxError(msg, self.pattern, index) + if self.debug: # pragma: no cover + print('## END PARSING') + + def process_selectors(self, index: int = 0, flags: int = 0) -> ct.SelectorList: + """Process selectors.""" + + return self.parse_selectors(self.selector_iter(self.pattern), index, flags) + + +# Precompile CSS selector lists for pseudo-classes (additional logic may be required beyond the pattern) +# A few patterns are order dependent as they use patterns previous compiled. + +# CSS pattern for `:link` and `:any-link` +CSS_LINK = CSSParser( + 'html|*:is(a, area)[href]' +).process_selectors(flags=FLG_PSEUDO | FLG_HTML) +# CSS pattern for `:checked` +CSS_CHECKED = CSSParser( + ''' + html|*:is(input[type=checkbox], input[type=radio])[checked], html|option[selected] + ''' +).process_selectors(flags=FLG_PSEUDO | FLG_HTML) +# CSS pattern for `:default` (must compile CSS_CHECKED first) +CSS_DEFAULT = CSSParser( + ''' + :checked, + + /* + This pattern must be at the end. + Special logic is applied to the last selector. + */ + html|form html|*:is(button, input)[type="submit"] + ''' +).process_selectors(flags=FLG_PSEUDO | FLG_HTML | FLG_DEFAULT) +# CSS pattern for `:indeterminate` +CSS_INDETERMINATE = CSSParser( + ''' + html|input[type="checkbox"][indeterminate], + html|input[type="radio"]:is(:not([name]), [name=""]):not([checked]), + html|progress:not([value]), + + /* + This pattern must be at the end. + Special logic is applied to the last selector. + */ + html|input[type="radio"][name]:not([name='']):not([checked]) + ''' +).process_selectors(flags=FLG_PSEUDO | FLG_HTML | FLG_INDETERMINATE) +# CSS pattern for `:disabled` +CSS_DISABLED = CSSParser( + ''' + html|*:is(input:not([type=hidden]), button, select, textarea, fieldset, optgroup, option, fieldset)[disabled], + html|optgroup[disabled] > html|option, + html|fieldset[disabled] > html|*:is(input:not([type=hidden]), button, select, textarea, fieldset), + html|fieldset[disabled] > + html|*:not(legend:nth-of-type(1)) html|*:is(input:not([type=hidden]), button, select, textarea, fieldset) + ''' +).process_selectors(flags=FLG_PSEUDO | FLG_HTML) +# CSS pattern for `:enabled` +CSS_ENABLED = CSSParser( + ''' + html|*:is(input:not([type=hidden]), button, select, textarea, fieldset, optgroup, option, fieldset):not(:disabled) + ''' +).process_selectors(flags=FLG_PSEUDO | FLG_HTML) +# CSS pattern for `:required` +CSS_REQUIRED = CSSParser( + 'html|*:is(input, textarea, select)[required]' +).process_selectors(flags=FLG_PSEUDO | FLG_HTML) +# CSS pattern for `:optional` +CSS_OPTIONAL = CSSParser( + 'html|*:is(input, textarea, select):not([required])' +).process_selectors(flags=FLG_PSEUDO | FLG_HTML) +# CSS pattern for `:placeholder-shown` +CSS_PLACEHOLDER_SHOWN = CSSParser( + ''' + html|input:is( + :not([type]), + [type=""], + [type=text], + [type=search], + [type=url], + [type=tel], + [type=email], + [type=password], + [type=number] + )[placeholder]:not([placeholder='']):is(:not([value]), [value=""]), + html|textarea[placeholder]:not([placeholder='']) + ''' +).process_selectors(flags=FLG_PSEUDO | FLG_HTML | FLG_PLACEHOLDER_SHOWN) +# CSS pattern default for `:nth-child` "of S" feature +CSS_NTH_OF_S_DEFAULT = CSSParser( + '*|*' +).process_selectors(flags=FLG_PSEUDO) +# CSS pattern for `:read-write` (CSS_DISABLED must be compiled first) +CSS_READ_WRITE = CSSParser( + ''' + html|*:is( + textarea, + input:is( + :not([type]), + [type=""], + [type=text], + [type=search], + [type=url], + [type=tel], + [type=email], + [type=number], + [type=password], + [type=date], + [type=datetime-local], + [type=month], + [type=time], + [type=week] + ) + ):not([readonly], :disabled), + html|*:is([contenteditable=""], [contenteditable="true" i]) + ''' +).process_selectors(flags=FLG_PSEUDO | FLG_HTML) +# CSS pattern for `:read-only` +CSS_READ_ONLY = CSSParser( + ''' + html|*:not(:read-write) + ''' +).process_selectors(flags=FLG_PSEUDO | FLG_HTML) +# CSS pattern for `:in-range` +CSS_IN_RANGE = CSSParser( + ''' + html|input:is( + [type="date"], + [type="month"], + [type="week"], + [type="time"], + [type="datetime-local"], + [type="number"], + [type="range"] + ):is( + [min], + [max] + ) + ''' +).process_selectors(flags=FLG_PSEUDO | FLG_IN_RANGE | FLG_HTML) +# CSS pattern for `:out-of-range` +CSS_OUT_OF_RANGE = CSSParser( + ''' + html|input:is( + [type="date"], + [type="month"], + [type="week"], + [type="time"], + [type="datetime-local"], + [type="number"], + [type="range"] + ):is( + [min], + [max] + ) + ''' +).process_selectors(flags=FLG_PSEUDO | FLG_OUT_OF_RANGE | FLG_HTML) diff --git a/shared/package-files/33/33451c69e142a8b3e01ac17c379987c3bb376ecae56c37c9636ba12e8cc9f7b2/_compat.pyi b/shared/package-files/33/33451c69e142a8b3e01ac17c379987c3bb376ecae56c37c9636ba12e8cc9f7b2/_compat.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f40d7556dee87d2107f7b18708f03040bc04a3f2 --- /dev/null +++ b/shared/package-files/33/33451c69e142a8b3e01ac17c379987c3bb376ecae56c37c9636ba12e8cc9f7b2/_compat.pyi @@ -0,0 +1,40 @@ +"""Static type stubs for `_compat.py`.""" + +# https://github.com/scikit-learn/scikit-learn/pull/27910#issuecomment-2568023972 +from __future__ import annotations + +from types import ModuleType + +# TODO import from typing (requires Python >=3.13) +from typing_extensions import TypeIs + +from ._typing import Array, Device + +# pylint: disable=missing-class-docstring,unused-argument + +class Namespace(ModuleType): + def device(self, x: Array, /) -> Device: ... + +def array_namespace( + *xs: Array | complex | None, + api_version: str | None = None, + use_compat: bool | None = None, +) -> Namespace: ... +def device(x: Array, /) -> Device: ... +def is_array_api_obj(x: object, /) -> TypeIs[Array]: ... +def is_array_api_strict_namespace(xp: ModuleType, /) -> TypeIs[Namespace]: ... +def is_cupy_namespace(xp: ModuleType, /) -> TypeIs[Namespace]: ... +def is_dask_namespace(xp: ModuleType, /) -> TypeIs[Namespace]: ... +def is_jax_namespace(xp: ModuleType, /) -> TypeIs[Namespace]: ... +def is_numpy_namespace(xp: ModuleType, /) -> TypeIs[Namespace]: ... +def is_pydata_sparse_namespace(xp: ModuleType, /) -> TypeIs[Namespace]: ... +def is_torch_namespace(xp: ModuleType, /) -> TypeIs[Namespace]: ... +def is_cupy_array(x: object, /) -> TypeIs[Array]: ... +def is_dask_array(x: object, /) -> TypeIs[Array]: ... +def is_jax_array(x: object, /) -> TypeIs[Array]: ... +def is_numpy_array(x: object, /) -> TypeIs[Array]: ... +def is_pydata_sparse_array(x: object, /) -> TypeIs[Array]: ... +def is_torch_array(x: object, /) -> TypeIs[Array]: ... +def is_lazy_array(x: object, /) -> TypeIs[Array]: ... +def is_writeable_array(x: object, /) -> TypeIs[Array]: ... +def size(x: Array, /) -> int | None: ... diff --git a/shared/package-files/33/3348b29618eeaad3dc6ceda901574383d9fd7b5113df9f6743db7138412b98ca/__init__.py b/shared/package-files/33/3348b29618eeaad3dc6ceda901574383d9fd7b5113df9f6743db7138412b98ca/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d79bdbfe83209f18b17cc8c7b245f322871d6c0 --- /dev/null +++ b/shared/package-files/33/3348b29618eeaad3dc6ceda901574383d9fd7b5113df9f6743db7138412b98ca/__init__.py @@ -0,0 +1 @@ +from .modules import * # noqa: F403 diff --git a/shared/package-files/33/3348cd5dcc3c57790e839d3009ea86e17335a401228dc8666b1bb0cd3672d511/conv3d_native.h b/shared/package-files/33/3348cd5dcc3c57790e839d3009ea86e17335a401228dc8666b1bb0cd3672d511/conv3d_native.h new file mode 100644 index 0000000000000000000000000000000000000000..fb6909464ae2cba395abcfebcf93fe84f43d59e0 --- /dev/null +++ b/shared/package-files/33/3348cd5dcc3c57790e839d3009ea86e17335a401228dc8666b1bb0cd3672d511/conv3d_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor conv3d_symint(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1), c10::SymInt groups=1); +TORCH_API at::Tensor conv3d_padding_symint(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::string_view padding="valid", c10::SymIntArrayRef dilation=c10::SymInt(1), c10::SymInt groups=1); +} // namespace native +} // namespace at diff --git a/shared/package-files/33/334b52745a1434c677fadeed0991dc8144b7ee2058cd9af335a0ee8b8696a11e/elnino.dat b/shared/package-files/33/334b52745a1434c677fadeed0991dc8144b7ee2058cd9af335a0ee8b8696a11e/elnino.dat new file mode 100644 index 0000000000000000000000000000000000000000..28c4035c3876b48b14186a88c9d77aae85a69207 --- /dev/null +++ b/shared/package-files/33/334b52745a1434c677fadeed0991dc8144b7ee2058cd9af335a0ee8b8696a11e/elnino.dat @@ -0,0 +1,733 @@ + YR MON NINO1+2 ANOM NINO3 ANOM NINO4 ANOM NINO3.4 ANOM +1950 1 23.11 -1.42 23.74 -1.91 27.03 -1.12 24.83 -1.72 +1950 2 24.20 -1.71 24.92 -1.45 27.15 -0.92 25.20 -1.53 +1950 3 25.37 -1.00 26.33 -0.80 27.06 -1.11 26.03 -1.20 +1950 4 23.86 -1.71 26.46 -0.97 27.29 -1.10 26.36 -1.30 +1950 5 23.03 -1.39 25.72 -1.38 27.59 -1.10 26.19 -1.58 +1950 6 21.57 -1.50 25.55 -0.92 27.97 -0.70 26.52 -1.01 +1950 7 20.63 -1.34 24.97 -0.68 27.83 -0.78 26.42 -0.69 +1950 8 20.15 -0.86 24.61 -0.45 27.72 -0.78 25.98 -0.77 +1950 9 19.67 -1.10 24.22 -0.72 27.66 -0.85 25.78 -0.92 +1950 10 20.03 -1.04 24.39 -0.56 27.44 -1.07 25.96 -0.68 +1950 11 20.02 -1.72 24.00 -1.05 27.35 -1.11 25.64 -0.96 +1950 12 21.80 -1.11 24.30 -0.91 27.30 -1.05 25.50 -1.07 +1951 1 24.19 -0.35 25.00 -0.65 27.36 -0.79 25.46 -1.09 +1951 2 25.28 -0.64 25.80 -0.57 27.27 -0.80 25.78 -0.96 +1951 3 25.60 -0.78 26.91 -0.22 27.96 -0.21 26.72 -0.51 +1951 4 25.37 -0.20 27.31 -0.11 28.49 0.09 27.24 -0.43 +1951 5 24.79 0.37 27.08 -0.02 29.04 0.35 27.68 -0.09 +1951 6 24.69 1.62 26.57 0.10 28.74 0.07 27.46 -0.07 +1951 7 23.86 1.88 26.54 0.89 28.82 0.21 27.72 0.61 +1951 8 22.32 1.31 25.67 0.62 28.53 0.04 27.36 0.61 +1951 9 21.44 0.67 25.56 0.62 28.62 0.11 27.51 0.81 +1951 10 21.77 0.70 25.85 0.90 28.71 0.20 27.43 0.78 +1951 11 22.33 0.59 26.18 1.13 28.74 0.29 27.48 0.87 +1951 12 22.89 -0.01 25.98 0.77 28.53 0.19 27.12 0.55 +1952 1 24.52 -0.02 25.85 0.20 28.35 0.19 26.85 0.30 +1952 2 26.21 0.29 26.46 0.08 28.08 0.00 26.79 0.06 +1952 3 26.37 0.00 27.18 0.05 28.10 -0.07 27.32 0.09 +1952 4 24.73 -0.84 27.41 -0.02 28.52 0.12 27.88 0.21 +1952 5 23.71 -0.71 26.92 -0.18 28.69 -0.01 27.99 0.21 +1952 6 22.34 -0.73 25.84 -0.63 28.47 -0.20 27.33 -0.20 +1952 7 20.89 -1.09 24.92 -0.73 28.24 -0.37 26.72 -0.38 +1952 8 20.02 -0.99 24.50 -0.56 28.09 -0.40 26.46 -0.29 +1952 9 19.63 -1.14 24.43 -0.51 28.55 0.04 26.54 -0.17 +1952 10 20.40 -0.67 24.52 -0.42 28.25 -0.26 26.54 -0.10 +1952 11 20.77 -0.97 24.36 -0.69 28.28 -0.17 26.36 -0.24 +1952 12 22.39 -0.52 24.88 -0.33 28.30 -0.04 26.53 -0.04 +1953 1 24.15 -0.39 25.77 0.11 28.31 0.15 26.85 0.29 +1953 2 26.34 0.42 26.74 0.36 28.26 0.18 27.19 0.45 +1953 3 27.36 0.98 27.57 0.44 28.10 -0.07 27.68 0.45 +1953 4 27.03 1.46 27.91 0.49 28.53 0.14 28.19 0.53 +1953 5 25.47 1.05 27.39 0.28 28.92 0.23 28.29 0.52 +1953 6 23.49 0.42 26.77 0.30 29.18 0.51 28.02 0.49 +1953 7 22.20 0.23 25.81 0.16 29.02 0.41 27.52 0.42 +1953 8 21.45 0.44 25.20 0.14 28.83 0.34 27.16 0.41 +1953 9 21.25 0.49 25.17 0.24 28.61 0.09 27.13 0.43 +1953 10 20.95 -0.12 25.07 0.13 28.91 0.41 27.02 0.38 +1953 11 21.60 -0.14 25.25 0.19 28.91 0.46 26.96 0.36 +1953 12 22.44 -0.47 25.55 0.34 28.74 0.40 26.99 0.42 +1954 1 23.02 -1.52 25.73 0.07 28.30 0.14 27.03 0.47 +1954 2 25.00 -0.92 26.43 0.05 28.16 0.08 27.22 0.48 +1954 3 25.33 -1.05 26.85 -0.28 27.89 -0.28 27.21 -0.02 +1954 4 22.97 -2.60 25.85 -1.57 28.20 -0.19 26.87 -0.80 +1954 5 21.73 -2.69 25.67 -1.44 28.40 -0.30 27.06 -0.71 +1954 6 20.77 -2.30 25.20 -1.27 28.32 -0.35 26.93 -0.60 +1954 7 19.52 -2.46 24.47 -1.17 28.00 -0.61 26.37 -0.74 +1954 8 19.33 -1.68 23.83 -1.23 27.76 -0.73 25.73 -1.02 +1954 9 18.95 -1.82 23.51 -1.43 27.61 -0.90 25.38 -1.33 +1954 10 19.11 -1.96 23.63 -1.31 27.54 -0.97 25.51 -1.13 +1954 11 20.27 -1.47 23.86 -1.19 27.53 -0.92 25.67 -0.93 +1954 12 21.30 -1.61 23.79 -1.42 27.61 -0.74 25.37 -1.20 +1955 1 23.75 -0.79 24.79 -0.86 27.60 -0.56 25.54 -1.02 +1955 2 24.82 -1.10 25.76 -0.62 27.30 -0.77 25.90 -0.84 +1955 3 25.14 -1.23 26.35 -0.78 27.37 -0.81 26.37 -0.86 +1955 4 24.22 -1.35 26.32 -1.11 27.82 -0.57 26.66 -1.01 +1955 5 22.16 -2.26 25.52 -1.58 28.03 -0.66 26.66 -1.11 +1955 6 21.20 -1.87 25.08 -1.39 28.08 -0.59 26.56 -0.97 +1955 7 20.46 -1.52 24.55 -1.10 28.14 -0.47 26.31 -0.80 +1955 8 19.63 -1.38 23.69 -1.37 27.94 -0.55 25.60 -1.15 +1955 9 19.24 -1.53 23.36 -1.57 27.71 -0.81 25.63 -1.07 +1955 10 19.16 -1.91 22.71 -2.24 27.22 -1.29 24.66 -1.98 +1955 11 19.84 -1.90 22.66 -2.39 26.79 -1.66 24.29 -2.32 +1955 12 21.19 -1.71 23.08 -2.13 27.20 -1.15 24.58 -1.99 +1956 1 23.24 -1.30 24.47 -1.18 27.18 -0.97 25.28 -1.27 +1956 2 24.71 -1.20 25.80 -0.57 27.27 -0.81 26.00 -0.73 +1956 3 25.90 -0.47 26.84 -0.29 27.49 -0.68 26.62 -0.61 +1956 4 24.66 -0.91 27.12 -0.30 27.72 -0.68 26.96 -0.70 +1956 5 23.14 -1.28 26.63 -0.47 28.11 -0.58 27.23 -0.54 +1956 6 22.04 -1.03 25.87 -0.60 28.22 -0.46 26.99 -0.54 +1956 7 21.47 -0.51 24.82 -0.82 28.07 -0.54 26.37 -0.73 +1956 8 20.55 -0.46 24.16 -0.90 27.67 -0.82 25.91 -0.84 +1956 9 19.89 -0.88 23.97 -0.97 27.71 -0.80 25.91 -0.79 +1956 10 19.69 -1.39 24.01 -0.94 27.92 -0.59 25.83 -0.81 +1956 11 20.57 -1.17 23.91 -1.14 28.02 -0.43 25.64 -0.97 +1956 12 21.58 -1.32 24.06 -1.15 28.09 -0.26 25.71 -0.86 +1957 1 23.13 -1.40 25.05 -0.60 28.03 -0.12 26.09 -0.47 +1957 2 26.30 0.38 26.23 -0.15 28.10 0.02 26.58 -0.16 +1957 3 27.63 1.26 27.55 0.42 28.33 0.16 27.65 0.41 +1957 4 27.15 1.59 27.94 0.51 28.86 0.47 28.34 0.68 +1957 5 26.72 2.30 27.81 0.71 29.15 0.46 28.59 0.82 +1957 6 25.04 1.97 27.30 0.84 28.83 0.16 28.28 0.75 +1957 7 23.83 1.85 26.95 1.31 28.73 0.12 28.11 1.00 +1957 8 22.34 1.33 26.14 1.08 28.91 0.41 27.75 1.00 +1957 9 21.80 1.03 25.71 0.77 28.96 0.45 27.54 0.84 +1957 10 21.80 0.73 25.68 0.74 29.12 0.61 27.49 0.85 +1957 11 22.39 0.65 26.23 1.18 29.12 0.67 27.79 1.19 +1957 12 23.69 0.78 26.64 1.43 29.08 0.74 28.08 1.51 +1958 1 24.89 0.35 27.04 1.38 29.26 1.10 28.37 1.81 +1958 2 26.55 0.63 27.57 1.20 29.28 1.21 28.41 1.68 +1958 3 27.09 0.72 27.85 0.72 29.04 0.86 28.34 1.11 +1958 4 26.37 0.80 27.86 0.44 29.04 0.65 28.35 0.69 +1958 5 24.71 0.29 27.39 0.28 29.21 0.52 28.35 0.57 +1958 6 23.23 0.16 26.70 0.23 29.13 0.46 28.05 0.52 +1958 7 22.31 0.33 25.73 0.09 28.89 0.28 27.48 0.37 +1958 8 20.72 -0.29 24.97 -0.08 28.53 0.04 26.90 0.15 +1958 9 20.62 -0.14 24.45 -0.48 28.50 -0.02 26.50 -0.20 +1958 10 21.05 -0.02 24.65 -0.30 28.68 0.17 26.61 -0.03 +1958 11 21.52 -0.22 25.06 0.01 28.79 0.34 26.89 0.29 +1958 12 22.50 -0.40 25.02 -0.19 28.76 0.41 26.77 0.20 +1959 1 23.97 -0.57 25.75 0.10 28.63 0.48 27.14 0.58 +1959 2 25.90 -0.01 26.50 0.13 28.38 0.31 27.25 0.51 +1959 3 26.94 0.56 27.17 0.04 28.48 0.31 27.55 0.32 +1959 4 25.84 0.27 27.56 0.14 28.75 0.36 27.93 0.27 +1959 5 24.23 -0.19 26.94 -0.16 28.85 0.16 27.80 0.03 +1959 6 22.57 -0.50 26.07 -0.39 28.39 -0.28 27.34 -0.19 +1959 7 21.50 -0.47 24.94 -0.71 28.30 -0.31 26.56 -0.55 +1959 8 20.15 -0.86 24.40 -0.66 28.27 -0.22 26.32 -0.43 +1959 9 20.23 -0.54 24.37 -0.57 28.19 -0.32 26.17 -0.53 +1959 10 20.86 -0.21 24.67 -0.28 28.21 -0.30 26.42 -0.22 +1959 11 21.88 0.14 24.74 -0.31 28.12 -0.34 26.32 -0.28 +1959 12 22.55 -0.36 24.94 -0.27 28.07 -0.27 26.44 -0.13 +1960 1 24.40 -0.14 25.34 -0.32 27.77 -0.38 26.25 -0.31 +1960 2 25.59 -0.32 25.87 -0.50 27.49 -0.58 26.27 -0.47 +1960 3 26.01 -0.36 26.75 -0.38 27.77 -0.40 26.97 -0.26 +1960 4 24.66 -0.91 27.03 -0.39 28.08 -0.31 27.51 -0.16 +1960 5 23.53 -0.89 26.66 -0.45 28.52 -0.18 27.62 -0.16 +1960 6 21.83 -1.24 25.95 -0.52 28.35 -0.32 27.24 -0.29 +1960 7 20.73 -1.25 25.38 -0.26 28.31 -0.30 27.07 -0.04 +1960 8 20.10 -0.91 24.95 -0.11 28.19 -0.30 26.85 0.10 +1960 9 20.56 -0.20 24.70 -0.24 28.32 -0.20 26.60 -0.11 +1960 10 20.27 -0.80 24.24 -0.71 28.33 -0.17 26.35 -0.29 +1960 11 20.93 -0.81 24.31 -0.75 28.37 -0.09 26.34 -0.26 +1960 12 22.74 -0.17 24.73 -0.48 28.36 0.02 26.41 -0.16 +1961 1 24.58 0.04 25.19 -0.46 27.94 -0.21 26.38 -0.17 +1961 2 26.66 0.75 26.25 -0.13 27.85 -0.23 26.61 -0.13 +1961 3 25.95 -0.42 26.83 -0.30 27.92 -0.26 27.00 -0.24 +1961 4 25.17 -0.40 27.40 -0.02 27.96 -0.43 27.50 -0.16 +1961 5 23.60 -0.82 27.08 -0.02 28.38 -0.31 27.85 0.08 +1961 6 22.36 -0.71 26.37 -0.10 28.49 -0.18 27.86 0.33 +1961 7 20.52 -1.46 24.95 -0.70 28.33 -0.28 27.16 0.05 +1961 8 19.97 -1.04 24.20 -0.86 28.12 -0.37 26.43 -0.32 +1961 9 19.70 -1.07 23.65 -1.29 28.19 -0.33 25.97 -0.73 +1961 10 20.07 -1.01 23.89 -1.06 28.09 -0.42 25.94 -0.71 +1961 11 21.09 -0.65 24.38 -0.67 28.26 -0.19 26.20 -0.40 +1961 12 22.11 -0.80 24.75 -0.46 28.06 -0.28 26.20 -0.37 +1962 1 24.02 -0.52 25.23 -0.42 27.66 -0.49 26.12 -0.43 +1962 2 25.35 -0.56 26.07 -0.31 27.57 -0.51 26.28 -0.46 +1962 3 24.47 -1.90 26.49 -0.64 27.83 -0.34 26.80 -0.44 +1962 4 23.43 -2.14 26.59 -0.83 28.19 -0.20 27.22 -0.44 +1962 5 23.03 -1.39 26.28 -0.82 28.23 -0.47 27.23 -0.54 +1962 6 21.81 -1.26 25.83 -0.64 28.30 -0.37 27.18 -0.35 +1962 7 20.60 -1.37 25.21 -0.44 28.24 -0.37 26.93 -0.17 +1962 8 20.17 -0.84 24.72 -0.33 28.15 -0.34 26.52 -0.23 +1962 9 20.02 -0.75 24.20 -0.74 28.11 -0.40 26.07 -0.63 +1962 10 20.14 -0.93 24.23 -0.72 28.10 -0.41 26.06 -0.58 +1962 11 20.99 -0.75 24.10 -0.95 28.12 -0.33 25.88 -0.72 +1962 12 21.82 -1.09 24.12 -1.09 27.96 -0.38 25.75 -0.82 +1963 1 23.81 -0.73 24.96 -0.69 27.74 -0.41 25.86 -0.69 +1963 2 25.36 -0.55 25.91 -0.47 27.70 -0.38 26.39 -0.35 +1963 3 26.02 -0.36 27.06 -0.07 28.01 -0.16 27.31 0.08 +1963 4 24.67 -0.90 27.66 0.23 28.28 -0.11 27.87 0.20 +1963 5 23.97 -0.45 27.10 0.00 28.40 -0.30 27.71 -0.06 +1963 6 22.41 -0.66 26.74 0.27 28.38 -0.29 27.69 0.16 +1963 7 21.80 -0.18 26.36 0.71 28.72 0.11 27.91 0.80 +1963 8 21.31 0.30 25.80 0.74 29.01 0.51 27.63 0.88 +1963 9 21.00 0.23 25.41 0.48 29.03 0.52 27.47 0.76 +1963 10 21.13 0.06 25.58 0.63 29.07 0.56 27.56 0.92 +1963 11 21.64 -0.10 25.83 0.78 29.11 0.66 27.61 1.00 +1963 12 22.55 -0.35 26.08 0.87 28.87 0.52 27.71 1.14 +1964 1 24.15 -0.39 26.07 0.42 28.70 0.55 27.43 0.87 +1964 2 25.08 -0.83 26.41 0.04 28.39 0.31 27.27 0.53 +1964 3 25.30 -1.08 26.76 -0.37 28.08 -0.09 27.10 -0.13 +1964 4 24.61 -0.96 26.34 -1.09 28.24 -0.15 27.06 -0.60 +1964 5 21.93 -2.49 25.56 -1.54 28.39 -0.30 26.94 -0.84 +1964 6 21.44 -1.63 25.10 -1.37 28.06 -0.61 26.66 -0.87 +1964 7 20.25 -1.72 24.82 -0.82 27.87 -0.74 26.42 -0.69 +1964 8 19.48 -1.53 23.73 -1.33 27.64 -0.85 25.74 -1.01 +1964 9 19.67 -1.10 23.89 -1.04 27.38 -1.13 25.49 -1.22 +1964 10 19.79 -1.28 23.95 -0.99 27.38 -1.13 25.53 -1.11 +1964 11 20.88 -0.86 24.04 -1.02 27.34 -1.11 25.40 -1.20 +1964 12 21.83 -1.08 23.86 -1.35 27.25 -1.10 25.42 -1.15 +1965 1 24.22 -0.32 24.84 -0.81 27.57 -0.59 25.78 -0.77 +1965 2 26.17 0.26 25.96 -0.41 27.77 -0.31 26.37 -0.37 +1965 3 26.71 0.33 27.07 -0.06 27.93 -0.24 27.12 -0.11 +1965 4 27.01 1.45 27.66 0.23 28.06 -0.33 27.62 -0.05 +1965 5 26.09 1.67 27.68 0.57 28.70 0.01 28.07 0.29 +1965 6 24.60 1.54 27.24 0.78 29.02 0.35 28.19 0.66 +1965 7 23.26 1.29 26.64 0.99 29.08 0.47 28.02 0.91 +1965 8 22.54 1.53 26.25 1.20 29.19 0.70 28.07 1.32 +1965 9 21.26 0.49 26.07 1.13 29.11 0.60 28.03 1.32 +1965 10 21.57 0.50 26.15 1.21 29.30 0.80 28.26 1.62 +1965 11 22.29 0.55 26.50 1.45 29.17 0.72 28.29 1.69 +1965 12 23.35 0.44 26.59 1.38 29.03 0.68 28.07 1.50 +1966 1 25.15 0.62 26.70 1.05 28.87 0.71 27.75 1.19 +1966 2 25.88 -0.03 26.86 0.49 28.85 0.78 27.66 0.92 +1966 3 25.35 -1.02 27.26 0.13 29.18 1.01 28.22 0.99 +1966 4 24.26 -1.31 27.40 -0.03 28.99 0.60 28.24 0.58 +1966 5 22.92 -1.50 26.28 -0.82 29.08 0.39 27.67 -0.10 +1966 6 21.80 -1.27 26.08 -0.39 29.13 0.46 27.77 0.24 +1966 7 20.85 -1.13 25.42 -0.22 29.03 0.42 27.42 0.31 +1966 8 20.17 -0.84 24.51 -0.55 28.76 0.27 26.65 -0.10 +1966 9 20.04 -0.73 24.17 -0.77 28.71 0.20 26.49 -0.22 +1966 10 20.51 -0.56 24.42 -0.53 28.57 0.06 26.40 -0.25 +1966 11 21.03 -0.71 24.26 -0.79 28.65 0.20 26.42 -0.19 +1966 12 22.25 -0.66 24.30 -0.91 28.27 -0.07 26.21 -0.36 +1967 1 23.66 -0.88 25.09 -0.56 27.69 -0.46 26.18 -0.38 +1967 2 25.54 -0.37 26.09 -0.28 27.48 -0.60 26.35 -0.39 +1967 3 25.55 -0.83 26.46 -0.67 27.78 -0.39 26.67 -0.56 +1967 4 24.98 -0.59 26.46 -0.96 28.40 0.01 26.91 -0.76 +1967 5 23.77 -0.65 26.69 -0.41 28.80 0.11 27.49 -0.28 +1967 6 22.04 -1.03 26.40 -0.07 28.69 0.02 27.62 0.09 +1967 7 21.10 -0.88 25.32 -0.32 28.62 0.01 27.17 0.06 +1967 8 19.84 -1.17 24.30 -0.76 28.42 -0.07 26.62 -0.13 +1967 9 19.08 -1.68 23.69 -1.25 28.19 -0.32 26.10 -0.60 +1967 10 19.47 -1.60 23.80 -1.14 28.32 -0.19 26.19 -0.45 +1967 11 20.20 -1.54 24.01 -1.04 28.43 -0.02 26.26 -0.34 +1967 12 21.28 -1.62 24.14 -1.07 28.27 -0.08 26.10 -0.47 +1968 1 23.19 -1.35 24.40 -1.25 27.92 -0.24 25.78 -0.78 +1968 2 24.88 -1.04 25.00 -1.38 27.80 -0.28 25.79 -0.95 +1968 3 25.11 -1.27 25.86 -1.27 27.87 -0.30 26.38 -0.85 +1968 4 23.97 -1.60 26.57 -0.85 28.16 -0.24 27.09 -0.58 +1968 5 22.44 -1.98 26.19 -0.92 28.30 -0.40 27.15 -0.62 +1968 6 21.70 -1.36 26.22 -0.25 28.90 0.23 27.69 0.16 +1968 7 21.25 -0.72 26.00 0.35 28.70 0.09 27.61 0.51 +1968 8 20.97 -0.04 25.28 0.22 28.68 0.19 27.12 0.37 +1968 9 21.23 0.46 24.96 0.02 28.66 0.15 26.90 0.19 +1968 10 21.12 0.05 25.17 0.22 28.77 0.26 26.99 0.34 +1968 11 21.68 -0.06 25.35 0.29 29.17 0.72 27.38 0.78 +1968 12 23.20 0.29 25.79 0.58 29.17 0.83 27.42 0.85 +1969 1 24.67 0.13 26.27 0.62 29.11 0.95 27.55 0.99 +1969 2 25.56 -0.36 26.92 0.54 29.28 1.20 27.95 1.21 +1969 3 27.09 0.72 27.63 0.50 28.99 0.82 28.02 0.79 +1969 4 26.66 1.10 27.94 0.52 29.03 0.64 28.39 0.73 +1969 5 26.07 1.65 27.92 0.81 29.21 0.52 28.50 0.73 +1969 6 24.39 1.32 27.05 0.58 29.09 0.42 27.99 0.46 +1969 7 22.47 0.50 25.84 0.19 28.85 0.24 27.30 0.20 +1969 8 21.06 0.05 25.41 0.35 28.93 0.44 27.16 0.41 +1969 9 20.88 0.12 25.46 0.52 29.14 0.63 27.34 0.63 +1969 10 21.74 0.67 25.69 0.75 29.20 0.69 27.50 0.86 +1969 11 22.47 0.73 25.75 0.70 29.20 0.75 27.35 0.74 +1969 12 23.60 0.69 26.16 0.95 28.87 0.52 27.30 0.73 +1970 1 25.02 0.48 26.38 0.73 28.57 0.42 27.05 0.50 +1970 2 25.76 -0.16 26.52 0.14 28.57 0.50 27.02 0.29 +1970 3 25.53 -0.85 26.97 -0.16 28.52 0.35 27.35 0.12 +1970 4 24.76 -0.81 27.20 -0.23 28.73 0.34 27.96 0.29 +1970 5 22.94 -1.48 26.44 -0.66 28.97 0.28 27.77 0.00 +1970 6 21.27 -1.80 25.30 -1.17 28.75 0.08 27.14 -0.39 +1970 7 19.69 -2.28 24.18 -1.47 28.66 0.05 26.48 -0.63 +1970 8 19.27 -1.74 23.69 -1.37 28.16 -0.34 25.86 -0.89 +1970 9 19.50 -1.26 23.89 -1.05 27.88 -0.64 25.86 -0.84 +1970 10 20.16 -0.91 23.80 -1.14 27.86 -0.65 25.79 -0.85 +1970 11 20.61 -1.13 23.78 -1.28 27.91 -0.54 25.83 -0.77 +1970 12 21.77 -1.13 24.01 -1.20 27.44 -0.91 25.47 -1.10 +1971 1 23.33 -1.21 24.19 -1.47 26.94 -1.21 25.09 -1.46 +1971 2 24.58 -1.34 24.91 -1.47 27.07 -1.00 25.40 -1.34 +1971 3 25.24 -1.13 26.01 -1.11 27.25 -0.92 26.10 -1.13 +1971 4 24.95 -0.62 26.61 -0.81 27.63 -0.76 26.78 -0.89 +1971 5 23.29 -1.13 26.26 -0.85 28.02 -0.67 27.06 -0.71 +1971 6 21.60 -1.47 25.44 -1.03 28.03 -0.64 26.70 -0.83 +1971 7 21.01 -0.96 24.78 -0.86 27.93 -0.68 26.29 -0.82 +1971 8 19.97 -1.04 23.90 -1.16 27.84 -0.66 25.99 -0.76 +1971 9 19.74 -1.03 23.92 -1.02 27.75 -0.77 25.94 -0.76 +1971 10 19.88 -1.19 23.73 -1.21 27.80 -0.71 25.65 -0.99 +1971 11 20.94 -0.80 23.93 -1.12 27.87 -0.58 25.69 -0.91 +1971 12 21.99 -0.92 23.92 -1.29 27.98 -0.36 25.55 -1.02 +1972 1 24.51 -0.03 25.02 -0.63 27.97 -0.19 25.84 -0.72 +1972 2 26.66 0.75 26.04 -0.34 28.15 0.07 26.42 -0.32 +1972 3 27.09 0.72 27.12 -0.01 28.36 0.19 27.21 -0.02 +1972 4 26.25 0.68 27.78 0.35 28.82 0.43 27.93 0.26 +1972 5 25.47 1.05 27.62 0.52 29.21 0.52 28.27 0.49 +1972 6 25.01 1.95 27.37 0.90 29.19 0.52 28.23 0.70 +1972 7 24.11 2.13 27.14 1.49 29.09 0.48 28.18 1.07 +1972 8 23.42 2.41 26.86 1.81 28.92 0.43 28.10 1.35 +1972 9 22.12 1.35 26.48 1.54 29.10 0.58 28.10 1.40 +1972 10 22.58 1.51 26.83 1.89 29.44 0.93 28.46 1.82 +1972 11 23.32 1.58 27.17 2.11 29.48 1.03 28.69 2.09 +1972 12 24.89 1.99 27.60 2.39 29.35 1.00 28.81 2.24 +1973 1 26.03 1.49 27.52 1.86 29.03 0.88 28.44 1.88 +1973 2 26.48 0.56 27.24 0.87 28.77 0.70 28.00 1.26 +1973 3 26.27 -0.10 27.37 0.24 28.52 0.35 27.71 0.48 +1973 4 24.87 -0.70 26.87 -0.55 28.39 0.00 27.39 -0.28 +1973 5 23.44 -0.98 26.06 -1.04 28.51 -0.18 27.13 -0.65 +1973 6 21.76 -1.31 25.34 -1.12 28.23 -0.44 26.74 -0.79 +1973 7 20.84 -1.14 24.31 -1.34 28.01 -0.60 25.95 -1.16 +1973 8 19.47 -1.54 23.69 -1.36 27.65 -0.84 25.46 -1.29 +1973 9 19.49 -1.28 23.56 -1.38 27.53 -0.98 25.32 -1.39 +1973 10 19.80 -1.27 23.49 -1.46 27.32 -1.19 25.03 -1.61 +1973 11 20.71 -1.03 23.35 -1.71 26.97 -1.48 24.50 -2.11 +1973 12 21.74 -1.17 23.40 -1.81 26.69 -1.65 24.43 -2.14 +1974 1 23.29 -1.25 23.93 -1.72 26.50 -1.65 24.52 -2.04 +1974 2 24.87 -1.04 25.11 -1.27 26.87 -1.21 25.12 -1.61 +1974 3 25.69 -0.68 26.28 -0.85 27.21 -0.96 25.91 -1.32 +1974 4 25.28 -0.29 26.84 -0.58 27.46 -0.93 26.63 -1.03 +1974 5 24.35 -0.07 26.56 -0.54 27.94 -0.75 26.84 -0.93 +1974 6 22.48 -0.58 25.91 -0.55 27.97 -0.70 26.71 -0.82 +1974 7 21.58 -0.40 25.30 -0.35 27.83 -0.78 26.48 -0.63 +1974 8 20.73 -0.28 24.82 -0.24 27.97 -0.52 26.37 -0.38 +1974 9 20.15 -0.62 24.38 -0.56 27.91 -0.61 26.23 -0.47 +1974 10 19.88 -1.19 24.14 -0.81 27.74 -0.77 25.92 -0.73 +1974 11 20.68 -1.06 24.07 -0.98 27.72 -0.73 25.63 -0.97 +1974 12 21.41 -1.50 24.31 -0.90 27.61 -0.74 25.70 -0.87 +1975 1 23.55 -0.99 25.34 -0.31 27.86 -0.30 26.18 -0.37 +1975 2 24.95 -0.97 25.74 -0.64 27.96 -0.12 26.22 -0.52 +1975 3 26.06 -0.32 26.49 -0.64 27.76 -0.41 26.44 -0.79 +1975 4 25.53 -0.04 27.08 -0.34 27.83 -0.56 26.99 -0.67 +1975 5 23.71 -0.72 26.27 -0.83 27.95 -0.74 26.97 -0.80 +1975 6 21.84 -1.22 25.29 -1.18 27.71 -0.96 26.29 -1.24 +1975 7 21.05 -0.92 24.72 -0.93 27.57 -1.04 25.98 -1.12 +1975 8 19.97 -1.04 24.15 -0.91 27.29 -1.21 25.47 -1.28 +1975 9 19.14 -1.63 23.67 -1.27 26.91 -1.60 25.20 -1.50 +1975 10 19.17 -1.90 23.40 -1.54 26.76 -1.75 24.87 -1.77 +1975 11 19.44 -2.30 23.73 -1.33 26.80 -1.66 25.10 -1.50 +1975 12 21.05 -1.85 23.39 -1.82 26.84 -1.50 24.76 -1.81 +1976 1 23.51 -1.02 23.91 -1.74 26.92 -1.23 24.72 -1.84 +1976 2 25.36 -0.56 25.31 -1.07 27.19 -0.89 25.58 -1.16 +1976 3 25.88 -0.49 26.46 -0.66 27.56 -0.61 26.61 -0.62 +1976 4 25.72 0.15 26.94 -0.49 27.98 -0.42 26.99 -0.67 +1976 5 25.11 0.69 26.98 -0.12 28.32 -0.37 27.27 -0.50 +1976 6 24.46 1.39 26.95 0.48 28.32 -0.35 27.34 -0.19 +1976 7 23.30 1.33 26.29 0.65 28.42 -0.19 27.26 0.16 +1976 8 21.91 0.90 25.87 0.81 28.34 -0.15 27.09 0.34 +1976 9 21.56 0.79 25.76 0.83 28.50 -0.01 27.12 0.42 +1976 10 21.69 0.62 25.97 1.03 28.82 0.31 27.48 0.84 +1976 11 22.14 0.40 25.93 0.87 28.92 0.47 27.42 0.82 +1976 12 23.29 0.39 25.91 0.70 28.45 0.10 27.17 0.60 +1977 1 24.93 0.39 26.57 0.92 28.38 0.23 27.31 0.76 +1977 2 25.79 -0.13 27.03 0.65 28.11 0.04 27.15 0.41 +1977 3 26.13 -0.24 27.51 0.38 28.28 0.10 27.57 0.34 +1977 4 25.29 -0.28 27.02 -0.41 28.50 0.10 27.61 -0.05 +1977 5 23.88 -0.54 27.04 -0.06 28.78 0.09 27.97 0.19 +1977 6 22.70 -0.37 26.56 0.09 28.97 0.30 27.96 0.43 +1977 7 21.63 -0.34 25.70 0.05 29.13 0.52 27.56 0.45 +1977 8 20.25 -0.76 24.81 -0.25 28.87 0.38 26.93 0.18 +1977 9 19.82 -0.95 24.97 0.04 28.98 0.47 27.21 0.50 +1977 10 20.61 -0.46 25.34 0.39 28.96 0.45 27.37 0.73 +1977 11 21.29 -0.45 25.41 0.35 29.10 0.65 27.28 0.67 +1977 12 22.47 -0.44 25.54 0.33 29.11 0.76 27.37 0.80 +1978 1 24.32 -0.22 25.92 0.27 28.80 0.65 27.32 0.77 +1978 2 25.77 -0.15 26.46 0.09 28.48 0.41 27.17 0.43 +1978 3 25.39 -0.98 26.83 -0.30 28.26 0.09 27.24 0.01 +1978 4 24.73 -0.84 26.66 -0.77 28.28 -0.11 27.26 -0.41 +1978 5 23.15 -1.27 26.13 -0.97 28.72 0.03 27.36 -0.42 +1978 6 21.89 -1.18 25.68 -0.79 28.56 -0.11 27.16 -0.37 +1978 7 21.01 -0.96 25.08 -0.57 28.26 -0.35 26.81 -0.29 +1978 8 19.66 -1.35 24.35 -0.71 28.25 -0.24 26.23 -0.52 +1978 9 19.98 -0.79 24.33 -0.61 28.43 -0.08 26.20 -0.50 +1978 10 20.22 -0.86 24.72 -0.22 28.35 -0.16 26.40 -0.24 +1978 11 21.62 -0.12 24.94 -0.11 28.37 -0.09 26.43 -0.17 +1978 12 22.94 0.03 25.34 0.13 28.27 -0.08 26.48 -0.09 +1979 1 24.71 0.17 25.43 -0.23 28.40 0.25 26.45 -0.11 +1979 2 25.60 -0.32 26.19 -0.19 28.22 0.14 26.60 -0.13 +1979 3 25.93 -0.44 27.25 0.12 28.26 0.09 27.48 0.25 +1979 4 25.58 0.01 27.66 0.23 28.35 -0.05 27.87 0.20 +1979 5 24.52 0.10 27.26 0.16 28.70 0.01 27.74 -0.03 +1979 6 23.28 0.22 26.54 0.08 28.74 0.07 27.55 0.02 +1979 7 21.79 -0.19 25.56 -0.09 28.66 0.05 26.95 -0.15 +1979 8 21.05 0.04 25.29 0.23 28.36 -0.13 26.77 0.02 +1979 9 21.15 0.39 25.58 0.65 28.67 0.16 27.15 0.45 +1979 10 21.43 0.36 25.54 0.60 28.81 0.31 27.01 0.36 +1979 11 21.95 0.21 25.58 0.53 28.87 0.42 27.08 0.48 +1979 12 22.97 0.07 25.68 0.47 28.79 0.45 27.09 0.52 +1980 1 24.35 -0.18 26.12 0.47 28.62 0.47 27.10 0.54 +1980 2 25.73 -0.18 26.52 0.15 28.47 0.39 27.03 0.29 +1980 3 26.46 0.08 27.05 -0.07 28.51 0.34 27.38 0.15 +1980 4 25.71 0.14 27.33 -0.10 28.70 0.30 27.78 0.12 +1980 5 24.46 0.04 27.15 0.05 29.08 0.39 27.99 0.21 +1980 6 22.88 -0.19 26.76 0.29 29.15 0.48 27.99 0.46 +1980 7 21.26 -0.71 25.65 0.00 28.95 0.34 27.35 0.24 +1980 8 20.57 -0.44 24.87 -0.19 28.47 -0.02 26.62 -0.13 +1980 9 20.45 -0.32 24.86 -0.08 28.50 -0.01 26.57 -0.13 +1980 10 20.43 -0.64 24.62 -0.32 28.66 0.15 26.51 -0.13 +1980 11 21.23 -0.51 25.07 0.02 28.58 0.13 26.63 0.03 +1980 12 22.34 -0.56 25.28 0.07 28.44 0.10 26.58 0.01 +1981 1 22.98 -1.56 25.05 -0.61 28.08 -0.08 26.17 -0.39 +1981 2 24.90 -1.01 25.63 -0.75 27.94 -0.14 26.13 -0.60 +1981 3 25.94 -0.43 26.74 -0.39 28.08 -0.09 26.75 -0.48 +1981 4 24.89 -0.68 27.10 -0.32 28.17 -0.22 27.32 -0.34 +1981 5 23.90 -0.52 26.74 -0.37 28.34 -0.35 27.41 -0.36 +1981 6 22.57 -0.50 26.26 -0.20 28.36 -0.31 27.35 -0.18 +1981 7 21.10 -0.87 25.26 -0.39 28.29 -0.32 26.66 -0.44 +1981 8 20.03 -0.98 24.43 -0.63 28.22 -0.28 26.25 -0.50 +1981 9 20.09 -0.68 24.74 -0.20 28.30 -0.22 26.54 -0.17 +1981 10 20.58 -0.49 24.92 -0.03 28.45 -0.06 26.52 -0.12 +1981 11 21.26 -0.48 24.83 -0.22 28.47 0.02 26.41 -0.19 +1981 12 22.60 -0.30 25.23 0.03 28.43 0.09 26.47 -0.10 +1982 1 24.36 -0.18 25.96 0.30 28.19 0.03 26.69 0.14 +1982 2 25.42 -0.49 26.55 0.17 28.04 -0.04 26.71 -0.02 +1982 3 25.40 -0.98 27.06 -0.07 28.37 0.19 27.36 0.13 +1982 4 24.96 -0.61 27.52 0.10 28.78 0.39 27.90 0.24 +1982 5 24.21 -0.21 27.66 0.56 29.21 0.52 28.42 0.65 +1982 6 23.35 0.29 27.31 0.84 29.20 0.53 28.32 0.79 +1982 7 22.50 0.52 26.33 0.68 28.83 0.22 27.65 0.54 +1982 8 21.89 0.88 26.21 1.15 28.81 0.32 27.64 0.89 +1982 9 22.04 1.27 26.82 1.88 28.98 0.47 28.21 1.50 +1982 10 22.88 1.81 27.31 2.37 29.37 0.86 28.68 2.04 +1982 11 24.57 2.83 27.68 2.63 29.18 0.73 28.72 2.11 +1982 12 25.89 2.98 28.23 3.02 29.13 0.79 28.94 2.37 +1983 1 27.25 2.71 28.60 2.95 28.96 0.81 28.93 2.37 +1983 2 28.23 2.32 28.63 2.26 28.80 0.73 28.75 2.01 +1983 3 28.85 2.48 28.91 1.78 28.81 0.64 28.76 1.53 +1983 4 28.82 3.25 29.06 1.63 28.81 0.42 28.74 1.07 +1983 5 28.37 3.95 28.98 1.87 29.21 0.51 28.82 1.05 +1983 6 27.43 4.36 28.19 1.72 28.98 0.31 28.27 0.74 +1983 7 25.73 3.75 26.66 1.01 28.64 0.03 27.18 0.07 +1983 8 23.88 2.87 25.78 0.72 28.35 -0.14 26.51 -0.24 +1983 9 22.26 1.49 25.02 0.09 28.05 -0.46 26.18 -0.52 +1983 10 22.22 1.15 24.48 -0.46 27.92 -0.59 25.75 -0.89 +1983 11 22.21 0.47 24.19 -0.86 27.73 -0.73 25.54 -1.06 +1983 12 23.19 0.29 24.58 -0.63 27.75 -0.59 25.82 -0.75 +1984 1 24.32 -0.21 25.30 -0.35 27.64 -0.51 26.14 -0.42 +1984 2 25.12 -0.79 26.43 0.05 27.60 -0.48 26.72 -0.02 +1984 3 25.75 -0.63 27.14 0.01 27.59 -0.58 27.05 -0.19 +1984 4 25.40 -0.17 27.24 -0.18 27.78 -0.61 27.30 -0.37 +1984 5 23.58 -0.84 26.38 -0.72 28.19 -0.51 27.31 -0.47 +1984 6 22.30 -0.77 25.50 -0.97 28.38 -0.29 26.95 -0.58 +1984 7 21.53 -0.44 25.04 -0.60 28.47 -0.14 26.84 -0.26 +1984 8 20.64 -0.37 24.81 -0.25 28.30 -0.19 26.67 -0.08 +1984 9 20.73 -0.04 24.63 -0.30 28.26 -0.25 26.43 -0.27 +1984 10 20.62 -0.45 24.34 -0.61 28.19 -0.32 26.15 -0.49 +1984 11 21.70 -0.04 24.23 -0.83 27.92 -0.53 25.60 -1.00 +1984 12 22.47 -0.44 24.10 -1.11 27.60 -0.74 25.38 -1.19 +1985 1 23.84 -0.70 24.68 -0.97 27.55 -0.60 25.58 -0.98 +1985 2 24.83 -1.08 25.65 -0.72 27.68 -0.39 26.11 -0.63 +1985 3 25.60 -0.77 26.45 -0.68 27.59 -0.58 26.53 -0.71 +1985 4 24.28 -1.29 26.63 -0.79 27.78 -0.61 26.93 -0.74 +1985 5 22.67 -1.75 26.26 -0.84 27.99 -0.70 27.09 -0.68 +1985 6 21.84 -1.23 25.66 -0.81 28.09 -0.58 26.92 -0.61 +1985 7 20.75 -1.23 24.72 -0.93 28.32 -0.30 26.64 -0.46 +1985 8 19.90 -1.11 24.12 -0.94 28.34 -0.16 26.28 -0.47 +1985 9 19.86 -0.91 24.05 -0.88 28.32 -0.20 26.08 -0.62 +1985 10 20.26 -0.81 24.23 -0.71 28.40 -0.11 26.22 -0.42 +1985 11 20.97 -0.77 24.40 -0.65 28.48 0.03 26.39 -0.22 +1985 12 22.49 -0.41 24.56 -0.65 28.39 0.05 26.19 -0.38 +1986 1 24.31 -0.23 24.99 -0.67 27.96 -0.19 26.04 -0.52 +1986 2 25.90 -0.02 26.04 -0.33 27.95 -0.13 26.26 -0.48 +1986 3 25.78 -0.59 26.92 -0.21 28.11 -0.06 26.99 -0.24 +1986 4 24.86 -0.71 27.30 -0.13 28.23 -0.17 27.65 -0.02 +1986 5 23.35 -1.07 26.78 -0.32 28.53 -0.17 27.58 -0.20 +1986 6 22.03 -1.04 26.27 -0.20 28.76 0.09 27.56 0.03 +1986 7 21.64 -0.33 25.82 0.18 28.75 0.14 27.39 0.28 +1986 8 21.07 0.06 25.38 0.33 28.95 0.46 27.21 0.46 +1986 9 21.13 0.36 25.38 0.44 29.20 0.69 27.35 0.65 +1986 10 21.46 0.39 25.65 0.70 29.27 0.76 27.60 0.95 +1986 11 22.17 0.43 25.94 0.88 29.33 0.88 27.67 1.07 +1986 12 23.53 0.63 26.26 1.05 28.97 0.63 27.75 1.18 +1987 1 25.60 1.07 26.74 1.09 28.81 0.65 27.82 1.27 +1987 2 27.02 1.10 27.60 1.23 28.82 0.74 28.02 1.29 +1987 3 27.89 1.51 28.38 1.26 28.95 0.77 28.49 1.26 +1987 4 26.95 1.38 28.63 1.20 28.97 0.58 28.68 1.02 +1987 5 25.96 1.53 28.30 1.19 29.24 0.55 28.70 0.93 +1987 6 24.04 0.97 27.51 1.04 29.44 0.77 28.67 1.14 +1987 7 23.00 1.03 26.94 1.30 29.37 0.76 28.52 1.42 +1987 8 21.92 0.91 26.59 1.53 29.40 0.91 28.48 1.73 +1987 9 22.00 1.23 26.62 1.68 29.47 0.96 28.42 1.71 +1987 10 22.54 1.47 26.19 1.25 29.67 1.17 28.08 1.43 +1987 11 22.84 1.10 26.21 1.16 29.53 1.08 27.94 1.34 +1987 12 23.51 0.60 26.33 1.12 29.25 0.90 27.60 1.03 +1988 1 24.76 0.22 26.47 0.82 28.97 0.81 27.49 0.94 +1988 2 25.74 -0.18 26.43 0.05 28.54 0.46 27.01 0.28 +1988 3 25.71 -0.66 27.10 -0.03 28.46 0.29 27.45 0.22 +1988 4 24.68 -0.89 27.01 -0.41 28.41 0.02 27.56 -0.10 +1988 5 23.18 -1.24 25.88 -1.22 28.26 -0.43 26.97 -0.80 +1988 6 21.66 -1.41 24.61 -1.86 28.00 -0.67 26.21 -1.32 +1988 7 20.59 -1.38 23.79 -1.85 27.95 -0.67 25.66 -1.45 +1988 8 19.63 -1.38 23.71 -1.35 28.07 -0.43 25.71 -1.04 +1988 9 19.44 -1.32 23.88 -1.06 27.90 -0.61 25.72 -0.99 +1988 10 19.83 -1.24 23.41 -1.53 27.12 -1.39 24.82 -1.82 +1988 11 20.96 -0.78 23.45 -1.61 27.06 -1.39 24.73 -1.87 +1988 12 22.25 -0.66 23.50 -1.71 26.85 -1.49 24.68 -1.89 +1989 1 24.36 -0.18 24.27 -1.38 26.63 -1.52 24.70 -1.86 +1989 2 26.02 0.10 25.49 -0.89 26.75 -1.33 25.34 -1.40 +1989 3 26.21 -0.17 26.23 -0.90 27.25 -0.93 26.12 -1.12 +1989 4 25.54 -0.03 26.85 -0.57 27.71 -0.68 26.83 -0.83 +1989 5 23.36 -1.06 26.58 -0.53 28.24 -0.46 27.18 -0.60 +1989 6 22.14 -0.93 26.42 -0.05 28.12 -0.55 27.23 -0.30 +1989 7 21.27 -0.70 25.32 -0.32 28.23 -0.38 26.80 -0.31 +1989 8 20.86 -0.15 24.73 -0.33 28.10 -0.39 26.43 -0.32 +1989 9 20.17 -0.60 24.67 -0.27 28.37 -0.14 26.46 -0.24 +1989 10 20.52 -0.55 24.61 -0.34 28.27 -0.24 26.31 -0.34 +1989 11 21.44 -0.30 24.56 -0.49 28.10 -0.36 26.29 -0.31 +1989 12 22.61 -0.30 24.92 -0.29 28.51 0.17 26.58 0.01 +1990 1 24.22 -0.32 25.45 -0.20 28.49 0.33 26.63 0.07 +1990 2 26.17 0.26 26.54 0.16 28.58 0.50 27.03 0.29 +1990 3 26.15 -0.22 27.01 -0.12 28.69 0.51 27.39 0.16 +1990 4 25.15 -0.42 27.56 0.14 28.83 0.44 27.94 0.27 +1990 5 24.14 -0.29 27.42 0.32 28.93 0.23 28.08 0.30 +1990 6 22.76 -0.31 26.55 0.08 28.97 0.30 27.63 0.10 +1990 7 21.36 -0.61 25.82 0.18 29.01 0.40 27.42 0.31 +1990 8 20.70 -0.31 25.32 0.26 28.99 0.49 27.16 0.41 +1990 9 20.28 -0.49 25.15 0.21 28.92 0.41 26.96 0.25 +1990 10 20.40 -0.67 24.96 0.02 29.10 0.59 27.01 0.37 +1990 11 21.19 -0.55 25.00 -0.06 29.13 0.68 26.88 0.28 +1990 12 22.29 -0.61 25.23 0.02 29.16 0.81 26.96 0.39 +1991 1 23.99 -0.55 25.84 0.19 28.96 0.81 27.07 0.51 +1991 2 25.59 -0.33 26.50 0.12 28.71 0.63 27.12 0.38 +1991 3 26.31 -0.06 27.12 -0.01 28.58 0.40 27.38 0.15 +1991 4 25.15 -0.42 27.65 0.22 28.94 0.55 28.10 0.44 +1991 5 24.44 0.02 27.64 0.54 29.37 0.68 28.36 0.58 +1991 6 23.28 0.21 27.43 0.96 29.28 0.61 28.41 0.88 +1991 7 22.39 0.42 26.75 1.10 29.27 0.66 28.17 1.07 +1991 8 21.39 0.38 25.71 0.65 29.23 0.74 27.73 0.98 +1991 9 21.22 0.45 25.32 0.39 29.24 0.73 27.42 0.71 +1991 10 21.73 0.66 25.63 0.69 29.44 0.93 27.62 0.98 +1991 11 22.40 0.66 26.10 1.04 29.40 0.95 27.93 1.33 +1991 12 23.75 0.85 26.42 1.21 29.46 1.12 28.32 1.75 +1992 1 25.02 0.48 27.03 1.38 29.03 0.87 28.36 1.81 +1992 2 26.62 0.71 27.61 1.23 29.00 0.92 28.43 1.69 +1992 3 27.72 1.34 28.22 1.09 29.03 0.86 28.66 1.42 +1992 4 27.58 2.01 28.79 1.37 29.16 0.77 29.05 1.39 +1992 5 26.44 2.02 28.49 1.38 29.39 0.70 29.01 1.24 +1992 6 23.86 0.79 27.28 0.82 29.28 0.60 28.35 0.82 +1992 7 21.84 -0.14 25.84 0.19 29.15 0.54 27.56 0.45 +1992 8 20.87 -0.14 25.11 0.06 28.92 0.43 26.96 0.21 +1992 9 20.85 0.08 24.90 -0.03 28.83 0.32 26.66 -0.04 +1992 10 21.15 0.08 24.65 -0.29 28.69 0.18 26.39 -0.25 +1992 11 21.84 0.10 24.77 -0.29 28.67 0.21 26.60 0.00 +1992 12 22.79 -0.12 24.97 -0.24 28.82 0.47 26.72 0.15 +1993 1 24.68 0.15 25.79 0.14 28.71 0.56 26.87 0.31 +1993 2 26.46 0.55 26.94 0.57 28.37 0.29 27.20 0.46 +1993 3 27.07 0.69 27.64 0.51 28.50 0.32 27.71 0.48 +1993 4 26.84 1.28 28.43 1.00 28.78 0.38 28.50 0.83 +1993 5 25.60 1.18 28.33 1.23 29.03 0.34 28.70 0.93 +1993 6 24.11 1.04 27.03 0.56 29.03 0.36 28.08 0.55 +1993 7 22.61 0.64 26.19 0.54 29.01 0.40 27.59 0.49 +1993 8 21.65 0.64 25.52 0.46 28.86 0.37 27.01 0.26 +1993 9 21.11 0.34 25.25 0.31 29.02 0.51 27.14 0.43 +1993 10 21.71 0.64 25.28 0.33 28.84 0.33 27.01 0.36 +1993 11 22.07 0.33 25.20 0.14 28.88 0.43 26.92 0.32 +1993 12 22.86 -0.05 25.30 0.09 28.85 0.50 26.79 0.22 +1994 1 24.56 0.02 25.84 0.18 28.54 0.39 26.74 0.19 +1994 2 25.89 -0.03 26.40 0.02 28.27 0.20 26.97 0.23 +1994 3 25.75 -0.62 26.88 -0.24 28.46 0.28 27.52 0.29 +1994 4 24.49 -1.08 27.15 -0.28 28.82 0.43 28.13 0.46 +1994 5 23.52 -0.90 27.17 0.06 29.20 0.51 28.27 0.50 +1994 6 22.31 -0.76 26.63 0.17 29.27 0.60 28.09 0.56 +1994 7 21.17 -0.80 25.61 -0.04 29.49 0.88 27.68 0.57 +1994 8 20.22 -0.79 24.93 -0.13 29.51 1.02 27.40 0.65 +1994 9 20.65 -0.12 24.97 0.03 29.38 0.87 27.25 0.54 +1994 10 22.04 0.97 25.65 0.70 29.51 1.00 27.53 0.89 +1994 11 22.27 0.53 26.17 1.12 29.60 1.15 27.95 1.35 +1994 12 23.75 0.85 26.23 1.02 29.56 1.22 28.02 1.45 +1995 1 25.48 0.94 26.51 0.86 29.24 1.09 27.74 1.18 +1995 2 26.25 0.33 26.90 0.52 29.16 1.09 27.67 0.94 +1995 3 26.09 -0.28 27.26 0.13 29.23 1.05 27.91 0.68 +1995 4 24.32 -1.25 27.20 -0.23 29.26 0.87 28.17 0.50 +1995 5 23.37 -1.05 26.55 -0.55 29.36 0.67 27.87 0.10 +1995 6 22.43 -0.64 26.30 -0.17 29.21 0.54 27.80 0.27 +1995 7 21.42 -0.55 25.65 0.00 29.03 0.42 27.24 0.14 +1995 8 20.46 -0.55 24.36 -0.70 28.81 0.32 26.42 -0.33 +1995 9 20.50 -0.27 24.05 -0.89 28.59 0.08 26.20 -0.50 +1995 10 20.62 -0.45 24.16 -0.78 28.52 0.01 26.08 -0.57 +1995 11 21.49 -0.25 24.22 -0.84 28.32 -0.13 25.82 -0.78 +1995 12 22.03 -0.87 24.45 -0.76 28.13 -0.22 25.86 -0.71 +1996 1 23.81 -0.73 25.06 -0.59 27.89 -0.27 25.83 -0.73 +1996 2 25.52 -0.40 25.84 -0.54 27.61 -0.46 25.98 -0.76 +1996 3 26.28 -0.09 26.75 -0.38 27.91 -0.27 26.73 -0.50 +1996 4 24.00 -1.57 26.83 -0.59 28.25 -0.15 27.42 -0.25 +1996 5 23.11 -1.31 26.63 -0.47 28.62 -0.07 27.65 -0.12 +1996 6 21.66 -1.41 26.10 -0.37 28.71 0.04 27.49 -0.04 +1996 7 20.72 -1.26 25.29 -0.36 28.65 0.04 27.02 -0.09 +1996 8 20.23 -0.78 24.78 -0.28 28.62 0.12 26.75 0.00 +1996 9 20.43 -0.34 24.53 -0.41 28.57 0.05 26.44 -0.27 +1996 10 20.52 -0.55 24.52 -0.42 28.62 0.11 26.49 -0.15 +1996 11 20.77 -0.97 24.56 -0.49 28.62 0.17 26.43 -0.17 +1996 12 21.68 -1.22 24.31 -0.90 28.52 0.18 26.13 -0.44 +1997 1 23.70 -0.83 24.80 -0.85 28.42 0.26 26.09 -0.47 +1997 2 26.08 0.16 25.78 -0.60 28.53 0.45 26.46 -0.28 +1997 3 27.17 0.80 26.97 -0.16 28.73 0.56 27.13 -0.10 +1997 4 26.74 1.17 27.50 0.07 29.33 0.94 27.97 0.31 +1997 5 26.77 2.35 28.03 0.92 29.51 0.82 28.63 0.85 +1997 6 26.15 3.08 28.23 1.76 29.37 0.70 28.86 1.33 +1997 7 25.59 3.61 27.99 2.34 29.41 0.80 28.86 1.76 +1997 8 24.95 3.94 27.75 2.69 29.31 0.82 28.69 1.94 +1997 9 24.69 3.92 27.82 2.88 29.54 1.03 28.89 2.19 +1997 10 24.64 3.57 28.09 3.15 29.51 1.00 29.14 2.50 +1997 11 25.85 4.11 28.40 3.35 29.45 1.00 29.13 2.52 +1997 12 27.08 4.18 28.53 3.32 29.27 0.93 29.04 2.48 +1998 1 28.12 3.58 28.71 3.06 29.06 0.91 28.98 2.43 +1998 2 28.82 2.90 28.86 2.48 28.90 0.82 28.71 1.97 +1998 3 29.24 2.87 29.10 1.97 28.83 0.66 28.66 1.43 +1998 4 28.45 2.88 29.16 1.74 28.77 0.38 28.64 0.98 +1998 5 27.36 2.94 28.53 1.42 28.87 0.18 28.47 0.70 +1998 6 25.19 2.12 27.04 0.57 28.46 -0.21 27.41 -0.12 +1998 7 23.61 1.64 25.60 -0.05 28.30 -0.31 26.52 -0.59 +1998 8 22.27 1.26 24.78 -0.28 27.99 -0.50 25.91 -0.84 +1998 9 21.31 0.54 24.19 -0.75 27.83 -0.68 25.66 -1.05 +1998 10 21.37 0.30 24.08 -0.86 27.51 -1.00 25.46 -1.19 +1998 11 21.60 -0.14 24.40 -0.66 27.41 -1.04 25.48 -1.12 +1998 12 22.81 -0.10 24.25 -0.96 27.19 -1.16 25.12 -1.45 +1999 1 24.23 -0.31 24.41 -1.24 26.89 -1.26 24.96 -1.59 +1999 2 25.73 -0.19 25.56 -0.82 26.90 -1.18 25.58 -1.16 +1999 3 26.47 0.10 26.81 -0.32 27.14 -1.04 26.43 -0.80 +1999 4 24.53 -1.04 26.90 -0.52 27.66 -0.73 26.92 -0.75 +1999 5 23.64 -0.78 26.55 -0.56 28.14 -0.55 26.99 -0.78 +1999 6 22.09 -0.98 25.89 -0.58 28.05 -0.62 26.66 -0.87 +1999 7 21.36 -0.61 25.03 -0.62 27.89 -0.72 26.28 -0.83 +1999 8 20.67 -0.34 24.36 -0.70 27.77 -0.73 25.82 -0.93 +1999 9 20.08 -0.69 23.91 -1.03 27.96 -0.56 25.77 -0.94 +1999 10 20.46 -0.61 23.77 -1.18 27.93 -0.58 25.62 -1.03 +1999 11 20.62 -1.12 23.72 -1.34 27.54 -0.91 25.20 -1.40 +1999 12 22.42 -0.48 23.76 -1.45 27.30 -1.05 24.97 -1.60 +2000 1 24.01 -0.53 24.12 -1.53 27.17 -0.99 24.88 -1.68 +2000 2 25.38 -0.54 25.35 -1.03 26.88 -1.20 25.23 -1.50 +2000 3 25.67 -0.70 26.78 -0.35 26.95 -1.22 26.27 -0.96 +2000 4 25.53 -0.04 27.46 0.04 27.40 -0.99 26.99 -0.68 +2000 5 24.27 -0.15 26.85 -0.26 27.90 -0.79 27.10 -0.67 +2000 6 22.93 -0.13 26.01 -0.46 28.25 -0.42 26.97 -0.56 +2000 7 21.47 -0.50 25.24 -0.41 28.41 -0.20 26.69 -0.41 +2000 8 20.07 -0.94 24.74 -0.31 28.28 -0.21 26.46 -0.29 +2000 9 20.64 -0.13 24.73 -0.21 28.37 -0.14 26.32 -0.39 +2000 10 20.90 -0.17 24.60 -0.34 28.27 -0.24 26.11 -0.53 +2000 11 20.67 -1.07 24.43 -0.62 28.06 -0.39 26.01 -0.59 +2000 12 22.08 -0.83 24.73 -0.48 27.66 -0.68 25.83 -0.74 +2001 1 24.24 -0.29 25.37 -0.29 27.49 -0.66 25.93 -0.63 +2001 2 26.11 0.20 26.38 0.01 27.38 -0.70 26.24 -0.49 +2001 3 26.89 0.52 27.31 0.18 27.68 -0.50 26.89 -0.35 +2001 4 25.99 0.42 27.52 0.09 28.16 -0.23 27.38 -0.28 +2001 5 23.98 -0.44 27.21 0.11 28.65 -0.04 27.70 -0.08 +2001 6 22.71 -0.36 26.44 -0.03 28.91 0.24 27.60 0.07 +2001 7 21.48 -0.50 25.63 -0.02 29.12 0.51 27.37 0.26 +2001 8 20.24 -0.77 25.03 -0.03 28.98 0.48 26.95 0.20 +2001 9 19.73 -1.04 24.49 -0.45 29.11 0.60 26.74 0.04 +2001 10 20.14 -0.93 24.59 -0.36 29.08 0.58 26.66 0.02 +2001 11 20.68 -1.06 24.53 -0.53 28.93 0.48 26.47 -0.13 +2001 12 21.73 -1.17 24.79 -0.42 28.77 0.42 26.32 -0.25 +2002 1 24.09 -0.45 25.23 -0.42 28.84 0.69 26.49 -0.07 +2002 2 26.23 0.31 26.22 -0.15 28.70 0.63 26.83 0.09 +2002 3 27.39 1.01 27.51 0.38 28.62 0.44 27.48 0.25 +2002 4 26.44 0.87 27.71 0.28 29.14 0.75 28.00 0.34 +2002 5 25.29 0.87 27.68 0.58 29.61 0.92 28.44 0.66 +2002 6 23.28 0.21 27.30 0.83 29.58 0.91 28.48 0.95 +2002 7 21.64 -0.34 26.31 0.67 29.53 0.92 28.03 0.93 +2002 8 21.32 0.31 25.62 0.56 29.41 0.92 27.67 0.92 +2002 9 21.42 0.65 25.69 0.75 29.41 0.90 27.75 1.05 +2002 10 21.85 0.78 25.94 1.00 29.52 1.01 27.95 1.31 +2002 11 22.85 1.11 26.43 1.37 29.66 1.21 28.14 1.54 +2002 12 24.05 1.15 26.62 1.41 29.57 1.23 28.08 1.52 +2003 1 25.01 0.47 26.68 1.02 29.09 0.94 27.68 1.12 +2003 2 26.27 0.35 27.01 0.63 28.94 0.86 27.63 0.89 +2003 3 26.91 0.53 27.48 0.35 28.95 0.78 27.84 0.61 +2003 4 25.41 -0.15 27.22 -0.20 28.94 0.55 27.75 0.08 +2003 5 23.24 -1.18 26.44 -0.66 29.01 0.32 27.42 -0.36 +2003 6 22.15 -0.91 26.20 -0.27 29.17 0.50 27.56 0.03 +2003 7 21.50 -0.48 26.16 0.52 29.19 0.58 27.66 0.55 +2003 8 21.25 0.24 25.65 0.59 29.09 0.59 27.32 0.57 +2003 9 20.75 -0.02 25.20 0.26 29.05 0.54 27.10 0.40 +2003 10 21.70 0.63 25.58 0.63 29.22 0.71 27.33 0.69 +2003 11 22.33 0.59 25.85 0.80 29.08 0.62 27.13 0.53 +2003 12 23.60 0.70 26.07 0.86 28.97 0.63 27.04 0.47 +2004 1 25.09 0.55 26.23 0.58 28.71 0.56 26.90 0.35 +2004 2 26.47 0.55 26.81 0.44 28.61 0.53 27.04 0.31 +2004 3 26.12 -0.26 27.47 0.34 28.53 0.36 27.38 0.15 +2004 4 25.27 -0.30 27.62 0.19 28.82 0.43 27.91 0.24 +2004 5 23.44 -0.98 26.96 -0.14 29.18 0.49 28.02 0.24 +2004 6 22.54 -0.53 26.55 0.08 29.24 0.57 27.93 0.40 +2004 7 21.26 -0.72 25.94 0.30 29.36 0.75 27.86 0.75 +2004 8 20.79 -0.22 25.47 0.41 29.47 0.98 27.67 0.92 +2004 9 20.83 0.06 25.42 0.48 29.54 1.02 27.58 0.88 +2004 10 21.56 0.49 25.64 0.70 29.53 1.03 27.53 0.89 +2004 11 22.88 1.14 25.84 0.79 29.49 1.04 27.37 0.77 +2004 12 23.39 0.49 25.95 0.74 29.41 1.07 27.38 0.81 +2005 1 24.61 0.07 26.10 0.45 29.23 1.08 27.32 0.76 +2005 2 25.09 -0.83 26.38 0.00 28.91 0.83 27.17 0.43 +2005 3 25.23 -1.14 27.12 -0.01 28.89 0.71 27.63 0.40 +2005 4 25.21 -0.36 27.62 0.20 29.03 0.64 28.02 0.36 +2005 5 24.31 -0.11 27.56 0.46 29.24 0.55 28.30 0.52 +2005 6 22.60 -0.47 26.86 0.39 29.20 0.53 27.99 0.46 +2005 7 21.61 -0.37 26.07 0.42 28.93 0.32 27.45 0.34 +2005 8 20.47 -0.54 25.44 0.38 28.78 0.29 27.11 0.36 +2005 9 20.00 -0.77 24.88 -0.05 28.85 0.34 26.79 0.09 +2005 10 19.89 -1.18 24.83 -0.12 28.85 0.34 26.70 0.06 +2005 11 20.61 -1.13 23.92 -1.14 28.65 0.19 26.13 -0.48 +2005 12 22.20 -0.70 24.01 -1.20 28.34 0.00 25.80 -0.77 +2006 1 24.76 0.22 24.66 -0.99 27.91 -0.25 25.68 -0.87 +2006 2 26.52 0.60 26.02 -0.35 27.58 -0.50 26.15 -0.59 +2006 3 26.22 -0.15 26.83 -0.30 27.82 -0.35 26.80 -0.43 +2006 4 24.29 -1.28 27.18 -0.24 28.36 -0.04 27.54 -0.13 +2006 5 23.84 -0.58 27.30 0.19 28.91 0.21 27.91 0.13 +2006 6 22.82 -0.24 26.73 0.27 29.15 0.48 27.82 0.29 +2006 7 22.20 0.22 25.93 0.28 29.14 0.53 27.36 0.25 +2006 8 21.89 0.88 25.68 0.62 29.20 0.71 27.25 0.50 +2006 9 21.93 1.16 25.77 0.83 29.30 0.79 27.32 0.61 +2006 10 22.46 1.39 26.00 1.06 29.43 0.92 27.47 0.83 +2006 11 22.61 0.87 26.39 1.33 29.55 1.09 27.81 1.21 +2006 12 24.15 1.24 26.63 1.42 29.45 1.11 27.86 1.29 +2007 1 25.82 1.28 26.68 1.03 28.98 0.82 27.36 0.81 +2007 2 26.81 0.90 26.56 0.18 28.69 0.61 26.98 0.24 +2007 3 26.41 0.04 26.77 -0.36 28.81 0.64 27.25 0.02 +2007 4 24.96 -0.61 26.93 -0.50 28.88 0.49 27.56 -0.10 +2007 5 23.05 -1.37 26.40 -0.70 28.90 0.21 27.54 -0.23 +2007 6 21.61 -1.46 26.11 -0.35 28.92 0.25 27.54 0.01 +2007 7 21.05 -0.93 25.14 -0.51 28.80 0.19 26.99 -0.12 +2007 8 19.95 -1.06 24.24 -0.82 28.57 0.08 26.41 -0.34 +2007 9 19.85 -0.91 23.84 -1.10 28.21 -0.31 25.86 -0.84 +2007 10 19.31 -1.76 23.85 -1.09 28.09 -0.42 25.73 -0.92 +2007 11 19.82 -1.92 23.76 -1.30 27.90 -0.56 25.47 -1.14 +2007 12 21.15 -1.76 23.91 -1.30 27.70 -0.64 25.40 -1.17 +2008 1 24.24 -0.30 24.42 -1.23 27.18 -0.98 25.06 -1.50 +2008 2 26.39 0.47 25.34 -1.04 26.79 -1.29 25.19 -1.55 +2008 3 26.91 0.53 26.54 -0.59 27.22 -0.95 26.16 -1.07 +2008 4 25.68 0.12 27.36 -0.07 27.53 -0.86 26.97 -0.70 +2008 5 24.43 0.00 27.15 0.05 27.93 -0.76 27.19 -0.58 +2008 6 23.19 0.12 26.49 0.02 28.10 -0.57 27.15 -0.38 +2008 7 23.02 1.05 26.01 0.36 28.18 -0.43 27.00 -0.11 +2008 8 22.14 1.13 25.56 0.51 28.27 -0.22 26.81 0.06 +2008 9 21.60 0.84 25.36 0.42 28.25 -0.27 26.70 0.00 +2008 10 21.39 0.32 25.48 0.53 28.23 -0.28 26.66 0.02 +2008 11 21.54 -0.20 25.25 0.20 28.16 -0.29 26.52 -0.08 +2008 12 22.73 -0.18 24.59 -0.62 27.83 -0.52 25.78 -0.79 +2009 1 24.39 -0.15 25.26 -0.39 27.47 -0.69 25.69 -0.87 +2009 2 25.53 -0.38 26.16 -0.22 27.34 -0.74 26.02 -0.71 +2009 3 25.48 -0.89 26.62 -0.51 27.85 -0.32 26.66 -0.57 +2009 4 25.84 0.27 27.38 -0.04 28.36 -0.03 27.53 -0.13 +2009 5 24.95 0.52 27.57 0.47 29.09 0.40 28.10 0.33 +2009 6 24.09 1.02 27.15 0.68 29.15 0.48 28.06 0.53 +2009 7 23.09 1.12 26.56 0.91 29.13 0.52 27.88 0.78 +2009 8 22.03 1.02 25.90 0.84 29.20 0.71 27.51 0.76 +2009 9 21.48 0.71 25.74 0.80 29.24 0.73 27.48 0.78 +2009 10 21.64 0.57 25.82 0.87 29.68 1.17 27.73 1.09 +2009 11 21.99 0.25 26.13 1.07 29.90 1.44 28.17 1.57 +2009 12 23.21 0.31 26.69 1.48 29.80 1.45 28.51 1.94 +2010 1 24.70 0.17 26.86 1.21 29.58 1.42 28.32 1.76 +2010 2 26.16 0.24 27.37 1.00 29.25 1.18 28.19 1.45 +2010 3 26.54 0.16 28.04 0.91 29.18 1.01 28.46 1.23 +2010 4 26.04 0.47 28.08 0.66 29.28 0.89 28.49 0.82 +2010 5 24.75 0.33 27.34 0.24 29.27 0.57 28.13 0.36 +2010 6 23.26 0.19 26.32 -0.15 28.76 0.09 27.35 -0.18 +2010 7 21.11 -0.87 24.95 -0.70 28.33 -0.28 26.44 -0.67 +2010 8 19.49 -1.52 24.21 -0.85 27.82 -0.68 25.70 -1.05 +2010 9 19.28 -1.49 23.83 -1.11 27.47 -1.05 25.36 -1.34 +2010 10 19.73 -1.34 23.67 -1.28 27.35 -1.16 25.25 -1.40 +2010 11 20.44 -1.30 23.68 -1.37 27.47 -0.99 25.20 -1.41 +2010 12 22.07 -0.83 24.00 -1.21 27.54 -0.81 25.29 -1.28 diff --git a/shared/package-files/33/334bd92019e33c11d5e2f1549cf0482daaa247f7204ae539d24141fafee5d600/test_numbers.py b/shared/package-files/33/334bd92019e33c11d5e2f1549cf0482daaa247f7204ae539d24141fafee5d600/test_numbers.py new file mode 100644 index 0000000000000000000000000000000000000000..f8f350719cc740901a29d03e45ae9f3978446f31 --- /dev/null +++ b/shared/package-files/33/334bd92019e33c11d5e2f1549cf0482daaa247f7204ae539d24141fafee5d600/test_numbers.py @@ -0,0 +1,202 @@ +"""Tests on algebraic numbers. """ + +from sympy.core.containers import Tuple +from sympy.core.numbers import (AlgebraicNumber, I, Rational) +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.polys.polytools import Poly +from sympy.polys.numberfields.subfield import to_number_field +from sympy.polys.polyclasses import DMP +from sympy.polys.domains import QQ +from sympy.polys.rootoftools import CRootOf +from sympy.abc import x, y + + +def test_AlgebraicNumber(): + minpoly, root = x**2 - 2, sqrt(2) + + a = AlgebraicNumber(root, gen=x) + + assert a.rep == DMP([QQ(1), QQ(0)], QQ) + assert a.root == root + assert a.alias is None + assert a.minpoly == minpoly + assert a.is_number + + assert a.is_aliased is False + + assert a.coeffs() == [S.One, S.Zero] + assert a.native_coeffs() == [QQ(1), QQ(0)] + + a = AlgebraicNumber(root, gen=x, alias='y') + + assert a.rep == DMP([QQ(1), QQ(0)], QQ) + assert a.root == root + assert a.alias == Symbol('y') + assert a.minpoly == minpoly + assert a.is_number + + assert a.is_aliased is True + + a = AlgebraicNumber(root, gen=x, alias=Symbol('y')) + + assert a.rep == DMP([QQ(1), QQ(0)], QQ) + assert a.root == root + assert a.alias == Symbol('y') + assert a.minpoly == minpoly + assert a.is_number + + assert a.is_aliased is True + + assert AlgebraicNumber(sqrt(2), []).rep == DMP([], QQ) + assert AlgebraicNumber(sqrt(2), ()).rep == DMP([], QQ) + assert AlgebraicNumber(sqrt(2), (0, 0)).rep == DMP([], QQ) + + assert AlgebraicNumber(sqrt(2), [8]).rep == DMP([QQ(8)], QQ) + assert AlgebraicNumber(sqrt(2), [Rational(8, 3)]).rep == DMP([QQ(8, 3)], QQ) + + assert AlgebraicNumber(sqrt(2), [7, 3]).rep == DMP([QQ(7), QQ(3)], QQ) + assert AlgebraicNumber( + sqrt(2), [Rational(7, 9), Rational(3, 2)]).rep == DMP([QQ(7, 9), QQ(3, 2)], QQ) + + assert AlgebraicNumber(sqrt(2), [1, 2, 3]).rep == DMP([QQ(2), QQ(5)], QQ) + + a = AlgebraicNumber(AlgebraicNumber(root, gen=x), [1, 2]) + + assert a.rep == DMP([QQ(1), QQ(2)], QQ) + assert a.root == root + assert a.alias is None + assert a.minpoly == minpoly + assert a.is_number + + assert a.is_aliased is False + + assert a.coeffs() == [S.One, S(2)] + assert a.native_coeffs() == [QQ(1), QQ(2)] + + a = AlgebraicNumber((minpoly, root), [1, 2]) + + assert a.rep == DMP([QQ(1), QQ(2)], QQ) + assert a.root == root + assert a.alias is None + assert a.minpoly == minpoly + assert a.is_number + + assert a.is_aliased is False + + a = AlgebraicNumber((Poly(minpoly), root), [1, 2]) + + assert a.rep == DMP([QQ(1), QQ(2)], QQ) + assert a.root == root + assert a.alias is None + assert a.minpoly == minpoly + assert a.is_number + + assert a.is_aliased is False + + assert AlgebraicNumber( sqrt(3)).rep == DMP([ QQ(1), QQ(0)], QQ) + assert AlgebraicNumber(-sqrt(3)).rep == DMP([ QQ(1), QQ(0)], QQ) + + a = AlgebraicNumber(sqrt(2)) + b = AlgebraicNumber(sqrt(2)) + + assert a == b + + c = AlgebraicNumber(sqrt(2), gen=x) + + assert a == b + assert a == c + + a = AlgebraicNumber(sqrt(2), [1, 2]) + b = AlgebraicNumber(sqrt(2), [1, 3]) + + assert a != b and a != sqrt(2) + 3 + + assert (a == x) is False and (a != x) is True + + a = AlgebraicNumber(sqrt(2), [1, 0]) + b = AlgebraicNumber(sqrt(2), [1, 0], alias=y) + + assert a.as_poly(x) == Poly(x, domain='QQ') + assert b.as_poly() == Poly(y, domain='QQ') + + assert a.as_expr() == sqrt(2) + assert a.as_expr(x) == x + assert b.as_expr() == sqrt(2) + assert b.as_expr(x) == x + + a = AlgebraicNumber(sqrt(2), [2, 3]) + b = AlgebraicNumber(sqrt(2), [2, 3], alias=y) + + p = a.as_poly() + + assert p == Poly(2*p.gen + 3) + + assert a.as_poly(x) == Poly(2*x + 3, domain='QQ') + assert b.as_poly() == Poly(2*y + 3, domain='QQ') + + assert a.as_expr() == 2*sqrt(2) + 3 + assert a.as_expr(x) == 2*x + 3 + assert b.as_expr() == 2*sqrt(2) + 3 + assert b.as_expr(x) == 2*x + 3 + + a = AlgebraicNumber(sqrt(2)) + b = to_number_field(sqrt(2)) + assert a.args == b.args == (sqrt(2), Tuple(1, 0)) + b = AlgebraicNumber(sqrt(2), alias='alpha') + assert b.args == (sqrt(2), Tuple(1, 0), Symbol('alpha')) + + a = AlgebraicNumber(sqrt(2), [1, 2, 3]) + assert a.args == (sqrt(2), Tuple(1, 2, 3)) + + a = AlgebraicNumber(sqrt(2), [1, 2], "alpha") + b = AlgebraicNumber(a) + c = AlgebraicNumber(a, alias="gamma") + assert a == b + assert c.alias.name == "gamma" + + a = AlgebraicNumber(sqrt(2) + sqrt(3), [S(1)/2, 0, S(-9)/2, 0]) + b = AlgebraicNumber(a, [1, 0, 0]) + assert b.root == a.root + assert a.to_root() == sqrt(2) + assert b.to_root() == 2 + + a = AlgebraicNumber(2) + assert a.is_primitive_element is True + + +def test_to_algebraic_integer(): + a = AlgebraicNumber(sqrt(3), gen=x).to_algebraic_integer() + + assert a.minpoly == x**2 - 3 + assert a.root == sqrt(3) + assert a.rep == DMP([QQ(1), QQ(0)], QQ) + + a = AlgebraicNumber(2*sqrt(3), gen=x).to_algebraic_integer() + assert a.minpoly == x**2 - 12 + assert a.root == 2*sqrt(3) + assert a.rep == DMP([QQ(1), QQ(0)], QQ) + + a = AlgebraicNumber(sqrt(3)/2, gen=x).to_algebraic_integer() + + assert a.minpoly == x**2 - 12 + assert a.root == 2*sqrt(3) + assert a.rep == DMP([QQ(1), QQ(0)], QQ) + + a = AlgebraicNumber(sqrt(3)/2, [Rational(7, 19), 3], gen=x).to_algebraic_integer() + + assert a.minpoly == x**2 - 12 + assert a.root == 2*sqrt(3) + assert a.rep == DMP([QQ(7, 19), QQ(3)], QQ) + + +def test_AlgebraicNumber_to_root(): + assert AlgebraicNumber(sqrt(2)).to_root() == sqrt(2) + + zeta5_squared = AlgebraicNumber(CRootOf(x**5 - 1, 4), coeffs=[1, 0, 0]) + assert zeta5_squared.to_root() == CRootOf(x**4 + x**3 + x**2 + x + 1, 1) + + zeta3_squared = AlgebraicNumber(CRootOf(x**3 - 1, 2), coeffs=[1, 0, 0]) + assert zeta3_squared.to_root() == -S(1)/2 - sqrt(3)*I/2 + assert zeta3_squared.to_root(radicals=False) == CRootOf(x**2 + x + 1, 0) diff --git a/shared/package-files/33/334f71e0cc7a85c040c24b6fc2fd7a62f3d19acb838d9103c074f452691c832a/Center b/shared/package-files/33/334f71e0cc7a85c040c24b6fc2fd7a62f3d19acb838d9103c074f452691c832a/Center new file mode 100644 index 0000000000000000000000000000000000000000..d03bda045d31662adc65450b33e9665c54fdb245 Binary files /dev/null and b/shared/package-files/33/334f71e0cc7a85c040c24b6fc2fd7a62f3d19acb838d9103c074f452691c832a/Center differ diff --git a/shared/package-files/33/3352c161f9ce47e35e01d8cdd20fb76753cfd89e71cbc402c338099e1f13c26d/_neg_view_compositeexplicitautograd_dispatch.h b/shared/package-files/33/3352c161f9ce47e35e01d8cdd20fb76753cfd89e71cbc402c338099e1f13c26d/_neg_view_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..37530952213f8af0b831467f6a5638b54e03bdc3 --- /dev/null +++ b/shared/package-files/33/3352c161f9ce47e35e01d8cdd20fb76753cfd89e71cbc402c338099e1f13c26d/_neg_view_compositeexplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor _neg_view(const at::Tensor & self); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/33/3353358982c168f4c099f0d278b065bc3af648d7a61dc7708c70c56b2d3fa1a3/regression.py b/shared/package-files/33/3353358982c168f4c099f0d278b065bc3af648d7a61dc7708c70c56b2d3fa1a3/regression.py new file mode 100644 index 0000000000000000000000000000000000000000..5e5503a422820191a124fa9a08b6d1319faffd6f --- /dev/null +++ b/shared/package-files/33/3353358982c168f4c099f0d278b065bc3af648d7a61dc7708c70c56b2d3fa1a3/regression.py @@ -0,0 +1,940 @@ +"""Plotting functions for linear models (broadly construed).""" +import copy +from textwrap import dedent +import warnings +import numpy as np +import pandas as pd +import matplotlib as mpl +import matplotlib.pyplot as plt + +try: + import statsmodels + assert statsmodels + _has_statsmodels = True +except ImportError: + _has_statsmodels = False + +from . import utils +from . import algorithms as algo +from .axisgrid import FacetGrid, _facet_docs + + +__all__ = ["lmplot", "regplot", "residplot"] + + +class _LinearPlotter: + """Base class for plotting relational data in tidy format. + + To get anything useful done you'll have to inherit from this, but setup + code that can be abstracted out should be put here. + + """ + def establish_variables(self, data, **kws): + """Extract variables from data or use directly.""" + self.data = data + + # Validate the inputs + any_strings = any([isinstance(v, str) for v in kws.values()]) + if any_strings and data is None: + raise ValueError("Must pass `data` if using named variables.") + + # Set the variables + for var, val in kws.items(): + if isinstance(val, str): + vector = data[val] + elif isinstance(val, list): + vector = np.asarray(val) + else: + vector = val + if vector is not None and vector.shape != (1,): + vector = np.squeeze(vector) + if np.ndim(vector) > 1: + err = "regplot inputs must be 1d" + raise ValueError(err) + setattr(self, var, vector) + + def dropna(self, *vars): + """Remove observations with missing data.""" + vals = [getattr(self, var) for var in vars] + vals = [v for v in vals if v is not None] + not_na = np.all(np.column_stack([pd.notnull(v) for v in vals]), axis=1) + for var in vars: + val = getattr(self, var) + if val is not None: + setattr(self, var, val[not_na]) + + def plot(self, ax): + raise NotImplementedError + + +class _RegressionPlotter(_LinearPlotter): + """Plotter for numeric independent variables with regression model. + + This does the computations and drawing for the `regplot` function, and + is thus also used indirectly by `lmplot`. + """ + def __init__(self, x, y, data=None, x_estimator=None, x_bins=None, + x_ci="ci", scatter=True, fit_reg=True, ci=95, n_boot=1000, + units=None, seed=None, order=1, logistic=False, lowess=False, + robust=False, logx=False, x_partial=None, y_partial=None, + truncate=False, dropna=True, x_jitter=None, y_jitter=None, + color=None, label=None): + + # Set member attributes + self.x_estimator = x_estimator + self.ci = ci + self.x_ci = ci if x_ci == "ci" else x_ci + self.n_boot = n_boot + self.seed = seed + self.scatter = scatter + self.fit_reg = fit_reg + self.order = order + self.logistic = logistic + self.lowess = lowess + self.robust = robust + self.logx = logx + self.truncate = truncate + self.x_jitter = x_jitter + self.y_jitter = y_jitter + self.color = color + self.label = label + + # Validate the regression options: + if sum((order > 1, logistic, robust, lowess, logx)) > 1: + raise ValueError("Mutually exclusive regression options.") + + # Extract the data vals from the arguments or passed dataframe + self.establish_variables(data, x=x, y=y, units=units, + x_partial=x_partial, y_partial=y_partial) + + # Drop null observations + if dropna: + self.dropna("x", "y", "units", "x_partial", "y_partial") + + # Regress nuisance variables out of the data + if self.x_partial is not None: + self.x = self.regress_out(self.x, self.x_partial) + if self.y_partial is not None: + self.y = self.regress_out(self.y, self.y_partial) + + # Possibly bin the predictor variable, which implies a point estimate + if x_bins is not None: + self.x_estimator = np.mean if x_estimator is None else x_estimator + x_discrete, x_bins = self.bin_predictor(x_bins) + self.x_discrete = x_discrete + else: + self.x_discrete = self.x + + # Disable regression in case of singleton inputs + if len(self.x) <= 1: + self.fit_reg = False + + # Save the range of the x variable for the grid later + if self.fit_reg: + self.x_range = self.x.min(), self.x.max() + + @property + def scatter_data(self): + """Data where each observation is a point.""" + x_j = self.x_jitter + if x_j is None: + x = self.x + else: + x = self.x + np.random.uniform(-x_j, x_j, len(self.x)) + + y_j = self.y_jitter + if y_j is None: + y = self.y + else: + y = self.y + np.random.uniform(-y_j, y_j, len(self.y)) + + return x, y + + @property + def estimate_data(self): + """Data with a point estimate and CI for each discrete x value.""" + x, y = self.x_discrete, self.y + vals = sorted(np.unique(x)) + points, cis = [], [] + + for val in vals: + + # Get the point estimate of the y variable + _y = y[x == val] + est = self.x_estimator(_y) + points.append(est) + + # Compute the confidence interval for this estimate + if self.x_ci is None: + cis.append(None) + else: + units = None + if self.x_ci == "sd": + sd = np.std(_y) + _ci = est - sd, est + sd + else: + if self.units is not None: + units = self.units[x == val] + boots = algo.bootstrap(_y, + func=self.x_estimator, + n_boot=self.n_boot, + units=units, + seed=self.seed) + _ci = utils.ci(boots, self.x_ci) + cis.append(_ci) + + return vals, points, cis + + def _check_statsmodels(self): + """Check whether statsmodels is installed if any boolean options require it.""" + options = "logistic", "robust", "lowess" + err = "`{}=True` requires statsmodels, an optional dependency, to be installed." + for option in options: + if getattr(self, option) and not _has_statsmodels: + raise RuntimeError(err.format(option)) + + def fit_regression(self, ax=None, x_range=None, grid=None): + """Fit the regression model.""" + self._check_statsmodels() + + # Create the grid for the regression + if grid is None: + if self.truncate: + x_min, x_max = self.x_range + else: + if ax is None: + x_min, x_max = x_range + else: + x_min, x_max = ax.get_xlim() + grid = np.linspace(x_min, x_max, 100) + ci = self.ci + + # Fit the regression + if self.order > 1: + yhat, yhat_boots = self.fit_poly(grid, self.order) + elif self.logistic: + from statsmodels.genmod.generalized_linear_model import GLM + from statsmodels.genmod.families import Binomial + yhat, yhat_boots = self.fit_statsmodels(grid, GLM, + family=Binomial()) + elif self.lowess: + ci = None + grid, yhat = self.fit_lowess() + elif self.robust: + from statsmodels.robust.robust_linear_model import RLM + yhat, yhat_boots = self.fit_statsmodels(grid, RLM) + elif self.logx: + yhat, yhat_boots = self.fit_logx(grid) + else: + yhat, yhat_boots = self.fit_fast(grid) + + # Compute the confidence interval at each grid point + if ci is None: + err_bands = None + else: + err_bands = utils.ci(yhat_boots, ci, axis=0) + + return grid, yhat, err_bands + + def fit_fast(self, grid): + """Low-level regression and prediction using linear algebra.""" + def reg_func(_x, _y): + return np.linalg.pinv(_x).dot(_y) + + X, y = np.c_[np.ones(len(self.x)), self.x], self.y + grid = np.c_[np.ones(len(grid)), grid] + yhat = grid.dot(reg_func(X, y)) + if self.ci is None: + return yhat, None + + beta_boots = algo.bootstrap(X, y, + func=reg_func, + n_boot=self.n_boot, + units=self.units, + seed=self.seed).T + yhat_boots = grid.dot(beta_boots).T + return yhat, yhat_boots + + def fit_poly(self, grid, order): + """Regression using numpy polyfit for higher-order trends.""" + def reg_func(_x, _y): + return np.polyval(np.polyfit(_x, _y, order), grid) + + x, y = self.x, self.y + yhat = reg_func(x, y) + if self.ci is None: + return yhat, None + + yhat_boots = algo.bootstrap(x, y, + func=reg_func, + n_boot=self.n_boot, + units=self.units, + seed=self.seed) + return yhat, yhat_boots + + def fit_statsmodels(self, grid, model, **kwargs): + """More general regression function using statsmodels objects.""" + import statsmodels.tools.sm_exceptions as sme + X, y = np.c_[np.ones(len(self.x)), self.x], self.y + grid = np.c_[np.ones(len(grid)), grid] + + def reg_func(_x, _y): + err_classes = (sme.PerfectSeparationError,) + try: + with warnings.catch_warnings(): + if hasattr(sme, "PerfectSeparationWarning"): + # statsmodels>=0.14.0 + warnings.simplefilter("error", sme.PerfectSeparationWarning) + err_classes = (*err_classes, sme.PerfectSeparationWarning) + yhat = model(_y, _x, **kwargs).fit().predict(grid) + except err_classes: + yhat = np.empty(len(grid)) + yhat.fill(np.nan) + return yhat + + yhat = reg_func(X, y) + if self.ci is None: + return yhat, None + + yhat_boots = algo.bootstrap(X, y, + func=reg_func, + n_boot=self.n_boot, + units=self.units, + seed=self.seed) + return yhat, yhat_boots + + def fit_lowess(self): + """Fit a locally-weighted regression, which returns its own grid.""" + from statsmodels.nonparametric.smoothers_lowess import lowess + grid, yhat = lowess(self.y, self.x).T + return grid, yhat + + def fit_logx(self, grid): + """Fit the model in log-space.""" + X, y = np.c_[np.ones(len(self.x)), self.x], self.y + grid = np.c_[np.ones(len(grid)), np.log(grid)] + + def reg_func(_x, _y): + _x = np.c_[_x[:, 0], np.log(_x[:, 1])] + return np.linalg.pinv(_x).dot(_y) + + yhat = grid.dot(reg_func(X, y)) + if self.ci is None: + return yhat, None + + beta_boots = algo.bootstrap(X, y, + func=reg_func, + n_boot=self.n_boot, + units=self.units, + seed=self.seed).T + yhat_boots = grid.dot(beta_boots).T + return yhat, yhat_boots + + def bin_predictor(self, bins): + """Discretize a predictor by assigning value to closest bin.""" + x = np.asarray(self.x) + if np.isscalar(bins): + percentiles = np.linspace(0, 100, bins + 2)[1:-1] + bins = np.percentile(x, percentiles) + else: + bins = np.ravel(bins) + + dist = np.abs(np.subtract.outer(x, bins)) + x_binned = bins[np.argmin(dist, axis=1)].ravel() + + return x_binned, bins + + def regress_out(self, a, b): + """Regress b from a keeping a's original mean.""" + a_mean = a.mean() + a = a - a_mean + b = b - b.mean() + b = np.c_[b] + a_prime = a - b.dot(np.linalg.pinv(b).dot(a)) + return np.asarray(a_prime + a_mean).reshape(a.shape) + + def plot(self, ax, scatter_kws, line_kws): + """Draw the full plot.""" + # Insert the plot label into the correct set of keyword arguments + if self.scatter: + scatter_kws["label"] = self.label + else: + line_kws["label"] = self.label + + # Use the current color cycle state as a default + if self.color is None: + lines, = ax.plot([], []) + color = lines.get_color() + lines.remove() + else: + color = self.color + + # Ensure that color is hex to avoid matplotlib weirdness + color = mpl.colors.rgb2hex(mpl.colors.colorConverter.to_rgb(color)) + + # Let color in keyword arguments override overall plot color + scatter_kws.setdefault("color", color) + line_kws.setdefault("color", color) + + # Draw the constituent plots + if self.scatter: + self.scatterplot(ax, scatter_kws) + + if self.fit_reg: + self.lineplot(ax, line_kws) + + # Label the axes + if hasattr(self.x, "name"): + ax.set_xlabel(self.x.name) + if hasattr(self.y, "name"): + ax.set_ylabel(self.y.name) + + def scatterplot(self, ax, kws): + """Draw the data.""" + # Treat the line-based markers specially, explicitly setting larger + # linewidth than is provided by the seaborn style defaults. + # This would ideally be handled better in matplotlib (i.e., distinguish + # between edgewidth for solid glyphs and linewidth for line glyphs + # but this should do for now. + line_markers = ["1", "2", "3", "4", "+", "x", "|", "_"] + if self.x_estimator is None: + if "marker" in kws and kws["marker"] in line_markers: + lw = mpl.rcParams["lines.linewidth"] + else: + lw = mpl.rcParams["lines.markeredgewidth"] + kws.setdefault("linewidths", lw) + + if not hasattr(kws['color'], 'shape') or kws['color'].shape[1] < 4: + kws.setdefault("alpha", .8) + + x, y = self.scatter_data + ax.scatter(x, y, **kws) + else: + # TODO abstraction + ci_kws = {"color": kws["color"]} + if "alpha" in kws: + ci_kws["alpha"] = kws["alpha"] + ci_kws["linewidth"] = mpl.rcParams["lines.linewidth"] * 1.75 + kws.setdefault("s", 50) + + xs, ys, cis = self.estimate_data + if [ci for ci in cis if ci is not None]: + for x, ci in zip(xs, cis): + ax.plot([x, x], ci, **ci_kws) + ax.scatter(xs, ys, **kws) + + def lineplot(self, ax, kws): + """Draw the model.""" + # Fit the regression model + grid, yhat, err_bands = self.fit_regression(ax) + edges = grid[0], grid[-1] + + # Get set default aesthetics + fill_color = kws["color"] + lw = kws.pop("lw", mpl.rcParams["lines.linewidth"] * 1.5) + kws.setdefault("linewidth", lw) + + # Draw the regression line and confidence interval + line, = ax.plot(grid, yhat, **kws) + if not self.truncate: + line.sticky_edges.x[:] = edges # Prevent mpl from adding margin + if err_bands is not None: + ax.fill_between(grid, *err_bands, facecolor=fill_color, alpha=.15) + + +_regression_docs = dict( + + model_api=dedent("""\ + There are a number of mutually exclusive options for estimating the + regression model. See the :ref:`tutorial ` for more + information.\ + """), + regplot_vs_lmplot=dedent("""\ + The :func:`regplot` and :func:`lmplot` functions are closely related, but + the former is an axes-level function while the latter is a figure-level + function that combines :func:`regplot` and :class:`FacetGrid`.\ + """), + x_estimator=dedent("""\ + x_estimator : callable that maps vector -> scalar, optional + Apply this function to each unique value of ``x`` and plot the + resulting estimate. This is useful when ``x`` is a discrete variable. + If ``x_ci`` is given, this estimate will be bootstrapped and a + confidence interval will be drawn.\ + """), + x_bins=dedent("""\ + x_bins : int or vector, optional + Bin the ``x`` variable into discrete bins and then estimate the central + tendency and a confidence interval. This binning only influences how + the scatterplot is drawn; the regression is still fit to the original + data. This parameter is interpreted either as the number of + evenly-sized (not necessary spaced) bins or the positions of the bin + centers. When this parameter is used, it implies that the default of + ``x_estimator`` is ``numpy.mean``.\ + """), + x_ci=dedent("""\ + x_ci : "ci", "sd", int in [0, 100] or None, optional + Size of the confidence interval used when plotting a central tendency + for discrete values of ``x``. If ``"ci"``, defer to the value of the + ``ci`` parameter. If ``"sd"``, skip bootstrapping and show the + standard deviation of the observations in each bin.\ + """), + scatter=dedent("""\ + scatter : bool, optional + If ``True``, draw a scatterplot with the underlying observations (or + the ``x_estimator`` values).\ + """), + fit_reg=dedent("""\ + fit_reg : bool, optional + If ``True``, estimate and plot a regression model relating the ``x`` + and ``y`` variables.\ + """), + ci=dedent("""\ + ci : int in [0, 100] or None, optional + Size of the confidence interval for the regression estimate. This will + be drawn using translucent bands around the regression line. The + confidence interval is estimated using a bootstrap; for large + datasets, it may be advisable to avoid that computation by setting + this parameter to None.\ + """), + n_boot=dedent("""\ + n_boot : int, optional + Number of bootstrap resamples used to estimate the ``ci``. The default + value attempts to balance time and stability; you may want to increase + this value for "final" versions of plots.\ + """), + units=dedent("""\ + units : variable name in ``data``, optional + If the ``x`` and ``y`` observations are nested within sampling units, + those can be specified here. This will be taken into account when + computing the confidence intervals by performing a multilevel bootstrap + that resamples both units and observations (within unit). This does not + otherwise influence how the regression is estimated or drawn.\ + """), + seed=dedent("""\ + seed : int, numpy.random.Generator, or numpy.random.RandomState, optional + Seed or random number generator for reproducible bootstrapping.\ + """), + order=dedent("""\ + order : int, optional + If ``order`` is greater than 1, use ``numpy.polyfit`` to estimate a + polynomial regression.\ + """), + logistic=dedent("""\ + logistic : bool, optional + If ``True``, assume that ``y`` is a binary variable and use + ``statsmodels`` to estimate a logistic regression model. Note that this + is substantially more computationally intensive than linear regression, + so you may wish to decrease the number of bootstrap resamples + (``n_boot``) or set ``ci`` to None.\ + """), + lowess=dedent("""\ + lowess : bool, optional + If ``True``, use ``statsmodels`` to estimate a nonparametric lowess + model (locally weighted linear regression). Note that confidence + intervals cannot currently be drawn for this kind of model.\ + """), + robust=dedent("""\ + robust : bool, optional + If ``True``, use ``statsmodels`` to estimate a robust regression. This + will de-weight outliers. Note that this is substantially more + computationally intensive than standard linear regression, so you may + wish to decrease the number of bootstrap resamples (``n_boot``) or set + ``ci`` to None.\ + """), + logx=dedent("""\ + logx : bool, optional + If ``True``, estimate a linear regression of the form y ~ log(x), but + plot the scatterplot and regression model in the input space. Note that + ``x`` must be positive for this to work.\ + """), + xy_partial=dedent("""\ + {x,y}_partial : strings in ``data`` or matrices + Confounding variables to regress out of the ``x`` or ``y`` variables + before plotting.\ + """), + truncate=dedent("""\ + truncate : bool, optional + If ``True``, the regression line is bounded by the data limits. If + ``False``, it extends to the ``x`` axis limits. + """), + xy_jitter=dedent("""\ + {x,y}_jitter : floats, optional + Add uniform random noise of this size to either the ``x`` or ``y`` + variables. The noise is added to a copy of the data after fitting the + regression, and only influences the look of the scatterplot. This can + be helpful when plotting variables that take discrete values.\ + """), + scatter_line_kws=dedent("""\ + {scatter,line}_kws : dictionaries + Additional keyword arguments to pass to ``plt.scatter`` and + ``plt.plot``.\ + """), +) +_regression_docs.update(_facet_docs) + + +def lmplot( + data, *, + x=None, y=None, hue=None, col=None, row=None, + palette=None, col_wrap=None, height=5, aspect=1, markers="o", + sharex=None, sharey=None, hue_order=None, col_order=None, row_order=None, + legend=True, legend_out=None, x_estimator=None, x_bins=None, + x_ci="ci", scatter=True, fit_reg=True, ci=95, n_boot=1000, + units=None, seed=None, order=1, logistic=False, lowess=False, + robust=False, logx=False, x_partial=None, y_partial=None, + truncate=True, x_jitter=None, y_jitter=None, scatter_kws=None, + line_kws=None, facet_kws=None, +): + + if facet_kws is None: + facet_kws = {} + + def facet_kw_deprecation(key, val): + msg = ( + f"{key} is deprecated from the `lmplot` function signature. " + "Please update your code to pass it using `facet_kws`." + ) + if val is not None: + warnings.warn(msg, UserWarning) + facet_kws[key] = val + + facet_kw_deprecation("sharex", sharex) + facet_kw_deprecation("sharey", sharey) + facet_kw_deprecation("legend_out", legend_out) + + if data is None: + raise TypeError("Missing required keyword argument `data`.") + + # Reduce the dataframe to only needed columns + need_cols = [x, y, hue, col, row, units, x_partial, y_partial] + cols = np.unique([a for a in need_cols if a is not None]).tolist() + data = data[cols] + + # Initialize the grid + facets = FacetGrid( + data, row=row, col=col, hue=hue, + palette=palette, + row_order=row_order, col_order=col_order, hue_order=hue_order, + height=height, aspect=aspect, col_wrap=col_wrap, + **facet_kws, + ) + + # Add the markers here as FacetGrid has figured out how many levels of the + # hue variable are needed and we don't want to duplicate that process + if facets.hue_names is None: + n_markers = 1 + else: + n_markers = len(facets.hue_names) + if not isinstance(markers, list): + markers = [markers] * n_markers + if len(markers) != n_markers: + raise ValueError("markers must be a singleton or a list of markers " + "for each level of the hue variable") + facets.hue_kws = {"marker": markers} + + def update_datalim(data, x, y, ax, **kws): + xys = data[[x, y]].to_numpy().astype(float) + ax.update_datalim(xys, updatey=False) + ax.autoscale_view(scaley=False) + + facets.map_dataframe(update_datalim, x=x, y=y) + + # Draw the regression plot on each facet + regplot_kws = dict( + x_estimator=x_estimator, x_bins=x_bins, x_ci=x_ci, + scatter=scatter, fit_reg=fit_reg, ci=ci, n_boot=n_boot, units=units, + seed=seed, order=order, logistic=logistic, lowess=lowess, + robust=robust, logx=logx, x_partial=x_partial, y_partial=y_partial, + truncate=truncate, x_jitter=x_jitter, y_jitter=y_jitter, + scatter_kws=scatter_kws, line_kws=line_kws, + ) + facets.map_dataframe(regplot, x=x, y=y, **regplot_kws) + facets.set_axis_labels(x, y) + + # Add a legend + if legend and (hue is not None) and (hue not in [col, row]): + facets.add_legend() + return facets + + +lmplot.__doc__ = dedent("""\ + Plot data and regression model fits across a FacetGrid. + + This function combines :func:`regplot` and :class:`FacetGrid`. It is + intended as a convenient interface to fit regression models across + conditional subsets of a dataset. + + When thinking about how to assign variables to different facets, a general + rule is that it makes sense to use ``hue`` for the most important + comparison, followed by ``col`` and ``row``. However, always think about + your particular dataset and the goals of the visualization you are + creating. + + {model_api} + + The parameters to this function span most of the options in + :class:`FacetGrid`, although there may be occasional cases where you will + want to use that class and :func:`regplot` directly. + + Parameters + ---------- + {data} + x, y : strings, optional + Input variables; these should be column names in ``data``. + hue, col, row : strings + Variables that define subsets of the data, which will be drawn on + separate facets in the grid. See the ``*_order`` parameters to control + the order of levels of this variable. + {palette} + {col_wrap} + {height} + {aspect} + markers : matplotlib marker code or list of marker codes, optional + Markers for the scatterplot. If a list, each marker in the list will be + used for each level of the ``hue`` variable. + {share_xy} + + .. deprecated:: 0.12.0 + Pass using the `facet_kws` dictionary. + + {{hue,col,row}}_order : lists, optional + Order for the levels of the faceting variables. By default, this will + be the order that the levels appear in ``data`` or, if the variables + are pandas categoricals, the category order. + legend : bool, optional + If ``True`` and there is a ``hue`` variable, add a legend. + {legend_out} + + .. deprecated:: 0.12.0 + Pass using the `facet_kws` dictionary. + + {x_estimator} + {x_bins} + {x_ci} + {scatter} + {fit_reg} + {ci} + {n_boot} + {units} + {seed} + {order} + {logistic} + {lowess} + {robust} + {logx} + {xy_partial} + {truncate} + {xy_jitter} + {scatter_line_kws} + facet_kws : dict + Dictionary of keyword arguments for :class:`FacetGrid`. + + See Also + -------- + regplot : Plot data and a conditional model fit. + FacetGrid : Subplot grid for plotting conditional relationships. + pairplot : Combine :func:`regplot` and :class:`PairGrid` (when used with + ``kind="reg"``). + + Notes + ----- + + {regplot_vs_lmplot} + + Examples + -------- + + .. include:: ../docstrings/lmplot.rst + + """).format(**_regression_docs) + + +def regplot( + data=None, *, x=None, y=None, + x_estimator=None, x_bins=None, x_ci="ci", + scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, + seed=None, order=1, logistic=False, lowess=False, robust=False, + logx=False, x_partial=None, y_partial=None, + truncate=True, dropna=True, x_jitter=None, y_jitter=None, + label=None, color=None, marker="o", + scatter_kws=None, line_kws=None, ax=None +): + + plotter = _RegressionPlotter(x, y, data, x_estimator, x_bins, x_ci, + scatter, fit_reg, ci, n_boot, units, seed, + order, logistic, lowess, robust, logx, + x_partial, y_partial, truncate, dropna, + x_jitter, y_jitter, color, label) + + if ax is None: + ax = plt.gca() + + scatter_kws = {} if scatter_kws is None else copy.copy(scatter_kws) + scatter_kws["marker"] = marker + line_kws = {} if line_kws is None else copy.copy(line_kws) + plotter.plot(ax, scatter_kws, line_kws) + return ax + + +regplot.__doc__ = dedent("""\ + Plot data and a linear regression model fit. + + {model_api} + + Parameters + ---------- + x, y: string, series, or vector array + Input variables. If strings, these should correspond with column names + in ``data``. When pandas objects are used, axes will be labeled with + the series name. + {data} + {x_estimator} + {x_bins} + {x_ci} + {scatter} + {fit_reg} + {ci} + {n_boot} + {units} + {seed} + {order} + {logistic} + {lowess} + {robust} + {logx} + {xy_partial} + {truncate} + {xy_jitter} + label : string + Label to apply to either the scatterplot or regression line (if + ``scatter`` is ``False``) for use in a legend. + color : matplotlib color + Color to apply to all plot elements; will be superseded by colors + passed in ``scatter_kws`` or ``line_kws``. + marker : matplotlib marker code + Marker to use for the scatterplot glyphs. + {scatter_line_kws} + ax : matplotlib Axes, optional + Axes object to draw the plot onto, otherwise uses the current Axes. + + Returns + ------- + ax : matplotlib Axes + The Axes object containing the plot. + + See Also + -------- + lmplot : Combine :func:`regplot` and :class:`FacetGrid` to plot multiple + linear relationships in a dataset. + jointplot : Combine :func:`regplot` and :class:`JointGrid` (when used with + ``kind="reg"``). + pairplot : Combine :func:`regplot` and :class:`PairGrid` (when used with + ``kind="reg"``). + residplot : Plot the residuals of a linear regression model. + + Notes + ----- + + {regplot_vs_lmplot} + + + It's also easy to combine :func:`regplot` and :class:`JointGrid` or + :class:`PairGrid` through the :func:`jointplot` and :func:`pairplot` + functions, although these do not directly accept all of :func:`regplot`'s + parameters. + + Examples + -------- + + .. include:: ../docstrings/regplot.rst + + """).format(**_regression_docs) + + +def residplot( + data=None, *, x=None, y=None, + x_partial=None, y_partial=None, lowess=False, + order=1, robust=False, dropna=True, label=None, color=None, + scatter_kws=None, line_kws=None, ax=None +): + """Plot the residuals of a linear regression. + + This function will regress y on x (possibly as a robust or polynomial + regression) and then draw a scatterplot of the residuals. You can + optionally fit a lowess smoother to the residual plot, which can + help in determining if there is structure to the residuals. + + Parameters + ---------- + data : DataFrame, optional + DataFrame to use if `x` and `y` are column names. + x : vector or string + Data or column name in `data` for the predictor variable. + y : vector or string + Data or column name in `data` for the response variable. + {x, y}_partial : vectors or string(s) , optional + These variables are treated as confounding and are removed from + the `x` or `y` variables before plotting. + lowess : boolean, optional + Fit a lowess smoother to the residual scatterplot. + order : int, optional + Order of the polynomial to fit when calculating the residuals. + robust : boolean, optional + Fit a robust linear regression when calculating the residuals. + dropna : boolean, optional + If True, ignore observations with missing data when fitting and + plotting. + label : string, optional + Label that will be used in any plot legends. + color : matplotlib color, optional + Color to use for all elements of the plot. + {scatter, line}_kws : dictionaries, optional + Additional keyword arguments passed to scatter() and plot() for drawing + the components of the plot. + ax : matplotlib axis, optional + Plot into this axis, otherwise grab the current axis or make a new + one if not existing. + + Returns + ------- + ax: matplotlib axes + Axes with the regression plot. + + See Also + -------- + regplot : Plot a simple linear regression model. + jointplot : Draw a :func:`residplot` with univariate marginal distributions + (when used with ``kind="resid"``). + + Examples + -------- + + .. include:: ../docstrings/residplot.rst + + """ + plotter = _RegressionPlotter(x, y, data, ci=None, + order=order, robust=robust, + x_partial=x_partial, y_partial=y_partial, + dropna=dropna, color=color, label=label) + + if ax is None: + ax = plt.gca() + + # Calculate the residual from a linear regression + _, yhat, _ = plotter.fit_regression(grid=plotter.x) + plotter.y = plotter.y - yhat + + # Set the regression option on the plotter + if lowess: + plotter.lowess = True + else: + plotter.fit_reg = False + + # Plot a horizontal line at 0 + ax.axhline(0, ls=":", c=".2") + + # Draw the scatterplot + scatter_kws = {} if scatter_kws is None else scatter_kws.copy() + line_kws = {} if line_kws is None else line_kws.copy() + plotter.plot(ax, scatter_kws, line_kws) + return ax diff --git a/shared/package-files/33/335449ddfb59e317ccded7a8fd45adfa06bb827e3bc9f24d9b80569a6a8da815/_rgi.py b/shared/package-files/33/335449ddfb59e317ccded7a8fd45adfa06bb827e3bc9f24d9b80569a6a8da815/_rgi.py new file mode 100644 index 0000000000000000000000000000000000000000..8e20200568ed961849b5510e8626cdbe6e5b9643 --- /dev/null +++ b/shared/package-files/33/335449ddfb59e317ccded7a8fd45adfa06bb827e3bc9f24d9b80569a6a8da815/_rgi.py @@ -0,0 +1,759 @@ +__all__ = ['RegularGridInterpolator', 'interpn'] + +import itertools + +import numpy as np + +import scipy.sparse.linalg as ssl + +from ._interpnd import _ndim_coords_from_arrays +from ._cubic import PchipInterpolator +from ._rgi_cython import evaluate_linear_2d, find_indices +from ._bsplines import make_interp_spline +from ._fitpack2 import RectBivariateSpline +from ._ndbspline import make_ndbspl + + +def _check_points(points): + descending_dimensions = [] + grid = [] + for i, p in enumerate(points): + # early make points float + # see https://github.com/scipy/scipy/pull/17230 + p = np.asarray(p, dtype=float) + if not np.all(p[1:] > p[:-1]): + if np.all(p[1:] < p[:-1]): + # input is descending, so make it ascending + descending_dimensions.append(i) + p = np.flip(p) + else: + raise ValueError( + "The points in dimension %d must be strictly " + "ascending or descending" % i) + # see https://github.com/scipy/scipy/issues/17716 + p = np.ascontiguousarray(p) + grid.append(p) + return tuple(grid), tuple(descending_dimensions) + + +def _check_dimensionality(points, values): + if len(points) > values.ndim: + raise ValueError("There are %d point arrays, but values has %d " + "dimensions" % (len(points), values.ndim)) + for i, p in enumerate(points): + if not np.asarray(p).ndim == 1: + raise ValueError("The points in dimension %d must be " + "1-dimensional" % i) + if not values.shape[i] == len(p): + raise ValueError("There are %d points and %d values in " + "dimension %d" % (len(p), values.shape[i], i)) + + +class RegularGridInterpolator: + """ + Interpolator on a regular or rectilinear grid in arbitrary dimensions. + + The data must be defined on a rectilinear grid; that is, a rectangular + grid with even or uneven spacing. Linear, nearest-neighbor, spline + interpolations are supported. After setting up the interpolator object, + the interpolation method may be chosen at each evaluation. + + Parameters + ---------- + points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, ) + The points defining the regular grid in n dimensions. The points in + each dimension (i.e. every elements of the points tuple) must be + strictly ascending or descending. + + values : array_like, shape (m1, ..., mn, ...) + The data on the regular grid in n dimensions. Complex data is + accepted. + + method : str, optional + The method of interpolation to perform. Supported are "linear", + "nearest", "slinear", "cubic", "quintic" and "pchip". This + parameter will become the default for the object's ``__call__`` + method. Default is "linear". + + bounds_error : bool, optional + If True, when interpolated values are requested outside of the + domain of the input data, a ValueError is raised. + If False, then `fill_value` is used. + Default is True. + + fill_value : float or None, optional + The value to use for points outside of the interpolation domain. + If None, values outside the domain are extrapolated. + Default is ``np.nan``. + + solver : callable, optional + Only used for methods "slinear", "cubic" and "quintic". + Sparse linear algebra solver for construction of the NdBSpline instance. + Default is the iterative solver `scipy.sparse.linalg.gcrotmk`. + + .. versionadded:: 1.13 + + solver_args: dict, optional + Additional arguments to pass to `solver`, if any. + + .. versionadded:: 1.13 + + Methods + ------- + __call__ + + Attributes + ---------- + grid : tuple of ndarrays + The points defining the regular grid in n dimensions. + This tuple defines the full grid via + ``np.meshgrid(*grid, indexing='ij')`` + values : ndarray + Data values at the grid. + method : str + Interpolation method. + fill_value : float or ``None`` + Use this value for out-of-bounds arguments to `__call__`. + bounds_error : bool + If ``True``, out-of-bounds argument raise a ``ValueError``. + + Notes + ----- + Contrary to `LinearNDInterpolator` and `NearestNDInterpolator`, this class + avoids expensive triangulation of the input data by taking advantage of the + regular grid structure. + + In other words, this class assumes that the data is defined on a + *rectilinear* grid. + + .. versionadded:: 0.14 + + The 'slinear'(k=1), 'cubic'(k=3), and 'quintic'(k=5) methods are + tensor-product spline interpolators, where `k` is the spline degree, + If any dimension has fewer points than `k` + 1, an error will be raised. + + .. versionadded:: 1.9 + + If the input data is such that dimensions have incommensurate + units and differ by many orders of magnitude, the interpolant may have + numerical artifacts. Consider rescaling the data before interpolating. + + **Choosing a solver for spline methods** + + Spline methods, "slinear", "cubic" and "quintic" involve solving a + large sparse linear system at instantiation time. Depending on data, + the default solver may or may not be adequate. When it is not, you may + need to experiment with an optional `solver` argument, where you may + choose between the direct solver (`scipy.sparse.linalg.spsolve`) or + iterative solvers from `scipy.sparse.linalg`. You may need to supply + additional parameters via the optional `solver_args` parameter (for instance, + you may supply the starting value or target tolerance). See the + `scipy.sparse.linalg` documentation for the full list of available options. + + Alternatively, you may instead use the legacy methods, "slinear_legacy", + "cubic_legacy" and "quintic_legacy". These methods allow faster construction + but evaluations will be much slower. + + Examples + -------- + **Evaluate a function on the points of a 3-D grid** + + As a first example, we evaluate a simple example function on the points of + a 3-D grid: + + >>> from scipy.interpolate import RegularGridInterpolator + >>> import numpy as np + >>> def f(x, y, z): + ... return 2 * x**3 + 3 * y**2 - z + >>> x = np.linspace(1, 4, 11) + >>> y = np.linspace(4, 7, 22) + >>> z = np.linspace(7, 9, 33) + >>> xg, yg ,zg = np.meshgrid(x, y, z, indexing='ij', sparse=True) + >>> data = f(xg, yg, zg) + + ``data`` is now a 3-D array with ``data[i, j, k] = f(x[i], y[j], z[k])``. + Next, define an interpolating function from this data: + + >>> interp = RegularGridInterpolator((x, y, z), data) + + Evaluate the interpolating function at the two points + ``(x,y,z) = (2.1, 6.2, 8.3)`` and ``(3.3, 5.2, 7.1)``: + + >>> pts = np.array([[2.1, 6.2, 8.3], + ... [3.3, 5.2, 7.1]]) + >>> interp(pts) + array([ 125.80469388, 146.30069388]) + + which is indeed a close approximation to + + >>> f(2.1, 6.2, 8.3), f(3.3, 5.2, 7.1) + (125.54200000000002, 145.894) + + **Interpolate and extrapolate a 2D dataset** + + As a second example, we interpolate and extrapolate a 2D data set: + + >>> x, y = np.array([-2, 0, 4]), np.array([-2, 0, 2, 5]) + >>> def ff(x, y): + ... return x**2 + y**2 + + >>> xg, yg = np.meshgrid(x, y, indexing='ij') + >>> data = ff(xg, yg) + >>> interp = RegularGridInterpolator((x, y), data, + ... bounds_error=False, fill_value=None) + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax = fig.add_subplot(projection='3d') + >>> ax.scatter(xg.ravel(), yg.ravel(), data.ravel(), + ... s=60, c='k', label='data') + + Evaluate and plot the interpolator on a finer grid + + >>> xx = np.linspace(-4, 9, 31) + >>> yy = np.linspace(-4, 9, 31) + >>> X, Y = np.meshgrid(xx, yy, indexing='ij') + + >>> # interpolator + >>> ax.plot_wireframe(X, Y, interp((X, Y)), rstride=3, cstride=3, + ... alpha=0.4, color='m', label='linear interp') + + >>> # ground truth + >>> ax.plot_wireframe(X, Y, ff(X, Y), rstride=3, cstride=3, + ... alpha=0.4, label='ground truth') + >>> plt.legend() + >>> plt.show() + + Other examples are given + :ref:`in the tutorial `. + + See Also + -------- + NearestNDInterpolator : Nearest neighbor interpolator on *unstructured* + data in N dimensions + + LinearNDInterpolator : Piecewise linear interpolator on *unstructured* data + in N dimensions + + interpn : a convenience function which wraps `RegularGridInterpolator` + + scipy.ndimage.map_coordinates : interpolation on grids with equal spacing + (suitable for e.g., N-D image resampling) + + References + ---------- + .. [1] Python package *regulargrid* by Johannes Buchner, see + https://pypi.python.org/pypi/regulargrid/ + .. [2] Wikipedia, "Trilinear interpolation", + https://en.wikipedia.org/wiki/Trilinear_interpolation + .. [3] Weiser, Alan, and Sergio E. Zarantonello. "A note on piecewise linear + and multilinear table interpolation in many dimensions." MATH. + COMPUT. 50.181 (1988): 189-196. + https://www.ams.org/journals/mcom/1988-50-181/S0025-5718-1988-0917826-0/S0025-5718-1988-0917826-0.pdf + :doi:`10.1090/S0025-5718-1988-0917826-0` + + """ + # this class is based on code originally programmed by Johannes Buchner, + # see https://github.com/JohannesBuchner/regulargrid + + _SPLINE_DEGREE_MAP = {"slinear": 1, "cubic": 3, "quintic": 5, 'pchip': 3, + "slinear_legacy": 1, "cubic_legacy": 3, "quintic_legacy": 5,} + _SPLINE_METHODS_recursive = {"slinear_legacy", "cubic_legacy", + "quintic_legacy", "pchip"} + _SPLINE_METHODS_ndbspl = {"slinear", "cubic", "quintic"} + _SPLINE_METHODS = list(_SPLINE_DEGREE_MAP.keys()) + _ALL_METHODS = ["linear", "nearest"] + _SPLINE_METHODS + + def __init__(self, points, values, method="linear", bounds_error=True, + fill_value=np.nan, *, solver=None, solver_args=None): + if method not in self._ALL_METHODS: + raise ValueError(f"Method '{method}' is not defined") + elif method in self._SPLINE_METHODS: + self._validate_grid_dimensions(points, method) + self.method = method + self._spline = None + self.bounds_error = bounds_error + self.grid, self._descending_dimensions = _check_points(points) + self.values = self._check_values(values) + self._check_dimensionality(self.grid, self.values) + self.fill_value = self._check_fill_value(self.values, fill_value) + if self._descending_dimensions: + self.values = np.flip(values, axis=self._descending_dimensions) + if self.method == "pchip" and np.iscomplexobj(self.values): + msg = ("`PchipInterpolator` only works with real values. If you are trying " + "to use the real components of the passed array, use `np.real` on " + "the array before passing to `RegularGridInterpolator`.") + raise ValueError(msg) + if method in self._SPLINE_METHODS_ndbspl: + if solver_args is None: + solver_args = {} + self._spline = self._construct_spline(method, solver, **solver_args) + else: + if solver is not None or solver_args: + raise ValueError( + f"{method =} does not accept the 'solver' argument. Got " + f" {solver = } and with arguments {solver_args}." + ) + + def _construct_spline(self, method, solver=None, **solver_args): + if solver is None: + solver = ssl.gcrotmk + spl = make_ndbspl( + self.grid, self.values, self._SPLINE_DEGREE_MAP[method], + solver=solver, **solver_args + ) + return spl + + def _check_dimensionality(self, grid, values): + _check_dimensionality(grid, values) + + def _check_points(self, points): + return _check_points(points) + + def _check_values(self, values): + if not hasattr(values, 'ndim'): + # allow reasonable duck-typed values + values = np.asarray(values) + + if hasattr(values, 'dtype') and hasattr(values, 'astype'): + if not np.issubdtype(values.dtype, np.inexact): + values = values.astype(float) + + return values + + def _check_fill_value(self, values, fill_value): + if fill_value is not None: + fill_value_dtype = np.asarray(fill_value).dtype + if (hasattr(values, 'dtype') and not + np.can_cast(fill_value_dtype, values.dtype, + casting='same_kind')): + raise ValueError("fill_value must be either 'None' or " + "of a type compatible with values") + return fill_value + + def __call__(self, xi, method=None, *, nu=None): + """ + Interpolation at coordinates. + + Parameters + ---------- + xi : ndarray of shape (..., ndim) + The coordinates to evaluate the interpolator at. + + method : str, optional + The method of interpolation to perform. Supported are "linear", + "nearest", "slinear", "cubic", "quintic" and "pchip". Default is + the method chosen when the interpolator was created. + + nu : sequence of ints, length ndim, optional + If not None, the orders of the derivatives to evaluate. + Each entry must be non-negative. + Only allowed for methods "slinear", "cubic" and "quintic". + + .. versionadded:: 1.13 + + Returns + ------- + values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:] + Interpolated values at `xi`. See notes for behaviour when + ``xi.ndim == 1``. + + Notes + ----- + In the case that ``xi.ndim == 1`` a new axis is inserted into + the 0 position of the returned array, values_x, so its shape is + instead ``(1,) + values.shape[ndim:]``. + + Examples + -------- + Here we define a nearest-neighbor interpolator of a simple function + + >>> import numpy as np + >>> x, y = np.array([0, 1, 2]), np.array([1, 3, 7]) + >>> def f(x, y): + ... return x**2 + y**2 + >>> data = f(*np.meshgrid(x, y, indexing='ij', sparse=True)) + >>> from scipy.interpolate import RegularGridInterpolator + >>> interp = RegularGridInterpolator((x, y), data, method='nearest') + + By construction, the interpolator uses the nearest-neighbor + interpolation + + >>> interp([[1.5, 1.3], [0.3, 4.5]]) + array([2., 9.]) + + We can however evaluate the linear interpolant by overriding the + `method` parameter + + >>> interp([[1.5, 1.3], [0.3, 4.5]], method='linear') + array([ 4.7, 24.3]) + """ + _spline = self._spline + method = self.method if method is None else method + is_method_changed = self.method != method + if method not in self._ALL_METHODS: + raise ValueError(f"Method '{method}' is not defined") + if is_method_changed and method in self._SPLINE_METHODS_ndbspl: + _spline = self._construct_spline(method) + + if nu is not None and method not in self._SPLINE_METHODS_ndbspl: + raise ValueError( + f"Can only compute derivatives for methods " + f"{self._SPLINE_METHODS_ndbspl}, got {method =}." + ) + + xi, xi_shape, ndim, nans, out_of_bounds = self._prepare_xi(xi) + + if method == "linear": + indices, norm_distances = self._find_indices(xi.T) + if (ndim == 2 and hasattr(self.values, 'dtype') and + self.values.ndim == 2 and self.values.flags.writeable and + self.values.dtype in (np.float64, np.complex128) and + self.values.dtype.byteorder == '='): + # until cython supports const fused types, the fast path + # cannot support non-writeable values + # a fast path + out = np.empty(indices.shape[1], dtype=self.values.dtype) + result = evaluate_linear_2d(self.values, + indices, + norm_distances, + self.grid, + out) + else: + result = self._evaluate_linear(indices, norm_distances) + elif method == "nearest": + indices, norm_distances = self._find_indices(xi.T) + result = self._evaluate_nearest(indices, norm_distances) + elif method in self._SPLINE_METHODS: + if is_method_changed: + self._validate_grid_dimensions(self.grid, method) + if method in self._SPLINE_METHODS_recursive: + result = self._evaluate_spline(xi, method) + else: + result = _spline(xi, nu=nu) + + if not self.bounds_error and self.fill_value is not None: + result[out_of_bounds] = self.fill_value + + # f(nan) = nan, if any + if np.any(nans): + result[nans] = np.nan + return result.reshape(xi_shape[:-1] + self.values.shape[ndim:]) + + def _prepare_xi(self, xi): + ndim = len(self.grid) + xi = _ndim_coords_from_arrays(xi, ndim=ndim) + if xi.shape[-1] != len(self.grid): + raise ValueError("The requested sample points xi have dimension " + f"{xi.shape[-1]} but this " + f"RegularGridInterpolator has dimension {ndim}") + + xi_shape = xi.shape + xi = xi.reshape(-1, xi_shape[-1]) + xi = np.asarray(xi, dtype=float) + + # find nans in input + nans = np.any(np.isnan(xi), axis=-1) + + if self.bounds_error: + for i, p in enumerate(xi.T): + if not np.logical_and(np.all(self.grid[i][0] <= p), + np.all(p <= self.grid[i][-1])): + raise ValueError("One of the requested xi is out of bounds " + "in dimension %d" % i) + out_of_bounds = None + else: + out_of_bounds = self._find_out_of_bounds(xi.T) + + return xi, xi_shape, ndim, nans, out_of_bounds + + def _evaluate_linear(self, indices, norm_distances): + # slice for broadcasting over trailing dimensions in self.values + vslice = (slice(None),) + (None,)*(self.values.ndim - len(indices)) + + # Compute shifting up front before zipping everything together + shift_norm_distances = [1 - yi for yi in norm_distances] + shift_indices = [i + 1 for i in indices] + + # The formula for linear interpolation in 2d takes the form: + # values = self.values[(i0, i1)] * (1 - y0) * (1 - y1) + \ + # self.values[(i0, i1 + 1)] * (1 - y0) * y1 + \ + # self.values[(i0 + 1, i1)] * y0 * (1 - y1) + \ + # self.values[(i0 + 1, i1 + 1)] * y0 * y1 + # We pair i with 1 - yi (zipped1) and i + 1 with yi (zipped2) + zipped1 = zip(indices, shift_norm_distances) + zipped2 = zip(shift_indices, norm_distances) + + # Take all products of zipped1 and zipped2 and iterate over them + # to get the terms in the above formula. This corresponds to iterating + # over the vertices of a hypercube. + hypercube = itertools.product(*zip(zipped1, zipped2)) + value = np.array([0.]) + for h in hypercube: + edge_indices, weights = zip(*h) + weight = np.array([1.]) + for w in weights: + weight = weight * w + term = np.asarray(self.values[edge_indices]) * weight[vslice] + value = value + term # cannot use += because broadcasting + return value + + def _evaluate_nearest(self, indices, norm_distances): + idx_res = [np.where(yi <= .5, i, i + 1) + for i, yi in zip(indices, norm_distances)] + return self.values[tuple(idx_res)] + + def _validate_grid_dimensions(self, points, method): + k = self._SPLINE_DEGREE_MAP[method] + for i, point in enumerate(points): + ndim = len(np.atleast_1d(point)) + if ndim <= k: + raise ValueError(f"There are {ndim} points in dimension {i}," + f" but method {method} requires at least " + f" {k+1} points per dimension.") + + def _evaluate_spline(self, xi, method): + # ensure xi is 2D list of points to evaluate (`m` is the number of + # points and `n` is the number of interpolation dimensions, + # ``n == len(self.grid)``.) + if xi.ndim == 1: + xi = xi.reshape((1, xi.size)) + m, n = xi.shape + + # Reorder the axes: n-dimensional process iterates over the + # interpolation axes from the last axis downwards: E.g. for a 4D grid + # the order of axes is 3, 2, 1, 0. Each 1D interpolation works along + # the 0th axis of its argument array (for 1D routine it's its ``y`` + # array). Thus permute the interpolation axes of `values` *and keep + # trailing dimensions trailing*. + axes = tuple(range(self.values.ndim)) + axx = axes[:n][::-1] + axes[n:] + values = self.values.transpose(axx) + + if method == 'pchip': + _eval_func = self._do_pchip + else: + _eval_func = self._do_spline_fit + k = self._SPLINE_DEGREE_MAP[method] + + # Non-stationary procedure: difficult to vectorize this part entirely + # into numpy-level operations. Unfortunately this requires explicit + # looping over each point in xi. + + # can at least vectorize the first pass across all points in the + # last variable of xi. + last_dim = n - 1 + first_values = _eval_func(self.grid[last_dim], + values, + xi[:, last_dim], + k) + + # the rest of the dimensions have to be on a per point-in-xi basis + shape = (m, *self.values.shape[n:]) + result = np.empty(shape, dtype=self.values.dtype) + for j in range(m): + # Main process: Apply 1D interpolate in each dimension + # sequentially, starting with the last dimension. + # These are then "folded" into the next dimension in-place. + folded_values = first_values[j, ...] + for i in range(last_dim-1, -1, -1): + # Interpolate for each 1D from the last dimensions. + # This collapses each 1D sequence into a scalar. + folded_values = _eval_func(self.grid[i], + folded_values, + xi[j, i], + k) + result[j, ...] = folded_values + + return result + + @staticmethod + def _do_spline_fit(x, y, pt, k): + local_interp = make_interp_spline(x, y, k=k, axis=0) + values = local_interp(pt) + return values + + @staticmethod + def _do_pchip(x, y, pt, k): + local_interp = PchipInterpolator(x, y, axis=0) + values = local_interp(pt) + return values + + def _find_indices(self, xi): + return find_indices(self.grid, xi) + + def _find_out_of_bounds(self, xi): + # check for out of bounds xi + out_of_bounds = np.zeros((xi.shape[1]), dtype=bool) + # iterate through dimensions + for x, grid in zip(xi, self.grid): + out_of_bounds += x < grid[0] + out_of_bounds += x > grid[-1] + return out_of_bounds + + +def interpn(points, values, xi, method="linear", bounds_error=True, + fill_value=np.nan): + """ + Multidimensional interpolation on regular or rectilinear grids. + + Strictly speaking, not all regular grids are supported - this function + works on *rectilinear* grids, that is, a rectangular grid with even or + uneven spacing. + + Parameters + ---------- + points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, ) + The points defining the regular grid in n dimensions. The points in + each dimension (i.e. every elements of the points tuple) must be + strictly ascending or descending. + + values : array_like, shape (m1, ..., mn, ...) + The data on the regular grid in n dimensions. Complex data is + accepted. + + .. deprecated:: 1.13.0 + Complex data is deprecated with ``method="pchip"`` and will raise an + error in SciPy 1.15.0. This is because ``PchipInterpolator`` only + works with real values. If you are trying to use the real components of + the passed array, use ``np.real`` on ``values``. + + xi : ndarray of shape (..., ndim) + The coordinates to sample the gridded data at + + method : str, optional + The method of interpolation to perform. Supported are "linear", + "nearest", "slinear", "cubic", "quintic", "pchip", and "splinef2d". + "splinef2d" is only supported for 2-dimensional data. + + bounds_error : bool, optional + If True, when interpolated values are requested outside of the + domain of the input data, a ValueError is raised. + If False, then `fill_value` is used. + + fill_value : number, optional + If provided, the value to use for points outside of the + interpolation domain. If None, values outside + the domain are extrapolated. Extrapolation is not supported by method + "splinef2d". + + Returns + ------- + values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:] + Interpolated values at `xi`. See notes for behaviour when + ``xi.ndim == 1``. + + See Also + -------- + NearestNDInterpolator : Nearest neighbor interpolation on unstructured + data in N dimensions + LinearNDInterpolator : Piecewise linear interpolant on unstructured data + in N dimensions + RegularGridInterpolator : interpolation on a regular or rectilinear grid + in arbitrary dimensions (`interpn` wraps this + class). + RectBivariateSpline : Bivariate spline approximation over a rectangular mesh + scipy.ndimage.map_coordinates : interpolation on grids with equal spacing + (suitable for e.g., N-D image resampling) + + Notes + ----- + + .. versionadded:: 0.14 + + In the case that ``xi.ndim == 1`` a new axis is inserted into + the 0 position of the returned array, values_x, so its shape is + instead ``(1,) + values.shape[ndim:]``. + + If the input data is such that input dimensions have incommensurate + units and differ by many orders of magnitude, the interpolant may have + numerical artifacts. Consider rescaling the data before interpolation. + + Examples + -------- + Evaluate a simple example function on the points of a regular 3-D grid: + + >>> import numpy as np + >>> from scipy.interpolate import interpn + >>> def value_func_3d(x, y, z): + ... return 2 * x + 3 * y - z + >>> x = np.linspace(0, 4, 5) + >>> y = np.linspace(0, 5, 6) + >>> z = np.linspace(0, 6, 7) + >>> points = (x, y, z) + >>> values = value_func_3d(*np.meshgrid(*points, indexing='ij')) + + Evaluate the interpolating function at a point + + >>> point = np.array([2.21, 3.12, 1.15]) + >>> print(interpn(points, values, point)) + [12.63] + + """ + # sanity check 'method' kwarg + if method not in ["linear", "nearest", "cubic", "quintic", "pchip", + "splinef2d", "slinear", + "slinear_legacy", "cubic_legacy", "quintic_legacy"]: + raise ValueError("interpn only understands the methods 'linear', " + "'nearest', 'slinear', 'cubic', 'quintic', 'pchip', " + f"and 'splinef2d'. You provided {method}.") + + if not hasattr(values, 'ndim'): + values = np.asarray(values) + + ndim = values.ndim + if ndim > 2 and method == "splinef2d": + raise ValueError("The method splinef2d can only be used for " + "2-dimensional input data") + if not bounds_error and fill_value is None and method == "splinef2d": + raise ValueError("The method splinef2d does not support extrapolation.") + + # sanity check consistency of input dimensions + if len(points) > ndim: + raise ValueError("There are %d point arrays, but values has %d " + "dimensions" % (len(points), ndim)) + if len(points) != ndim and method == 'splinef2d': + raise ValueError("The method splinef2d can only be used for " + "scalar data with one point per coordinate") + + grid, descending_dimensions = _check_points(points) + _check_dimensionality(grid, values) + + # sanity check requested xi + xi = _ndim_coords_from_arrays(xi, ndim=len(grid)) + if xi.shape[-1] != len(grid): + raise ValueError("The requested sample points xi have dimension " + "%d, but this RegularGridInterpolator has " + "dimension %d" % (xi.shape[-1], len(grid))) + + if bounds_error: + for i, p in enumerate(xi.T): + if not np.logical_and(np.all(grid[i][0] <= p), + np.all(p <= grid[i][-1])): + raise ValueError("One of the requested xi is out of bounds " + "in dimension %d" % i) + + # perform interpolation + if method in RegularGridInterpolator._ALL_METHODS: + interp = RegularGridInterpolator(points, values, method=method, + bounds_error=bounds_error, + fill_value=fill_value) + return interp(xi) + elif method == "splinef2d": + xi_shape = xi.shape + xi = xi.reshape(-1, xi.shape[-1]) + + # RectBivariateSpline doesn't support fill_value; we need to wrap here + idx_valid = np.all((grid[0][0] <= xi[:, 0], xi[:, 0] <= grid[0][-1], + grid[1][0] <= xi[:, 1], xi[:, 1] <= grid[1][-1]), + axis=0) + result = np.empty_like(xi[:, 0]) + + # make a copy of values for RectBivariateSpline + interp = RectBivariateSpline(points[0], points[1], values[:]) + result[idx_valid] = interp.ev(xi[idx_valid, 0], xi[idx_valid, 1]) + result[np.logical_not(idx_valid)] = fill_value + + return result.reshape(xi_shape[:-1]) + else: + raise ValueError(f"unknown {method = }") diff --git a/shared/package-files/33/335515c7106005c298d2bee9bfc0ef384ebf0896afc3439dddf8bc887f803c49/__init__.pyi b/shared/package-files/33/335515c7106005c298d2bee9bfc0ef384ebf0896afc3439dddf8bc887f803c49/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4bd5cdf73a049f6e83dafcc35c60d0a97db4502d --- /dev/null +++ b/shared/package-files/33/335515c7106005c298d2bee9bfc0ef384ebf0896afc3439dddf8bc887f803c49/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Dict, Any + +LANG_INFO: Dict[str, Any] = ... diff --git a/shared/package-files/33/3357196f3fa52433326a6626880e34964e00c5570aee50e9a0a0a7c6d86f6e4f/utf_16_be.py b/shared/package-files/33/3357196f3fa52433326a6626880e34964e00c5570aee50e9a0a0a7c6d86f6e4f/utf_16_be.py new file mode 100644 index 0000000000000000000000000000000000000000..86b458eb9bcd96b50f128df1978a14f5d1e41835 --- /dev/null +++ b/shared/package-files/33/3357196f3fa52433326a6626880e34964e00c5570aee50e9a0a0a7c6d86f6e4f/utf_16_be.py @@ -0,0 +1,42 @@ +""" Python 'utf-16-be' Codec + + +Written by Marc-Andre Lemburg (mal@lemburg.com). + +(c) Copyright CNRI, All Rights Reserved. NO WARRANTY. + +""" +import codecs + +### Codec APIs + +encode = codecs.utf_16_be_encode + +def decode(input, errors='strict'): + return codecs.utf_16_be_decode(input, errors, True) + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input, final=False): + return codecs.utf_16_be_encode(input, self.errors)[0] + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + _buffer_decode = codecs.utf_16_be_decode + +class StreamWriter(codecs.StreamWriter): + encode = codecs.utf_16_be_encode + +class StreamReader(codecs.StreamReader): + decode = codecs.utf_16_be_decode + +### encodings module API + +def getregentry(): + return codecs.CodecInfo( + name='utf-16-be', + encode=encode, + decode=decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamreader=StreamReader, + streamwriter=StreamWriter, + ) diff --git a/shared/package-files/33/3359968d2ef4a582c525abb9df836d82c95ca58ffc362638751991813ef74d5a/dataframe.py b/shared/package-files/33/3359968d2ef4a582c525abb9df836d82c95ca58ffc362638751991813ef74d5a/dataframe.py new file mode 100644 index 0000000000000000000000000000000000000000..1abacddfc7e3b7035a9446cd4118097c6accd385 --- /dev/null +++ b/shared/package-files/33/3359968d2ef4a582c525abb9df836d82c95ca58ffc362638751991813ef74d5a/dataframe.py @@ -0,0 +1,113 @@ +from __future__ import annotations + +from collections import abc +from typing import TYPE_CHECKING + +from pandas.core.interchange.column import PandasColumn +from pandas.core.interchange.dataframe_protocol import DataFrame as DataFrameXchg +from pandas.core.interchange.utils import maybe_rechunk + +if TYPE_CHECKING: + from collections.abc import ( + Iterable, + Sequence, + ) + + from pandas import ( + DataFrame, + Index, + ) + + +class PandasDataFrameXchg(DataFrameXchg): + """ + A data frame class, with only the methods required by the interchange + protocol defined. + Instances of this (private) class are returned from + ``pd.DataFrame.__dataframe__`` as objects with the methods and + attributes defined on this class. + """ + + def __init__(self, df: DataFrame, allow_copy: bool = True) -> None: + """ + Constructor - an instance of this (private) class is returned from + `pd.DataFrame.__dataframe__`. + """ + self._df = df.rename(columns=str, copy=False) + self._allow_copy = allow_copy + for i, _col in enumerate(self._df.columns): + rechunked = maybe_rechunk(self._df.iloc[:, i], allow_copy=allow_copy) + if rechunked is not None: + self._df.isetitem(i, rechunked) + + def __dataframe__( + self, nan_as_null: bool = False, allow_copy: bool = True + ) -> PandasDataFrameXchg: + # `nan_as_null` can be removed here once it's removed from + # Dataframe.__dataframe__ + return PandasDataFrameXchg(self._df, allow_copy) + + @property + def metadata(self) -> dict[str, Index]: + # `index` isn't a regular column, and the protocol doesn't support row + # labels - so we export it as Pandas-specific metadata here. + return {"pandas.index": self._df.index} + + def num_columns(self) -> int: + return len(self._df.columns) + + def num_rows(self) -> int: + return len(self._df) + + def num_chunks(self) -> int: + return 1 + + def column_names(self) -> Index: + return self._df.columns + + def get_column(self, i: int) -> PandasColumn: + return PandasColumn(self._df.iloc[:, i], allow_copy=self._allow_copy) + + def get_column_by_name(self, name: str) -> PandasColumn: + return PandasColumn(self._df[name], allow_copy=self._allow_copy) + + def get_columns(self) -> list[PandasColumn]: + return [ + PandasColumn(self._df[name], allow_copy=self._allow_copy) + for name in self._df.columns + ] + + def select_columns(self, indices: Sequence[int]) -> PandasDataFrameXchg: + if not isinstance(indices, abc.Sequence): + raise ValueError("`indices` is not a sequence") + if not isinstance(indices, list): + indices = list(indices) + + return PandasDataFrameXchg( + self._df.iloc[:, indices], allow_copy=self._allow_copy + ) + + def select_columns_by_name(self, names: list[str]) -> PandasDataFrameXchg: # type: ignore[override] + if not isinstance(names, abc.Sequence): + raise ValueError("`names` is not a sequence") + if not isinstance(names, list): + names = list(names) + + return PandasDataFrameXchg(self._df.loc[:, names], allow_copy=self._allow_copy) + + def get_chunks(self, n_chunks: int | None = None) -> Iterable[PandasDataFrameXchg]: + """ + Return an iterator yielding the chunks. + """ + if n_chunks and n_chunks > 1: + size = len(self._df) + step = size // n_chunks + if size % n_chunks != 0: + step += 1 + for start in range(0, step * n_chunks, step): + yield PandasDataFrameXchg( + self._df.iloc[start : start + step, :], + allow_copy=self._allow_copy, + ) + else: + yield self diff --git a/shared/package-files/33/335d111c3ea2342e83a5b02c3eb2e423783fad1fdfb3424854a6988135c720d2/apple80p b/shared/package-files/33/335d111c3ea2342e83a5b02c3eb2e423783fad1fdfb3424854a6988135c720d2/apple80p new file mode 100644 index 0000000000000000000000000000000000000000..60c92c6fd4556546b4736f2b7d363819a9061cd2 Binary files /dev/null and b/shared/package-files/33/335d111c3ea2342e83a5b02c3eb2e423783fad1fdfb3424854a6988135c720d2/apple80p differ diff --git a/shared/package-files/33/335fb9da0445995a7f6748e7c997d3503a9bc8c4db9a1693711b7e3fb1fd276f/missing.py b/shared/package-files/33/335fb9da0445995a7f6748e7c997d3503a9bc8c4db9a1693711b7e3fb1fd276f/missing.py new file mode 100644 index 0000000000000000000000000000000000000000..0ea262b5c561c75c8ce4e36dad8a53db7df9538a --- /dev/null +++ b/shared/package-files/33/335fb9da0445995a7f6748e7c997d3503a9bc8c4db9a1693711b7e3fb1fd276f/missing.py @@ -0,0 +1,269 @@ +# This file is part of Patsy +# Copyright (C) 2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Missing data detection/handling + +# First, how do we represent missing data? (i.e., which values count as +# "missing"?) In the long run, we want to use numpy's NA support... but that +# doesn't exist yet. Until then, people use various sorts of ad-hoc +# things. Some things that might be considered NA: +# NA (eventually) +# NaN (in float or object arrays) +# None (in object arrays) +# np.ma.masked (in numpy.ma masked arrays) +# Pandas compatibility considerations: +# For numeric arrays, None is unconditionally converted to NaN. +# For object arrays (including string arrays!), None and NaN are preserved, +# but pandas.isnull() returns True for both. +# np.ma compatibility considerations: +# Preserving array subtypes is a huge pain, because it means that we can't +# just call 'asarray' and be done... we already jump through tons of hoops +# to write code that can handle both ndarray's and pandas objects, and +# just thinking about adding another item to this list makes me tired. So +# for now we don't support np.ma missing values. Use pandas! + +# Next, what should be done once we find missing data? R's options: +# -- throw away those rows (from all aligned matrices) +# -- with or without preserving information on which rows were discarded +# -- error out +# -- carry on +# The 'carry on' option requires that we have some way to represent NA in our +# output array. To avoid further solidifying the use of NaN for this purpose, +# we'll leave this option out for now, until real NA support is +# available. Also, we always preserve information on which rows were +# discarded, using the pandas index functionality (currently this is only +# returned to the original caller if they used return_type="dataframe", +# though). + +import numpy as np +from patsy import PatsyError +from patsy.util import safe_isnan, safe_scalar_isnan, no_pickling, assert_no_pickling + +# These are made available in the patsy.* namespace +__all__ = ["NAAction"] + +_valid_NA_types = ["None", "NaN"] +_valid_NA_responses = ["raise", "drop"] + + +def _desc_options(options): + return ", ".join([repr(opt) for opt in options]) + + +class NAAction(object): + """An :class:`NAAction` object defines a strategy for handling missing + data. + + "NA" is short for "Not Available", and is used to refer to any value which + is somehow unmeasured or unavailable. In the long run, it is devoutly + hoped that numpy will gain first-class missing value support. Until then, + we work around this lack as best we're able. + + There are two parts to this: First, we have to determine what counts as + missing data. For numerical data, the default is to treat NaN values + (e.g., ``numpy.nan``) as missing. For categorical data, the default is to + treat NaN values, and also the Python object None, as missing. (This is + consistent with how pandas does things, so if you're already using + None/NaN to mark missing data in your pandas DataFrames, you're good to + go.) + + Second, we have to decide what to do with any missing data when we + encounter it. One option is to simply discard any rows which contain + missing data from our design matrices (``drop``). Another option is to + raise an error (``raise``). A third option would be to simply let the + missing values pass through into the returned design matrices. However, + this last option is not yet implemented, because of the lack of any + standard way to represent missing values in arbitrary numpy matrices; + we're hoping numpy will get this sorted out before we standardize on + anything ourselves. + + You can control how patsy handles missing data through the ``NA_action=`` + argument to functions like :func:`build_design_matrices` and + :func:`dmatrix`. If all you want to do is to choose between ``drop`` and + ``raise`` behaviour, you can pass one of those strings as the + ``NA_action=`` argument directly. If you want more fine-grained control + over how missing values are detected and handled, then you can create an + instance of this class, or your own object that implements the same + interface, and pass that as the ``NA_action=`` argument instead. + """ + + def __init__(self, on_NA="drop", NA_types=["None", "NaN"]): + """The :class:`NAAction` constructor takes the following arguments: + + :arg on_NA: How to handle missing values. The default is ``"drop"``, + which removes all rows from all matrices which contain any missing + values. Also available is ``"raise"``, which raises an exception + when any missing values are encountered. + :arg NA_types: Which rules are used to identify missing values, as a + list of strings. Allowed values are: + + * ``"None"``: treat the ``None`` object as missing in categorical + data. + * ``"NaN"``: treat floating point NaN values as missing in + categorical and numerical data. + + .. versionadded:: 0.2.0 + """ + self.on_NA = on_NA + if self.on_NA not in _valid_NA_responses: + raise ValueError( + "invalid on_NA action %r " + "(should be one of %s)" % (on_NA, _desc_options(_valid_NA_responses)) + ) + if isinstance(NA_types, str): + raise ValueError("NA_types should be a list of strings") + self.NA_types = tuple(NA_types) + for NA_type in self.NA_types: + if NA_type not in _valid_NA_types: + raise ValueError( + "invalid NA_type %r " + "(should be one of %s)" % (NA_type, _desc_options(_valid_NA_types)) + ) + + def is_categorical_NA(self, obj): + """Return True if `obj` is a categorical NA value. + + Note that here `obj` is a single scalar value.""" + if "NaN" in self.NA_types and safe_scalar_isnan(obj): + return True + if "None" in self.NA_types and obj is None: + return True + return False + + def is_numerical_NA(self, arr): + """Returns a 1-d mask array indicating which rows in an array of + numerical values contain at least one NA value. + + Note that here `arr` is a numpy array or pandas DataFrame.""" + mask = np.zeros(arr.shape, dtype=bool) + if "NaN" in self.NA_types: + mask |= np.isnan(arr) + if mask.ndim > 1: + mask = np.any(mask, axis=1) + return mask + + def handle_NA(self, values, is_NAs, origins): + """Takes a set of factor values that may have NAs, and handles them + appropriately. + + :arg values: A list of `ndarray` objects representing the data. + These may be 1- or 2-dimensional, and may be of varying dtype. All + will have the same number of rows (or entries, for 1-d arrays). + :arg is_NAs: A list with the same number of entries as `values`, + containing boolean `ndarray` objects that indicate which rows + contain NAs in the corresponding entry in `values`. + :arg origins: A list with the same number of entries as + `values`, containing information on the origin of each + value. If we encounter a problem with some particular value, we use + the corresponding entry in `origins` as the origin argument when + raising a :class:`PatsyError`. + :returns: A list of new values (which may have a differing number of + rows.) + """ + assert len(values) == len(is_NAs) == len(origins) + if len(values) == 0: + return values + if self.on_NA == "raise": + return self._handle_NA_raise(values, is_NAs, origins) + elif self.on_NA == "drop": + return self._handle_NA_drop(values, is_NAs, origins) + else: # pragma: no cover + assert False + + def _handle_NA_raise(self, values, is_NAs, origins): + for is_NA, origin in zip(is_NAs, origins): + if np.any(is_NA): + raise PatsyError("factor contains missing values", origin) + return values + + def _handle_NA_drop(self, values, is_NAs, origins): + total_mask = np.zeros(is_NAs[0].shape[0], dtype=bool) + for is_NA in is_NAs: + total_mask |= is_NA + good_mask = ~total_mask + # "..." to handle 1- versus 2-dim indexing + return [v[good_mask] if v.ndim == 1 else v[good_mask, ...] for v in values] + + __getstate__ = no_pickling + + +def test_NAAction_basic(): + import pytest + + pytest.raises(ValueError, NAAction, on_NA="pord") + pytest.raises(ValueError, NAAction, NA_types=("NaN", "asdf")) + pytest.raises(ValueError, NAAction, NA_types="NaN") + + assert_no_pickling(NAAction()) + + +def test_NAAction_NA_types_numerical(): + for NA_types in [[], ["NaN"], ["None"], ["NaN", "None"]]: + action = NAAction(NA_types=NA_types) + for extra_shape in [(), (1,), (2,)]: + arr = np.ones((4,) + extra_shape, dtype=float) + nan_rows = [0, 2] + if arr.ndim > 1 and arr.shape[1] > 1: + arr[nan_rows, [0, 1]] = np.nan + else: + arr[nan_rows] = np.nan + exp_NA_mask = np.zeros(4, dtype=bool) + if "NaN" in NA_types: + exp_NA_mask[nan_rows] = True + got_NA_mask = action.is_numerical_NA(arr) + assert np.array_equal(got_NA_mask, exp_NA_mask) + + +def test_NAAction_NA_types_categorical(): + for NA_types in [[], ["NaN"], ["None"], ["NaN", "None"]]: + action = NAAction(NA_types=NA_types) + assert not action.is_categorical_NA("a") + assert not action.is_categorical_NA(1) + assert action.is_categorical_NA(None) == ("None" in NA_types) + assert action.is_categorical_NA(np.nan) == ("NaN" in NA_types) + + +def test_NAAction_drop(): + action = NAAction("drop") + in_values = [ + np.asarray([-1, 2, -1, 4, 5]), + np.asarray([10.0, 20.0, 30.0, 40.0, 50.0]), + np.asarray([[1.0, np.nan], [3.0, 4.0], [10.0, 5.0], [6.0, 7.0], [8.0, np.nan]]), + ] + is_NAs = [ + np.asarray([True, False, True, False, False]), + np.zeros(5, dtype=bool), + np.asarray([True, False, False, False, True]), + ] + out_values = action.handle_NA(in_values, is_NAs, [None] * 3) + assert len(out_values) == 3 + assert np.array_equal(out_values[0], [2, 4]) + assert np.array_equal(out_values[1], [20.0, 40.0]) + assert np.array_equal(out_values[2], [[3.0, 4.0], [6.0, 7.0]]) + + +def test_NAAction_raise(): + action = NAAction(on_NA="raise") + + # no-NA just passes through: + in_arrs = [np.asarray([1.1, 1.2]), np.asarray([1, 2])] + is_NAs = [np.asarray([False, False])] * 2 + got_arrs = action.handle_NA(in_arrs, is_NAs, [None, None]) + assert np.array_equal(got_arrs[0], in_arrs[0]) + assert np.array_equal(got_arrs[1], in_arrs[1]) + + from patsy.origin import Origin + + o1 = Origin("asdf", 0, 1) + o2 = Origin("asdf", 2, 3) + + # NA raises an error with a correct origin + in_idx = np.arange(2) + in_arrs = [np.asarray([1.1, 1.2]), np.asarray([1.0, np.nan])] + is_NAs = [np.asarray([False, False]), np.asarray([False, True])] + try: + action.handle_NA(in_arrs, is_NAs, [o1, o2]) + assert False + except PatsyError as e: + assert e.origin is o2 diff --git a/shared/package-files/33/335fe549be2e3479766a466442580e7f6d529dfbeb590cfaaf26ed0885407584/types.pxi b/shared/package-files/33/335fe549be2e3479766a466442580e7f6d529dfbeb590cfaaf26ed0885407584/types.pxi new file mode 100644 index 0000000000000000000000000000000000000000..792c0840f813de7ff7b54568dc3360328af38270 --- /dev/null +++ b/shared/package-files/33/335fe549be2e3479766a466442580e7f6d529dfbeb590cfaaf26ed0885407584/types.pxi @@ -0,0 +1,6103 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from cpython.pycapsule cimport ( + PyCapsule_CheckExact, + PyCapsule_GetPointer, + PyCapsule_GetName, + PyCapsule_New, + PyCapsule_IsValid +) + +import atexit +from collections.abc import Mapping +import pickle +import re +import sys +import warnings +from cython import sizeof + +# These are imprecise because the type (in pandas 0.x) depends on the presence +# of nulls +cdef dict _pandas_type_map = {} + + +def _get_pandas_type_map(): + global _pandas_type_map + if not _pandas_type_map: + _pandas_type_map.update({ + _Type_NA: np.object_, # NaNs + _Type_BOOL: np.bool_, + _Type_INT8: np.int8, + _Type_INT16: np.int16, + _Type_INT32: np.int32, + _Type_INT64: np.int64, + _Type_UINT8: np.uint8, + _Type_UINT16: np.uint16, + _Type_UINT32: np.uint32, + _Type_UINT64: np.uint64, + _Type_HALF_FLOAT: np.float16, + _Type_FLOAT: np.float32, + _Type_DOUBLE: np.float64, + # Pandas does not support [D]ay, so default to [ms] for date32 + _Type_DATE32: np.dtype('datetime64[ms]'), + _Type_DATE64: np.dtype('datetime64[ms]'), + _Type_TIMESTAMP: { + 's': np.dtype('datetime64[s]'), + 'ms': np.dtype('datetime64[ms]'), + 'us': np.dtype('datetime64[us]'), + 'ns': np.dtype('datetime64[ns]'), + }, + _Type_DURATION: { + 's': np.dtype('timedelta64[s]'), + 'ms': np.dtype('timedelta64[ms]'), + 'us': np.dtype('timedelta64[us]'), + 'ns': np.dtype('timedelta64[ns]'), + }, + _Type_BINARY: np.object_, + _Type_LARGE_BINARY: np.object_, + _Type_BINARY_VIEW: np.object_, + _Type_FIXED_SIZE_BINARY: np.object_, + _Type_STRING: np.object_, + _Type_LARGE_STRING: np.object_, + _Type_STRING_VIEW: np.object_, + _Type_LIST: np.object_, + _Type_MAP: np.object_, + _Type_DECIMAL32: np.object_, + _Type_DECIMAL64: np.object_, + _Type_DECIMAL128: np.object_, + _Type_DECIMAL256: np.object_, + }) + return _pandas_type_map + + +cdef dict _pep3118_type_map = { + _Type_INT8: b'b', + _Type_INT16: b'h', + _Type_INT32: b'i', + _Type_INT64: b'q', + _Type_UINT8: b'B', + _Type_UINT16: b'H', + _Type_UINT32: b'I', + _Type_UINT64: b'Q', + _Type_HALF_FLOAT: b'e', + _Type_FLOAT: b'f', + _Type_DOUBLE: b'd', +} + + +cdef bytes _datatype_to_pep3118(CDataType* type): + """ + Construct a PEP 3118 format string describing the given datatype. + None is returned for unsupported types. + """ + try: + char = _pep3118_type_map[type.id()] + except KeyError: + return None + else: + if char in b'bBhHiIqQ': + # Use "standard" int widths, not native + return b'=' + char + else: + return char + + +cdef void* _as_c_pointer(v, allow_null=False) except *: + """ + Convert a Python object to a raw C pointer. + + Used mainly for the C data interface. + Integers are accepted as well as capsule objects with a NULL name. + (the latter for compatibility with raw pointers exported by reticulate) + """ + cdef void* c_ptr + cdef const char* capsule_name + if isinstance(v, int): + c_ptr = v + elif isinstance(v, float): + warnings.warn( + "Passing a pointer value as a float is unsafe and only " + "supported for compatibility with older versions of the R " + "Arrow library", UserWarning, stacklevel=2) + c_ptr = v + elif PyCapsule_CheckExact(v): + # An R external pointer was how the R bindings passed pointer values to + # Python from versions 7 to 15 (inclusive); however, the reticulate 1.35.0 + # update changed the name of the capsule from NULL to "r_extptr". + # Newer versions of the R package pass a Python integer; however, this + # workaround ensures that old versions of the R package continue to work + # with newer versions of pyarrow. + capsule_name = PyCapsule_GetName(v) + if capsule_name == NULL or capsule_name == b"r_extptr": + c_ptr = PyCapsule_GetPointer(v, capsule_name) + else: + capsule_name_str = capsule_name.decode() + raise ValueError( + f"Can't convert PyCapsule with name '{capsule_name_str}' to pointer address" + ) + else: + raise TypeError(f"Expected a pointer value, got {type(v)!r}") + if not allow_null and c_ptr == NULL: + raise ValueError(f"Null pointer (value before cast = {v!r})") + return c_ptr + + +def _is_primitive(Type type): + # This is simply a redirect, the official API is in pyarrow.types. + return is_primitive(type) + + +def _get_pandas_type(arrow_type, coerce_to_ns=False): + cdef Type type_id = arrow_type.id + cdef dict pandas_type_map = _get_pandas_type_map() + if type_id not in pandas_type_map: + return None + if coerce_to_ns: + # ARROW-3789: Coerce date/timestamp types to datetime64[ns] + if type_id == _Type_DURATION: + return np.dtype('timedelta64[ns]') + return np.dtype('datetime64[ns]') + pandas_type = pandas_type_map[type_id] + if isinstance(pandas_type, dict): + unit = getattr(arrow_type, 'unit', None) + pandas_type = pandas_type.get(unit, None) + return pandas_type + + +def _get_pandas_tz_type(arrow_type, coerce_to_ns=False): + from pyarrow.pandas_compat import make_datetimetz + unit = 'ns' if coerce_to_ns else arrow_type.unit + return make_datetimetz(unit, arrow_type.tz) + + +def _to_pandas_dtype(arrow_type, options=None): + coerce_to_ns = (options and options.get('coerce_temporal_nanoseconds', False)) or ( + _pandas_api.is_v1() and arrow_type.id in + [_Type_DATE32, _Type_DATE64, _Type_TIMESTAMP, _Type_DURATION]) + + if getattr(arrow_type, 'tz', None): + dtype = _get_pandas_tz_type(arrow_type, coerce_to_ns) + else: + dtype = _get_pandas_type(arrow_type, coerce_to_ns) + + if not dtype: + raise NotImplementedError(str(arrow_type)) + + return dtype + + +# Workaround for Cython parsing bug +# https://github.com/cython/cython/issues/2143 +ctypedef CFixedWidthType* _CFixedWidthTypePtr + + +cdef class DataType(_Weakrefable): + """ + Base class of all Arrow data types. + + Each data type is an *instance* of this class. + + Examples + -------- + Instance of int64 type: + + >>> import pyarrow as pa + >>> pa.int64() + DataType(int64) + """ + + def __cinit__(self): + pass + + def __init__(self): + raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly, use public " + "functions like pyarrow.int64, pyarrow.list_, etc. " + "instead.") + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + assert type != nullptr + self.sp_type = type + self.type = type.get() + self.pep3118_format = _datatype_to_pep3118(self.type) + + cpdef Field field(self, i): + """ + Parameters + ---------- + i : int + + Returns + ------- + pyarrow.Field + """ + if not isinstance(i, int): + raise TypeError(f"Expected int index, got type '{type(i)}'") + cdef int index = _normalize_index(i, self.type.num_fields()) + return pyarrow_wrap_field(self.type.field(index)) + + @property + def id(self): + return self.type.id() + + @property + def bit_width(self): + """ + Bit width for fixed width type. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.int64() + DataType(int64) + >>> pa.int64().bit_width + 64 + """ + cdef _CFixedWidthTypePtr ty + ty = dynamic_cast[_CFixedWidthTypePtr](self.type) + if ty == nullptr: + raise ValueError("Non-fixed width type") + return ty.bit_width() + + @property + def byte_width(self): + """ + Byte width for fixed width type. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.int64() + DataType(int64) + >>> pa.int64().byte_width + 8 + """ + cdef _CFixedWidthTypePtr ty + ty = dynamic_cast[_CFixedWidthTypePtr](self.type) + if ty == nullptr: + raise ValueError("Non-fixed width type") + byte_width = ty.byte_width() + if byte_width == 0 and self.bit_width != 0: + raise ValueError("Less than one byte") + return byte_width + + @property + def num_fields(self): + """ + The number of child fields. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.int64() + DataType(int64) + >>> pa.int64().num_fields + 0 + >>> pa.list_(pa.string()) + ListType(list) + >>> pa.list_(pa.string()).num_fields + 1 + >>> struct = pa.struct({'x': pa.int32(), 'y': pa.string()}) + >>> struct.num_fields + 2 + """ + return self.type.num_fields() + + @property + def num_buffers(self): + """ + Number of data buffers required to construct Array type + excluding children. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.int64().num_buffers + 2 + >>> pa.string().num_buffers + 3 + """ + return self.type.layout().buffers.size() + + @property + def has_variadic_buffers(self): + """ + If True, the number of expected buffers is only + lower-bounded by num_buffers. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.int64().has_variadic_buffers + False + >>> pa.string_view().has_variadic_buffers + True + """ + return self.type.layout().variadic_spec.has_value() + + def __str__(self): + return frombytes(self.type.ToString(), safe=True) + + def __hash__(self): + return hash(str(self)) + + def __reduce__(self): + return type_for_alias, (str(self),) + + def __repr__(self): + return f'{self.__class__.__name__}({self})' + + def __eq__(self, other): + try: + return self.equals(other) + except (TypeError, ValueError): + return NotImplemented + + def equals(self, other, *, check_metadata=False): + """ + Return true if type is equivalent to passed value. + + Parameters + ---------- + other : DataType or string convertible to DataType + check_metadata : bool + Whether nested Field metadata equality should be checked as well. + + Returns + ------- + is_equal : bool + + Examples + -------- + >>> import pyarrow as pa + >>> pa.int64().equals(pa.string()) + False + >>> pa.int64().equals(pa.int64()) + True + """ + cdef: + DataType other_type + c_bool c_check_metadata + + other_type = ensure_type(other) + c_check_metadata = check_metadata + return self.type.Equals(deref(other_type.type), c_check_metadata) + + def to_pandas_dtype(self): + """ + Return the equivalent NumPy / Pandas dtype. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.int64().to_pandas_dtype() + + """ + return _to_pandas_dtype(self) + + def _export_to_c(self, out_ptr): + """ + Export to a C ArrowSchema struct, given its pointer. + + Be careful: if you don't pass the ArrowSchema struct to a consumer, + its memory will leak. This is a low-level function intended for + expert users. + """ + check_status(ExportType(deref(self.type), + _as_c_pointer(out_ptr))) + + @staticmethod + def _import_from_c(in_ptr): + """ + Import DataType from a C ArrowSchema struct, given its pointer. + + This is a low-level function intended for expert users. + """ + result = GetResultValue(ImportType( + _as_c_pointer(in_ptr))) + return pyarrow_wrap_data_type(result) + + def __arrow_c_schema__(self): + """ + Export to a ArrowSchema PyCapsule + + Unlike _export_to_c, this will not leak memory if the capsule is not used. + """ + cdef ArrowSchema* c_schema + capsule = alloc_c_schema(&c_schema) + + with nogil: + check_status(ExportType(deref(self.type), c_schema)) + + return capsule + + @staticmethod + def _import_from_c_capsule(schema): + """ + Import a DataType from a ArrowSchema PyCapsule + + Parameters + ---------- + schema : PyCapsule + A valid PyCapsule with name 'arrow_schema' containing an + ArrowSchema pointer. + """ + cdef: + ArrowSchema* c_schema + shared_ptr[CDataType] c_type + + if not PyCapsule_IsValid(schema, 'arrow_schema'): + raise TypeError( + "Not an ArrowSchema object" + ) + c_schema = PyCapsule_GetPointer(schema, 'arrow_schema') + + with nogil: + c_type = GetResultValue(ImportType(c_schema)) + + return pyarrow_wrap_data_type(c_type) + + +cdef class DictionaryMemo(_Weakrefable): + """ + Tracking container for dictionary-encoded fields. + """ + + def __cinit__(self): + self.sp_memo.reset(new CDictionaryMemo()) + self.memo = self.sp_memo.get() + + +cdef class DictionaryType(DataType): + """ + Concrete class for dictionary data types. + + Examples + -------- + Create an instance of dictionary type: + + >>> import pyarrow as pa + >>> pa.dictionary(pa.int64(), pa.utf8()) + DictionaryType(dictionary) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.dict_type = type.get() + + def __reduce__(self): + return dictionary, (self.index_type, self.value_type, self.ordered) + + @property + def ordered(self): + """ + Whether the dictionary is ordered, i.e. whether the ordering of values + in the dictionary is important. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.dictionary(pa.int64(), pa.utf8()).ordered + False + """ + return self.dict_type.ordered() + + @property + def index_type(self): + """ + The data type of dictionary indices (a signed integer type). + + Examples + -------- + >>> import pyarrow as pa + >>> pa.dictionary(pa.int16(), pa.utf8()).index_type + DataType(int16) + """ + return pyarrow_wrap_data_type(self.dict_type.index_type()) + + @property + def value_type(self): + """ + The dictionary value type. + + The dictionary values are found in an instance of DictionaryArray. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.dictionary(pa.int16(), pa.utf8()).value_type + DataType(string) + """ + return pyarrow_wrap_data_type(self.dict_type.value_type()) + + +cdef class ListType(DataType): + """ + Concrete class for list data types. + + Examples + -------- + Create an instance of ListType: + + >>> import pyarrow as pa + >>> pa.list_(pa.string()) + ListType(list) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.list_type = type.get() + + def __reduce__(self): + return list_, (self.value_field,) + + @property + def value_field(self): + """ + The field for list values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.list_(pa.string()).value_field + pyarrow.Field + """ + return pyarrow_wrap_field(self.list_type.value_field()) + + @property + def value_type(self): + """ + The data type of list values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.list_(pa.string()).value_type + DataType(string) + """ + return pyarrow_wrap_data_type(self.list_type.value_type()) + + +cdef class LargeListType(DataType): + """ + Concrete class for large list data types + (like ListType, but with 64-bit offsets). + + Examples + -------- + Create an instance of LargeListType: + + >>> import pyarrow as pa + >>> pa.large_list(pa.string()) + LargeListType(large_list) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.list_type = type.get() + + def __reduce__(self): + return large_list, (self.value_field,) + + @property + def value_field(self): + return pyarrow_wrap_field(self.list_type.value_field()) + + @property + def value_type(self): + """ + The data type of large list values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.large_list(pa.string()).value_type + DataType(string) + """ + return pyarrow_wrap_data_type(self.list_type.value_type()) + + +cdef class ListViewType(DataType): + """ + Concrete class for list view data types. + + Examples + -------- + Create an instance of ListViewType: + + >>> import pyarrow as pa + >>> pa.list_view(pa.string()) + ListViewType(list_view) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.list_view_type = type.get() + + def __reduce__(self): + return list_view, (self.value_field,) + + @property + def value_field(self): + """ + The field for list view values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.list_view(pa.string()).value_field + pyarrow.Field + """ + return pyarrow_wrap_field(self.list_view_type.value_field()) + + @property + def value_type(self): + """ + The data type of list view values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.list_view(pa.string()).value_type + DataType(string) + """ + return pyarrow_wrap_data_type(self.list_view_type.value_type()) + + +cdef class LargeListViewType(DataType): + """ + Concrete class for large list view data types + (like ListViewType, but with 64-bit offsets). + + Examples + -------- + Create an instance of LargeListViewType: + + >>> import pyarrow as pa + >>> pa.large_list_view(pa.string()) + LargeListViewType(large_list_view) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.list_view_type = type.get() + + def __reduce__(self): + return large_list_view, (self.value_field,) + + @property + def value_field(self): + """ + The field for large list view values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.large_list_view(pa.string()).value_field + pyarrow.Field + """ + return pyarrow_wrap_field(self.list_view_type.value_field()) + + @property + def value_type(self): + """ + The data type of large list view values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.large_list_view(pa.string()).value_type + DataType(string) + """ + return pyarrow_wrap_data_type(self.list_view_type.value_type()) + + +cdef class MapType(DataType): + """ + Concrete class for map data types. + + Examples + -------- + Create an instance of MapType: + + >>> import pyarrow as pa + >>> pa.map_(pa.string(), pa.int32()) + MapType(map) + >>> pa.map_(pa.string(), pa.int32(), keys_sorted=True) + MapType(map) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.map_type = type.get() + + def __reduce__(self): + return map_, (self.key_field, self.item_field) + + @property + def key_field(self): + """ + The field for keys in the map entries. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.map_(pa.string(), pa.int32()).key_field + pyarrow.Field + """ + return pyarrow_wrap_field(self.map_type.key_field()) + + @property + def key_type(self): + """ + The data type of keys in the map entries. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.map_(pa.string(), pa.int32()).key_type + DataType(string) + """ + return pyarrow_wrap_data_type(self.map_type.key_type()) + + @property + def item_field(self): + """ + The field for items in the map entries. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.map_(pa.string(), pa.int32()).item_field + pyarrow.Field + """ + return pyarrow_wrap_field(self.map_type.item_field()) + + @property + def item_type(self): + """ + The data type of items in the map entries. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.map_(pa.string(), pa.int32()).item_type + DataType(int32) + """ + return pyarrow_wrap_data_type(self.map_type.item_type()) + + @property + def keys_sorted(self): + """ + Should the entries be sorted according to keys. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.map_(pa.string(), pa.int32(), keys_sorted=True).keys_sorted + True + """ + return self.map_type.keys_sorted() + + +cdef class FixedSizeListType(DataType): + """ + Concrete class for fixed size list data types. + + Examples + -------- + Create an instance of FixedSizeListType: + + >>> import pyarrow as pa + >>> pa.list_(pa.int32(), 2) + FixedSizeListType(fixed_size_list[2]) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.list_type = type.get() + + def __reduce__(self): + return list_, (self.value_type, self.list_size) + + @property + def value_field(self): + """ + The field for list values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.list_(pa.int32(), 2).value_field + pyarrow.Field + """ + return pyarrow_wrap_field(self.list_type.value_field()) + + @property + def value_type(self): + """ + The data type of large list values. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.list_(pa.int32(), 2).value_type + DataType(int32) + """ + return pyarrow_wrap_data_type(self.list_type.value_type()) + + @property + def list_size(self): + """ + The size of the fixed size lists. + + Examples + -------- + >>> import pyarrow as pa + >>> pa.list_(pa.int32(), 2).list_size + 2 + """ + return self.list_type.list_size() + + +cdef class StructType(DataType): + """ + Concrete class for struct data types. + + ``StructType`` supports direct indexing using ``[...]`` (implemented via + ``__getitem__``) to access its fields. + It will return the struct field with the given index or name. + + Examples + -------- + >>> import pyarrow as pa + + Accessing fields using direct indexing: + + >>> struct_type = pa.struct({'x': pa.int32(), 'y': pa.string()}) + >>> struct_type[0] + pyarrow.Field + >>> struct_type['y'] + pyarrow.Field + + Accessing fields using ``field()``: + + >>> struct_type.field(1) + pyarrow.Field + >>> struct_type.field('x') + pyarrow.Field + + # Creating a schema from the struct type's fields: + >>> pa.schema(list(struct_type)) + x: int32 + y: string + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.struct_type = type.get() + + cdef Field field_by_name(self, name): + """ + Return a child field by its name. + + Parameters + ---------- + name : str + The name of the field to look up. + + Returns + ------- + field : Field + The child field with the given name. + + Raises + ------ + KeyError + If the name isn't found, or if several fields have the given + name. + """ + cdef vector[shared_ptr[CField]] fields + + fields = self.struct_type.GetAllFieldsByName(tobytes(name)) + if fields.size() == 0: + raise KeyError(name) + elif fields.size() > 1: + warnings.warn("Struct field name corresponds to more " + "than one field", UserWarning) + raise KeyError(name) + else: + return pyarrow_wrap_field(fields[0]) + + def get_field_index(self, name): + """ + Return index of the unique field with the given name. + + Parameters + ---------- + name : str + The name of the field to look up. + + Returns + ------- + index : int + The index of the field with the given name; -1 if the + name isn't found or there are several fields with the given + name. + + Examples + -------- + >>> import pyarrow as pa + >>> struct_type = pa.struct({'x': pa.int32(), 'y': pa.string()}) + + Index of the field with a name 'y': + + >>> struct_type.get_field_index('y') + 1 + + Index of the field that does not exist: + + >>> struct_type.get_field_index('z') + -1 + """ + return self.struct_type.GetFieldIndex(tobytes(name)) + + cpdef Field field(self, i): + """ + Select a field by its column name or numeric index. + + Parameters + ---------- + i : int or str + + Returns + ------- + pyarrow.Field + + Examples + -------- + + >>> import pyarrow as pa + >>> struct_type = pa.struct({'x': pa.int32(), 'y': pa.string()}) + + Select the second field: + + >>> struct_type.field(1) + pyarrow.Field + + Select the field named 'x': + + >>> struct_type.field('x') + pyarrow.Field + """ + if isinstance(i, (bytes, str)): + return self.field_by_name(i) + elif isinstance(i, int): + return DataType.field(self, i) + else: + raise TypeError('Expected integer or string index') + + def get_all_field_indices(self, name): + """ + Return sorted list of indices for the fields with the given name. + + Parameters + ---------- + name : str + The name of the field to look up. + + Returns + ------- + indices : List[int] + + Examples + -------- + >>> import pyarrow as pa + >>> struct_type = pa.struct({'x': pa.int32(), 'y': pa.string()}) + >>> struct_type.get_all_field_indices('x') + [0] + """ + return self.struct_type.GetAllFieldIndices(tobytes(name)) + + def __len__(self): + """ + Like num_fields(). + """ + return self.type.num_fields() + + def __iter__(self): + """ + Iterate over struct fields, in order. + """ + for i in range(len(self)): + yield self[i] + + def __getitem__(self, i): + """ + Return the struct field with the given index or name. + + Alias of ``field``. + """ + return self.field(i) + + def __reduce__(self): + return struct, (list(self),) + + @property + def names(self): + """ + Lists the field names. + + Examples + -------- + >>> import pyarrow as pa + >>> struct_type = pa.struct([('a', pa.int64()), ('b', pa.float64()), ('c', pa.string())]) + >>> struct_type.names + ['a', 'b', 'c'] + """ + return [f.name for f in self] + + @property + def fields(self): + """ + Lists all fields within the StructType. + + Examples + -------- + >>> import pyarrow as pa + >>> struct_type = pa.struct([('a', pa.int64()), ('b', pa.float64()), ('c', pa.string())]) + >>> struct_type.fields + [pyarrow.Field, pyarrow.Field, pyarrow.Field] + """ + return list(self) + +cdef class UnionType(DataType): + """ + Base class for union data types. + + Examples + -------- + Create an instance of a dense UnionType using ``pa.union``: + + >>> import pyarrow as pa + >>> pa.union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())], + ... mode=pa.lib.UnionMode_DENSE), + (DenseUnionType(dense_union),) + + Create an instance of a dense UnionType using ``pa.dense_union``: + + >>> pa.dense_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())]) + DenseUnionType(dense_union) + + Create an instance of a sparse UnionType using ``pa.union``: + + >>> pa.union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())], + ... mode=pa.lib.UnionMode_SPARSE), + (SparseUnionType(sparse_union),) + + Create an instance of a sparse UnionType using ``pa.sparse_union``: + + >>> pa.sparse_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())]) + SparseUnionType(sparse_union) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + + @property + def mode(self): + """ + The mode of the union ("dense" or "sparse"). + + Examples + -------- + >>> import pyarrow as pa + >>> union = pa.sparse_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())]) + >>> union.mode + 'sparse' + """ + cdef CUnionType* type = self.sp_type.get() + cdef int mode = type.mode() + if mode == _UnionMode_DENSE: + return 'dense' + if mode == _UnionMode_SPARSE: + return 'sparse' + assert 0 + + @property + def type_codes(self): + """ + The type code to indicate each data type in this union. + + Examples + -------- + >>> import pyarrow as pa + >>> union = pa.sparse_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())]) + >>> union.type_codes + [0, 1] + """ + cdef CUnionType* type = self.sp_type.get() + return type.type_codes() + + def __len__(self): + """ + Like num_fields(). + """ + return self.type.num_fields() + + def __iter__(self): + """ + Iterate over union members, in order. + """ + for i in range(len(self)): + yield self[i] + + cpdef Field field(self, i): + """ + Return a child field by its numeric index. + + Parameters + ---------- + i : int + + Returns + ------- + pyarrow.Field + + Examples + -------- + >>> import pyarrow as pa + >>> union = pa.sparse_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())]) + >>> union[0] + pyarrow.Field + """ + if isinstance(i, int): + return DataType.field(self, i) + else: + raise TypeError('Expected integer') + + def __getitem__(self, i): + """ + Return a child field by its index. + + Alias of ``field``. + """ + return self.field(i) + + def __reduce__(self): + return union, (list(self), self.mode, self.type_codes) + + +cdef class SparseUnionType(UnionType): + """ + Concrete class for sparse union types. + + Examples + -------- + Create an instance of a sparse UnionType using ``pa.union``: + + >>> import pyarrow as pa + >>> pa.union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())], + ... mode=pa.lib.UnionMode_SPARSE), + (SparseUnionType(sparse_union),) + + Create an instance of a sparse UnionType using ``pa.sparse_union``: + + >>> pa.sparse_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())]) + SparseUnionType(sparse_union) + """ + + +cdef class DenseUnionType(UnionType): + """ + Concrete class for dense union types. + + Examples + -------- + Create an instance of a dense UnionType using ``pa.union``: + + >>> import pyarrow as pa + >>> pa.union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())], + ... mode=pa.lib.UnionMode_DENSE), + (DenseUnionType(dense_union),) + + Create an instance of a dense UnionType using ``pa.dense_union``: + + >>> pa.dense_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())]) + DenseUnionType(dense_union) + """ + + +cdef class TimestampType(DataType): + """ + Concrete class for timestamp data types. + + Examples + -------- + >>> import pyarrow as pa + + Create an instance of timestamp type: + + >>> pa.timestamp('us') + TimestampType(timestamp[us]) + + Create an instance of timestamp type with timezone: + + >>> pa.timestamp('s', tz='UTC') + TimestampType(timestamp[s, tz=UTC]) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.ts_type = type.get() + + @property + def unit(self): + """ + The timestamp unit ('s', 'ms', 'us' or 'ns'). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.timestamp('us') + >>> t.unit + 'us' + """ + return timeunit_to_string(self.ts_type.unit()) + + @property + def tz(self): + """ + The timestamp time zone, if any, or None. + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.timestamp('s', tz='UTC') + >>> t.tz + 'UTC' + """ + if self.ts_type.timezone().size() > 0: + return frombytes(self.ts_type.timezone()) + else: + return None + + def __reduce__(self): + return timestamp, (self.unit, self.tz) + + +cdef class Time32Type(DataType): + """ + Concrete class for time32 data types. + + Supported time unit resolutions are 's' [second] + and 'ms' [millisecond]. + + Examples + -------- + Create an instance of time32 type: + + >>> import pyarrow as pa + >>> pa.time32('ms') + Time32Type(time32[ms]) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.time_type = type.get() + + @property + def unit(self): + """ + The time unit ('s' or 'ms'). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.time32('ms') + >>> t.unit + 'ms' + """ + return timeunit_to_string(self.time_type.unit()) + + +cdef class Time64Type(DataType): + """ + Concrete class for time64 data types. + + Supported time unit resolutions are 'us' [microsecond] + and 'ns' [nanosecond]. + + Examples + -------- + Create an instance of time64 type: + + >>> import pyarrow as pa + >>> pa.time64('us') + Time64Type(time64[us]) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.time_type = type.get() + + @property + def unit(self): + """ + The time unit ('us' or 'ns'). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.time64('us') + >>> t.unit + 'us' + """ + return timeunit_to_string(self.time_type.unit()) + + +cdef class DurationType(DataType): + """ + Concrete class for duration data types. + + Examples + -------- + Create an instance of duration type: + + >>> import pyarrow as pa + >>> pa.duration('s') + DurationType(duration[s]) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.duration_type = type.get() + + @property + def unit(self): + """ + The duration unit ('s', 'ms', 'us' or 'ns'). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.duration('s') + >>> t.unit + 's' + """ + return timeunit_to_string(self.duration_type.unit()) + + +cdef class FixedSizeBinaryType(DataType): + """ + Concrete class for fixed-size binary data types. + + Examples + -------- + Create an instance of fixed-size binary type: + + >>> import pyarrow as pa + >>> pa.binary(3) + FixedSizeBinaryType(fixed_size_binary[3]) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.fixed_size_binary_type = ( + type.get()) + + def __reduce__(self): + return binary, (self.byte_width,) + + +cdef class Decimal32Type(FixedSizeBinaryType): + """ + Concrete class for decimal32 data types. + + Examples + -------- + Create an instance of decimal32 type: + + >>> import pyarrow as pa + >>> pa.decimal32(5, 2) + Decimal32Type(decimal32(5, 2)) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + FixedSizeBinaryType.init(self, type) + self.decimal32_type = type.get() + + def __reduce__(self): + return decimal32, (self.precision, self.scale) + + @property + def precision(self): + """ + The decimal precision, in number of decimal digits (an integer). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.decimal32(5, 2) + >>> t.precision + 5 + """ + return self.decimal32_type.precision() + + @property + def scale(self): + """ + The decimal scale (an integer). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.decimal32(5, 2) + >>> t.scale + 2 + """ + return self.decimal32_type.scale() + + +cdef class Decimal64Type(FixedSizeBinaryType): + """ + Concrete class for decimal64 data types. + + Examples + -------- + Create an instance of decimal64 type: + + >>> import pyarrow as pa + >>> pa.decimal64(5, 2) + Decimal64Type(decimal64(5, 2)) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + FixedSizeBinaryType.init(self, type) + self.decimal64_type = type.get() + + def __reduce__(self): + return decimal64, (self.precision, self.scale) + + @property + def precision(self): + """ + The decimal precision, in number of decimal digits (an integer). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.decimal64(5, 2) + >>> t.precision + 5 + """ + return self.decimal64_type.precision() + + @property + def scale(self): + """ + The decimal scale (an integer). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.decimal64(5, 2) + >>> t.scale + 2 + """ + return self.decimal64_type.scale() + + +cdef class Decimal128Type(FixedSizeBinaryType): + """ + Concrete class for decimal128 data types. + + Examples + -------- + Create an instance of decimal128 type: + + >>> import pyarrow as pa + >>> pa.decimal128(5, 2) + Decimal128Type(decimal128(5, 2)) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + FixedSizeBinaryType.init(self, type) + self.decimal128_type = type.get() + + def __reduce__(self): + return decimal128, (self.precision, self.scale) + + @property + def precision(self): + """ + The decimal precision, in number of decimal digits (an integer). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.decimal128(5, 2) + >>> t.precision + 5 + """ + return self.decimal128_type.precision() + + @property + def scale(self): + """ + The decimal scale (an integer). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.decimal128(5, 2) + >>> t.scale + 2 + """ + return self.decimal128_type.scale() + + +cdef class Decimal256Type(FixedSizeBinaryType): + """ + Concrete class for decimal256 data types. + + Examples + -------- + Create an instance of decimal256 type: + + >>> import pyarrow as pa + >>> pa.decimal256(76, 38) + Decimal256Type(decimal256(76, 38)) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + FixedSizeBinaryType.init(self, type) + self.decimal256_type = type.get() + + def __reduce__(self): + return decimal256, (self.precision, self.scale) + + @property + def precision(self): + """ + The decimal precision, in number of decimal digits (an integer). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.decimal256(76, 38) + >>> t.precision + 76 + """ + return self.decimal256_type.precision() + + @property + def scale(self): + """ + The decimal scale (an integer). + + Examples + -------- + >>> import pyarrow as pa + >>> t = pa.decimal256(76, 38) + >>> t.scale + 38 + """ + return self.decimal256_type.scale() + + +cdef class RunEndEncodedType(DataType): + """ + Concrete class for run-end encoded types. + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.run_end_encoded_type = type.get() + + def __reduce__(self): + return run_end_encoded, (self.run_end_type, self.value_type) + + @property + def run_end_type(self): + return pyarrow_wrap_data_type(self.run_end_encoded_type.run_end_type()) + + @property + def value_type(self): + return pyarrow_wrap_data_type(self.run_end_encoded_type.value_type()) + + +cdef class BaseExtensionType(DataType): + """ + Concrete base class for extension types. + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + DataType.init(self, type) + self.ext_type = type.get() + + def __arrow_ext_class__(self): + """ + The associated array extension class + """ + return ExtensionArray + + def __arrow_ext_scalar_class__(self): + """ + The associated scalar class + """ + return ExtensionScalar + + @property + def extension_name(self): + """ + The extension type name. + """ + return frombytes(self.ext_type.extension_name()) + + @property + def storage_type(self): + """ + The underlying storage type. + """ + return pyarrow_wrap_data_type(self.ext_type.storage_type()) + + @property + def byte_width(self): + """ + The byte width of the extension type. + """ + if self.ext_type.byte_width() == -1: + raise ValueError("Non-fixed width type") + return self.ext_type.byte_width() + + @property + def bit_width(self): + """ + The bit width of the extension type. + """ + if self.ext_type.bit_width() == -1: + raise ValueError("Non-fixed width type") + return self.ext_type.bit_width() + + def wrap_array(self, storage): + """ + Wrap the given storage array as an extension array. + + Parameters + ---------- + storage : Array or ChunkedArray + + Returns + ------- + array : Array or ChunkedArray + Extension array wrapping the storage array + """ + cdef: + shared_ptr[CDataType] c_storage_type + + if isinstance(storage, Array): + c_storage_type = ( storage).ap.type() + elif isinstance(storage, ChunkedArray): + c_storage_type = ( storage).chunked_array.type() + else: + raise TypeError( + f"Expected array or chunked array, got {storage.__class__}") + + if not c_storage_type.get().Equals(deref(self.ext_type) + .storage_type(), False): + raise TypeError( + f"Incompatible storage type for {self}: " + f"expected {self.storage_type}, got {storage.type}") + + if isinstance(storage, Array): + return pyarrow_wrap_array( + self.ext_type.WrapArray( + self.sp_type, ( storage).sp_array)) + else: + return pyarrow_wrap_chunked_array( + self.ext_type.WrapArray( + self.sp_type, ( storage).sp_chunked_array)) + + +cdef class ExtensionType(BaseExtensionType): + """ + Concrete base class for Python-defined extension types. + + Parameters + ---------- + storage_type : DataType + The underlying storage type for the extension type. + extension_name : str + A unique name distinguishing this extension type. The name will be + used when deserializing IPC data. + + Examples + -------- + Define a RationalType extension type subclassing ExtensionType: + + >>> import pyarrow as pa + >>> class RationalType(pa.ExtensionType): + ... def __init__(self, data_type: pa.DataType): + ... if not pa.types.is_integer(data_type): + ... raise TypeError(f"data_type must be an integer type not {data_type}") + ... super().__init__( + ... pa.struct( + ... [ + ... ("numer", data_type), + ... ("denom", data_type), + ... ], + ... ), + ... # N.B. This name does _not_ reference `data_type` so deserialization + ... # will work for _any_ integer `data_type` after registration + ... "my_package.rational", + ... ) + ... def __arrow_ext_serialize__(self) -> bytes: + ... # No parameters are necessary + ... return b"" + ... @classmethod + ... def __arrow_ext_deserialize__(cls, storage_type, serialized): + ... # return an instance of this subclass + ... return RationalType(storage_type[0].type) + + Register the extension type: + + >>> pa.register_extension_type(RationalType(pa.int64())) + + Create an instance of RationalType extension type: + + >>> rational_type = RationalType(pa.int32()) + + Inspect the extension type: + + >>> rational_type.extension_name + 'my_package.rational' + >>> rational_type.storage_type + StructType(struct) + + Wrap an array as an extension array: + + >>> storage_array = pa.array( + ... [ + ... {"numer": 10, "denom": 17}, + ... {"numer": 20, "denom": 13}, + ... ], + ... type=rational_type.storage_type + ... ) + >>> rational_array = rational_type.wrap_array(storage_array) + >>> rational_array + + -- is_valid: all not null + -- child 0 type: int32 + [ + 10, + 20 + ] + -- child 1 type: int32 + [ + 17, + 13 + ] + + Or do the same with creating an ExtensionArray: + + >>> rational_array = pa.ExtensionArray.from_storage(rational_type, storage_array) + >>> rational_array + + -- is_valid: all not null + -- child 0 type: int32 + [ + 10, + 20 + ] + -- child 1 type: int32 + [ + 17, + 13 + ] + + Unregister the extension type: + + >>> pa.unregister_extension_type("my_package.rational") + + Note that even though we registered the concrete type + ``RationalType(pa.int64())``, PyArrow will be able to deserialize + ``RationalType(integer_type)`` for any ``integer_type``, as the deserializer + will reference the name ``my_package.rational`` and the ``@classmethod`` + ``__arrow_ext_deserialize__``. + """ + + def __cinit__(self): + if type(self) is ExtensionType: + raise TypeError("Can only instantiate subclasses of " + "ExtensionType") + + def __init__(self, DataType storage_type, extension_name): + """ + Initialize an extension type instance. + + This should be called at the end of the subclass' + ``__init__`` method. + """ + cdef: + shared_ptr[CExtensionType] cpy_ext_type + c_string c_extension_name + + c_extension_name = tobytes(extension_name) + + assert storage_type is not None + check_status(CPyExtensionType.FromClass( + storage_type.sp_type, c_extension_name, type(self), + &cpy_ext_type)) + self.init( cpy_ext_type) + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + BaseExtensionType.init(self, type) + self.cpy_ext_type = type.get() + # Store weakref and serialized version of self on C++ type instance + check_status(self.cpy_ext_type.SetInstance(self)) + + def __eq__(self, other): + # Default implementation to avoid infinite recursion through + # DataType.__eq__ -> ExtensionType::ExtensionEquals -> DataType.__eq__ + if isinstance(other, ExtensionType): + return (type(self) == type(other) and + self.extension_name == other.extension_name and + self.storage_type == other.storage_type) + else: + return NotImplemented + + def __repr__(self): + return f'{self.__class__.__name__}({repr(self.storage_type)})' + + def __arrow_ext_serialize__(self): + """ + Serialized representation of metadata to reconstruct the type object. + + This method should return a bytes object, and those serialized bytes + are stored in the custom metadata of the Field holding an extension + type in an IPC message. + The bytes are passed to ``__arrow_ext_deserialize`` and should hold + sufficient information to reconstruct the data type instance. + """ + return NotImplementedError + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type, serialized): + """ + Return an extension type instance from the storage type and serialized + metadata. + + This method should return an instance of the ExtensionType subclass + that matches the passed storage type and serialized metadata (the + return value of ``__arrow_ext_serialize__``). + """ + return NotImplementedError + + def __reduce__(self): + return self.__arrow_ext_deserialize__, (self.storage_type, self.__arrow_ext_serialize__()) + + def __arrow_ext_class__(self): + """Return an extension array class to be used for building or + deserializing arrays with this extension type. + + This method should return a subclass of the ExtensionArray class. By + default, if not specialized in the extension implementation, an + extension type array will be a built-in ExtensionArray instance. + """ + return ExtensionArray + + def __arrow_ext_scalar_class__(self): + """Return an extension scalar class for building scalars with this + extension type. + + This method should return subclass of the ExtensionScalar class. By + default, if not specialized in the extension implementation, an + extension type scalar will be a built-in ExtensionScalar instance. + """ + return ExtensionScalar + + +cdef class JsonType(BaseExtensionType): + """ + Concrete class for JSON extension type. + + Examples + -------- + Define the extension type for JSON array + + >>> import pyarrow as pa + >>> json_type = pa.json_(pa.large_utf8()) + + Create an extension array + + >>> arr = [None, '{ "id":30, "values":["a", "b"] }'] + >>> storage = pa.array(arr, pa.large_utf8()) + >>> pa.ExtensionArray.from_storage(json_type, storage) + + [ + null, + "{ "id":30, "values":["a", "b"] }" + ] + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + BaseExtensionType.init(self, type) + self.json_ext_type = type.get() + + def __arrow_ext_class__(self): + return JsonArray + + def __reduce__(self): + return json_, (self.storage_type,) + + def __arrow_ext_scalar_class__(self): + return JsonScalar + + +cdef class UuidType(BaseExtensionType): + """ + Concrete class for UUID extension type. + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + BaseExtensionType.init(self, type) + self.uuid_ext_type = type.get() + + def __arrow_ext_class__(self): + return UuidArray + + def __reduce__(self): + return uuid, () + + def __arrow_ext_scalar_class__(self): + return UuidScalar + + +cdef class FixedShapeTensorType(BaseExtensionType): + """ + Concrete class for fixed shape tensor extension type. + + Examples + -------- + Create an instance of fixed shape tensor extension type: + + >>> import pyarrow as pa + >>> pa.fixed_shape_tensor(pa.int32(), [2, 2]) + FixedShapeTensorType(extension) + + Create an instance of fixed shape tensor extension type with + permutation: + + >>> tensor_type = pa.fixed_shape_tensor(pa.int8(), (2, 2, 3), + ... permutation=[0, 2, 1]) + >>> tensor_type.permutation + [0, 2, 1] + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + BaseExtensionType.init(self, type) + self.tensor_ext_type = type.get() + + @property + def value_type(self): + """ + Data type of an individual tensor. + """ + return pyarrow_wrap_data_type(self.tensor_ext_type.value_type()) + + @property + def shape(self): + """ + Shape of the tensors. + """ + return self.tensor_ext_type.shape() + + @property + def dim_names(self): + """ + Explicit names of the dimensions. + """ + list_of_bytes = self.tensor_ext_type.dim_names() + if len(list_of_bytes) != 0: + return [frombytes(x) for x in list_of_bytes] + else: + return None + + @property + def permutation(self): + """ + Indices of the dimensions ordering. + """ + indices = self.tensor_ext_type.permutation() + if len(indices) != 0: + return indices + else: + return None + + def __arrow_ext_class__(self): + return FixedShapeTensorArray + + def __reduce__(self): + return fixed_shape_tensor, (self.value_type, self.shape, + self.dim_names, self.permutation) + + def __arrow_ext_scalar_class__(self): + return FixedShapeTensorScalar + + +cdef class Bool8Type(BaseExtensionType): + """ + Concrete class for bool8 extension type. + + Bool8 is an alternate representation for boolean + arrays using 8 bits instead of 1 bit per value. The underlying + storage type is int8. + + Examples + -------- + Create an instance of bool8 extension type: + + >>> import pyarrow as pa + >>> pa.bool8() + Bool8Type(extension) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + BaseExtensionType.init(self, type) + self.bool8_ext_type = type.get() + + def __arrow_ext_class__(self): + return Bool8Array + + def __reduce__(self): + return bool8, () + + def __arrow_ext_scalar_class__(self): + return Bool8Scalar + + +cdef class OpaqueType(BaseExtensionType): + """ + Concrete class for opaque extension type. + + Opaque is a placeholder for a type from an external (often non-Arrow) + system that could not be interpreted. + + Examples + -------- + Create an instance of opaque extension type: + + >>> import pyarrow as pa + >>> pa.opaque(pa.int32(), "geometry", "postgis") + OpaqueType(extension) + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + BaseExtensionType.init(self, type) + self.opaque_ext_type = type.get() + + @property + def type_name(self): + """ + The name of the type in the external system. + """ + return frombytes(c_string(self.opaque_ext_type.type_name())) + + @property + def vendor_name(self): + """ + The name of the external system. + """ + return frombytes(c_string(self.opaque_ext_type.vendor_name())) + + def __arrow_ext_class__(self): + return OpaqueArray + + def __reduce__(self): + return opaque, (self.storage_type, self.type_name, self.vendor_name) + + def __arrow_ext_scalar_class__(self): + return OpaqueScalar + + +cdef class UnknownExtensionType(ExtensionType): + """ + A concrete class for Python-defined extension types that refer to + an unknown Python implementation. + + Parameters + ---------- + storage_type : DataType + The storage type for which the extension is built. + serialized : bytes + The serialised output. + """ + + cdef: + bytes serialized + + def __init__(self, DataType storage_type, serialized): + self.serialized = serialized + super().__init__(storage_type, "pyarrow.unknown") + + def __arrow_ext_serialize__(self): + return self.serialized + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type, serialized): + return UnknownExtensionType() + + +_python_extension_types_registry = [] + + +def register_extension_type(ext_type): + """ + Register a Python extension type. + + Registration is based on the extension name (so different registered types + need unique extension names). Registration needs an extension type + instance, but then works for any instance of the same subclass regardless + of parametrization of the type. + + Parameters + ---------- + ext_type : BaseExtensionType instance + The ExtensionType subclass to register. + + Examples + -------- + Define a RationalType extension type subclassing ExtensionType: + + >>> import pyarrow as pa + >>> class RationalType(pa.ExtensionType): + ... def __init__(self, data_type: pa.DataType): + ... if not pa.types.is_integer(data_type): + ... raise TypeError(f"data_type must be an integer type not {data_type}") + ... super().__init__( + ... pa.struct( + ... [ + ... ("numer", data_type), + ... ("denom", data_type), + ... ], + ... ), + ... # N.B. This name does _not_ reference `data_type` so deserialization + ... # will work for _any_ integer `data_type` after registration + ... "my_package.rational", + ... ) + ... def __arrow_ext_serialize__(self) -> bytes: + ... # No parameters are necessary + ... return b"" + ... @classmethod + ... def __arrow_ext_deserialize__(cls, storage_type, serialized): + ... # return an instance of this subclass + ... return RationalType(storage_type[0].type) + + Register the extension type: + + >>> pa.register_extension_type(RationalType(pa.int64())) + + Unregister the extension type: + + >>> pa.unregister_extension_type("my_package.rational") + """ + cdef: + DataType _type = ensure_type(ext_type, allow_none=False) + + if not isinstance(_type, BaseExtensionType): + raise TypeError("Only extension types can be registered") + + # register on the C++ side + check_status( + RegisterPyExtensionType( _type.sp_type)) + + # register on the python side + _python_extension_types_registry.append(_type) + + +def unregister_extension_type(type_name): + """ + Unregister a Python extension type. + + Parameters + ---------- + type_name : str + The name of the ExtensionType subclass to unregister. + + Examples + -------- + Define a RationalType extension type subclassing ExtensionType: + + >>> import pyarrow as pa + >>> class RationalType(pa.ExtensionType): + ... def __init__(self, data_type: pa.DataType): + ... if not pa.types.is_integer(data_type): + ... raise TypeError(f"data_type must be an integer type not {data_type}") + ... super().__init__( + ... pa.struct( + ... [ + ... ("numer", data_type), + ... ("denom", data_type), + ... ], + ... ), + ... # N.B. This name does _not_ reference `data_type` so deserialization + ... # will work for _any_ integer `data_type` after registration + ... "my_package.rational", + ... ) + ... def __arrow_ext_serialize__(self) -> bytes: + ... # No parameters are necessary + ... return b"" + ... @classmethod + ... def __arrow_ext_deserialize__(cls, storage_type, serialized): + ... # return an instance of this subclass + ... return RationalType(storage_type[0].type) + + Register the extension type: + + >>> pa.register_extension_type(RationalType(pa.int64())) + + Unregister the extension type: + + >>> pa.unregister_extension_type("my_package.rational") + """ + cdef: + c_string c_type_name = tobytes(type_name) + check_status(UnregisterPyExtensionType(c_type_name)) + + +cdef class KeyValueMetadata(_Metadata, Mapping): + """ + KeyValueMetadata + + Parameters + ---------- + __arg0__ : dict + A dict of the key-value metadata + **kwargs : optional + additional key-value metadata + """ + + def __init__(self, __arg0__=None, **kwargs): + cdef: + vector[c_string] keys, values + shared_ptr[const CKeyValueMetadata] result + + items = [] + if __arg0__ is not None: + other = (__arg0__.items() if isinstance(__arg0__, Mapping) + else __arg0__) + items.extend((tobytes(k), v) for k, v in other) + + prior_keys = {k for k, v in items} + for k, v in kwargs.items(): + k = tobytes(k) + if k in prior_keys: + raise KeyError("Duplicate key {}, " + "use pass all items as list of tuples if you " + "intend to have duplicate keys") + items.append((k, v)) + + keys.reserve(len(items)) + for key, value in items: + keys.push_back(tobytes(key)) + values.push_back(tobytes(value)) + result.reset(new CKeyValueMetadata(move(keys), move(values))) + self.init(result) + + cdef void init(self, const shared_ptr[const CKeyValueMetadata]& wrapped): + self.wrapped = wrapped + self.metadata = wrapped.get() + + @staticmethod + cdef wrap(const shared_ptr[const CKeyValueMetadata]& sp): + cdef KeyValueMetadata self = KeyValueMetadata.__new__(KeyValueMetadata) + self.init(sp) + return self + + cdef inline shared_ptr[const CKeyValueMetadata] unwrap(self) nogil: + return self.wrapped + + def equals(self, KeyValueMetadata other): + """ + Parameters + ---------- + other : pyarrow.KeyValueMetadata + + Returns + ------- + bool + """ + return self.metadata.Equals(deref(other.wrapped)) + + def __repr__(self): + return str(self) + + def __str__(self): + return frombytes(self.metadata.ToString(), safe=True) + + def __eq__(self, other): + try: + return self.equals(other) + except TypeError: + pass + + if isinstance(other, Mapping): + try: + other = KeyValueMetadata(other) + return self.equals(other) + except TypeError: + pass + + return NotImplemented + + def __len__(self): + return self.metadata.size() + + def __contains__(self, key): + return self.metadata.Contains(tobytes(key)) + + def __getitem__(self, key): + return GetResultValue(self.metadata.Get(tobytes(key))) + + def __iter__(self): + return self.keys() + + def __reduce__(self): + return KeyValueMetadata, (list(self.items()),) + + def key(self, i): + """ + Parameters + ---------- + i : int + + Returns + ------- + byte + """ + return self.metadata.key(i) + + def value(self, i): + """ + Parameters + ---------- + i : int + + Returns + ------- + byte + """ + return self.metadata.value(i) + + def keys(self): + for i in range(self.metadata.size()): + yield self.metadata.key(i) + + def values(self): + for i in range(self.metadata.size()): + yield self.metadata.value(i) + + def items(self): + for i in range(self.metadata.size()): + yield (self.metadata.key(i), self.metadata.value(i)) + + def get_all(self, key): + """ + Parameters + ---------- + key : str + + Returns + ------- + list[byte] + """ + key = tobytes(key) + return [v for k, v in self.items() if k == key] + + def to_dict(self): + """ + Convert KeyValueMetadata to dict. If a key occurs twice, the value for + the first one is returned + """ + cdef object key # to force coercion to Python + result = ordered_dict() + for i in range(self.metadata.size()): + key = self.metadata.key(i) + if key not in result: + result[key] = self.metadata.value(i) + return result + + +cpdef KeyValueMetadata ensure_metadata(object meta, c_bool allow_none=False): + if allow_none and meta is None: + return None + elif isinstance(meta, KeyValueMetadata): + return meta + else: + return KeyValueMetadata(meta) + + +cdef class Field(_Weakrefable): + """ + A named field, with a data type, nullability, and optional metadata. + + Notes + ----- + Do not use this class's constructor directly; use pyarrow.field + + Examples + -------- + Create an instance of pyarrow.Field: + + >>> import pyarrow as pa + >>> pa.field('key', pa.int32()) + pyarrow.Field + >>> pa.field('key', pa.int32(), nullable=False) + pyarrow.Field + >>> field = pa.field('key', pa.int32(), + ... metadata={"key": "Something important"}) + >>> field + pyarrow.Field + >>> field.metadata + {b'key': b'Something important'} + + Use the field to create a struct type: + + >>> pa.struct([field]) + StructType(struct) + """ + + def __cinit__(self): + pass + + def __init__(self): + raise TypeError("Do not call Field's constructor directly, use " + "`pyarrow.field` instead.") + + cdef void init(self, const shared_ptr[CField]& field): + self.sp_field = field + self.field = field.get() + self.type = pyarrow_wrap_data_type(field.get().type()) + + def equals(self, Field other, bint check_metadata=False): + """ + Test if this field is equal to the other + + Parameters + ---------- + other : pyarrow.Field + check_metadata : bool, default False + Whether Field metadata equality should be checked as well. + + Returns + ------- + is_equal : bool + + Examples + -------- + >>> import pyarrow as pa + >>> f1 = pa.field('key', pa.int32()) + >>> f2 = pa.field('key', pa.int32(), nullable=False) + >>> f1.equals(f2) + False + >>> f1.equals(f1) + True + """ + return self.field.Equals(deref(other.field), check_metadata) + + def __eq__(self, other): + try: + return self.equals(other) + except TypeError: + return NotImplemented + + def __reduce__(self): + return field, (self.name, self.type, self.nullable, self.metadata) + + def __str__(self): + return f'pyarrow.Field<{frombytes(self.field.ToString(), safe=True)}>' + + def __repr__(self): + return self.__str__() + + def __hash__(self): + return hash((self.field.name(), self.type, self.field.nullable())) + + @property + def nullable(self): + """ + The field nullability. + + Examples + -------- + >>> import pyarrow as pa + >>> f1 = pa.field('key', pa.int32()) + >>> f2 = pa.field('key', pa.int32(), nullable=False) + >>> f1.nullable + True + >>> f2.nullable + False + """ + return self.field.nullable() + + @property + def name(self): + """ + The field name. + + Examples + -------- + >>> import pyarrow as pa + >>> field = pa.field('key', pa.int32()) + >>> field.name + 'key' + """ + return frombytes(self.field.name()) + + @property + def metadata(self): + """ + The field metadata (if any is set). + + Returns + ------- + metadata : dict or None + + Examples + -------- + >>> import pyarrow as pa + >>> field = pa.field('key', pa.int32(), + ... metadata={"key": "Something important"}) + >>> field.metadata + {b'key': b'Something important'} + """ + wrapped = pyarrow_wrap_metadata(self.field.metadata()) + if wrapped is not None: + return wrapped.to_dict() + else: + return wrapped + + def with_metadata(self, metadata): + """ + Add metadata as dict of string keys and values to Field + + Parameters + ---------- + metadata : dict + Keys and values must be string-like / coercible to bytes + + Returns + ------- + field : pyarrow.Field + + Examples + -------- + >>> import pyarrow as pa + >>> field = pa.field('key', pa.int32()) + + Create new field by adding metadata to existing one: + + >>> field_new = field.with_metadata({"key": "Something important"}) + >>> field_new + pyarrow.Field + >>> field_new.metadata + {b'key': b'Something important'} + """ + cdef shared_ptr[CField] c_field + + meta = ensure_metadata(metadata, allow_none=False) + with nogil: + c_field = self.field.WithMetadata(meta.unwrap()) + + return pyarrow_wrap_field(c_field) + + def remove_metadata(self): + """ + Create new field without metadata, if any + + Returns + ------- + field : pyarrow.Field + + Examples + -------- + >>> import pyarrow as pa + >>> field = pa.field('key', pa.int32(), + ... metadata={"key": "Something important"}) + >>> field.metadata + {b'key': b'Something important'} + + Create new field by removing the metadata from the existing one: + + >>> field_new = field.remove_metadata() + >>> field_new.metadata + """ + cdef shared_ptr[CField] new_field + with nogil: + new_field = self.field.RemoveMetadata() + return pyarrow_wrap_field(new_field) + + def with_type(self, DataType new_type): + """ + A copy of this field with the replaced type + + Parameters + ---------- + new_type : pyarrow.DataType + + Returns + ------- + field : pyarrow.Field + + Examples + -------- + >>> import pyarrow as pa + >>> field = pa.field('key', pa.int32()) + >>> field + pyarrow.Field + + Create new field by replacing type of an existing one: + + >>> field_new = field.with_type(pa.int64()) + >>> field_new + pyarrow.Field + """ + cdef: + shared_ptr[CField] c_field + shared_ptr[CDataType] c_datatype + + c_datatype = pyarrow_unwrap_data_type(new_type) + with nogil: + c_field = self.field.WithType(c_datatype) + + return pyarrow_wrap_field(c_field) + + def with_name(self, name): + """ + A copy of this field with the replaced name + + Parameters + ---------- + name : str + + Returns + ------- + field : pyarrow.Field + + Examples + -------- + >>> import pyarrow as pa + >>> field = pa.field('key', pa.int32()) + >>> field + pyarrow.Field + + Create new field by replacing the name of an existing one: + + >>> field_new = field.with_name('lock') + >>> field_new + pyarrow.Field + """ + cdef: + shared_ptr[CField] c_field + + c_field = self.field.WithName(tobytes(name)) + + return pyarrow_wrap_field(c_field) + + def with_nullable(self, nullable): + """ + A copy of this field with the replaced nullability + + Parameters + ---------- + nullable : bool + + Returns + ------- + field: pyarrow.Field + + Examples + -------- + >>> import pyarrow as pa + >>> field = pa.field('key', pa.int32()) + >>> field + pyarrow.Field + >>> field.nullable + True + + Create new field by replacing the nullability of an existing one: + + >>> field_new = field.with_nullable(False) + >>> field_new + pyarrow.Field + >>> field_new.nullable + False + """ + cdef: + shared_ptr[CField] field + c_bool c_nullable + + c_nullable = bool(nullable) + with nogil: + c_field = self.field.WithNullable(c_nullable) + + return pyarrow_wrap_field(c_field) + + def flatten(self): + """ + Flatten this field. If a struct field, individual child fields + will be returned with their names prefixed by the parent's name. + + Returns + ------- + fields : List[pyarrow.Field] + + Examples + -------- + >>> import pyarrow as pa + >>> f1 = pa.field('bar', pa.float64(), nullable=False) + >>> f2 = pa.field('foo', pa.int32()).with_metadata({"key": "Something important"}) + >>> ff = pa.field('ff', pa.struct([f1, f2]), nullable=False) + + Flatten a struct field: + + >>> ff + pyarrow.Field not null> + >>> ff.flatten() + [pyarrow.Field, pyarrow.Field] + """ + cdef vector[shared_ptr[CField]] flattened + with nogil: + flattened = self.field.Flatten() + return [pyarrow_wrap_field(f) for f in flattened] + + def _export_to_c(self, out_ptr): + """ + Export to a C ArrowSchema struct, given its pointer. + + Be careful: if you don't pass the ArrowSchema struct to a consumer, + its memory will leak. This is a low-level function intended for + expert users. + """ + check_status(ExportField(deref(self.field), + _as_c_pointer(out_ptr))) + + @staticmethod + def _import_from_c(in_ptr): + """ + Import Field from a C ArrowSchema struct, given its pointer. + + This is a low-level function intended for expert users. + """ + cdef void* c_ptr = _as_c_pointer(in_ptr) + with nogil: + result = GetResultValue(ImportField( c_ptr)) + return pyarrow_wrap_field(result) + + def __arrow_c_schema__(self): + """ + Export to a ArrowSchema PyCapsule + + Unlike _export_to_c, this will not leak memory if the capsule is not used. + """ + cdef ArrowSchema* c_schema + capsule = alloc_c_schema(&c_schema) + + with nogil: + check_status(ExportField(deref(self.field), c_schema)) + + return capsule + + @staticmethod + def _import_from_c_capsule(schema): + """ + Import a Field from a ArrowSchema PyCapsule + + Parameters + ---------- + schema : PyCapsule + A valid PyCapsule with name 'arrow_schema' containing an + ArrowSchema pointer. + """ + cdef: + ArrowSchema* c_schema + shared_ptr[CField] c_field + + if not PyCapsule_IsValid(schema, 'arrow_schema'): + raise ValueError( + "Not an ArrowSchema object" + ) + c_schema = PyCapsule_GetPointer(schema, 'arrow_schema') + + with nogil: + c_field = GetResultValue(ImportField(c_schema)) + + return pyarrow_wrap_field(c_field) + + +cdef class Schema(_Weakrefable): + """ + A named collection of types a.k.a schema. A schema defines the + column names and types in a record batch or table data structure. + They also contain metadata about the columns. For example, schemas + converted from Pandas contain metadata about their original Pandas + types so they can be converted back to the same types. + + Warnings + -------- + Do not call this class's constructor directly. Instead use + :func:`pyarrow.schema` factory function which makes a new Arrow + Schema object. + + Examples + -------- + Create a new Arrow Schema object: + + >>> import pyarrow as pa + >>> pa.schema([ + ... ('some_int', pa.int32()), + ... ('some_string', pa.string()) + ... ]) + some_int: int32 + some_string: string + + Create Arrow Schema with metadata: + + >>> pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())], + ... metadata={"n_legs": "Number of legs per animal"}) + n_legs: int64 + animals: string + -- schema metadata -- + n_legs: 'Number of legs per animal' + """ + + def __cinit__(self): + pass + + def __init__(self): + raise TypeError("Do not call Schema's constructor directly, use " + "`pyarrow.schema` instead.") + + def __len__(self): + return self.schema.num_fields() + + def __getitem__(self, key): + # access by integer index + return self._field(key) + + def __iter__(self): + for i in range(len(self)): + yield self[i] + + cdef void init(self, const vector[shared_ptr[CField]]& fields): + self.schema = new CSchema(fields) + self.sp_schema.reset(self.schema) + + cdef void init_schema(self, const shared_ptr[CSchema]& schema): + self.schema = schema.get() + self.sp_schema = schema + + def __reduce__(self): + return schema, (list(self), self.metadata) + + def __hash__(self): + metadata = frozenset(self.metadata.items() if self.metadata else {}) + return hash((tuple(self), metadata)) + + def __sizeof__(self): + size = 0 + if self.metadata: + for key, value in self.metadata.items(): + size += sys.getsizeof(key) + size += sys.getsizeof(value) + + return size + super(Schema, self).__sizeof__() + + @property + def pandas_metadata(self): + """ + Return deserialized-from-JSON pandas metadata field (if it exists) + + Examples + -------- + >>> import pyarrow as pa + >>> import pandas as pd + >>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100], + ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) + >>> schema = pa.Table.from_pandas(df).schema + + Select pandas metadata field from Arrow Schema: + + >>> schema.pandas_metadata + {'index_columns': [{'kind': 'range', 'name': None, 'start': 0, 'stop': 4, 'step': 1}], ... + """ + metadata = self.metadata + key = b'pandas' + if metadata is None or key not in metadata: + return None + + import json + return json.loads(metadata[key].decode('utf8')) + + @property + def names(self): + """ + The schema's field names. + + Returns + ------- + list of str + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Get the names of the schema's fields: + + >>> schema.names + ['n_legs', 'animals'] + """ + cdef int i + result = [] + for i in range(self.schema.num_fields()): + name = frombytes(self.schema.field(i).get().name()) + result.append(name) + return result + + @property + def types(self): + """ + The schema's field types. + + Returns + ------- + list of DataType + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Get the types of the schema's fields: + + >>> schema.types + [DataType(int64), DataType(string)] + """ + return [field.type for field in self] + + @property + def metadata(self): + """ + The schema's metadata (if any is set). + + Returns + ------- + metadata: dict or None + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())], + ... metadata={"n_legs": "Number of legs per animal"}) + + Get the metadata of the schema's fields: + + >>> schema.metadata + {b'n_legs': b'Number of legs per animal'} + """ + wrapped = pyarrow_wrap_metadata(self.schema.metadata()) + if wrapped is not None: + return wrapped.to_dict() + else: + return wrapped + + def __eq__(self, other): + try: + return self.equals(other) + except TypeError: + return NotImplemented + + def empty_table(self): + """ + Provide an empty table according to the schema. + + Returns + ------- + table: pyarrow.Table + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Create an empty table with schema's fields: + + >>> schema.empty_table() + pyarrow.Table + n_legs: int64 + animals: string + ---- + n_legs: [[]] + animals: [[]] + """ + arrays = [_empty_array(field.type) for field in self] + return Table.from_arrays(arrays, schema=self) + + def equals(self, Schema other not None, bint check_metadata=False): + """ + Test if this schema is equal to the other + + Parameters + ---------- + other : pyarrow.Schema + check_metadata : bool, default False + Key/value metadata must be equal too + + Returns + ------- + is_equal : bool + + Examples + -------- + >>> import pyarrow as pa + >>> schema1 = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())], + ... metadata={"n_legs": "Number of legs per animal"}) + >>> schema2 = pa.schema([ + ... ('some_int', pa.int32()), + ... ('some_string', pa.string()) + ... ]) + + Test two equal schemas: + + >>> schema1.equals(schema1) + True + + Test two unequal schemas: + + >>> schema1.equals(schema2) + False + """ + return self.sp_schema.get().Equals(deref(other.schema), + check_metadata) + + @classmethod + def from_pandas(cls, df, preserve_index=None): + """ + Returns implied schema from dataframe + + Parameters + ---------- + df : pandas.DataFrame + + preserve_index : bool, optional + Whether to store the index as an additional field in the resulting + ``Schema``. The default of None will store the index as a field, + except for RangeIndex which is stored as metadata only. Use + ``preserve_index=True`` to force it to be stored as a field. + + Returns + ------- + pyarrow.Schema + + Examples + -------- + >>> import pandas as pd + >>> import pyarrow as pa + >>> df = pd.DataFrame({ + ... 'int': [1, 2], + ... 'str': ['a', 'b'] + ... }) + + Create an Arrow Schema from the schema of a pandas dataframe: + + >>> pa.Schema.from_pandas(df) + int: int64 + str: string + -- schema metadata -- + pandas: '{"index_columns": [{"kind": "range", "name": null, ... + """ + from pyarrow.pandas_compat import dataframe_to_types + names, types, metadata = dataframe_to_types( + df, + preserve_index=preserve_index + ) + fields = [] + for name, type_ in zip(names, types): + fields.append(field(name, type_)) + return schema(fields, metadata) + + def field(self, i): + """ + Select a field by its column name or numeric index. + + Parameters + ---------- + i : int or string + + Returns + ------- + pyarrow.Field + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Select the second field: + + >>> schema.field(1) + pyarrow.Field + + Select the field of the column named 'n_legs': + + >>> schema.field('n_legs') + pyarrow.Field + """ + if isinstance(i, (bytes, str)): + field_index = self.get_field_index(i) + if field_index < 0: + raise KeyError(f"Column {i} does not exist in schema") + else: + return self._field(field_index) + elif isinstance(i, int): + return self._field(i) + else: + raise TypeError("Index must either be string or integer") + + def _field(self, int i): + """ + Select a field by its numeric index. + + Parameters + ---------- + i : int + + Returns + ------- + pyarrow.Field + """ + cdef int index = _normalize_index(i, self.schema.num_fields()) + return pyarrow_wrap_field(self.schema.field(index)) + + def field_by_name(self, name): + """ + DEPRECATED + + Parameters + ---------- + name : str + + Returns + ------- + field: pyarrow.Field + """ + cdef: + vector[shared_ptr[CField]] results + + warnings.warn( + "The 'field_by_name' method is deprecated, use 'field' instead", + FutureWarning, stacklevel=2) + + results = self.schema.GetAllFieldsByName(tobytes(name)) + if results.size() == 0: + return None + elif results.size() > 1: + warnings.warn("Schema field name corresponds to more " + "than one field", UserWarning) + return None + else: + return pyarrow_wrap_field(results[0]) + + def get_field_index(self, name): + """ + Return index of the unique field with the given name. + + Parameters + ---------- + name : str + The name of the field to look up. + + Returns + ------- + index : int + The index of the field with the given name; -1 if the + name isn't found or there are several fields with the given + name. + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Get the index of the field named 'animals': + + >>> schema.get_field_index("animals") + 1 + + Index in case of several fields with the given name: + + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string()), + ... pa.field('animals', pa.bool_())], + ... metadata={"n_legs": "Number of legs per animal"}) + >>> schema.get_field_index("animals") + -1 + """ + return self.schema.GetFieldIndex(tobytes(name)) + + def get_all_field_indices(self, name): + """ + Return sorted list of indices for the fields with the given name. + + Parameters + ---------- + name : str + The name of the field to look up. + + Returns + ------- + indices : List[int] + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string()), + ... pa.field('animals', pa.bool_())]) + + Get the indexes of the fields named 'animals': + + >>> schema.get_all_field_indices("animals") + [1, 2] + """ + return self.schema.GetAllFieldIndices(tobytes(name)) + + def append(self, Field field): + """ + Append a field at the end of the schema. + + In contrast to Python's ``list.append()`` it does return a new + object, leaving the original Schema unmodified. + + Parameters + ---------- + field : Field + + Returns + ------- + schema: Schema + New object with appended field. + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Append a field 'extra' at the end of the schema: + + >>> schema_new = schema.append(pa.field('extra', pa.bool_())) + >>> schema_new + n_legs: int64 + animals: string + extra: bool + + Original schema is unmodified: + + >>> schema + n_legs: int64 + animals: string + """ + return self.insert(self.schema.num_fields(), field) + + def insert(self, int i, Field field): + """ + Add a field at position i to the schema. + + Parameters + ---------- + i : int + field : Field + + Returns + ------- + schema: Schema + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Insert a new field on the second position: + + >>> schema.insert(1, pa.field('extra', pa.bool_())) + n_legs: int64 + extra: bool + animals: string + """ + cdef: + shared_ptr[CSchema] new_schema + shared_ptr[CField] c_field + + c_field = field.sp_field + + with nogil: + new_schema = GetResultValue(self.schema.AddField(i, c_field)) + + return pyarrow_wrap_schema(new_schema) + + def remove(self, int i): + """ + Remove the field at index i from the schema. + + Parameters + ---------- + i : int + + Returns + ------- + schema: Schema + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Remove the second field of the schema: + + >>> schema.remove(1) + n_legs: int64 + """ + cdef shared_ptr[CSchema] new_schema + + with nogil: + new_schema = GetResultValue(self.schema.RemoveField(i)) + + return pyarrow_wrap_schema(new_schema) + + def set(self, int i, Field field): + """ + Replace a field at position i in the schema. + + Parameters + ---------- + i : int + field : Field + + Returns + ------- + schema: Schema + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Replace the second field of the schema with a new field 'extra': + + >>> schema.set(1, pa.field('replaced', pa.bool_())) + n_legs: int64 + replaced: bool + """ + cdef: + shared_ptr[CSchema] new_schema + shared_ptr[CField] c_field + + c_field = field.sp_field + + with nogil: + new_schema = GetResultValue(self.schema.SetField(i, c_field)) + + return pyarrow_wrap_schema(new_schema) + + def add_metadata(self, metadata): + """ + DEPRECATED + + Parameters + ---------- + metadata : dict + Keys and values must be string-like / coercible to bytes + """ + warnings.warn("The 'add_metadata' method is deprecated, use " + "'with_metadata' instead", FutureWarning, stacklevel=2) + return self.with_metadata(metadata) + + def with_metadata(self, metadata): + """ + Add metadata as dict of string keys and values to Schema + + Parameters + ---------- + metadata : dict + Keys and values must be string-like / coercible to bytes + + Returns + ------- + schema : pyarrow.Schema + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Add metadata to existing schema field: + + >>> schema.with_metadata({"n_legs": "Number of legs per animal"}) + n_legs: int64 + animals: string + -- schema metadata -- + n_legs: 'Number of legs per animal' + """ + cdef shared_ptr[CSchema] c_schema + + meta = ensure_metadata(metadata, allow_none=False) + with nogil: + c_schema = self.schema.WithMetadata(meta.unwrap()) + + return pyarrow_wrap_schema(c_schema) + + def serialize(self, memory_pool=None): + """ + Write Schema to Buffer as encapsulated IPC message + + Parameters + ---------- + memory_pool : MemoryPool, default None + Uses default memory pool if not specified + + Returns + ------- + serialized : Buffer + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())]) + + Write schema to Buffer: + + >>> schema.serialize() + + """ + cdef: + shared_ptr[CBuffer] buffer + CMemoryPool* pool = maybe_unbox_memory_pool(memory_pool) + + with nogil: + buffer = GetResultValue(SerializeSchema(deref(self.schema), + pool)) + return pyarrow_wrap_buffer(buffer) + + def remove_metadata(self): + """ + Create new schema without metadata, if any + + Returns + ------- + schema : pyarrow.Schema + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([ + ... pa.field('n_legs', pa.int64()), + ... pa.field('animals', pa.string())], + ... metadata={"n_legs": "Number of legs per animal"}) + >>> schema + n_legs: int64 + animals: string + -- schema metadata -- + n_legs: 'Number of legs per animal' + + Create a new schema with removing the metadata from the original: + + >>> schema.remove_metadata() + n_legs: int64 + animals: string + """ + cdef shared_ptr[CSchema] new_schema + with nogil: + new_schema = self.schema.RemoveMetadata() + return pyarrow_wrap_schema(new_schema) + + def to_string(self, truncate_metadata=True, show_field_metadata=True, + show_schema_metadata=True, element_size_limit=100): + """ + Return human-readable representation of Schema + + Parameters + ---------- + truncate_metadata : boolean, default True + Limit metadata key/value display to a single line of ~80 characters + or less + show_field_metadata : boolean, default True + Display Field-level KeyValueMetadata + show_schema_metadata : boolean, default True + Display Schema-level KeyValueMetadata + element_size_limit : int, default 100 + Maximum number of characters of a single element before it is truncated. + + Returns + ------- + str : the formatted output + """ + cdef: + c_string result + PrettyPrintOptions options = PrettyPrintOptions.Defaults() + + options.indent = 0 + options.truncate_metadata = truncate_metadata + options.show_field_metadata = show_field_metadata + options.show_schema_metadata = show_schema_metadata + options.element_size_limit = element_size_limit + + with nogil: + check_status( + PrettyPrint( + deref(self.schema), + options, + &result + ) + ) + + return frombytes(result, safe=True) + + def _export_to_c(self, out_ptr): + """ + Export to a C ArrowSchema struct, given its pointer. + + Be careful: if you don't pass the ArrowSchema struct to a consumer, + its memory will leak. This is a low-level function intended for + expert users. + """ + check_status(ExportSchema(deref(self.schema), + _as_c_pointer(out_ptr))) + + @staticmethod + def _import_from_c(in_ptr): + """ + Import Schema from a C ArrowSchema struct, given its pointer. + + This is a low-level function intended for expert users. + """ + cdef void* c_ptr = _as_c_pointer(in_ptr) + with nogil: + result = GetResultValue(ImportSchema( c_ptr)) + return pyarrow_wrap_schema(result) + + def __str__(self): + return self.to_string() + + def __repr__(self): + return self.__str__() + + def __arrow_c_schema__(self): + """ + Export to a ArrowSchema PyCapsule + + Unlike _export_to_c, this will not leak memory if the capsule is not used. + """ + cdef ArrowSchema* c_schema + capsule = alloc_c_schema(&c_schema) + + with nogil: + check_status(ExportSchema(deref(self.schema), c_schema)) + + return capsule + + @staticmethod + def _import_from_c_capsule(schema): + """ + Import a Schema from a ArrowSchema PyCapsule + + Parameters + ---------- + schema : PyCapsule + A valid PyCapsule with name 'arrow_schema' containing an + ArrowSchema pointer. + """ + cdef: + ArrowSchema* c_schema + + if not PyCapsule_IsValid(schema, 'arrow_schema'): + raise ValueError( + "Not an ArrowSchema object" + ) + c_schema = PyCapsule_GetPointer(schema, 'arrow_schema') + + with nogil: + result = GetResultValue(ImportSchema(c_schema)) + + return pyarrow_wrap_schema(result) + + +cdef CField.CMergeOptions _parse_field_merge_options(str promote_options) except *: + """ + Returns MergeOptions::Permissive() or MergeOptions::Defaults() based on the value + of `promote_options`. + """ + if promote_options == "permissive": + return CField.CMergeOptions.Permissive() + elif promote_options == "default": + return CField.CMergeOptions.Defaults() + else: + raise ValueError(f"Invalid promote_options: {promote_options}") + + +def unify_schemas(schemas, *, promote_options="default"): + """ + Unify schemas by merging fields by name. + + The resulting schema will contain the union of fields from all schemas. + Fields with the same name will be merged. Note that two fields with + different types will fail merging by default. + + - The unified field will inherit the metadata from the schema where + that field is first defined. + - The first N fields in the schema will be ordered the same as the + N fields in the first schema. + + The resulting schema will inherit its metadata from the first input + schema. + + Parameters + ---------- + schemas : list of Schema + Schemas to merge into a single one. + promote_options : str, default default + Accepts strings "default" and "permissive". + Default: null and only null can be unified with another type. + Permissive: types are promoted to the greater common denominator. + + Returns + ------- + Schema + + Raises + ------ + ArrowInvalid : + If any input schema contains fields with duplicate names. + If Fields of the same name are not mergeable. + """ + cdef: + Schema schema + CField.CMergeOptions c_options + vector[shared_ptr[CSchema]] c_schemas + for schema in schemas: + if not isinstance(schema, Schema): + raise TypeError(f"Expected Schema, got {type(schema)}") + c_schemas.push_back(pyarrow_unwrap_schema(schema)) + + c_options = _parse_field_merge_options(promote_options) + + return pyarrow_wrap_schema( + GetResultValue(UnifySchemas(c_schemas, c_options))) + + +cdef dict _type_cache = {} + + +cdef DataType primitive_type(Type type): + if type in _type_cache: + return _type_cache[type] + + cdef DataType out = DataType.__new__(DataType) + out.init(GetPrimitiveType(type)) + + _type_cache[type] = out + return out + + +# ----------------------------------------------------------- +# Type factory functions + + +def field(name, type=None, nullable=None, metadata=None): + """ + Create a pyarrow.Field instance. + + Parameters + ---------- + name : str or bytes + Name of the field. + Alternatively, you can also pass an object that implements the Arrow + PyCapsule Protocol for schemas (has an ``__arrow_c_schema__`` method). + type : pyarrow.DataType or str + Arrow datatype of the field or a string matching one. + nullable : bool, default True + Whether the field's values are nullable. + metadata : dict, default None + Optional field metadata, the keys and values must be coercible to + bytes. + + Returns + ------- + field : pyarrow.Field + + Examples + -------- + Create an instance of pyarrow.Field: + + >>> import pyarrow as pa + >>> pa.field('key', pa.int32()) + pyarrow.Field + >>> pa.field('key', pa.int32(), nullable=False) + pyarrow.Field + + >>> field = pa.field('key', pa.int32(), + ... metadata={"key": "Something important"}) + >>> field + pyarrow.Field + >>> field.metadata + {b'key': b'Something important'} + + Use the field to create a struct type: + + >>> pa.struct([field]) + StructType(struct) + + A str can also be passed for the type parameter: + + >>> pa.field('key', 'int32') + pyarrow.Field + """ + if hasattr(name, "__arrow_c_schema__"): + if type is not None: + raise ValueError( + "cannot specify 'type' when creating a Field from an ArrowSchema" + ) + field = Field._import_from_c_capsule(name.__arrow_c_schema__()) + if metadata is not None: + field = field.with_metadata(metadata) + if nullable is not None: + field = field.with_nullable(nullable) + return field + + cdef: + Field result = Field.__new__(Field) + DataType _type = ensure_type(type, allow_none=False) + shared_ptr[const CKeyValueMetadata] c_meta + + nullable = True if nullable is None else nullable + + metadata = ensure_metadata(metadata, allow_none=True) + c_meta = pyarrow_unwrap_metadata(metadata) + + if _type.type.id() == _Type_NA and not nullable: + raise ValueError("A null type field may not be non-nullable") + + result.sp_field.reset( + new CField(tobytes(name), _type.sp_type, nullable, c_meta) + ) + result.field = result.sp_field.get() + result.type = _type + + return result + + +cdef set PRIMITIVE_TYPES = set([ + _Type_NA, _Type_BOOL, + _Type_UINT8, _Type_INT8, + _Type_UINT16, _Type_INT16, + _Type_UINT32, _Type_INT32, + _Type_UINT64, _Type_INT64, + _Type_TIMESTAMP, _Type_DATE32, + _Type_TIME32, _Type_TIME64, + _Type_DATE64, + _Type_HALF_FLOAT, + _Type_FLOAT, + _Type_DOUBLE]) + + +def null(): + """ + Create instance of null type. + + Examples + -------- + Create an instance of a null type: + + >>> import pyarrow as pa + >>> pa.null() + DataType(null) + >>> print(pa.null()) + null + + Create a ``Field`` type with a null type and a name: + + >>> pa.field('null_field', pa.null()) + pyarrow.Field + """ + return primitive_type(_Type_NA) + + +def bool_(): + """ + Create instance of boolean type. + + Examples + -------- + Create an instance of a boolean type: + + >>> import pyarrow as pa + >>> pa.bool_() + DataType(bool) + >>> print(pa.bool_()) + bool + + Create a ``Field`` type with a boolean type + and a name: + + >>> pa.field('bool_field', pa.bool_()) + pyarrow.Field + """ + return primitive_type(_Type_BOOL) + + +def uint8(): + """ + Create instance of unsigned int8 type. + + Examples + -------- + Create an instance of unsigned int8 type: + + >>> import pyarrow as pa + >>> pa.uint8() + DataType(uint8) + >>> print(pa.uint8()) + uint8 + + Create an array with unsigned int8 type: + + >>> pa.array([0, 1, 2], type=pa.uint8()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_UINT8) + + +def int8(): + """ + Create instance of signed int8 type. + + Examples + -------- + Create an instance of int8 type: + + >>> import pyarrow as pa + >>> pa.int8() + DataType(int8) + >>> print(pa.int8()) + int8 + + Create an array with int8 type: + + >>> pa.array([0, 1, 2], type=pa.int8()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_INT8) + + +def uint16(): + """ + Create instance of unsigned uint16 type. + + Examples + -------- + Create an instance of unsigned int16 type: + + >>> import pyarrow as pa + >>> pa.uint16() + DataType(uint16) + >>> print(pa.uint16()) + uint16 + + Create an array with unsigned int16 type: + + >>> pa.array([0, 1, 2], type=pa.uint16()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_UINT16) + + +def int16(): + """ + Create instance of signed int16 type. + + Examples + -------- + Create an instance of int16 type: + + >>> import pyarrow as pa + >>> pa.int16() + DataType(int16) + >>> print(pa.int16()) + int16 + + Create an array with int16 type: + + >>> pa.array([0, 1, 2], type=pa.int16()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_INT16) + + +def uint32(): + """ + Create instance of unsigned uint32 type. + + Examples + -------- + Create an instance of unsigned int32 type: + + >>> import pyarrow as pa + >>> pa.uint32() + DataType(uint32) + >>> print(pa.uint32()) + uint32 + + Create an array with unsigned int32 type: + + >>> pa.array([0, 1, 2], type=pa.uint32()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_UINT32) + + +def int32(): + """ + Create instance of signed int32 type. + + Examples + -------- + Create an instance of int32 type: + + >>> import pyarrow as pa + >>> pa.int32() + DataType(int32) + >>> print(pa.int32()) + int32 + + Create an array with int32 type: + + >>> pa.array([0, 1, 2], type=pa.int32()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_INT32) + + +def uint64(): + """ + Create instance of unsigned uint64 type. + + Examples + -------- + Create an instance of unsigned int64 type: + + >>> import pyarrow as pa + >>> pa.uint64() + DataType(uint64) + >>> print(pa.uint64()) + uint64 + + Create an array with unsigned uint64 type: + + >>> pa.array([0, 1, 2], type=pa.uint64()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_UINT64) + + +def int64(): + """ + Create instance of signed int64 type. + + Examples + -------- + Create an instance of int64 type: + + >>> import pyarrow as pa + >>> pa.int64() + DataType(int64) + >>> print(pa.int64()) + int64 + + Create an array with int64 type: + + >>> pa.array([0, 1, 2], type=pa.int64()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_INT64) + + +cdef dict _timestamp_type_cache = {} +cdef dict _time_type_cache = {} +cdef dict _duration_type_cache = {} + + +cdef timeunit_to_string(TimeUnit unit): + if unit == TimeUnit_SECOND: + return 's' + elif unit == TimeUnit_MILLI: + return 'ms' + elif unit == TimeUnit_MICRO: + return 'us' + elif unit == TimeUnit_NANO: + return 'ns' + + +cdef TimeUnit string_to_timeunit(unit) except *: + if unit == 's': + return TimeUnit_SECOND + elif unit == 'ms': + return TimeUnit_MILLI + elif unit == 'us': + return TimeUnit_MICRO + elif unit == 'ns': + return TimeUnit_NANO + else: + raise ValueError(f"Invalid time unit: {unit!r}") + + +def tzinfo_to_string(tz): + """ + Converts a time zone object into a string indicating the name of a time + zone, one of: + * As used in the Olson time zone database (the "tz database" or + "tzdata"), such as "America/New_York" + * An absolute time zone offset of the form +XX:XX or -XX:XX, such as +07:30 + + Parameters + ---------- + tz : datetime.tzinfo + Time zone object + + Returns + ------- + name : str + Time zone name + """ + return frombytes(GetResultValue(TzinfoToString(tz))) + + +def string_to_tzinfo(name): + """ + Convert a time zone name into a time zone object. + + Supported input strings are: + * As used in the Olson time zone database (the "tz database" or + "tzdata"), such as "America/New_York" + * An absolute time zone offset of the form +XX:XX or -XX:XX, such as +07:30 + + Parameters + ---------- + name: str + Time zone name. + + Returns + ------- + tz : datetime.tzinfo + Time zone object + """ + cdef PyObject* tz = GetResultValue(StringToTzinfo(name.encode('utf-8'))) + return PyObject_to_object(tz) + + +def timestamp(unit, tz=None): + """ + Create instance of timestamp type with resolution and optional time zone. + + Parameters + ---------- + unit : str + one of 's' [second], 'ms' [millisecond], 'us' [microsecond], or 'ns' + [nanosecond] + tz : str, default None + Time zone name. None indicates time zone naive + + Examples + -------- + Create an instance of timestamp type: + + >>> import pyarrow as pa + >>> pa.timestamp('us') + TimestampType(timestamp[us]) + >>> pa.timestamp('s', tz='America/New_York') + TimestampType(timestamp[s, tz=America/New_York]) + >>> pa.timestamp('s', tz='+07:30') + TimestampType(timestamp[s, tz=+07:30]) + + Use timestamp type when creating a scalar object: + + >>> from datetime import datetime + >>> pa.scalar(datetime(2012, 1, 1), type=pa.timestamp('s', tz='UTC')) + + >>> pa.scalar(datetime(2012, 1, 1), type=pa.timestamp('us')) + + + Returns + ------- + timestamp_type : TimestampType + """ + cdef: + TimeUnit unit_code + c_string c_timezone + + unit_code = string_to_timeunit(unit) + + cdef TimestampType out = TimestampType.__new__(TimestampType) + + if tz is None: + out.init(ctimestamp(unit_code)) + if unit_code in _timestamp_type_cache: + return _timestamp_type_cache[unit_code] + _timestamp_type_cache[unit_code] = out + else: + if not isinstance(tz, (bytes, str)): + tz = tzinfo_to_string(tz) + + c_timezone = tobytes(tz) + out.init(ctimestamp(unit_code, c_timezone)) + + return out + + +def time32(unit): + """ + Create instance of 32-bit time (time of day) type with unit resolution. + + Parameters + ---------- + unit : str + one of 's' [second], or 'ms' [millisecond] + + Returns + ------- + type : pyarrow.Time32Type + + Examples + -------- + >>> import pyarrow as pa + >>> pa.time32('s') + Time32Type(time32[s]) + >>> pa.time32('ms') + Time32Type(time32[ms]) + """ + cdef: + TimeUnit unit_code + c_string c_timezone + + if unit == 's': + unit_code = TimeUnit_SECOND + elif unit == 'ms': + unit_code = TimeUnit_MILLI + else: + raise ValueError(f"Invalid time unit for time32: {unit!r}") + + if unit_code in _time_type_cache: + return _time_type_cache[unit_code] + + cdef Time32Type out = Time32Type.__new__(Time32Type) + + out.init(ctime32(unit_code)) + _time_type_cache[unit_code] = out + + return out + + +def time64(unit): + """ + Create instance of 64-bit time (time of day) type with unit resolution. + + Parameters + ---------- + unit : str + One of 'us' [microsecond], or 'ns' [nanosecond]. + + Returns + ------- + type : pyarrow.Time64Type + + Examples + -------- + >>> import pyarrow as pa + >>> pa.time64('us') + Time64Type(time64[us]) + >>> pa.time64('ns') + Time64Type(time64[ns]) + """ + cdef: + TimeUnit unit_code + c_string c_timezone + + if unit == 'us': + unit_code = TimeUnit_MICRO + elif unit == 'ns': + unit_code = TimeUnit_NANO + else: + raise ValueError(f"Invalid time unit for time64: {unit!r}") + + if unit_code in _time_type_cache: + return _time_type_cache[unit_code] + + cdef Time64Type out = Time64Type.__new__(Time64Type) + + out.init(ctime64(unit_code)) + _time_type_cache[unit_code] = out + + return out + + +def duration(unit): + """ + Create instance of a duration type with unit resolution. + + Parameters + ---------- + unit : str + One of 's' [second], 'ms' [millisecond], 'us' [microsecond], or + 'ns' [nanosecond]. + + Returns + ------- + type : pyarrow.DurationType + + Examples + -------- + Create an instance of duration type: + + >>> import pyarrow as pa + >>> pa.duration('us') + DurationType(duration[us]) + >>> pa.duration('s') + DurationType(duration[s]) + + Create an array with duration type: + + >>> pa.array([0, 1, 2], type=pa.duration('s')) + + [ + 0, + 1, + 2 + ] + """ + cdef: + TimeUnit unit_code + + unit_code = string_to_timeunit(unit) + + if unit_code in _duration_type_cache: + return _duration_type_cache[unit_code] + + cdef DurationType out = DurationType.__new__(DurationType) + + out.init(cduration(unit_code)) + _duration_type_cache[unit_code] = out + + return out + + +def month_day_nano_interval(): + """ + Create instance of an interval type representing months, days and + nanoseconds between two dates. + + Examples + -------- + Create an instance of an month_day_nano_interval type: + + >>> import pyarrow as pa + >>> pa.month_day_nano_interval() + DataType(month_day_nano_interval) + + Create a scalar with month_day_nano_interval type: + + >>> pa.scalar((1, 15, -30), type=pa.month_day_nano_interval()) + + """ + return primitive_type(_Type_INTERVAL_MONTH_DAY_NANO) + + +def date32(): + """ + Create instance of 32-bit date (days since UNIX epoch 1970-01-01). + + Examples + -------- + Create an instance of 32-bit date type: + + >>> import pyarrow as pa + >>> pa.date32() + DataType(date32[day]) + + Create a scalar with 32-bit date type: + + >>> from datetime import date + >>> pa.scalar(date(2012, 1, 1), type=pa.date32()) + + """ + return primitive_type(_Type_DATE32) + + +def date64(): + """ + Create instance of 64-bit date (milliseconds since UNIX epoch 1970-01-01). + + Examples + -------- + Create an instance of 64-bit date type: + + >>> import pyarrow as pa + >>> pa.date64() + DataType(date64[ms]) + + Create a scalar with 64-bit date type: + + >>> from datetime import datetime + >>> pa.scalar(datetime(2012, 1, 1), type=pa.date64()) + + """ + return primitive_type(_Type_DATE64) + + +def float16(): + """ + Create half-precision floating point type. + + Examples + -------- + Create an instance of float16 type: + + >>> import pyarrow as pa + >>> pa.float16() + DataType(halffloat) + >>> print(pa.float16()) + halffloat + + Create an array with float16 type: + + >>> arr = np.array([1.5, np.nan], dtype=np.float16) + >>> a = pa.array(arr, type=pa.float16()) + >>> a + + [ + 1.5, + nan + ] + + Note that unlike other float types, if you convert this array + to a python list, the types of its elements will be ``np.float16`` + + >>> [type(val) for val in a.to_pylist()] + [, ] + """ + return primitive_type(_Type_HALF_FLOAT) + + +def float32(): + """ + Create single-precision floating point type. + + Examples + -------- + Create an instance of float32 type: + + >>> import pyarrow as pa + >>> pa.float32() + DataType(float) + >>> print(pa.float32()) + float + + Create an array with float32 type: + + >>> pa.array([0.0, 1.0, 2.0], type=pa.float32()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_FLOAT) + + +def float64(): + """ + Create double-precision floating point type. + + Examples + -------- + Create an instance of float64 type: + + >>> import pyarrow as pa + >>> pa.float64() + DataType(double) + >>> print(pa.float64()) + double + + Create an array with float64 type: + + >>> pa.array([0.0, 1.0, 2.0], type=pa.float64()) + + [ + 0, + 1, + 2 + ] + """ + return primitive_type(_Type_DOUBLE) + + +cpdef DataType decimal32(int precision, int scale=0): + """ + Create decimal type with precision and scale and 32-bit width. + + Arrow decimals are fixed-point decimal numbers encoded as a scaled + integer. The precision is the number of significant digits that the + decimal type can represent; the scale is the number of digits after + the decimal point (note the scale can be negative). + + As an example, ``decimal32(7, 3)`` can exactly represent the numbers + 1234.567 and -1234.567 (encoded internally as the 32-bit integers + 1234567 and -1234567, respectively), but neither 12345.67 nor 123.4567. + + ``decimal32(5, -3)`` can exactly represent the number 12345000 + (encoded internally as the 32-bit integer 12345), but neither + 123450000 nor 1234500. + + If you need a precision higher than 9 significant digits, consider + using ``decimal64``, ``decimal128``, or ``decimal256``. + + Parameters + ---------- + precision : int + Must be between 1 and 9 + scale : int + + Returns + ------- + decimal_type : Decimal32Type + + Examples + -------- + Create an instance of decimal type: + + >>> import pyarrow as pa + >>> pa.decimal32(5, 2) + Decimal32Type(decimal32(5, 2)) + + Create an array with decimal type: + + >>> import decimal + >>> a = decimal.Decimal('123.45') + >>> pa.array([a], pa.decimal32(5, 2)) + + [ + 123.45 + ] + """ + cdef shared_ptr[CDataType] decimal_type + if precision < 1 or precision > 9: + raise ValueError("precision should be between 1 and 9") + decimal_type.reset(new CDecimal32Type(precision, scale)) + return pyarrow_wrap_data_type(decimal_type) + + +cpdef DataType decimal64(int precision, int scale=0): + """ + Create decimal type with precision and scale and 64-bit width. + + Arrow decimals are fixed-point decimal numbers encoded as a scaled + integer. The precision is the number of significant digits that the + decimal type can represent; the scale is the number of digits after + the decimal point (note the scale can be negative). + + As an example, ``decimal64(7, 3)`` can exactly represent the numbers + 1234.567 and -1234.567 (encoded internally as the 64-bit integers + 1234567 and -1234567, respectively), but neither 12345.67 nor 123.4567. + + ``decimal64(5, -3)`` can exactly represent the number 12345000 + (encoded internally as the 64-bit integer 12345), but neither + 123450000 nor 1234500. + + If you need a precision higher than 18 significant digits, consider + using ``decimal128``, or ``decimal256``. + + Parameters + ---------- + precision : int + Must be between 1 and 18 + scale : int + + Returns + ------- + decimal_type : Decimal64Type + + Examples + -------- + Create an instance of decimal type: + + >>> import pyarrow as pa + >>> pa.decimal64(5, 2) + Decimal64Type(decimal64(5, 2)) + + Create an array with decimal type: + + >>> import decimal + >>> a = decimal.Decimal('123.45') + >>> pa.array([a], pa.decimal64(5, 2)) + + [ + 123.45 + ] + """ + cdef shared_ptr[CDataType] decimal_type + if precision < 1 or precision > 18: + raise ValueError("precision should be between 1 and 18") + decimal_type.reset(new CDecimal64Type(precision, scale)) + return pyarrow_wrap_data_type(decimal_type) + + +cpdef DataType decimal128(int precision, int scale=0): + """ + Create decimal type with precision and scale and 128-bit width. + + Arrow decimals are fixed-point decimal numbers encoded as a scaled + integer. The precision is the number of significant digits that the + decimal type can represent; the scale is the number of digits after + the decimal point (note the scale can be negative). + + As an example, ``decimal128(7, 3)`` can exactly represent the numbers + 1234.567 and -1234.567 (encoded internally as the 128-bit integers + 1234567 and -1234567, respectively), but neither 12345.67 nor 123.4567. + + ``decimal128(5, -3)`` can exactly represent the number 12345000 + (encoded internally as the 128-bit integer 12345), but neither + 123450000 nor 1234500. + + If you need a precision higher than 38 significant digits, consider + using ``decimal256``. + + Parameters + ---------- + precision : int + Must be between 1 and 38 + scale : int + + Returns + ------- + decimal_type : Decimal128Type + + Examples + -------- + Create an instance of decimal type: + + >>> import pyarrow as pa + >>> pa.decimal128(5, 2) + Decimal128Type(decimal128(5, 2)) + + Create an array with decimal type: + + >>> import decimal + >>> a = decimal.Decimal('123.45') + >>> pa.array([a], pa.decimal128(5, 2)) + + [ + 123.45 + ] + """ + cdef shared_ptr[CDataType] decimal_type + if precision < 1 or precision > 38: + raise ValueError("precision should be between 1 and 38") + decimal_type.reset(new CDecimal128Type(precision, scale)) + return pyarrow_wrap_data_type(decimal_type) + + +cpdef DataType decimal256(int precision, int scale=0): + """ + Create decimal type with precision and scale and 256-bit width. + + Arrow decimals are fixed-point decimal numbers encoded as a scaled + integer. The precision is the number of significant digits that the + decimal type can represent; the scale is the number of digits after + the decimal point (note the scale can be negative). + + For most use cases, the maximum precision offered by ``decimal128`` + is sufficient, and it will result in a more compact and more efficient + encoding. ``decimal256`` is useful if you need a precision higher + than 38 significant digits. + + Parameters + ---------- + precision : int + Must be between 1 and 76 + scale : int + + Returns + ------- + decimal_type : Decimal256Type + """ + cdef shared_ptr[CDataType] decimal_type + if precision < 1 or precision > 76: + raise ValueError("precision should be between 1 and 76") + decimal_type.reset(new CDecimal256Type(precision, scale)) + return pyarrow_wrap_data_type(decimal_type) + + +def string(): + """ + Create UTF8 variable-length string type. + + Examples + -------- + Create an instance of a string type: + + >>> import pyarrow as pa + >>> pa.string() + DataType(string) + + and use the string type to create an array: + + >>> pa.array(['foo', 'bar', 'baz'], type=pa.string()) + + [ + "foo", + "bar", + "baz" + ] + """ + return primitive_type(_Type_STRING) + + +def utf8(): + """ + Alias for string(). + + Examples + -------- + Create an instance of a string type: + + >>> import pyarrow as pa + >>> pa.utf8() + DataType(string) + + and use the string type to create an array: + + >>> pa.array(['foo', 'bar', 'baz'], type=pa.utf8()) + + [ + "foo", + "bar", + "baz" + ] + """ + return string() + + +def binary(int length=-1): + """ + Create variable-length or fixed size binary type. + + Parameters + ---------- + length : int, optional, default -1 + If length == -1 then return a variable length binary type. If length is + greater than or equal to 0 then return a fixed size binary type of + width `length`. + + Examples + -------- + Create an instance of a variable-length binary type: + + >>> import pyarrow as pa + >>> pa.binary() + DataType(binary) + + and use the variable-length binary type to create an array: + + >>> pa.array(['foo', 'bar', 'baz'], type=pa.binary()) + + [ + 666F6F, + 626172, + 62617A + ] + + Create an instance of a fixed-size binary type: + + >>> pa.binary(3) + FixedSizeBinaryType(fixed_size_binary[3]) + + and use the fixed-length binary type to create an array: + + >>> pa.array(['foo', 'bar', 'baz'], type=pa.binary(3)) + + [ + 666F6F, + 626172, + 62617A + ] + """ + if length == -1: + return primitive_type(_Type_BINARY) + + cdef shared_ptr[CDataType] fixed_size_binary_type + fixed_size_binary_type.reset(new CFixedSizeBinaryType(length)) + return pyarrow_wrap_data_type(fixed_size_binary_type) + + +def large_binary(): + """ + Create large variable-length binary type. + + This data type may not be supported by all Arrow implementations. Unless + you need to represent data larger than 2GB, you should prefer binary(). + + Examples + -------- + Create an instance of large variable-length binary type: + + >>> import pyarrow as pa + >>> pa.large_binary() + DataType(large_binary) + + and use the type to create an array: + + >>> pa.array(['foo', 'bar', 'baz'], type=pa.large_binary()) + + [ + 666F6F, + 626172, + 62617A + ] + """ + return primitive_type(_Type_LARGE_BINARY) + + +def large_string(): + """ + Create large UTF8 variable-length string type. + + This data type may not be supported by all Arrow implementations. Unless + you need to represent data larger than 2GB, you should prefer string(). + + Examples + -------- + Create an instance of large UTF8 variable-length binary type: + + >>> import pyarrow as pa + >>> pa.large_string() + DataType(large_string) + + and use the type to create an array: + + >>> pa.array(['foo', 'bar'] * 50, type=pa.large_string()) + + [ + "foo", + "bar", + ... + "foo", + "bar" + ] + """ + return primitive_type(_Type_LARGE_STRING) + + +def large_utf8(): + """ + Alias for large_string(). + + Examples + -------- + Create an instance of large UTF8 variable-length binary type: + + >>> import pyarrow as pa + >>> pa.large_utf8() + DataType(large_string) + + and use the type to create an array: + + >>> pa.array(['foo', 'bar'] * 50, type=pa.large_utf8()) + + [ + "foo", + "bar", + ... + "foo", + "bar" + ] + """ + return large_string() + + +def binary_view(): + """ + Create a variable-length binary view type. + + Examples + -------- + Create an instance of a string type: + + >>> import pyarrow as pa + >>> pa.binary_view() + DataType(binary_view) + """ + return primitive_type(_Type_BINARY_VIEW) + + +def string_view(): + """ + Create UTF8 variable-length string view type. + + Examples + -------- + Create an instance of a string type: + + >>> import pyarrow as pa + >>> pa.string_view() + DataType(string_view) + """ + return primitive_type(_Type_STRING_VIEW) + + +def list_(value_type, int list_size=-1): + """ + Create ListType instance from child data type or field. + + Parameters + ---------- + value_type : DataType or Field + list_size : int, optional, default -1 + If length == -1 then return a variable length list type. If length is + greater than or equal to 0 then return a fixed size list type. + + Returns + ------- + list_type : DataType + + Examples + -------- + Create an instance of ListType: + + >>> import pyarrow as pa + >>> pa.list_(pa.string()) + ListType(list) + >>> pa.list_(pa.int32(), 2) + FixedSizeListType(fixed_size_list[2]) + + Use the ListType to create a scalar: + + >>> pa.scalar(['foo', None], type=pa.list_(pa.string(), 2)) + + + or an array: + + >>> pa.array([[1, 2], [3, 4]], pa.list_(pa.int32(), 2)) + + [ + [ + 1, + 2 + ], + [ + 3, + 4 + ] + ] + """ + cdef: + Field _field + shared_ptr[CDataType] list_type + + if isinstance(value_type, DataType): + _field = field('item', value_type) + elif isinstance(value_type, Field): + _field = value_type + else: + raise TypeError('List requires DataType or Field') + + if list_size == -1: + list_type.reset(new CListType(_field.sp_field)) + else: + if list_size < 0: + raise ValueError("list_size should be a positive integer") + list_type.reset(new CFixedSizeListType(_field.sp_field, list_size)) + + return pyarrow_wrap_data_type(list_type) + + +cpdef LargeListType large_list(value_type): + """ + Create LargeListType instance from child data type or field. + + This data type may not be supported by all Arrow implementations. + Unless you need to represent data larger than 2**31 elements, you should + prefer list_(). + + Parameters + ---------- + value_type : DataType or Field + + Returns + ------- + list_type : DataType + + Examples + -------- + Create an instance of LargeListType: + + >>> import pyarrow as pa + >>> pa.large_list(pa.int8()) + LargeListType(large_list) + + Use the LargeListType to create an array: + + >>> pa.array([[-1, 3]] * 5, type=pa.large_list(pa.int8())) + + [ + [ + -1, + 3 + ], + [ + -1, + 3 + ], + ... + """ + cdef: + DataType data_type + Field _field + shared_ptr[CDataType] list_type + LargeListType out = LargeListType.__new__(LargeListType) + + if isinstance(value_type, DataType): + _field = field('item', value_type) + elif isinstance(value_type, Field): + _field = value_type + else: + raise TypeError('List requires DataType or Field') + + list_type.reset(new CLargeListType(_field.sp_field)) + out.init(list_type) + return out + + +cpdef ListViewType list_view(value_type): + """ + Create ListViewType instance from child data type or field. + + This data type may not be supported by all Arrow implementations + because it is an alternative to the ListType. + + Parameters + ---------- + value_type : DataType or Field + + Returns + ------- + list_view_type : DataType + + Examples + -------- + Create an instance of ListViewType: + + >>> import pyarrow as pa + >>> pa.list_view(pa.string()) + ListViewType(list_view) + """ + cdef: + Field _field + shared_ptr[CDataType] list_view_type + + if isinstance(value_type, DataType): + _field = field('item', value_type) + elif isinstance(value_type, Field): + _field = value_type + else: + raise TypeError('ListView requires DataType or Field') + + list_view_type = CMakeListViewType(_field.sp_field) + return pyarrow_wrap_data_type(list_view_type) + + +cpdef LargeListViewType large_list_view(value_type): + """ + Create LargeListViewType instance from child data type or field. + + This data type may not be supported by all Arrow implementations + because it is an alternative to the ListType. + + Parameters + ---------- + value_type : DataType or Field + + Returns + ------- + list_view_type : DataType + + Examples + -------- + Create an instance of LargeListViewType: + + >>> import pyarrow as pa + >>> pa.large_list_view(pa.int8()) + LargeListViewType(large_list_view) + """ + cdef: + Field _field + shared_ptr[CDataType] list_view_type + + if isinstance(value_type, DataType): + _field = field('item', value_type) + elif isinstance(value_type, Field): + _field = value_type + else: + raise TypeError('LargeListView requires DataType or Field') + + list_view_type = CMakeLargeListViewType(_field.sp_field) + return pyarrow_wrap_data_type(list_view_type) + + +cpdef MapType map_(key_type, item_type, keys_sorted=False): + """ + Create MapType instance from key and item data types or fields. + + Parameters + ---------- + key_type : DataType or Field + item_type : DataType or Field + keys_sorted : bool + + Returns + ------- + map_type : DataType + + Examples + -------- + Create an instance of MapType: + + >>> import pyarrow as pa + >>> pa.map_(pa.string(), pa.int32()) + MapType(map) + >>> pa.map_(pa.string(), pa.int32(), keys_sorted=True) + MapType(map) + + Use MapType to create an array: + + >>> data = [[{'key': 'a', 'value': 1}, {'key': 'b', 'value': 2}], [{'key': 'c', 'value': 3}]] + >>> pa.array(data, type=pa.map_(pa.string(), pa.int32(), keys_sorted=True)) + + [ + keys: + [ + "a", + "b" + ] + values: + [ + 1, + 2 + ], + keys: + [ + "c" + ] + values: + [ + 3 + ] + ] + """ + cdef: + Field _key_field + Field _item_field + shared_ptr[CDataType] map_type + MapType out = MapType.__new__(MapType) + + if isinstance(key_type, Field): + if key_type.nullable: + raise TypeError('Map key field should be non-nullable') + _key_field = key_type + else: + _key_field = field('key', ensure_type(key_type, allow_none=False), + nullable=False) + + if isinstance(item_type, Field): + _item_field = item_type + else: + _item_field = field('value', ensure_type(item_type, allow_none=False)) + + map_type.reset(new CMapType(_key_field.sp_field, _item_field.sp_field, + keys_sorted)) + out.init(map_type) + return out + + +cpdef DictionaryType dictionary(index_type, value_type, bint ordered=False): + """ + Dictionary (categorical, or simply encoded) type. + + Parameters + ---------- + index_type : DataType + value_type : DataType + ordered : bool + + Returns + ------- + type : DictionaryType + + Examples + -------- + Create an instance of dictionary type: + + >>> import pyarrow as pa + >>> pa.dictionary(pa.int64(), pa.utf8()) + DictionaryType(dictionary) + + Use dictionary type to create an array: + + >>> pa.array(["a", "b", None, "d"], pa.dictionary(pa.int64(), pa.utf8())) + + ... + -- dictionary: + [ + "a", + "b", + "d" + ] + -- indices: + [ + 0, + 1, + null, + 2 + ] + """ + cdef: + DataType _index_type = ensure_type(index_type, allow_none=False) + DataType _value_type = ensure_type(value_type, allow_none=False) + DictionaryType out = DictionaryType.__new__(DictionaryType) + shared_ptr[CDataType] dict_type + + if _index_type.id not in { + Type_INT8, Type_INT16, Type_INT32, Type_INT64, + Type_UINT8, Type_UINT16, Type_UINT32, Type_UINT64, + }: + raise TypeError("The dictionary index type should be integer.") + + dict_type.reset(new CDictionaryType(_index_type.sp_type, + _value_type.sp_type, ordered == 1)) + out.init(dict_type) + return out + + +def struct(fields): + """ + Create StructType instance from fields. + + A struct is a nested type parameterized by an ordered sequence of types + (which can all be distinct), called its fields. + + Parameters + ---------- + fields : iterable of Fields or tuples, or mapping of strings to DataTypes + Each field must have a UTF8-encoded name, and these field names are + part of the type metadata. + + Examples + -------- + Create an instance of StructType from an iterable of tuples: + + >>> import pyarrow as pa + >>> fields = [ + ... ('f1', pa.int32()), + ... ('f2', pa.string()), + ... ] + >>> struct_type = pa.struct(fields) + >>> struct_type + StructType(struct) + + Retrieve a field from a StructType: + + >>> struct_type[0] + pyarrow.Field + >>> struct_type['f1'] + pyarrow.Field + + Create an instance of StructType from an iterable of Fields: + + >>> fields = [ + ... pa.field('f1', pa.int32()), + ... pa.field('f2', pa.string(), nullable=False), + ... ] + >>> pa.struct(fields) + StructType(struct) + + Returns + ------- + type : DataType + """ + cdef: + Field py_field + vector[shared_ptr[CField]] c_fields + cdef shared_ptr[CDataType] struct_type + + if isinstance(fields, Mapping): + fields = fields.items() + + for item in fields: + if isinstance(item, tuple): + py_field = field(*item) + else: + py_field = item + c_fields.push_back(py_field.sp_field) + + struct_type.reset(new CStructType(c_fields)) + return pyarrow_wrap_data_type(struct_type) + + +cdef _extract_union_params(child_fields, type_codes, + vector[shared_ptr[CField]]* c_fields, + vector[int8_t]* c_type_codes): + cdef: + Field child_field + + for child_field in child_fields: + c_fields[0].push_back(child_field.sp_field) + + if type_codes is not None: + if len(type_codes) != (c_fields.size()): + raise ValueError("type_codes should have the same length " + "as fields") + for code in type_codes: + c_type_codes[0].push_back(code) + else: + c_type_codes[0] = range(c_fields.size()) + + +def sparse_union(child_fields, type_codes=None): + """ + Create SparseUnionType from child fields. + + A sparse union is a nested type where each logical value is taken from + a single child. A buffer of 8-bit type ids indicates which child + a given logical value is to be taken from. + + In a sparse union, each child array should have the same length as the + union array, regardless of the actual number of union values that + refer to it. + + Parameters + ---------- + child_fields : sequence of Field values + Each field must have a UTF8-encoded name, and these field names are + part of the type metadata. + type_codes : list of integers, default None + + Returns + ------- + type : SparseUnionType + """ + cdef: + vector[shared_ptr[CField]] c_fields + vector[int8_t] c_type_codes + + _extract_union_params(child_fields, type_codes, + &c_fields, &c_type_codes) + + return pyarrow_wrap_data_type( + CMakeSparseUnionType(move(c_fields), move(c_type_codes))) + + +def dense_union(child_fields, type_codes=None): + """ + Create DenseUnionType from child fields. + + A dense union is a nested type where each logical value is taken from + a single child, at a specific offset. A buffer of 8-bit type ids + indicates which child a given logical value is to be taken from, + and a buffer of 32-bit offsets indicates at which physical position + in the given child array the logical value is to be taken from. + + Unlike a sparse union, a dense union allows encoding only the child array + values which are actually referred to by the union array. This is + counterbalanced by the additional footprint of the offsets buffer, and + the additional indirection cost when looking up values. + + Parameters + ---------- + child_fields : sequence of Field values + Each field must have a UTF8-encoded name, and these field names are + part of the type metadata. + type_codes : list of integers, default None + + Returns + ------- + type : DenseUnionType + """ + cdef: + vector[shared_ptr[CField]] c_fields + vector[int8_t] c_type_codes + + _extract_union_params(child_fields, type_codes, + &c_fields, &c_type_codes) + + return pyarrow_wrap_data_type( + CMakeDenseUnionType(move(c_fields), move(c_type_codes))) + + +def union(child_fields, mode, type_codes=None): + """ + Create UnionType from child fields. + + A union is a nested type where each logical value is taken from a + single child. A buffer of 8-bit type ids indicates which child + a given logical value is to be taken from. + + Unions come in two flavors: sparse and dense + (see also `pyarrow.sparse_union` and `pyarrow.dense_union`). + + Parameters + ---------- + child_fields : sequence of Field values + Each field must have a UTF8-encoded name, and these field names are + part of the type metadata. + mode : str + Must be 'sparse' or 'dense' + type_codes : list of integers, default None + + Returns + ------- + type : UnionType + """ + if isinstance(mode, int): + if mode not in (_UnionMode_SPARSE, _UnionMode_DENSE): + raise ValueError(f"Invalid union mode {mode!r}") + else: + if mode == 'sparse': + mode = _UnionMode_SPARSE + elif mode == 'dense': + mode = _UnionMode_DENSE + else: + raise ValueError(f"Invalid union mode {mode!r}") + + if mode == _UnionMode_SPARSE: + return sparse_union(child_fields, type_codes) + else: + return dense_union(child_fields, type_codes) + + +def run_end_encoded(run_end_type, value_type): + """ + Create RunEndEncodedType from run-end and value types. + + Parameters + ---------- + run_end_type : pyarrow.DataType + The integer type of the run_ends array. Must be 'int16', 'int32', or 'int64'. + value_type : pyarrow.DataType + The type of the values array. + + Returns + ------- + type : RunEndEncodedType + """ + cdef: + DataType _run_end_type = ensure_type(run_end_type, allow_none=False) + DataType _value_type = ensure_type(value_type, allow_none=False) + shared_ptr[CDataType] ree_type + + if not _run_end_type.type.id() in [_Type_INT16, _Type_INT32, _Type_INT64]: + raise ValueError("The run_end_type should be 'int16', 'int32', or 'int64'") + ree_type = CMakeRunEndEncodedType(_run_end_type.sp_type, _value_type.sp_type) + return pyarrow_wrap_data_type(ree_type) + + +def json_(DataType storage_type=utf8()): + """ + Create instance of JSON extension type. + + Parameters + ---------- + storage_type : DataType, default pyarrow.string() + The underlying data type. Can be on of the following types: + string, large_string, string_view. + + Returns + ------- + type : JsonType + + Examples + -------- + Create an instance of JSON extension type: + + >>> import pyarrow as pa + >>> pa.json_(pa.utf8()) + JsonType(extension) + + Use the JSON type to create an array: + + >>> pa.array(['{"a": 1}', '{"b": 2}'], type=pa.json_(pa.utf8())) + + [ + "{"a": 1}", + "{"b": 2}" + ] + """ + + cdef JsonType out = JsonType.__new__(JsonType) + c_json_ext_type = GetResultValue(CJsonType.Make(storage_type.sp_type)) + out.init(c_json_ext_type) + return out + + +def uuid(): + """ + Create UuidType instance. + + Returns + ------- + type : UuidType + """ + + cdef UuidType out = UuidType.__new__(UuidType) + c_uuid_ext_type = GetResultValue(CUuidType.Make()) + out.init(c_uuid_ext_type) + return out + + +def fixed_shape_tensor(DataType value_type, shape, dim_names=None, permutation=None): + """ + Create instance of fixed shape tensor extension type with shape and optional + names of tensor dimensions and indices of the desired logical + ordering of dimensions. + + Parameters + ---------- + value_type : DataType + Data type of individual tensor elements. + shape : tuple or list of integers + The physical shape of the contained tensors. + dim_names : tuple or list of strings, default None + Explicit names to tensor dimensions. + permutation : tuple or list integers, default None + Indices of the desired ordering of the original dimensions. + The indices contain a permutation of the values ``[0, 1, .., N-1]`` where + N is the number of dimensions. The permutation indicates which dimension + of the logical layout corresponds to which dimension of the physical tensor. + For more information on this parameter see + :ref:`fixed_shape_tensor_extension`. + + Examples + -------- + Create an instance of fixed shape tensor extension type: + + >>> import pyarrow as pa + >>> tensor_type = pa.fixed_shape_tensor(pa.int32(), [2, 2]) + >>> tensor_type + FixedShapeTensorType(extension) + + Inspect the data type: + + >>> tensor_type.value_type + DataType(int32) + >>> tensor_type.shape + [2, 2] + + Create a table with fixed shape tensor extension array: + + >>> arr = [[1, 2, 3, 4], [10, 20, 30, 40], [100, 200, 300, 400]] + >>> storage = pa.array(arr, pa.list_(pa.int32(), 4)) + >>> tensor = pa.ExtensionArray.from_storage(tensor_type, storage) + >>> pa.table([tensor], names=["tensor_array"]) + pyarrow.Table + tensor_array: extension + ---- + tensor_array: [[[1,2,3,4],[10,20,30,40],[100,200,300,400]]] + + Create an instance of fixed shape tensor extension type with names + of tensor dimensions: + + >>> tensor_type = pa.fixed_shape_tensor(pa.int8(), (2, 2, 3), + ... dim_names=['C', 'H', 'W']) + >>> tensor_type.dim_names + ['C', 'H', 'W'] + + Create an instance of fixed shape tensor extension type with + permutation: + + >>> tensor_type = pa.fixed_shape_tensor(pa.int8(), (2, 2, 3), + ... permutation=[0, 2, 1]) + >>> tensor_type.permutation + [0, 2, 1] + + Returns + ------- + type : FixedShapeTensorType + """ + + cdef: + vector[int64_t] c_shape + vector[int64_t] c_permutation + vector[c_string] c_dim_names + shared_ptr[CDataType] c_tensor_ext_type + + assert value_type is not None + assert shape is not None + + for i in shape: + c_shape.push_back(i) + + if permutation is not None: + for i in permutation: + c_permutation.push_back(i) + + if dim_names is not None: + for x in dim_names: + c_dim_names.push_back(tobytes(x)) + + cdef FixedShapeTensorType out = FixedShapeTensorType.__new__(FixedShapeTensorType) + + with nogil: + c_tensor_ext_type = GetResultValue(CFixedShapeTensorType.Make( + value_type.sp_type, c_shape, c_permutation, c_dim_names)) + + out.init(c_tensor_ext_type) + + return out + + +def bool8(): + """ + Create instance of bool8 extension type. + + Examples + -------- + Create an instance of bool8 extension type: + + >>> import pyarrow as pa + >>> type = pa.bool8() + >>> type + Bool8Type(extension) + + Inspect the data type: + + >>> type.storage_type + DataType(int8) + + Create a table with a bool8 array: + + >>> arr = [-1, 0, 1, 2, None] + >>> storage = pa.array(arr, pa.int8()) + >>> other = pa.ExtensionArray.from_storage(type, storage) + >>> pa.table([other], names=["unknown_col"]) + pyarrow.Table + unknown_col: extension + ---- + unknown_col: [[-1,0,1,2,null]] + + Returns + ------- + type : Bool8Type + """ + + cdef Bool8Type out = Bool8Type.__new__(Bool8Type) + + c_type = GetResultValue(CBool8Type.Make()) + + out.init(c_type) + + return out + + +def opaque(DataType storage_type, str type_name not None, str vendor_name not None): + """ + Create instance of opaque extension type. + + Parameters + ---------- + storage_type : DataType + The underlying data type. + type_name : str + The name of the type in the external system. + vendor_name : str + The name of the external system. + + Examples + -------- + Create an instance of an opaque extension type: + + >>> import pyarrow as pa + >>> type = pa.opaque(pa.binary(), "other", "jdbc") + >>> type + OpaqueType(extension) + + Inspect the data type: + + >>> type.storage_type + DataType(binary) + >>> type.type_name + 'other' + >>> type.vendor_name + 'jdbc' + + Create a table with an opaque array: + + >>> arr = [None, b"foobar"] + >>> storage = pa.array(arr, pa.binary()) + >>> other = pa.ExtensionArray.from_storage(type, storage) + >>> pa.table([other], names=["unknown_col"]) + pyarrow.Table + unknown_col: extension + ---- + unknown_col: [[null,666F6F626172]] + + Returns + ------- + type : OpaqueType + """ + + cdef: + c_string c_type_name = tobytes(type_name) + c_string c_vendor_name = tobytes(vendor_name) + shared_ptr[COpaqueType] c_opaque_type = make_shared[COpaqueType]( + storage_type.sp_type, c_type_name, c_vendor_name) + shared_ptr[CDataType] c_type = static_pointer_cast[CDataType, COpaqueType](c_opaque_type) + OpaqueType out = OpaqueType.__new__(OpaqueType) + out.init(c_type) + return out + + +cdef dict _type_aliases = { + 'null': null, + 'bool': bool_, + 'boolean': bool_, + 'i1': int8, + 'int8': int8, + 'i2': int16, + 'int16': int16, + 'i4': int32, + 'int32': int32, + 'i8': int64, + 'int64': int64, + 'u1': uint8, + 'uint8': uint8, + 'u2': uint16, + 'uint16': uint16, + 'u4': uint32, + 'uint32': uint32, + 'u8': uint64, + 'uint64': uint64, + 'f2': float16, + 'halffloat': float16, + 'float16': float16, + 'f4': float32, + 'float': float32, + 'float32': float32, + 'f8': float64, + 'double': float64, + 'float64': float64, + 'string': string, + 'str': string, + 'utf8': string, + 'binary': binary, + 'large_string': large_string, + 'large_str': large_string, + 'large_utf8': large_string, + 'large_binary': large_binary, + 'binary_view': binary_view, + 'string_view': string_view, + 'date32': date32, + 'date64': date64, + 'date32[day]': date32, + 'date64[ms]': date64, + 'time32[s]': time32('s'), + 'time32[ms]': time32('ms'), + 'time64[us]': time64('us'), + 'time64[ns]': time64('ns'), + 'timestamp[s]': timestamp('s'), + 'timestamp[ms]': timestamp('ms'), + 'timestamp[us]': timestamp('us'), + 'timestamp[ns]': timestamp('ns'), + 'duration[s]': duration('s'), + 'duration[ms]': duration('ms'), + 'duration[us]': duration('us'), + 'duration[ns]': duration('ns'), + 'month_day_nano_interval': month_day_nano_interval(), +} + + +def type_for_alias(name): + """ + Return DataType given a string alias if one exists. + + Parameters + ---------- + name : str + The alias of the DataType that should be retrieved. + + Returns + ------- + type : DataType + """ + name = name.lower() + try: + alias = _type_aliases[name] + except KeyError: + raise ValueError(f'No type alias for {name}') + + if isinstance(alias, DataType): + return alias + return alias() + + +cpdef DataType ensure_type(object ty, bint allow_none=False): + if allow_none and ty is None: + return None + elif isinstance(ty, DataType): + return ty + elif isinstance(ty, str): + return type_for_alias(ty) + else: + raise TypeError(f'DataType expected, got {type(ty)!r}') + + +def schema(fields, metadata=None): + """ + Construct pyarrow.Schema from collection of fields. + + Parameters + ---------- + fields : iterable of Fields or tuples, or mapping of strings to DataTypes + Can also pass an object that implements the Arrow PyCapsule Protocol + for schemas (has an ``__arrow_c_schema__`` method). + metadata : dict, default None + Keys and values must be coercible to bytes. + + Examples + -------- + Create a Schema from iterable of tuples: + + >>> import pyarrow as pa + >>> pa.schema([ + ... ('some_int', pa.int32()), + ... ('some_string', pa.string()), + ... pa.field('some_required_string', pa.string(), nullable=False) + ... ]) + some_int: int32 + some_string: string + some_required_string: string not null + + Create a Schema from iterable of Fields: + + >>> pa.schema([ + ... pa.field('some_int', pa.int32()), + ... pa.field('some_string', pa.string()) + ... ]) + some_int: int32 + some_string: string + + DataTypes can also be passed as strings. The following is equivalent to the + above example: + + >>> pa.schema([ + ... pa.field('some_int', "int32"), + ... pa.field('some_string', "string") + ... ]) + some_int: int32 + some_string: string + + Or more concisely: + + >>> pa.schema([ + ... ('some_int', "int32"), + ... ('some_string', "string") + ... ]) + some_int: int32 + some_string: string + + Returns + ------- + schema : pyarrow.Schema + """ + cdef: + shared_ptr[const CKeyValueMetadata] c_meta + shared_ptr[CSchema] c_schema + Schema result + Field py_field + vector[shared_ptr[CField]] c_fields + + if hasattr(fields, "__arrow_c_schema__"): + result = Schema._import_from_c_capsule(fields.__arrow_c_schema__()) + if metadata is not None: + result = result.with_metadata(metadata) + return result + + if isinstance(fields, Mapping): + fields = fields.items() + + for item in fields: + if isinstance(item, tuple): + py_field = field(*item) + else: + py_field = item + if py_field is None: + raise TypeError("field or tuple expected, got None") + c_fields.push_back(py_field.sp_field) + + metadata = ensure_metadata(metadata, allow_none=True) + c_meta = pyarrow_unwrap_metadata(metadata) + + c_schema.reset(new CSchema(c_fields, c_meta)) + result = Schema.__new__(Schema) + result.init_schema(c_schema) + + return result + + +def from_numpy_dtype(object dtype): + """ + Convert NumPy dtype to pyarrow.DataType. + + Parameters + ---------- + dtype : the numpy dtype to convert + + + Examples + -------- + Create a pyarrow DataType from NumPy dtype: + + >>> import pyarrow as pa + >>> import numpy as np + >>> pa.from_numpy_dtype(np.dtype('float16')) + DataType(halffloat) + >>> pa.from_numpy_dtype('U') + DataType(string) + >>> pa.from_numpy_dtype(bool) + DataType(bool) + >>> pa.from_numpy_dtype(np.str_) + DataType(string) + """ + dtype = np.dtype(dtype) + return pyarrow_wrap_data_type(GetResultValue(NumPyDtypeToArrow(dtype))) + + +def is_boolean_value(object obj): + """ + Check if the object is a boolean. + + Parameters + ---------- + obj : object + The object to check + """ + return IsPyBool(obj) + + +def is_integer_value(object obj): + """ + Check if the object is an integer. + + Parameters + ---------- + obj : object + The object to check + """ + return IsPyInt(obj) + + +def is_float_value(object obj): + """ + Check if the object is a float. + + Parameters + ---------- + obj : object + The object to check + """ + return IsPyFloat(obj) + + +cdef class _ExtensionRegistryNanny(_Weakrefable): + # Keep the registry alive until we have unregistered PyExtensionType + cdef: + shared_ptr[CExtensionTypeRegistry] registry + + def __cinit__(self): + self.registry = CExtensionTypeRegistry.GetGlobalRegistry() + + def release_registry(self): + self.registry.reset() + + +_registry_nanny = _ExtensionRegistryNanny() + + +# +# PyCapsule export utilities +# + +cdef void pycapsule_schema_deleter(object schema_capsule) noexcept: + cdef ArrowSchema* schema = PyCapsule_GetPointer( + schema_capsule, 'arrow_schema' + ) + if schema.release != NULL: + schema.release(schema) + + free(schema) + +cdef object alloc_c_schema(ArrowSchema** c_schema): + c_schema[0] = malloc(sizeof(ArrowSchema)) + # Ensure the capsule destructor doesn't call a random release pointer + c_schema[0].release = NULL + return PyCapsule_New(c_schema[0], 'arrow_schema', &pycapsule_schema_deleter) + + +cdef void pycapsule_array_deleter(object array_capsule) noexcept: + cdef: + ArrowArray* array + # Do not invoke the deleter on a used/moved capsule + array = cpython.PyCapsule_GetPointer( + array_capsule, 'arrow_array' + ) + if array.release != NULL: + array.release(array) + + free(array) + +cdef object alloc_c_array(ArrowArray** c_array): + c_array[0] = malloc(sizeof(ArrowArray)) + # Ensure the capsule destructor doesn't call a random release pointer + c_array[0].release = NULL + return PyCapsule_New(c_array[0], 'arrow_array', &pycapsule_array_deleter) + + +cdef void pycapsule_stream_deleter(object stream_capsule) noexcept: + cdef: + ArrowArrayStream* stream + # Do not invoke the deleter on a used/moved capsule + stream = PyCapsule_GetPointer( + stream_capsule, 'arrow_array_stream' + ) + if stream.release != NULL: + stream.release(stream) + + free(stream) + +cdef object alloc_c_stream(ArrowArrayStream** c_stream): + c_stream[0] = malloc(sizeof(ArrowArrayStream)) + # Ensure the capsule destructor doesn't call a random release pointer + c_stream[0].release = NULL + return PyCapsule_New(c_stream[0], 'arrow_array_stream', &pycapsule_stream_deleter) + + +cdef void pycapsule_device_array_deleter(object array_capsule) noexcept: + cdef: + ArrowDeviceArray* device_array + # Do not invoke the deleter on a used/moved capsule + device_array = cpython.PyCapsule_GetPointer( + array_capsule, 'arrow_device_array' + ) + if device_array.array.release != NULL: + device_array.array.release(&device_array.array) + + free(device_array) + + +cdef object alloc_c_device_array(ArrowDeviceArray** c_array): + c_array[0] = malloc(sizeof(ArrowDeviceArray)) + # Ensure the capsule destructor doesn't call a random release pointer + c_array[0].array.release = NULL + return PyCapsule_New( + c_array[0], 'arrow_device_array', &pycapsule_device_array_deleter) diff --git a/shared/package-files/33/33604784129b509f04d81d901317d57fc35b00ae1916126d98a45e9416590e1e/registry.py b/shared/package-files/33/33604784129b509f04d81d901317d57fc35b00ae1916126d98a45e9416590e1e/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..7f5a53f917a4c349a8bd12c0b38455e11b4dc638 --- /dev/null +++ b/shared/package-files/33/33604784129b509f04d81d901317d57fc35b00ae1916126d98a45e9416590e1e/registry.py @@ -0,0 +1,414 @@ +from enum import Enum +import importlib + + +class BackendFilter(Enum): + """ + Filter used with :meth:`~matplotlib.backends.registry.BackendRegistry.list_builtin` + + .. versionadded:: 3.9 + """ + INTERACTIVE = 0 + NON_INTERACTIVE = 1 + + +class BackendRegistry: + """ + Registry of backends available within Matplotlib. + + This is the single source of truth for available backends. + + All use of ``BackendRegistry`` should be via the singleton instance + ``backend_registry`` which can be imported from ``matplotlib.backends``. + + Each backend has a name, a module name containing the backend code, and an + optional GUI framework that must be running if the backend is interactive. + There are three sources of backends: built-in (source code is within the + Matplotlib repository), explicit ``module://some.backend`` syntax (backend is + obtained by loading the module), or via an entry point (self-registering + backend in an external package). + + .. versionadded:: 3.9 + """ + # Mapping of built-in backend name to GUI framework, or "headless" for no + # GUI framework. Built-in backends are those which are included in the + # Matplotlib repo. A backend with name 'name' is located in the module + # f"matplotlib.backends.backend_{name.lower()}" + _BUILTIN_BACKEND_TO_GUI_FRAMEWORK = { + "gtk3agg": "gtk3", + "gtk3cairo": "gtk3", + "gtk4agg": "gtk4", + "gtk4cairo": "gtk4", + "macosx": "macosx", + "nbagg": "nbagg", + "notebook": "nbagg", + "qtagg": "qt", + "qtcairo": "qt", + "qt5agg": "qt5", + "qt5cairo": "qt5", + "tkagg": "tk", + "tkcairo": "tk", + "webagg": "webagg", + "wx": "wx", + "wxagg": "wx", + "wxcairo": "wx", + "agg": "headless", + "cairo": "headless", + "pdf": "headless", + "pgf": "headless", + "ps": "headless", + "svg": "headless", + "template": "headless", + } + + # Reverse mapping of gui framework to preferred built-in backend. + _GUI_FRAMEWORK_TO_BACKEND = { + "gtk3": "gtk3agg", + "gtk4": "gtk4agg", + "headless": "agg", + "macosx": "macosx", + "qt": "qtagg", + "qt5": "qt5agg", + "qt6": "qtagg", + "tk": "tkagg", + "wx": "wxagg", + } + + def __init__(self): + # Only load entry points when first needed. + self._loaded_entry_points = False + + # Mapping of non-built-in backend to GUI framework, added dynamically from + # entry points and from matplotlib.use("module://some.backend") format. + # New entries have an "unknown" GUI framework that is determined when first + # needed by calling _get_gui_framework_by_loading. + self._backend_to_gui_framework = {} + + # Mapping of backend name to module name, where different from + # f"matplotlib.backends.backend_{backend_name.lower()}". These are either + # hardcoded for backward compatibility, or loaded from entry points or + # "module://some.backend" syntax. + self._name_to_module = { + "notebook": "nbagg", + } + + def _backend_module_name(self, backend): + if backend.startswith("module://"): + return backend[9:] + + # Return name of module containing the specified backend. + # Does not check if the backend is valid, use is_valid_backend for that. + backend = backend.lower() + + # Check if have specific name to module mapping. + backend = self._name_to_module.get(backend, backend) + + return (backend[9:] if backend.startswith("module://") + else f"matplotlib.backends.backend_{backend}") + + def _clear(self): + # Clear all dynamically-added data, used for testing only. + self.__init__() + + def _ensure_entry_points_loaded(self): + # Load entry points, if they have not already been loaded. + if not self._loaded_entry_points: + entries = self._read_entry_points() + self._validate_and_store_entry_points(entries) + self._loaded_entry_points = True + + def _get_gui_framework_by_loading(self, backend): + # Determine GUI framework for a backend by loading its module and reading the + # FigureCanvas.required_interactive_framework attribute. + # Returns "headless" if there is no GUI framework. + module = self.load_backend_module(backend) + canvas_class = module.FigureCanvas + return canvas_class.required_interactive_framework or "headless" + + def _read_entry_points(self): + # Read entry points of modules that self-advertise as Matplotlib backends. + # Expects entry points like this one from matplotlib-inline (in pyproject.toml + # format): + # [project.entry-points."matplotlib.backend"] + # inline = "matplotlib_inline.backend_inline" + import importlib.metadata as im + + entry_points = im.entry_points(group="matplotlib.backend") + entries = [(entry.name, entry.value) for entry in entry_points] + + # For backward compatibility, if matplotlib-inline and/or ipympl are installed + # but too old to include entry points, create them. Do not import ipympl + # directly as this calls matplotlib.use() whilst in this function. + def backward_compatible_entry_points( + entries, module_name, threshold_version, names, target): + from matplotlib import _parse_to_version_info + try: + module_version = im.version(module_name) + if _parse_to_version_info(module_version) < threshold_version: + for name in names: + entries.append((name, target)) + except im.PackageNotFoundError: + pass + + names = [entry[0] for entry in entries] + if "inline" not in names: + backward_compatible_entry_points( + entries, "matplotlib_inline", (0, 1, 7), ["inline"], + "matplotlib_inline.backend_inline") + if "ipympl" not in names: + backward_compatible_entry_points( + entries, "ipympl", (0, 9, 4), ["ipympl", "widget"], + "ipympl.backend_nbagg") + + return entries + + def _validate_and_store_entry_points(self, entries): + # Validate and store entry points so that they can be used via matplotlib.use() + # in the normal manner. Entry point names cannot be of module:// format, cannot + # shadow a built-in backend name, and there cannot be multiple entry points + # with the same name but different modules. Multiple entry points with the same + # name and value are permitted (it can sometimes happen outside of our control, + # see https://github.com/matplotlib/matplotlib/issues/28367). + for name, module in set(entries): + name = name.lower() + if name.startswith("module://"): + raise RuntimeError( + f"Entry point name '{name}' cannot start with 'module://'") + if name in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK: + raise RuntimeError(f"Entry point name '{name}' is a built-in backend") + if name in self._backend_to_gui_framework: + raise RuntimeError(f"Entry point name '{name}' duplicated") + + self._name_to_module[name] = "module://" + module + # Do not yet know backend GUI framework, determine it only when necessary. + self._backend_to_gui_framework[name] = "unknown" + + def backend_for_gui_framework(self, framework): + """ + Return the name of the backend corresponding to the specified GUI framework. + + Parameters + ---------- + framework : str + GUI framework such as "qt". + + Returns + ------- + str or None + Backend name or None if GUI framework not recognised. + """ + return self._GUI_FRAMEWORK_TO_BACKEND.get(framework.lower()) + + def is_valid_backend(self, backend): + """ + Return True if the backend name is valid, False otherwise. + + A backend name is valid if it is one of the built-in backends or has been + dynamically added via an entry point. Those beginning with ``module://`` are + always considered valid and are added to the current list of all backends + within this function. + + Even if a name is valid, it may not be importable or usable. This can only be + determined by loading and using the backend module. + + Parameters + ---------- + backend : str + Name of backend. + + Returns + ------- + bool + True if backend is valid, False otherwise. + """ + if not backend.startswith("module://"): + backend = backend.lower() + + # For backward compatibility, convert ipympl and matplotlib-inline long + # module:// names to their shortened forms. + backwards_compat = { + "module://ipympl.backend_nbagg": "widget", + "module://matplotlib_inline.backend_inline": "inline", + } + backend = backwards_compat.get(backend, backend) + + if (backend in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK or + backend in self._backend_to_gui_framework): + return True + + if backend.startswith("module://"): + self._backend_to_gui_framework[backend] = "unknown" + return True + + # Only load entry points if really need to and not already done so. + self._ensure_entry_points_loaded() + if backend in self._backend_to_gui_framework: + return True + + return False + + def list_all(self): + """ + Return list of all known backends. + + These include built-in backends and those obtained at runtime either from entry + points or explicit ``module://some.backend`` syntax. + + Entry points will be loaded if they haven't been already. + + Returns + ------- + list of str + Backend names. + """ + self._ensure_entry_points_loaded() + return [*self.list_builtin(), *self._backend_to_gui_framework] + + def list_builtin(self, filter_=None): + """ + Return list of backends that are built into Matplotlib. + + Parameters + ---------- + filter_ : `~.BackendFilter`, optional + Filter to apply to returned backends. For example, to return only + non-interactive backends use `.BackendFilter.NON_INTERACTIVE`. + + Returns + ------- + list of str + Backend names. + """ + if filter_ == BackendFilter.INTERACTIVE: + return [k for k, v in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.items() + if v != "headless"] + elif filter_ == BackendFilter.NON_INTERACTIVE: + return [k for k, v in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.items() + if v == "headless"] + + return [*self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK] + + def list_gui_frameworks(self): + """ + Return list of GUI frameworks used by Matplotlib backends. + + Returns + ------- + list of str + GUI framework names. + """ + return [k for k in self._GUI_FRAMEWORK_TO_BACKEND if k != "headless"] + + def load_backend_module(self, backend): + """ + Load and return the module containing the specified backend. + + Parameters + ---------- + backend : str + Name of backend to load. + + Returns + ------- + Module + Module containing backend. + """ + module_name = self._backend_module_name(backend) + return importlib.import_module(module_name) + + def resolve_backend(self, backend): + """ + Return the backend and GUI framework for the specified backend name. + + If the GUI framework is not yet known then it will be determined by loading the + backend module and checking the ``FigureCanvas.required_interactive_framework`` + attribute. + + This function only loads entry points if they have not already been loaded and + the backend is not built-in and not of ``module://some.backend`` format. + + Parameters + ---------- + backend : str or None + Name of backend, or None to use the default backend. + + Returns + ------- + backend : str + The backend name. + framework : str or None + The GUI framework, which will be None for a backend that is non-interactive. + """ + if isinstance(backend, str): + if not backend.startswith("module://"): + backend = backend.lower() + else: # Might be _auto_backend_sentinel or None + # Use whatever is already running... + from matplotlib import get_backend + backend = get_backend() + + # Is backend already known (built-in or dynamically loaded)? + gui = (self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.get(backend) or + self._backend_to_gui_framework.get(backend)) + + # Is backend "module://something"? + if gui is None and isinstance(backend, str) and backend.startswith("module://"): + gui = "unknown" + + # Is backend a possible entry point? + if gui is None and not self._loaded_entry_points: + self._ensure_entry_points_loaded() + gui = self._backend_to_gui_framework.get(backend) + + # Backend known but not its gui framework. + if gui == "unknown": + gui = self._get_gui_framework_by_loading(backend) + self._backend_to_gui_framework[backend] = gui + + if gui is None: + raise RuntimeError(f"'{backend}' is not a recognised backend name") + + return backend, gui if gui != "headless" else None + + def resolve_gui_or_backend(self, gui_or_backend): + """ + Return the backend and GUI framework for the specified string that may be + either a GUI framework or a backend name, tested in that order. + + This is for use with the IPython %matplotlib magic command which may be a GUI + framework such as ``%matplotlib qt`` or a backend name such as + ``%matplotlib qtagg``. + + This function only loads entry points if they have not already been loaded and + the backend is not built-in and not of ``module://some.backend`` format. + + Parameters + ---------- + gui_or_backend : str or None + Name of GUI framework or backend, or None to use the default backend. + + Returns + ------- + backend : str + The backend name. + framework : str or None + The GUI framework, which will be None for a backend that is non-interactive. + """ + if not gui_or_backend.startswith("module://"): + gui_or_backend = gui_or_backend.lower() + + # First check if it is a gui loop name. + backend = self.backend_for_gui_framework(gui_or_backend) + if backend is not None: + return backend, gui_or_backend if gui_or_backend != "headless" else None + + # Then check if it is a backend name. + try: + return self.resolve_backend(gui_or_backend) + except Exception: # KeyError ? + raise RuntimeError( + f"'{gui_or_backend}' is not a recognised GUI loop or backend name") + + +# Singleton +backend_registry = BackendRegistry() diff --git a/shared/package-files/33/33608e94a85d3ddb541c831a396b65188564e4d1b36a0d4e1047172f4bed4e8e/__init__.pyi b/shared/package-files/33/33608e94a85d3ddb541c831a396b65188564e4d1b36a0d4e1047172f4bed4e8e/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..82af5aad02de38e3eeb7cc26f5d0b6b1e3ac946c --- /dev/null +++ b/shared/package-files/33/33608e94a85d3ddb541c831a396b65188564e4d1b36a0d4e1047172f4bed4e8e/__init__.pyi @@ -0,0 +1,27 @@ +from typing import Any, Container, Iterable, Optional, Text + +from bleach.linkifier import DEFAULT_CALLBACKS as DEFAULT_CALLBACKS, Linker as Linker, _Callback +from bleach.sanitizer import ( + ALLOWED_ATTRIBUTES as ALLOWED_ATTRIBUTES, + ALLOWED_PROTOCOLS as ALLOWED_PROTOCOLS, + ALLOWED_STYLES as ALLOWED_STYLES, + ALLOWED_TAGS as ALLOWED_TAGS, + Cleaner as Cleaner, +) + +__releasedate__: Text +__version__: Text +VERSION: Any # packaging.version.Version + +def clean( + text: Text, + tags: Container[Text] = ..., + attributes: Any = ..., + styles: Container[Text] = ..., + protocols: Container[Text] = ..., + strip: bool = ..., + strip_comments: bool = ..., +) -> Text: ... +def linkify( + text: Text, callbacks: Iterable[_Callback] = ..., skip_tags: Optional[Container[Text]] = ..., parse_email: bool = ... +) -> Text: ... diff --git a/shared/package-files/33/3362413bdaf128a2a0728bd5b478c1c99f60577b3d2cef8f4d7e183b2a9a8a1a/_foreach_tan_cpu_dispatch.h b/shared/package-files/33/3362413bdaf128a2a0728bd5b478c1c99f60577b3d2cef8f4d7e183b2a9a8a1a/_foreach_tan_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..fa6c0437fae5e206a9dc56e9390e40b5278925c6 --- /dev/null +++ b/shared/package-files/33/3362413bdaf128a2a0728bd5b478c1c99f60577b3d2cef8f4d7e183b2a9a8a1a/_foreach_tan_cpu_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API ::std::vector _foreach_tan(at::TensorList self); +TORCH_API void _foreach_tan_(at::TensorList self); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/33/336a18dca1fc91417a4e80c1f7161bcd667175e63e73ac8af2af0a50531703b5/arc.py b/shared/package-files/33/336a18dca1fc91417a4e80c1f7161bcd667175e63e73ac8af2af0a50531703b5/arc.py new file mode 100644 index 0000000000000000000000000000000000000000..20fb32f3e95d5abda39b58269cb4cdf7fb7932a3 --- /dev/null +++ b/shared/package-files/33/336a18dca1fc91417a4e80c1f7161bcd667175e63e73ac8af2af0a50531703b5/arc.py @@ -0,0 +1,153 @@ +"""Convert SVG Path's elliptical arcs to Bezier curves. + +The code is mostly adapted from Blink's SVGPathNormalizer::DecomposeArcToCubic +https://github.com/chromium/chromium/blob/93831f2/third_party/ +blink/renderer/core/svg/svg_path_parser.cc#L169-L278 +""" + +from fontTools.misc.transform import Identity, Scale +from math import atan2, ceil, cos, fabs, isfinite, pi, radians, sin, sqrt, tan + +TWO_PI = 2 * pi +PI_OVER_TWO = 0.5 * pi + + +def _map_point(matrix, pt): + # apply Transform matrix to a point represented as a complex number + r = matrix.transformPoint((pt.real, pt.imag)) + return r[0] + r[1] * 1j + + +class EllipticalArc(object): + def __init__(self, current_point, rx, ry, rotation, large, sweep, target_point): + self.current_point = current_point + self.rx = rx + self.ry = ry + self.rotation = rotation + self.large = large + self.sweep = sweep + self.target_point = target_point + + # SVG arc's rotation angle is expressed in degrees, whereas Transform.rotate + # uses radians + self.angle = radians(rotation) + + # these derived attributes are computed by the _parametrize method + self.center_point = self.theta1 = self.theta2 = self.theta_arc = None + + def _parametrize(self): + # convert from endopoint to center parametrization: + # https://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter + + # If rx = 0 or ry = 0 then this arc is treated as a straight line segment (a + # "lineto") joining the endpoints. + # http://www.w3.org/TR/SVG/implnote.html#ArcOutOfRangeParameters + rx = fabs(self.rx) + ry = fabs(self.ry) + if not (rx and ry): + return False + + # If the current point and target point for the arc are identical, it should + # be treated as a zero length path. This ensures continuity in animations. + if self.target_point == self.current_point: + return False + + mid_point_distance = (self.current_point - self.target_point) * 0.5 + + point_transform = Identity.rotate(-self.angle) + + transformed_mid_point = _map_point(point_transform, mid_point_distance) + square_rx = rx * rx + square_ry = ry * ry + square_x = transformed_mid_point.real * transformed_mid_point.real + square_y = transformed_mid_point.imag * transformed_mid_point.imag + + # Check if the radii are big enough to draw the arc, scale radii if not. + # http://www.w3.org/TR/SVG/implnote.html#ArcCorrectionOutOfRangeRadii + radii_scale = square_x / square_rx + square_y / square_ry + if radii_scale > 1: + rx *= sqrt(radii_scale) + ry *= sqrt(radii_scale) + self.rx, self.ry = rx, ry + + point_transform = Scale(1 / rx, 1 / ry).rotate(-self.angle) + + point1 = _map_point(point_transform, self.current_point) + point2 = _map_point(point_transform, self.target_point) + delta = point2 - point1 + + d = delta.real * delta.real + delta.imag * delta.imag + scale_factor_squared = max(1 / d - 0.25, 0.0) + + scale_factor = sqrt(scale_factor_squared) + if self.sweep == self.large: + scale_factor = -scale_factor + + delta *= scale_factor + center_point = (point1 + point2) * 0.5 + center_point += complex(-delta.imag, delta.real) + point1 -= center_point + point2 -= center_point + + theta1 = atan2(point1.imag, point1.real) + theta2 = atan2(point2.imag, point2.real) + + theta_arc = theta2 - theta1 + if theta_arc < 0 and self.sweep: + theta_arc += TWO_PI + elif theta_arc > 0 and not self.sweep: + theta_arc -= TWO_PI + + self.theta1 = theta1 + self.theta2 = theta1 + theta_arc + self.theta_arc = theta_arc + self.center_point = center_point + + return True + + def _decompose_to_cubic_curves(self): + if self.center_point is None and not self._parametrize(): + return + + point_transform = Identity.rotate(self.angle).scale(self.rx, self.ry) + + # Some results of atan2 on some platform implementations are not exact + # enough. So that we get more cubic curves than expected here. Adding 0.001f + # reduces the count of sgements to the correct count. + num_segments = int(ceil(fabs(self.theta_arc / (PI_OVER_TWO + 0.001)))) + for i in range(num_segments): + start_theta = self.theta1 + i * self.theta_arc / num_segments + end_theta = self.theta1 + (i + 1) * self.theta_arc / num_segments + + t = (4 / 3) * tan(0.25 * (end_theta - start_theta)) + if not isfinite(t): + return + + sin_start_theta = sin(start_theta) + cos_start_theta = cos(start_theta) + sin_end_theta = sin(end_theta) + cos_end_theta = cos(end_theta) + + point1 = complex( + cos_start_theta - t * sin_start_theta, + sin_start_theta + t * cos_start_theta, + ) + point1 += self.center_point + target_point = complex(cos_end_theta, sin_end_theta) + target_point += self.center_point + point2 = target_point + point2 += complex(t * sin_end_theta, -t * cos_end_theta) + + point1 = _map_point(point_transform, point1) + point2 = _map_point(point_transform, point2) + target_point = _map_point(point_transform, target_point) + + yield point1, point2, target_point + + def draw(self, pen): + for point1, point2, target_point in self._decompose_to_cubic_curves(): + pen.curveTo( + (point1.real, point1.imag), + (point2.real, point2.imag), + (target_point.real, target_point.imag), + ) diff --git a/shared/package-files/33/336c1b9dab51812fbc1c73515a4853342d8991c8ff8cf37a5b1f4c6a6ff88f64/soft_margin_loss_backward_native.h b/shared/package-files/33/336c1b9dab51812fbc1c73515a4853342d8991c8ff8cf37a5b1f4c6a6ff88f64/soft_margin_loss_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..91e13db8b1b8174c52376d5ee2d7a05739ba1aec --- /dev/null +++ b/shared/package-files/33/336c1b9dab51812fbc1c73515a4853342d8991c8ff8cf37a5b1f4c6a6ff88f64/soft_margin_loss_backward_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor soft_margin_loss_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction); +TORCH_API at::Tensor & soft_margin_loss_backward_out(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, at::Tensor & grad_input); +} // namespace native +} // namespace at diff --git a/shared/package-files/33/336ee1d67ea233bbbab3fbad5e543d1b4fb6a96d94d4d806a6df5e5648deb24f/test_news_blocks.m b/shared/package-files/33/336ee1d67ea233bbbab3fbad5e543d1b4fb6a96d94d4d806a6df5e5648deb24f/test_news_blocks.m new file mode 100644 index 0000000000000000000000000000000000000000..d7a4d33976301322d231cecfca9aa908a05c67b1 --- /dev/null +++ b/shared/package-files/33/336ee1d67ea233bbbab3fbad5e543d1b4fb6a96d94d4d806a6df5e5648deb24f/test_news_blocks.m @@ -0,0 +1,134 @@ +%%% Dynamic factor model (DFM) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% This script estimates a dynamic factor model (DFM) using a panel of +% monthly and quarterly series. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + +%% Clear workspace and set paths. +close all; clear; clc; +addpath('functions'); + + +%% User inputs. +vintage_old = '2016-06-29'; % vintage dataset to use for estimation +vintage_new = '2016-07-29'; % updated vintage dataset +country = 'US'; % United States macroeconomic data +sample_start = datenum('2000-01-01','yyyy-mm-dd'); % estimation sample + +series = 'GDPC1' ; % Nowcasting real GDP (GDPC1) +period = '2016q3'; % Forecasting target quarter + + +%% Load model specification and dataset. +Spec = load_spec('test_spec_blocks.xls'); +datafile_old = fullfile('data', country, [vintage_old '.xls']); +datafile_new = fullfile('data', country, [vintage_new '.xls']); +[X_old, ~] = load_data(datafile_old, Spec, sample_start); +[X_new, Time] = load_data(datafile_new, Spec, sample_start); + +% Basic settings +threshold = 1e-4; % Set to 1e-5 for more robust estimates +format long + +%% Test 1: p=1, k=1, max_iter=2 +Spec.p = 1; +Spec.k = 1; +max_iter = 2; + +% Run DFM model +Res = dfm(X_old, Spec, threshold, max_iter); + +% Update nowcast +Res = update_nowcast(X_old, X_new, Time, Spec, Res, series, period, ... + vintage_old, vintage_new); + + +% Store results +Res = rmfield(Res, {'X_sm', 'Z', 'Vsmooth', 'VVsmooth'}); +Res.news_table = Res.news_table{:,:}; + +k = Spec.k; +p = Spec.p; +kp = k * p; +p5 = max(5, Spec.p); +kp5 = k * p5; +Lambda = [Res.C(1:end, 1:k) ... + Res.C(1:end, kp5 + 1:kp5 + k) ... + Res.C(1:end, 2 * kp5 + 1:2 * kp5 + k)]'; +mask = logical(Spec.Blocks'); +Lambda = Lambda(mask)'; + +f_A1 = Res.A(1:k, 1:kp)'; +f_A2 = Res.A(kp5 + 1:kp5 + k, kp5 + 1:kp5 + kp)'; +f_A3 = Res.A(2 * kp5 + 1:2 * kp5 + k, 2 * kp5 + 1:2 * kp5 + kp)'; +f_A = [f_A1 f_A2 f_A3]; + +f_Q1 = Res.Q(1:k, 1:k); +f_Q2 = Res.Q(kp5 + 1:kp5 + k, kp5 + 1:kp5 + k); +f_Q3 = Res.Q(2 * kp5 + 1:2 * kp5 + k, 2 * kp5 + 1:2 * kp5 + k); +f_Q = [nonzeros(chol(f_Q1))' ... + nonzeros(chol(f_Q2))' ... + nonzeros(chol(f_Q3))']; + +Ad = diag(Res.A); +Qd = diag(Res.Q); + +idio = 3 * kp5 + 1; +params = [Lambda f_A f_Q ... + Ad(idio:idio+6)' Ad(idio+6+5) Qd(idio:idio+6)' Qd(idio+6+5)]'; + +save('test_news_blocks_112.mat','Res','Spec','params'); + +%% Test 2: p=2, k=2, max_iter=2 +Spec.p = 2; +Spec.k = 2; +max_iter = 2; + +% Run DFM model +Res = dfm(X_old, Spec, threshold, max_iter); + +% Update nowcast +Res = update_nowcast(X_old, X_new, Time, Spec, Res, series, period, ... + vintage_old, vintage_new); + + +% Store results +Res = rmfield(Res, {'X_sm', 'Z', 'Vsmooth', 'VVsmooth'}); +Res.news_table = Res.news_table{:,:}; + +k = Spec.k; +p = Spec.p; +kp = k * p; +p5 = max(5, Spec.p); +kp5 = k * p5; +Lambda1 = Res.C(1:end, 1:k); +mask1 = repmat(logical(Spec.Blocks(:, 1)), 1, 2); +Lambda2 = Res.C(1:end, kp5 + 1:kp5 + k); +mask2 = repmat(logical(Spec.Blocks(:, 2)), 1, 2); +Lambda3 = Res.C(1:end, 2 * kp5 + 1:2 * kp5 + k); +mask3 = repmat(logical(Spec.Blocks(:, 3)), 1, 2); +Lambda = [Lambda1 Lambda2 Lambda3]'; +mask = [mask1 mask2 mask3]'; +Lambda = Lambda(mask)'; + +f_A1 = Res.A(1:k, 1:kp)'; +f_A2 = Res.A(kp5 + 1:kp5 + k, kp5 + 1:kp5 + kp)'; +f_A3 = Res.A(2 * kp5 + 1:2 * kp5 + k, 2 * kp5 + 1:2 * kp5 + kp)'; +f_A = [f_A1 f_A2 f_A3]; +f_A = f_A(:)'; + +f_Q1 = Res.Q(1:k, 1:k); +f_Q2 = Res.Q(kp5 + 1:kp5 + k, kp5 + 1:kp5 + k); +f_Q3 = Res.Q(2 * kp5 + 1:2 * kp5 + k, 2 * kp5 + 1:2 * kp5 + k); +f_Q = [nonzeros(chol(f_Q1))' ... + nonzeros(chol(f_Q2))' ... + nonzeros(chol(f_Q3))']; + +Ad = diag(Res.A); +Qd = diag(Res.Q); + +idio = 3 * kp5 + 1; +params = [Lambda f_A f_Q ... + Ad(idio:idio+6)' Ad(idio+6+5) Qd(idio:idio+6)' Qd(idio+6+5)]'; + +save('test_news_blocks_222.mat','Res','Spec','params'); diff --git a/shared/package-files/33/336f2b6994f5aacca9689f32249db20a8dac36934314b7d5ba391d94169d63c6/test_window.py b/shared/package-files/33/336f2b6994f5aacca9689f32249db20a8dac36934314b7d5ba391d94169d63c6/test_window.py new file mode 100644 index 0000000000000000000000000000000000000000..5a2645b9cc27dcee4ceea7e8443dad8e9e0d80c7 --- /dev/null +++ b/shared/package-files/33/336f2b6994f5aacca9689f32249db20a8dac36934314b7d5ba391d94169d63c6/test_window.py @@ -0,0 +1,45 @@ +"Test window, coverage 47%." + +from idlelib import window +import unittest +from test.support import requires +from tkinter import Tk + + +class WindowListTest(unittest.TestCase): + + def test_init(self): + wl = window.WindowList() + self.assertEqual(wl.dict, {}) + self.assertEqual(wl.callbacks, []) + + # Further tests need mock Window. + + +class ListedToplevelTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + window.registry = set() + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + window.registry = window.WindowList() + cls.root.update_idletasks() +## for id in cls.root.tk.call('after', 'info'): +## cls.root.after_cancel(id) # Need for EditorWindow. + cls.root.destroy() + del cls.root + + def test_init(self): + + win = window.ListedToplevel(self.root) + self.assertIn(win, window.registry) + self.assertEqual(win.focused_widget, win) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/shared/package-files/33/336f57eb67367a4bc7d454efe7acb27b64cb717c9850233901e80041558b15cf/test_str_accessor.py b/shared/package-files/33/336f57eb67367a4bc7d454efe7acb27b64cb717c9850233901e80041558b15cf/test_str_accessor.py new file mode 100644 index 0000000000000000000000000000000000000000..09d965ef1f32268550bbf35a17f11529545054ed --- /dev/null +++ b/shared/package-files/33/336f57eb67367a4bc7d454efe7acb27b64cb717c9850233901e80041558b15cf/test_str_accessor.py @@ -0,0 +1,25 @@ +import pytest + +from pandas import Series +import pandas._testing as tm + + +class TestStrAccessor: + def test_str_attribute(self): + # GH#9068 + methods = ["strip", "rstrip", "lstrip"] + ser = Series([" jack", "jill ", " jesse ", "frank"]) + for method in methods: + expected = Series([getattr(str, method)(x) for x in ser.values]) + tm.assert_series_equal(getattr(Series.str, method)(ser.str), expected) + + # str accessor only valid with string values + ser = Series(range(5)) + with pytest.raises(AttributeError, match="only use .str accessor"): + ser.str.repeat(2) + + def test_str_accessor_updates_on_inplace(self): + ser = Series(list("abc")) + return_value = ser.drop([0], inplace=True) + assert return_value is None + assert len(ser.str.lower()) == 2 diff --git a/shared/package-files/33/336ff4bdb2fdf6ad2de98d262874fe4c9d051ce9d7adfcf45055714311c8a964/client.pyi b/shared/package-files/33/336ff4bdb2fdf6ad2de98d262874fe4c9d051ce9d7adfcf45055714311c8a964/client.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6fdf5cea80946591d2e3c40b31285f3191cacac2 --- /dev/null +++ b/shared/package-files/33/336ff4bdb2fdf6ad2de98d262874fe4c9d051ce9d7adfcf45055714311c8a964/client.pyi @@ -0,0 +1,9 @@ +from typing import Any + +from django.db.backends.base.base import BaseDatabaseWrapper + +class BaseDatabaseClient: + executable_name: Any = ... + connection: Any = ... + def __init__(self, connection: BaseDatabaseWrapper) -> None: ... + def runshell(self) -> None: ... diff --git a/shared/package-files/33/33708544410c5b5fc7d1a25d1700804719deb4e4cb57358d4d9d2e7328418bcb/expat-config.cmake b/shared/package-files/33/33708544410c5b5fc7d1a25d1700804719deb4e4cb57358d4d9d2e7328418bcb/expat-config.cmake new file mode 100644 index 0000000000000000000000000000000000000000..36a013198b665a6b72e2016253093a1e36b33aca --- /dev/null +++ b/shared/package-files/33/33708544410c5b5fc7d1a25d1700804719deb4e4cb57358d4d9d2e7328418bcb/expat-config.cmake @@ -0,0 +1,99 @@ +# __ __ _ +# ___\ \/ /_ __ __ _| |_ +# / _ \\ /| '_ \ / _` | __| +# | __// \| |_) | (_| | |_ +# \___/_/\_\ .__/ \__,_|\__| +# |_| XML parser +# +# Copyright (c) 2019 Expat development team +# Licensed under the MIT license: +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to permit +# persons to whom the Software is furnished to do so, subject to the +# following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +# USE OR OTHER DEALINGS IN THE SOFTWARE. +# +if(NOT _expat_config_included) + # Protect against multiple inclusion + set(_expat_config_included TRUE) + + +include("${CMAKE_CURRENT_LIST_DIR}/expat.cmake") + + +####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() ####### +####### Any changes to this file will be overwritten by the next CMake run #### +####### The input file was expat-config.cmake.in ######## + +get_filename_component(PACKAGE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/../../../" ABSOLUTE) + +macro(set_and_check _var _file) + set(${_var} "${_file}") + if(NOT EXISTS "${_file}") + message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist !") + endif() +endmacro() + +macro(check_required_components _NAME) + foreach(comp ${${_NAME}_FIND_COMPONENTS}) + if(NOT ${_NAME}_${comp}_FOUND) + if(${_NAME}_FIND_REQUIRED_${comp}) + set(${_NAME}_FOUND FALSE) + endif() + endif() + endforeach() +endmacro() + +#################################################################################### + +# +# Supported components +# +macro(expat_register_component _NAME _AVAILABE) + set(expat_${_NAME}_FOUND ${_AVAILABE}) +endmacro() + +expat_register_component(attr_info OFF) +expat_register_component(dtd ON) +expat_register_component(large_size OFF) +expat_register_component(min_size OFF) +expat_register_component(ns ON) + +if(1024) + expat_register_component(context_bytes ON) +else() + expat_register_component(context_bytes OFF) +endif() + +if("char" STREQUAL "char") + expat_register_component(char ON) + expat_register_component(ushort OFF) + expat_register_component(wchar_t OFF) +elseif("char" STREQUAL "ushort") + expat_register_component(char OFF) + expat_register_component(ushort ON) + expat_register_component(wchar_t OFF) +elseif("char" STREQUAL "wchar_t") + expat_register_component(char OFF) + expat_register_component(ushort OFF) + expat_register_component(wchar_t ON) +endif() + +check_required_components(expat) + + +endif(NOT _expat_config_included) diff --git a/shared/package-files/33/33740ab29ef943b1f55f769e13ff59a90962f5a12434209072d650e6c10abb4d/Apia b/shared/package-files/33/33740ab29ef943b1f55f769e13ff59a90962f5a12434209072d650e6c10abb4d/Apia new file mode 100644 index 0000000000000000000000000000000000000000..e592a68e53f6215de9e1d1ac61ce062a333283c0 Binary files /dev/null and b/shared/package-files/33/33740ab29ef943b1f55f769e13ff59a90962f5a12434209072d650e6c10abb4d/Apia differ diff --git a/shared/package-files/33/3374bcd808d94c88ae043c7e01464d7d33a1ad52204fab443c43d10765d8e604/test_typeconv.py b/shared/package-files/33/3374bcd808d94c88ae043c7e01464d7d33a1ad52204fab443c43d10765d8e604/test_typeconv.py new file mode 100644 index 0000000000000000000000000000000000000000..4042542b65b8e210f83134ee46959c650715a0da --- /dev/null +++ b/shared/package-files/33/3374bcd808d94c88ae043c7e01464d7d33a1ad52204fab443c43d10765d8e604/test_typeconv.py @@ -0,0 +1,295 @@ +import itertools + +from numba.core import types +from numba.core.typeconv.typeconv import TypeManager, TypeCastingRules +from numba.core.typeconv import rules +from numba.core.typeconv import castgraph, Conversion +import unittest + + +class CompatibilityTestMixin(unittest.TestCase): + + def check_number_compatibility(self, check_compatible): + b = types.boolean + i8 = types.int8 + i16 = types.int16 + i32 = types.int32 + i64 = types.int64 + u8 = types.uint8 + u16 = types.uint16 + u32 = types.uint32 + u64 = types.uint64 + f16 = types.float16 + f32 = types.float32 + f64 = types.float64 + c64 = types.complex64 + c128 = types.complex128 + + self.assertEqual(check_compatible(i32, i32), Conversion.exact) + + self.assertEqual(check_compatible(b, i8), Conversion.safe) + self.assertEqual(check_compatible(b, u8), Conversion.safe) + self.assertEqual(check_compatible(i8, b), Conversion.unsafe) + self.assertEqual(check_compatible(u8, b), Conversion.unsafe) + + self.assertEqual(check_compatible(i32, i64), Conversion.promote) + self.assertEqual(check_compatible(i32, u32), Conversion.unsafe) + self.assertEqual(check_compatible(u32, i32), Conversion.unsafe) + self.assertEqual(check_compatible(u32, i64), Conversion.safe) + + self.assertEqual(check_compatible(i16, f16), Conversion.unsafe) + self.assertEqual(check_compatible(i32, f32), Conversion.unsafe) + self.assertEqual(check_compatible(u32, f32), Conversion.unsafe) + self.assertEqual(check_compatible(i32, f64), Conversion.safe) + self.assertEqual(check_compatible(u32, f64), Conversion.safe) + # Note this is inconsistent with i32 -> f32... + self.assertEqual(check_compatible(i64, f64), Conversion.safe) + self.assertEqual(check_compatible(u64, f64), Conversion.safe) + + self.assertEqual(check_compatible(f32, c64), Conversion.safe) + self.assertEqual(check_compatible(f64, c128), Conversion.safe) + self.assertEqual(check_compatible(f64, c64), Conversion.unsafe) + + # Propagated compatibility relationships + self.assertEqual(check_compatible(i16, f64), Conversion.safe) + self.assertEqual(check_compatible(i16, i64), Conversion.promote) + self.assertEqual(check_compatible(i32, c64), Conversion.unsafe) + self.assertEqual(check_compatible(i32, c128), Conversion.safe) + self.assertEqual(check_compatible(i32, u64), Conversion.unsafe) + + for ta, tb in itertools.product(types.number_domain, + types.number_domain): + if ta in types.complex_domain and tb not in types.complex_domain: + continue + self.assertTrue(check_compatible(ta, tb) is not None, + msg="No cast from %s to %s" % (ta, tb)) + + +class TestTypeConv(CompatibilityTestMixin, unittest.TestCase): + + def test_typeconv(self): + tm = TypeManager() + + i32 = types.int32 + i64 = types.int64 + f32 = types.float32 + + tm.set_promote(i32, i64) + tm.set_unsafe_convert(i32, f32) + + sig = (i32, f32) + ovs = [ + (i32, i32), + (f32, f32), + (i64, i64), + ] + + # allow_unsafe = True => a conversion from i32 to f32 is chosen + sel = tm.select_overload(sig, ovs, True, False) + self.assertEqual(sel, 1) + # allow_unsafe = False => no overload available + with self.assertRaises(TypeError): + sel = tm.select_overload(sig, ovs, False, False) + + def test_default_rules(self): + tm = rules.default_type_manager + self.check_number_compatibility(tm.check_compatible) + + def test_overload1(self): + tm = rules.default_type_manager + + i32 = types.int32 + i64 = types.int64 + + sig = (i64, i32, i32) + ovs = [ + (i32, i32, i32), + (i64, i64, i64), + ] + # The first overload is unsafe, the second is safe => the second + # is always chosen, regardless of allow_unsafe. + self.assertEqual(tm.select_overload(sig, ovs, True, False), 1) + self.assertEqual(tm.select_overload(sig, ovs, False, False), 1) + + def test_overload2(self): + tm = rules.default_type_manager + + i16 = types.int16 + i32 = types.int32 + i64 = types.int64 + + sig = (i32, i16, i32) + ovs = [ + # Three promotes + (i64, i64, i64), + # One promotes, two exact types + (i32, i32, i32), + # Two unsafe converts, one exact type + (i16, i16, i16), + ] + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=False, + exact_match_required=False), 1) + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=True, + exact_match_required=False), 1) + + # The same in reverse order + ovs.reverse() + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=False, + exact_match_required=False), 1) + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=True, + exact_match_required=False), 1) + + def test_overload3(self): + # Promotes should be preferred over safe converts + tm = rules.default_type_manager + + i32 = types.int32 + i64 = types.int64 + f64 = types.float64 + + sig = (i32, i32) + ovs = [ + # Two promotes + (i64, i64), + # Two safe converts + (f64, f64), + ] + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=False, + exact_match_required=False), 0) + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=True, + exact_match_required=False), 0) + + # The same in reverse order + ovs.reverse() + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=False, + exact_match_required=False), 1) + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=True, + exact_match_required=False), 1) + + def test_overload4(self): + tm = rules.default_type_manager + + i16 = types.int16 + i32 = types.int32 + i64 = types.int64 + f16 = types.float16 + f32 = types.float32 + + sig = (i16, f16, f16) + ovs = [ + # One unsafe, one promote, one exact + (f16, f32, f16), + # Two unsafe, one exact types + (f32, i32, f16), + ] + + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=True, + exact_match_required=False), 0) + + def test_type_casting_rules(self): + tm = TypeManager() + tcr = TypeCastingRules(tm) + + i16 = types.int16 + i32 = types.int32 + i64 = types.int64 + f64 = types.float64 + f32 = types.float32 + f16 = types.float16 + made_up = types.Dummy("made_up") + + tcr.promote_unsafe(i32, i64) + tcr.safe_unsafe(i32, f64) + tcr.promote_unsafe(f32, f64) + tcr.promote_unsafe(f16, f32) + tcr.unsafe_unsafe(i16, f16) + + def base_test(): + # As declared + self.assertEqual(tm.check_compatible(i32, i64), Conversion.promote) + self.assertEqual(tm.check_compatible(i32, f64), Conversion.safe) + self.assertEqual(tm.check_compatible(f16, f32), Conversion.promote) + self.assertEqual(tm.check_compatible(f32, f64), Conversion.promote) + self.assertEqual(tm.check_compatible(i64, i32), Conversion.unsafe) + self.assertEqual(tm.check_compatible(f64, i32), Conversion.unsafe) + self.assertEqual(tm.check_compatible(f64, f32), Conversion.unsafe) + + # Propagated + self.assertEqual(tm.check_compatible(i64, f64), Conversion.unsafe) + self.assertEqual(tm.check_compatible(f64, i64), Conversion.unsafe) + self.assertEqual(tm.check_compatible(i64, f32), Conversion.unsafe) + self.assertEqual(tm.check_compatible(i32, f32), Conversion.unsafe) + self.assertEqual(tm.check_compatible(f32, i32), Conversion.unsafe) + self.assertEqual(tm.check_compatible(i16, f16), Conversion.unsafe) + self.assertEqual(tm.check_compatible(f16, i16), Conversion.unsafe) + + # Test base graph + base_test() + + self.assertIsNone(tm.check_compatible(i64, made_up)) + self.assertIsNone(tm.check_compatible(i32, made_up)) + self.assertIsNone(tm.check_compatible(f32, made_up)) + self.assertIsNone(tm.check_compatible(made_up, f64)) + self.assertIsNone(tm.check_compatible(made_up, i64)) + + # Add new test + tcr.promote(f64, made_up) + tcr.unsafe(made_up, i32) + + # Ensure the graph did not change by adding the new type + base_test() + + # To "made up" type + self.assertEqual(tm.check_compatible(i64, made_up), Conversion.unsafe) + self.assertEqual(tm.check_compatible(i32, made_up), Conversion.safe) + self.assertEqual(tm.check_compatible(f32, made_up), Conversion.promote) + self.assertEqual(tm.check_compatible(made_up, f64), Conversion.unsafe) + self.assertEqual(tm.check_compatible(made_up, i64), Conversion.unsafe) + + def test_castgraph_propagate(self): + saved = [] + + def callback(src, dst, rel): + saved.append((src, dst, rel)) + + tg = castgraph.TypeGraph(callback) + + i32 = types.int32 + i64 = types.int64 + f64 = types.float64 + f32 = types.float32 + + tg.insert_rule(i32, i64, Conversion.promote) + tg.insert_rule(i64, i32, Conversion.unsafe) + + saved.append(None) + + tg.insert_rule(i32, f64, Conversion.safe) + tg.insert_rule(f64, i32, Conversion.unsafe) + + saved.append(None) + + tg.insert_rule(f32, f64, Conversion.promote) + tg.insert_rule(f64, f32, Conversion.unsafe) + + self.assertIn((i32, i64, Conversion.promote), saved[0:2]) + self.assertIn((i64, i32, Conversion.unsafe), saved[0:2]) + self.assertIs(saved[2], None) + + self.assertIn((i32, f64, Conversion.safe), saved[3:7]) + self.assertIn((f64, i32, Conversion.unsafe), saved[3:7]) + self.assertIn((i64, f64, Conversion.unsafe), saved[3:7]) + self.assertIn((i64, f64, Conversion.unsafe), saved[3:7]) + self.assertIs(saved[7], None) + + self.assertIn((f32, f64, Conversion.promote), saved[8:14]) + self.assertIn((f64, f32, Conversion.unsafe), saved[8:14]) + self.assertIn((f32, i32, Conversion.unsafe), saved[8:14]) + self.assertIn((i32, f32, Conversion.unsafe), saved[8:14]) + self.assertIn((f32, i64, Conversion.unsafe), saved[8:14]) + self.assertIn((i64, f32, Conversion.unsafe), saved[8:14]) + self.assertEqual(len(saved[14:]), 0) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/33/3374c4cc80d5ea5e82a4ca4f65c015acef98fe961b4510ac6ee3cc180690117b/textplot.py b/shared/package-files/33/3374c4cc80d5ea5e82a4ca4f65c015acef98fe961b4510ac6ee3cc180690117b/textplot.py new file mode 100644 index 0000000000000000000000000000000000000000..cdd2bb42cd9ce2bc25c4d0df395f30e1740afdaa --- /dev/null +++ b/shared/package-files/33/3374c4cc80d5ea5e82a4ca4f65c015acef98fe961b4510ac6ee3cc180690117b/textplot.py @@ -0,0 +1,162 @@ +from sympy.core.numbers import Float +from sympy.core.symbol import Dummy +from sympy.utilities.lambdify import lambdify + +import math + + +def is_valid(x): + """Check if a floating point number is valid""" + if x is None: + return False + if isinstance(x, complex): + return False + return not math.isinf(x) and not math.isnan(x) + + +def rescale(y, W, H, mi, ma): + """Rescale the given array `y` to fit into the integer values + between `0` and `H-1` for the values between ``mi`` and ``ma``. + """ + y_new = [] + + norm = ma - mi + offset = (ma + mi) / 2 + + for x in range(W): + if is_valid(y[x]): + normalized = (y[x] - offset) / norm + if not is_valid(normalized): + y_new.append(None) + else: + rescaled = Float((normalized*H + H/2) * (H-1)/H).round() + rescaled = int(rescaled) + y_new.append(rescaled) + else: + y_new.append(None) + return y_new + + +def linspace(start, stop, num): + return [start + (stop - start) * x / (num-1) for x in range(num)] + + +def textplot_str(expr, a, b, W=55, H=21): + """Generator for the lines of the plot""" + free = expr.free_symbols + if len(free) > 1: + raise ValueError( + "The expression must have a single variable. (Got {})" + .format(free)) + x = free.pop() if free else Dummy() + f = lambdify([x], expr) + a = float(a) + b = float(b) + + # Calculate function values + x = linspace(a, b, W) + y = [] + for val in x: + try: + y.append(f(val)) + # Not sure what exceptions to catch here or why... + except (ValueError, TypeError, ZeroDivisionError): + y.append(None) + + # Normalize height to screen space + y_valid = list(filter(is_valid, y)) + if y_valid: + ma = max(y_valid) + mi = min(y_valid) + if ma == mi: + if ma: + mi, ma = sorted([0, 2*ma]) + else: + mi, ma = -1, 1 + else: + mi, ma = -1, 1 + y_range = ma - mi + precision = math.floor(math.log(y_range, 10)) - 1 + precision *= -1 + mi = round(mi, precision) + ma = round(ma, precision) + y = rescale(y, W, H, mi, ma) + + y_bins = linspace(mi, ma, H) + + # Draw plot + margin = 7 + for h in range(H - 1, -1, -1): + s = [' '] * W + for i in range(W): + if y[i] == h: + if (i == 0 or y[i - 1] == h - 1) and (i == W - 1 or y[i + 1] == h + 1): + s[i] = '/' + elif (i == 0 or y[i - 1] == h + 1) and (i == W - 1 or y[i + 1] == h - 1): + s[i] = '\\' + else: + s[i] = '.' + + if h == 0: + for i in range(W): + s[i] = '_' + + # Print y values + if h in (0, H//2, H - 1): + prefix = ("%g" % y_bins[h]).rjust(margin)[:margin] + else: + prefix = " "*margin + s = "".join(s) + if h == H//2: + s = s.replace(" ", "-") + yield prefix + " |" + s + + # Print x values + bottom = " " * (margin + 2) + bottom += ("%g" % x[0]).ljust(W//2) + if W % 2 == 1: + bottom += ("%g" % x[W//2]).ljust(W//2) + else: + bottom += ("%g" % x[W//2]).ljust(W//2-1) + bottom += "%g" % x[-1] + yield bottom + + +def textplot(expr, a, b, W=55, H=21): + r""" + Print a crude ASCII art plot of the SymPy expression 'expr' (which + should contain a single symbol, e.g. x or something else) over the + interval [a, b]. + + Examples + ======== + + >>> from sympy import Symbol, sin + >>> from sympy.plotting import textplot + >>> t = Symbol('t') + >>> textplot(sin(t)*t, 0, 15) + 14 | ... + | . + | . + | . + | . + | ... + | / . . + | / + | / . + | . . . + 1.5 |----.......-------------------------------------------- + |.... \ . . + | \ / . + | .. / . + | \ / . + | .... + | . + | . . + | + | . . + -11 |_______________________________________________________ + 0 7.5 15 + """ + for line in textplot_str(expr, a, b, W, H): + print(line) diff --git a/shared/package-files/33/33755418e0e1dcc2c495e3e362d8edf5bd3645e313870f975e9b904e4a2180db/pythonrational.py b/shared/package-files/33/33755418e0e1dcc2c495e3e362d8edf5bd3645e313870f975e9b904e4a2180db/pythonrational.py new file mode 100644 index 0000000000000000000000000000000000000000..87b56d6c929c3ce3ce153dce7b3c210821d706a0 --- /dev/null +++ b/shared/package-files/33/33755418e0e1dcc2c495e3e362d8edf5bd3645e313870f975e9b904e4a2180db/pythonrational.py @@ -0,0 +1,22 @@ +""" +Rational number type based on Python integers. + +The PythonRational class from here has been moved to +sympy.external.pythonmpq + +This module is just left here for backwards compatibility. +""" + + +from sympy.core.numbers import Rational +from sympy.core.sympify import _sympy_converter +from sympy.utilities import public +from sympy.external.pythonmpq import PythonMPQ + + +PythonRational = public(PythonMPQ) + + +def sympify_pythonrational(arg): + return Rational(arg.numerator, arg.denominator) +_sympy_converter[PythonRational] = sympify_pythonrational diff --git a/shared/package-files/33/3375f341b7638b593cfe1ca0b7cf29ae2c04309a962918b142c378a832e67de5/message.pyi b/shared/package-files/33/3375f341b7638b593cfe1ca0b7cf29ae2c04309a962918b142c378a832e67de5/message.pyi new file mode 100644 index 0000000000000000000000000000000000000000..642bba7c0102009ece4aa569b85608a10c326b3e --- /dev/null +++ b/shared/package-files/33/3375f341b7638b593cfe1ca0b7cf29ae2c04309a962918b142c378a832e67de5/message.pyi @@ -0,0 +1,45 @@ +from typing import Any, Generator + +class Message: + preamble = ... + epilogue = ... + defects = ... + def __init__(self): ... + def as_string(self, unixfrom=...): ... + def is_multipart(self) -> bool: ... + def set_unixfrom(self, unixfrom) -> None: ... + def get_unixfrom(self): ... + def attach(self, payload) -> None: ... + def get_payload(self, i=..., decode: bool = ...): ... + def set_payload(self, payload, charset=...) -> None: ... + def set_charset(self, charset): ... + def get_charset(self): ... + def __len__(self): ... + def __getitem__(self, name): ... + def __setitem__(self, name, val) -> None: ... + def __delitem__(self, name) -> None: ... + def __contains__(self, name): ... + def has_key(self, name) -> bool: ... + def keys(self): ... + def values(self): ... + def items(self): ... + def get(self, name, failobj=...): ... + def get_all(self, name, failobj=...): ... + def add_header(self, _name, _value, **_params) -> None: ... + def replace_header(self, _name, _value) -> None: ... + def get_content_type(self): ... + def get_content_maintype(self): ... + def get_content_subtype(self): ... + def get_default_type(self): ... + def set_default_type(self, ctype) -> None: ... + def get_params(self, failobj=..., header=..., unquote: bool = ...): ... + def get_param(self, param, failobj=..., header=..., unquote: bool = ...): ... + def set_param(self, param, value, header=..., requote: bool = ..., charset=..., language=...) -> None: ... + def del_param(self, param, header=..., requote: bool = ...): ... + def set_type(self, type, header=..., requote: bool = ...): ... + def get_filename(self, failobj=...): ... + def get_boundary(self, failobj=...): ... + def set_boundary(self, boundary) -> None: ... + def get_content_charset(self, failobj=...): ... + def get_charsets(self, failobj=...): ... + def walk(self) -> Generator[Any, Any, Any]: ... diff --git a/shared/package-files/33/3379d78b244aa905ffe1171a968caaf41b9a0154d1ddc76c05a2abaca2b289fd/cp1140.py b/shared/package-files/33/3379d78b244aa905ffe1171a968caaf41b9a0154d1ddc76c05a2abaca2b289fd/cp1140.py new file mode 100644 index 0000000000000000000000000000000000000000..0a919d837e1d4e80380f0e7bc1b91d537b5eec8d --- /dev/null +++ b/shared/package-files/33/3379d78b244aa905ffe1171a968caaf41b9a0154d1ddc76c05a2abaca2b289fd/cp1140.py @@ -0,0 +1,307 @@ +""" Python Character Mapping Codec cp1140 generated from 'python-mappings/CP1140.TXT' with gencodec.py. + +"""#" + +import codecs + +### Codec APIs + +class Codec(codecs.Codec): + + def encode(self,input,errors='strict'): + return codecs.charmap_encode(input,errors,encoding_table) + + def decode(self,input,errors='strict'): + return codecs.charmap_decode(input,errors,decoding_table) + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input, final=False): + return codecs.charmap_encode(input,self.errors,encoding_table)[0] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input, final=False): + return codecs.charmap_decode(input,self.errors,decoding_table)[0] + +class StreamWriter(Codec,codecs.StreamWriter): + pass + +class StreamReader(Codec,codecs.StreamReader): + pass + +### encodings module API + +def getregentry(): + return codecs.CodecInfo( + name='cp1140', + encode=Codec().encode, + decode=Codec().decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamreader=StreamReader, + streamwriter=StreamWriter, + ) + + +### Decoding Table + +decoding_table = ( + '\x00' # 0x00 -> NULL + '\x01' # 0x01 -> START OF HEADING + '\x02' # 0x02 -> START OF TEXT + '\x03' # 0x03 -> END OF TEXT + '\x9c' # 0x04 -> CONTROL + '\t' # 0x05 -> HORIZONTAL TABULATION + '\x86' # 0x06 -> CONTROL + '\x7f' # 0x07 -> DELETE + '\x97' # 0x08 -> CONTROL + '\x8d' # 0x09 -> CONTROL + '\x8e' # 0x0A -> CONTROL + '\x0b' # 0x0B -> VERTICAL TABULATION + '\x0c' # 0x0C -> FORM FEED + '\r' # 0x0D -> CARRIAGE RETURN + '\x0e' # 0x0E -> SHIFT OUT + '\x0f' # 0x0F -> SHIFT IN + '\x10' # 0x10 -> DATA LINK ESCAPE + '\x11' # 0x11 -> DEVICE CONTROL ONE + '\x12' # 0x12 -> DEVICE CONTROL TWO + '\x13' # 0x13 -> DEVICE CONTROL THREE + '\x9d' # 0x14 -> CONTROL + '\x85' # 0x15 -> CONTROL + '\x08' # 0x16 -> BACKSPACE + '\x87' # 0x17 -> CONTROL + '\x18' # 0x18 -> CANCEL + '\x19' # 0x19 -> END OF MEDIUM + '\x92' # 0x1A -> CONTROL + '\x8f' # 0x1B -> CONTROL + '\x1c' # 0x1C -> FILE SEPARATOR + '\x1d' # 0x1D -> GROUP SEPARATOR + '\x1e' # 0x1E -> RECORD SEPARATOR + '\x1f' # 0x1F -> UNIT SEPARATOR + '\x80' # 0x20 -> CONTROL + '\x81' # 0x21 -> CONTROL + '\x82' # 0x22 -> CONTROL + '\x83' # 0x23 -> CONTROL + '\x84' # 0x24 -> CONTROL + '\n' # 0x25 -> LINE FEED + '\x17' # 0x26 -> END OF TRANSMISSION BLOCK + '\x1b' # 0x27 -> ESCAPE + '\x88' # 0x28 -> CONTROL + '\x89' # 0x29 -> CONTROL + '\x8a' # 0x2A -> CONTROL + '\x8b' # 0x2B -> CONTROL + '\x8c' # 0x2C -> CONTROL + '\x05' # 0x2D -> ENQUIRY + '\x06' # 0x2E -> ACKNOWLEDGE + '\x07' # 0x2F -> BELL + '\x90' # 0x30 -> CONTROL + '\x91' # 0x31 -> CONTROL + '\x16' # 0x32 -> SYNCHRONOUS IDLE + '\x93' # 0x33 -> CONTROL + '\x94' # 0x34 -> CONTROL + '\x95' # 0x35 -> CONTROL + '\x96' # 0x36 -> CONTROL + '\x04' # 0x37 -> END OF TRANSMISSION + '\x98' # 0x38 -> CONTROL + '\x99' # 0x39 -> CONTROL + '\x9a' # 0x3A -> CONTROL + '\x9b' # 0x3B -> CONTROL + '\x14' # 0x3C -> DEVICE CONTROL FOUR + '\x15' # 0x3D -> NEGATIVE ACKNOWLEDGE + '\x9e' # 0x3E -> CONTROL + '\x1a' # 0x3F -> SUBSTITUTE + ' ' # 0x40 -> SPACE + '\xa0' # 0x41 -> NO-BREAK SPACE + '\xe2' # 0x42 -> LATIN SMALL LETTER A WITH CIRCUMFLEX + '\xe4' # 0x43 -> LATIN SMALL LETTER A WITH DIAERESIS + '\xe0' # 0x44 -> LATIN SMALL LETTER A WITH GRAVE + '\xe1' # 0x45 -> LATIN SMALL LETTER A WITH ACUTE + '\xe3' # 0x46 -> LATIN SMALL LETTER A WITH TILDE + '\xe5' # 0x47 -> LATIN SMALL LETTER A WITH RING ABOVE + '\xe7' # 0x48 -> LATIN SMALL LETTER C WITH CEDILLA + '\xf1' # 0x49 -> LATIN SMALL LETTER N WITH TILDE + '\xa2' # 0x4A -> CENT SIGN + '.' # 0x4B -> FULL STOP + '<' # 0x4C -> LESS-THAN SIGN + '(' # 0x4D -> LEFT PARENTHESIS + '+' # 0x4E -> PLUS SIGN + '|' # 0x4F -> VERTICAL LINE + '&' # 0x50 -> AMPERSAND + '\xe9' # 0x51 -> LATIN SMALL LETTER E WITH ACUTE + '\xea' # 0x52 -> LATIN SMALL LETTER E WITH CIRCUMFLEX + '\xeb' # 0x53 -> LATIN SMALL LETTER E WITH DIAERESIS + '\xe8' # 0x54 -> LATIN SMALL LETTER E WITH GRAVE + '\xed' # 0x55 -> LATIN SMALL LETTER I WITH ACUTE + '\xee' # 0x56 -> LATIN SMALL LETTER I WITH CIRCUMFLEX + '\xef' # 0x57 -> LATIN SMALL LETTER I WITH DIAERESIS + '\xec' # 0x58 -> LATIN SMALL LETTER I WITH GRAVE + '\xdf' # 0x59 -> LATIN SMALL LETTER SHARP S (GERMAN) + '!' # 0x5A -> EXCLAMATION MARK + '$' # 0x5B -> DOLLAR SIGN + '*' # 0x5C -> ASTERISK + ')' # 0x5D -> RIGHT PARENTHESIS + ';' # 0x5E -> SEMICOLON + '\xac' # 0x5F -> NOT SIGN + '-' # 0x60 -> HYPHEN-MINUS + '/' # 0x61 -> SOLIDUS + '\xc2' # 0x62 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX + '\xc4' # 0x63 -> LATIN CAPITAL LETTER A WITH DIAERESIS + '\xc0' # 0x64 -> LATIN CAPITAL LETTER A WITH GRAVE + '\xc1' # 0x65 -> LATIN CAPITAL LETTER A WITH ACUTE + '\xc3' # 0x66 -> LATIN CAPITAL LETTER A WITH TILDE + '\xc5' # 0x67 -> LATIN CAPITAL LETTER A WITH RING ABOVE + '\xc7' # 0x68 -> LATIN CAPITAL LETTER C WITH CEDILLA + '\xd1' # 0x69 -> LATIN CAPITAL LETTER N WITH TILDE + '\xa6' # 0x6A -> BROKEN BAR + ',' # 0x6B -> COMMA + '%' # 0x6C -> PERCENT SIGN + '_' # 0x6D -> LOW LINE + '>' # 0x6E -> GREATER-THAN SIGN + '?' # 0x6F -> QUESTION MARK + '\xf8' # 0x70 -> LATIN SMALL LETTER O WITH STROKE + '\xc9' # 0x71 -> LATIN CAPITAL LETTER E WITH ACUTE + '\xca' # 0x72 -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX + '\xcb' # 0x73 -> LATIN CAPITAL LETTER E WITH DIAERESIS + '\xc8' # 0x74 -> LATIN CAPITAL LETTER E WITH GRAVE + '\xcd' # 0x75 -> LATIN CAPITAL LETTER I WITH ACUTE + '\xce' # 0x76 -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX + '\xcf' # 0x77 -> LATIN CAPITAL LETTER I WITH DIAERESIS + '\xcc' # 0x78 -> LATIN CAPITAL LETTER I WITH GRAVE + '`' # 0x79 -> GRAVE ACCENT + ':' # 0x7A -> COLON + '#' # 0x7B -> NUMBER SIGN + '@' # 0x7C -> COMMERCIAL AT + "'" # 0x7D -> APOSTROPHE + '=' # 0x7E -> EQUALS SIGN + '"' # 0x7F -> QUOTATION MARK + '\xd8' # 0x80 -> LATIN CAPITAL LETTER O WITH STROKE + 'a' # 0x81 -> LATIN SMALL LETTER A + 'b' # 0x82 -> LATIN SMALL LETTER B + 'c' # 0x83 -> LATIN SMALL LETTER C + 'd' # 0x84 -> LATIN SMALL LETTER D + 'e' # 0x85 -> LATIN SMALL LETTER E + 'f' # 0x86 -> LATIN SMALL LETTER F + 'g' # 0x87 -> LATIN SMALL LETTER G + 'h' # 0x88 -> LATIN SMALL LETTER H + 'i' # 0x89 -> LATIN SMALL LETTER I + '\xab' # 0x8A -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + '\xbb' # 0x8B -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + '\xf0' # 0x8C -> LATIN SMALL LETTER ETH (ICELANDIC) + '\xfd' # 0x8D -> LATIN SMALL LETTER Y WITH ACUTE + '\xfe' # 0x8E -> LATIN SMALL LETTER THORN (ICELANDIC) + '\xb1' # 0x8F -> PLUS-MINUS SIGN + '\xb0' # 0x90 -> DEGREE SIGN + 'j' # 0x91 -> LATIN SMALL LETTER J + 'k' # 0x92 -> LATIN SMALL LETTER K + 'l' # 0x93 -> LATIN SMALL LETTER L + 'm' # 0x94 -> LATIN SMALL LETTER M + 'n' # 0x95 -> LATIN SMALL LETTER N + 'o' # 0x96 -> LATIN SMALL LETTER O + 'p' # 0x97 -> LATIN SMALL LETTER P + 'q' # 0x98 -> LATIN SMALL LETTER Q + 'r' # 0x99 -> LATIN SMALL LETTER R + '\xaa' # 0x9A -> FEMININE ORDINAL INDICATOR + '\xba' # 0x9B -> MASCULINE ORDINAL INDICATOR + '\xe6' # 0x9C -> LATIN SMALL LIGATURE AE + '\xb8' # 0x9D -> CEDILLA + '\xc6' # 0x9E -> LATIN CAPITAL LIGATURE AE + '\u20ac' # 0x9F -> EURO SIGN + '\xb5' # 0xA0 -> MICRO SIGN + '~' # 0xA1 -> TILDE + 's' # 0xA2 -> LATIN SMALL LETTER S + 't' # 0xA3 -> LATIN SMALL LETTER T + 'u' # 0xA4 -> LATIN SMALL LETTER U + 'v' # 0xA5 -> LATIN SMALL LETTER V + 'w' # 0xA6 -> LATIN SMALL LETTER W + 'x' # 0xA7 -> LATIN SMALL LETTER X + 'y' # 0xA8 -> LATIN SMALL LETTER Y + 'z' # 0xA9 -> LATIN SMALL LETTER Z + '\xa1' # 0xAA -> INVERTED EXCLAMATION MARK + '\xbf' # 0xAB -> INVERTED QUESTION MARK + '\xd0' # 0xAC -> LATIN CAPITAL LETTER ETH (ICELANDIC) + '\xdd' # 0xAD -> LATIN CAPITAL LETTER Y WITH ACUTE + '\xde' # 0xAE -> LATIN CAPITAL LETTER THORN (ICELANDIC) + '\xae' # 0xAF -> REGISTERED SIGN + '^' # 0xB0 -> CIRCUMFLEX ACCENT + '\xa3' # 0xB1 -> POUND SIGN + '\xa5' # 0xB2 -> YEN SIGN + '\xb7' # 0xB3 -> MIDDLE DOT + '\xa9' # 0xB4 -> COPYRIGHT SIGN + '\xa7' # 0xB5 -> SECTION SIGN + '\xb6' # 0xB6 -> PILCROW SIGN + '\xbc' # 0xB7 -> VULGAR FRACTION ONE QUARTER + '\xbd' # 0xB8 -> VULGAR FRACTION ONE HALF + '\xbe' # 0xB9 -> VULGAR FRACTION THREE QUARTERS + '[' # 0xBA -> LEFT SQUARE BRACKET + ']' # 0xBB -> RIGHT SQUARE BRACKET + '\xaf' # 0xBC -> MACRON + '\xa8' # 0xBD -> DIAERESIS + '\xb4' # 0xBE -> ACUTE ACCENT + '\xd7' # 0xBF -> MULTIPLICATION SIGN + '{' # 0xC0 -> LEFT CURLY BRACKET + 'A' # 0xC1 -> LATIN CAPITAL LETTER A + 'B' # 0xC2 -> LATIN CAPITAL LETTER B + 'C' # 0xC3 -> LATIN CAPITAL LETTER C + 'D' # 0xC4 -> LATIN CAPITAL LETTER D + 'E' # 0xC5 -> LATIN CAPITAL LETTER E + 'F' # 0xC6 -> LATIN CAPITAL LETTER F + 'G' # 0xC7 -> LATIN CAPITAL LETTER G + 'H' # 0xC8 -> LATIN CAPITAL LETTER H + 'I' # 0xC9 -> LATIN CAPITAL LETTER I + '\xad' # 0xCA -> SOFT HYPHEN + '\xf4' # 0xCB -> LATIN SMALL LETTER O WITH CIRCUMFLEX + '\xf6' # 0xCC -> LATIN SMALL LETTER O WITH DIAERESIS + '\xf2' # 0xCD -> LATIN SMALL LETTER O WITH GRAVE + '\xf3' # 0xCE -> LATIN SMALL LETTER O WITH ACUTE + '\xf5' # 0xCF -> LATIN SMALL LETTER O WITH TILDE + '}' # 0xD0 -> RIGHT CURLY BRACKET + 'J' # 0xD1 -> LATIN CAPITAL LETTER J + 'K' # 0xD2 -> LATIN CAPITAL LETTER K + 'L' # 0xD3 -> LATIN CAPITAL LETTER L + 'M' # 0xD4 -> LATIN CAPITAL LETTER M + 'N' # 0xD5 -> LATIN CAPITAL LETTER N + 'O' # 0xD6 -> LATIN CAPITAL LETTER O + 'P' # 0xD7 -> LATIN CAPITAL LETTER P + 'Q' # 0xD8 -> LATIN CAPITAL LETTER Q + 'R' # 0xD9 -> LATIN CAPITAL LETTER R + '\xb9' # 0xDA -> SUPERSCRIPT ONE + '\xfb' # 0xDB -> LATIN SMALL LETTER U WITH CIRCUMFLEX + '\xfc' # 0xDC -> LATIN SMALL LETTER U WITH DIAERESIS + '\xf9' # 0xDD -> LATIN SMALL LETTER U WITH GRAVE + '\xfa' # 0xDE -> LATIN SMALL LETTER U WITH ACUTE + '\xff' # 0xDF -> LATIN SMALL LETTER Y WITH DIAERESIS + '\\' # 0xE0 -> REVERSE SOLIDUS + '\xf7' # 0xE1 -> DIVISION SIGN + 'S' # 0xE2 -> LATIN CAPITAL LETTER S + 'T' # 0xE3 -> LATIN CAPITAL LETTER T + 'U' # 0xE4 -> LATIN CAPITAL LETTER U + 'V' # 0xE5 -> LATIN CAPITAL LETTER V + 'W' # 0xE6 -> LATIN CAPITAL LETTER W + 'X' # 0xE7 -> LATIN CAPITAL LETTER X + 'Y' # 0xE8 -> LATIN CAPITAL LETTER Y + 'Z' # 0xE9 -> LATIN CAPITAL LETTER Z + '\xb2' # 0xEA -> SUPERSCRIPT TWO + '\xd4' # 0xEB -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX + '\xd6' # 0xEC -> LATIN CAPITAL LETTER O WITH DIAERESIS + '\xd2' # 0xED -> LATIN CAPITAL LETTER O WITH GRAVE + '\xd3' # 0xEE -> LATIN CAPITAL LETTER O WITH ACUTE + '\xd5' # 0xEF -> LATIN CAPITAL LETTER O WITH TILDE + '0' # 0xF0 -> DIGIT ZERO + '1' # 0xF1 -> DIGIT ONE + '2' # 0xF2 -> DIGIT TWO + '3' # 0xF3 -> DIGIT THREE + '4' # 0xF4 -> DIGIT FOUR + '5' # 0xF5 -> DIGIT FIVE + '6' # 0xF6 -> DIGIT SIX + '7' # 0xF7 -> DIGIT SEVEN + '8' # 0xF8 -> DIGIT EIGHT + '9' # 0xF9 -> DIGIT NINE + '\xb3' # 0xFA -> SUPERSCRIPT THREE + '\xdb' # 0xFB -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX + '\xdc' # 0xFC -> LATIN CAPITAL LETTER U WITH DIAERESIS + '\xd9' # 0xFD -> LATIN CAPITAL LETTER U WITH GRAVE + '\xda' # 0xFE -> LATIN CAPITAL LETTER U WITH ACUTE + '\x9f' # 0xFF -> CONTROL +) + +### Encoding table +encoding_table=codecs.charmap_build(decoding_table) diff --git a/shared/package-files/33/33807a26d909530e7a50b11646cd64c95114b2ba0dae76f9141abd3a2a00c873/test_voronoi.py b/shared/package-files/33/33807a26d909530e7a50b11646cd64c95114b2ba0dae76f9141abd3a2a00c873/test_voronoi.py new file mode 100644 index 0000000000000000000000000000000000000000..3269ae62a023ff0cf9fdc55122cb6e7c8d2ba319 --- /dev/null +++ b/shared/package-files/33/33807a26d909530e7a50b11646cd64c95114b2ba0dae76f9141abd3a2a00c873/test_voronoi.py @@ -0,0 +1,103 @@ +import networkx as nx +from networkx.utils import pairwise + + +class TestVoronoiCells: + """Unit tests for the Voronoi cells function.""" + + def test_isolates(self): + """Tests that a graph with isolated nodes has all isolates in + one block of the partition. + + """ + G = nx.empty_graph(5) + cells = nx.voronoi_cells(G, {0, 2, 4}) + expected = {0: {0}, 2: {2}, 4: {4}, "unreachable": {1, 3}} + assert expected == cells + + def test_undirected_unweighted(self): + G = nx.cycle_graph(6) + cells = nx.voronoi_cells(G, {0, 3}) + expected = {0: {0, 1, 5}, 3: {2, 3, 4}} + assert expected == cells + + def test_directed_unweighted(self): + # This is the singly-linked directed cycle graph on six nodes. + G = nx.DiGraph(pairwise(range(6), cyclic=True)) + cells = nx.voronoi_cells(G, {0, 3}) + expected = {0: {0, 1, 2}, 3: {3, 4, 5}} + assert expected == cells + + def test_directed_inward(self): + """Tests that reversing the graph gives the "inward" Voronoi + partition. + + """ + # This is the singly-linked reverse directed cycle graph on six nodes. + G = nx.DiGraph(pairwise(range(6), cyclic=True)) + G = G.reverse(copy=False) + cells = nx.voronoi_cells(G, {0, 3}) + expected = {0: {0, 4, 5}, 3: {1, 2, 3}} + assert expected == cells + + def test_undirected_weighted(self): + edges = [(0, 1, 10), (1, 2, 1), (2, 3, 1)] + G = nx.Graph() + G.add_weighted_edges_from(edges) + cells = nx.voronoi_cells(G, {0, 3}) + expected = {0: {0}, 3: {1, 2, 3}} + assert expected == cells + + def test_directed_weighted(self): + edges = [(0, 1, 10), (1, 2, 1), (2, 3, 1), (3, 2, 1), (2, 1, 1)] + G = nx.DiGraph() + G.add_weighted_edges_from(edges) + cells = nx.voronoi_cells(G, {0, 3}) + expected = {0: {0}, 3: {1, 2, 3}} + assert expected == cells + + def test_multigraph_unweighted(self): + """Tests that the Voronoi cells for a multigraph are the same as + for a simple graph. + + """ + edges = [(0, 1), (1, 2), (2, 3)] + G = nx.MultiGraph(2 * edges) + H = nx.Graph(G) + G_cells = nx.voronoi_cells(G, {0, 3}) + H_cells = nx.voronoi_cells(H, {0, 3}) + assert G_cells == H_cells + + def test_multidigraph_unweighted(self): + # This is the twice-singly-linked directed cycle graph on six nodes. + edges = list(pairwise(range(6), cyclic=True)) + G = nx.MultiDiGraph(2 * edges) + H = nx.DiGraph(G) + G_cells = nx.voronoi_cells(G, {0, 3}) + H_cells = nx.voronoi_cells(H, {0, 3}) + assert G_cells == H_cells + + def test_multigraph_weighted(self): + edges = [(0, 1, 10), (0, 1, 10), (1, 2, 1), (1, 2, 100), (2, 3, 1), (2, 3, 100)] + G = nx.MultiGraph() + G.add_weighted_edges_from(edges) + cells = nx.voronoi_cells(G, {0, 3}) + expected = {0: {0}, 3: {1, 2, 3}} + assert expected == cells + + def test_multidigraph_weighted(self): + edges = [ + (0, 1, 10), + (0, 1, 10), + (1, 2, 1), + (2, 3, 1), + (3, 2, 10), + (3, 2, 1), + (2, 1, 10), + (2, 1, 1), + ] + G = nx.MultiDiGraph() + G.add_weighted_edges_from(edges) + cells = nx.voronoi_cells(G, {0, 3}) + expected = {0: {0}, 3: {1, 2, 3}} + assert expected == cells diff --git a/shared/package-files/33/3380b234b890a10e6886800c1f91c44bd461da5a6bc80335b682fe6f54c95e3d/__init__.py b/shared/package-files/33/3380b234b890a10e6886800c1f91c44bd461da5a6bc80335b682fe6f54c95e3d/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba8a4f1d0ee7adb668c6b0ac49b2360d3c0dc356 --- /dev/null +++ b/shared/package-files/33/3380b234b890a10e6886800c1f91c44bd461da5a6bc80335b682fe6f54c95e3d/__init__.py @@ -0,0 +1,31 @@ +from pandas.core.indexers.utils import ( + check_array_indexer, + check_key_length, + check_setitem_lengths, + disallow_ndim_indexing, + is_empty_indexer, + is_list_like_indexer, + is_scalar_indexer, + is_valid_positional_slice, + length_of_indexer, + maybe_convert_indices, + unpack_1tuple, + unpack_tuple_and_ellipses, + validate_indices, +) + +__all__ = [ + "is_valid_positional_slice", + "is_list_like_indexer", + "is_scalar_indexer", + "is_empty_indexer", + "check_setitem_lengths", + "validate_indices", + "maybe_convert_indices", + "length_of_indexer", + "disallow_ndim_indexing", + "unpack_1tuple", + "check_key_length", + "check_array_indexer", + "unpack_tuple_and_ellipses", +] diff --git a/shared/package-files/33/3383fdde3d766473dd41a90762e719761abcfeee1b20e1fe5037a5c98b757396/pool.py b/shared/package-files/33/3383fdde3d766473dd41a90762e719761abcfeee1b20e1fe5037a5c98b757396/pool.py new file mode 100644 index 0000000000000000000000000000000000000000..6915203566469cfaf7170d87894ce03cc8348dd5 --- /dev/null +++ b/shared/package-files/33/3383fdde3d766473dd41a90762e719761abcfeee1b20e1fe5037a5c98b757396/pool.py @@ -0,0 +1,52 @@ +import multiprocessing.pool +import multiprocessing.util as util + +from .queue import SimpleQueue + + +def clean_worker(*args, **kwargs): + import gc + + multiprocessing.pool.worker(*args, **kwargs) + # Regular multiprocessing workers don't fully clean up after themselves, + # so we have to explicitly trigger garbage collection to make sure that all + # destructors are called... + gc.collect() + + +class Pool(multiprocessing.pool.Pool): + """Pool implementation which uses our version of SimpleQueue. + + This lets us pass tensors in shared memory across processes instead of + serializing the underlying data. + """ + + def _setup_queues(self): + self._inqueue = SimpleQueue() + self._outqueue = SimpleQueue() + self._quick_put = self._inqueue._writer.send + self._quick_get = self._outqueue._reader.recv + + def _repopulate_pool(self): + """Increase the number of pool processes to the specified number. + + Bring the number of pool processes up to the specified number, for use after + reaping workers which have exited. + """ + for i in range(self._processes - len(self._pool)): + # changed worker -> clean_worker + args = ( + self._inqueue, + self._outqueue, + self._initializer, + self._initargs, + self._maxtasksperchild, + ) + if hasattr(self, "_wrap_exception"): + args += (self._wrap_exception,) + w = self.Process(target=clean_worker, args=args) + self._pool.append(w) + w.name = w.name.replace("Process", "PoolWorker") + w.daemon = True + w.start() + util.debug("added worker") diff --git a/shared/package-files/33/33846b3e701436825087285e86619583c7cda17610c974be1ed59c785af2744d/gam_penalties.py b/shared/package-files/33/33846b3e701436825087285e86619583c7cda17610c974be1ed59c785af2744d/gam_penalties.py new file mode 100644 index 0000000000000000000000000000000000000000..c01b4245ff9e39259c1d1e3fc4d0aeb35fbc19ab --- /dev/null +++ b/shared/package-files/33/33846b3e701436825087285e86619583c7cda17610c974be1ed59c785af2744d/gam_penalties.py @@ -0,0 +1,338 @@ +""" +Penalty classes for Generalized Additive Models + +Author: Luca Puggini +Author: Josef Perktold + +""" + +import numpy as np +from scipy.linalg import block_diag + +from statsmodels.base._penalties import Penalty +from statsmodels.tools.sm_exceptions import ModelWarning + + +class UnivariateGamPenalty(Penalty): + """ + Penalty for smooth term in Generalized Additive Models + + Parameters + ---------- + univariate_smoother : instance + instance of univariate smoother or spline class + alpha : float, optional + default penalty weight, alpha can be provided to each method + weights : array_like, optional + Not used and not verified, might be removed. + + Attributes + ---------- + univariate_smoother : instance + instance of univariate smoother or spline class + alpha : float + default penalty weight, alpha can be provided to each method + weights : array_like + Not used and not verified, might be removed. + nobs : int + The number of samples used during the estimation. + n_columns : int + Number of columns in smoother basis. + """ + + def __init__(self, univariate_smoother, alpha=1, weights=1): + self.weights = weights + self.alpha = alpha + self.univariate_smoother = univariate_smoother + self.nobs = self.univariate_smoother.nobs + self.n_columns = self.univariate_smoother.dim_basis + + def func(self, params, alpha=None): + """ + Evaluate penalization at params + + Parameters + ---------- + params : ndarray + coefficients for the spline basis in the regression model + alpha : float, optional + default penalty weight + + Returns + ------- + func : float + value of the penalty evaluated at params + """ + if alpha is None: + alpha = self.alpha + + f = params.dot(self.univariate_smoother.cov_der2.dot(params)) + return alpha * f / self.nobs + + def deriv(self, params, alpha=None): + """ + Evaluate derivative of penalty with respect to params + + Parameters + ---------- + params : ndarray + coefficients for the spline basis in the regression model + alpha : float, optional + default penalty weight + + Returns + ------- + deriv : ndarray + derivative, gradient of the penalty with respect to params + """ + if alpha is None: + alpha = self.alpha + + d = 2 * alpha * np.dot(self.univariate_smoother.cov_der2, params) + d /= self.nobs + return d + + def deriv2(self, params, alpha=None): + """ + Evaluate second derivative of penalty with respect to params + + Parameters + ---------- + params : ndarray + coefficients for the spline basis in the regression model + alpha : float, optional + default penalty weight + + Returns + ------- + deriv2 : ndarray, 2-Dim + second derivative, hessian of the penalty with respect to params + """ + if alpha is None: + alpha = self.alpha + + d2 = 2 * alpha * self.univariate_smoother.cov_der2 + d2 /= self.nobs + return d2 + + def penalty_matrix(self, alpha=None): + """ + Penalty matrix for the smooth term of a GAM + + Parameters + ---------- + alpha : float, optional + penalty weight + + Returns + ------- + penalty_matrix : ndarray + square penalty matrix for quadratic penalization. The number + of rows and columns are equal to the number of columns in the + smooth terms, i.e., the number of parameters for this smooth + term in the regression model + """ + if alpha is None: + alpha = self.alpha + + return alpha * self.univariate_smoother.cov_der2 + + +class MultivariateGamPenalty(Penalty): + """ + Penalty for Generalized Additive Models + + Parameters + ---------- + multivariate_smoother : instance + instance of additive smoother or spline class + alpha : list of float + default penalty weight, list with length equal to the number of smooth + terms. ``alpha`` can also be provided to each method. + weights : array_like, optional + currently not used + is a list of doubles of the same length as alpha or a list + of ndarrays where each component has the length equal to the number + of columns in that component + start_idx : int, optional + number of parameters that come before the smooth terms. If the model + has a linear component, then the parameters for the smooth components + start at ``start_index``. + + Attributes + ---------- + multivariate_smoother : instance + instance of additive smoother or spline class + alpha : list of float + default penalty weight, list with length equal to the number of smooth + terms + weights : array_like + currently not used + start_idx : int + number of parameters that come before the smooth terms + nobs : int + The number of samples used during the estimation. + dim_basis : int + number of columns of additive smoother. Number of columns + in all smoothers. + k_variables : int + number of smooth terms + k_params : int + total number of parameters in the regression model + """ + + def __init__(self, multivariate_smoother, alpha, weights=None, start_idx=0): + + if len(multivariate_smoother.smoothers) != len(alpha): + msg = ( + "all the input values should be of the same length." + f" len(smoothers)={len(multivariate_smoother.smoothers):d}, len(alphas)={len(alpha):d}" + ) + raise ValueError(msg) + + self.multivariate_smoother = multivariate_smoother + self.dim_basis = self.multivariate_smoother.dim_basis + self.k_variables = self.multivariate_smoother.k_variables + self.nobs = self.multivariate_smoother.nobs + self.alpha = alpha + self.start_idx = start_idx + self.k_params = start_idx + self.dim_basis + + # TODO: Review this, + if weights is None: + # weights should have total length as params + # but it can also be scalar in individual component + self.weights = [1.0 for _ in range(self.k_variables)] + else: + import warnings + + warnings.warn("weights is currently ignored", ModelWarning, stacklevel=2) + self.weights = weights + + self.mask = [ + np.zeros(self.k_params, dtype=bool) for _ in range(self.k_variables) + ] + param_count = start_idx + for i, smoother in enumerate(self.multivariate_smoother.smoothers): + # the mask[i] contains a vector of length k_columns. The index + # corresponding to the i-th input variable are set to True. + self.mask[i][param_count : param_count + smoother.dim_basis] = True + param_count += smoother.dim_basis + + self.gp = [] + for i in range(self.k_variables): + gp = UnivariateGamPenalty( + self.multivariate_smoother.smoothers[i], + weights=self.weights[i], + alpha=self.alpha[i], + ) + self.gp.append(gp) + + def func(self, params, alpha=None): + """ + Evaluate penalization at params + + Parameters + ---------- + params : ndarray + coefficients in the regression model + alpha : list of float, optional + penalty weights + + Returns + ------- + func : float + value of the penalty evaluated at params + """ + if alpha is None: + alpha = [None] * self.k_variables + + cost = 0 + for i in range(self.k_variables): + params_i = params[self.mask[i]] + cost += self.gp[i].func(params_i, alpha=alpha[i]) + + return cost + + def deriv(self, params, alpha=None): + """ + Evaluate derivative of penalty with respect to params + + Parameters + ---------- + params : ndarray + coefficients in the regression model + alpha : list of float, optional + penalty weights + + Returns + ------- + deriv : ndarray + derivative, gradient of the penalty with respect to params + """ + if alpha is None: + alpha = [None] * self.k_variables + + grad = [np.zeros(self.start_idx)] + for i in range(self.k_variables): + params_i = params[self.mask[i]] + grad.append(self.gp[i].deriv(params_i, alpha=alpha[i])) + + return np.concatenate(grad) + + def deriv2(self, params, alpha=None): + """ + Evaluate second derivative of penalty with respect to params + + Parameters + ---------- + params : ndarray + coefficients in the regression model + alpha : list of float, optional + penalty weights + + Returns + ------- + deriv2 : ndarray, 2-Dim + second derivative, hessian of the penalty with respect to params + """ + if alpha is None: + alpha = [None] * self.k_variables + + deriv2 = [np.zeros((self.start_idx, self.start_idx))] + for i in range(self.k_variables): + params_i = params[self.mask[i]] + deriv2.append(self.gp[i].deriv2(params_i, alpha=alpha[i])) + + return block_diag(*deriv2) + + def penalty_matrix(self, alpha=None): + """ + Penalty matrix for generalized additive model + + Parameters + ---------- + alpha : list of float, optional + penalty weights + + Returns + ------- + penalty_matrix : ndarray + block diagonal, square penalty matrix for quadratic penalization. + The number of rows and columns are equal to the number of + parameters in the regression model ``k_params``. + + Notes + ----- + statsmodels does not support backwards compatibility when keywords are + used as positional arguments. The order of keywords might change. + We might need to add a ``params`` keyword if the need arises. + """ + if alpha is None: + alpha = self.alpha + + s_all = [np.zeros((self.start_idx, self.start_idx))] + for i in range(self.k_variables): + s_all.append(self.gp[i].penalty_matrix(alpha=alpha[i])) + + return block_diag(*s_all) diff --git a/shared/package-files/33/3386c0928c55014831a9a8b94b4fe20874b911c3513c15fff7395d56a14b57dd/linker.py b/shared/package-files/33/3386c0928c55014831a9a8b94b4fe20874b911c3513c15fff7395d56a14b57dd/linker.py new file mode 100644 index 0000000000000000000000000000000000000000..31d1e26ffb99763af367d07c30fd77770103dc79 --- /dev/null +++ b/shared/package-files/33/3386c0928c55014831a9a8b94b4fe20874b911c3513c15fff7395d56a14b57dd/linker.py @@ -0,0 +1,20 @@ +from ctypes import c_int, c_char_p, POINTER +from llvmlite.binding import ffi + + +def link_modules(dst, src): + with ffi.OutputString() as outerr: + err = ffi.lib.LLVMPY_LinkModules(dst, src, outerr) + # The underlying module was destroyed + src.detach() + if err: + raise RuntimeError(str(outerr)) + + +ffi.lib.LLVMPY_LinkModules.argtypes = [ + ffi.LLVMModuleRef, + ffi.LLVMModuleRef, + POINTER(c_char_p), +] + +ffi.lib.LLVMPY_LinkModules.restype = c_int diff --git a/shared/package-files/33/3386fdffb3cab0eef80e1b08045a13001e48f7d857ae5049723c60856848f2f7/config.pyi b/shared/package-files/33/3386fdffb3cab0eef80e1b08045a13001e48f7d857ae5049723c60856848f2f7/config.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e60507e0b65aad77537fb38f1ba5dfec13095a53 --- /dev/null +++ b/shared/package-files/33/3386fdffb3cab0eef80e1b08045a13001e48f7d857ae5049723c60856848f2f7/config.pyi @@ -0,0 +1,17 @@ +from abc import abstractmethod +from distutils.cmd import Command +from typing import ClassVar, List, Optional, Tuple + +DEFAULT_PYPIRC: str + +class PyPIRCCommand(Command): + DEFAULT_REPOSITORY: ClassVar[str] + DEFAULT_REALM: ClassVar[str] + repository: None + realm: None + user_options: ClassVar[List[Tuple[str, Optional[str], str]]] + boolean_options: ClassVar[List[str]] + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + @abstractmethod + def run(self) -> None: ... diff --git a/shared/package-files/33/3389135aa69241a57500c8722d2be6c2804917b5fd89cac82dbbd0270a7de348/Guadalcanal b/shared/package-files/33/3389135aa69241a57500c8722d2be6c2804917b5fd89cac82dbbd0270a7de348/Guadalcanal new file mode 100644 index 0000000000000000000000000000000000000000..1ab8353464ddb93947f871f07cfd12540373269c Binary files /dev/null and b/shared/package-files/33/3389135aa69241a57500c8722d2be6c2804917b5fd89cac82dbbd0270a7de348/Guadalcanal differ diff --git a/shared/package-files/33/3389135aa69241a57500c8722d2be6c2804917b5fd89cac82dbbd0270a7de348/Pohnpei b/shared/package-files/33/3389135aa69241a57500c8722d2be6c2804917b5fd89cac82dbbd0270a7de348/Pohnpei new file mode 100644 index 0000000000000000000000000000000000000000..1ab8353464ddb93947f871f07cfd12540373269c Binary files /dev/null and b/shared/package-files/33/3389135aa69241a57500c8722d2be6c2804917b5fd89cac82dbbd0270a7de348/Pohnpei differ diff --git a/shared/package-files/33/3389135aa69241a57500c8722d2be6c2804917b5fd89cac82dbbd0270a7de348/Ponape b/shared/package-files/33/3389135aa69241a57500c8722d2be6c2804917b5fd89cac82dbbd0270a7de348/Ponape new file mode 100644 index 0000000000000000000000000000000000000000..1ab8353464ddb93947f871f07cfd12540373269c Binary files /dev/null and b/shared/package-files/33/3389135aa69241a57500c8722d2be6c2804917b5fd89cac82dbbd0270a7de348/Ponape differ diff --git a/shared/package-files/33/338aeb61daafcccf87d2a49db0ee7d3be964639ecda3823a10d488f4c926f8be/kron_compositeimplicitautograd_dispatch.h b/shared/package-files/33/338aeb61daafcccf87d2a49db0ee7d3be964639ecda3823a10d488f4c926f8be/kron_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..0a7675c2860154b74817d55e3ecc269052e0c8f1 --- /dev/null +++ b/shared/package-files/33/338aeb61daafcccf87d2a49db0ee7d3be964639ecda3823a10d488f4c926f8be/kron_compositeimplicitautograd_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor kron(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & kron_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & kron_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/33/3391fd30bf227db58c7df708d66c9fee23f8f6f20c0e7fa098b137093cc40463/aaa-30-s-rv-ct b/shared/package-files/33/3391fd30bf227db58c7df708d66c9fee23f8f6f20c0e7fa098b137093cc40463/aaa-30-s-rv-ct new file mode 100644 index 0000000000000000000000000000000000000000..c9314e25018d1bb94b19f189b4ad40d84ae4f25f Binary files /dev/null and b/shared/package-files/33/3391fd30bf227db58c7df708d66c9fee23f8f6f20c0e7fa098b137093cc40463/aaa-30-s-rv-ct differ diff --git a/shared/package-files/33/3391fd30bf227db58c7df708d66c9fee23f8f6f20c0e7fa098b137093cc40463/aaa-s-rv-ctxt b/shared/package-files/33/3391fd30bf227db58c7df708d66c9fee23f8f6f20c0e7fa098b137093cc40463/aaa-s-rv-ctxt new file mode 100644 index 0000000000000000000000000000000000000000..c9314e25018d1bb94b19f189b4ad40d84ae4f25f Binary files /dev/null and b/shared/package-files/33/3391fd30bf227db58c7df708d66c9fee23f8f6f20c0e7fa098b137093cc40463/aaa-s-rv-ctxt differ diff --git a/shared/package-files/33/3393c9a147fe79d24935d0361fbdec3994efa8aaf7dd6858500a30fcb05aa003/test_mathlib.py b/shared/package-files/33/3393c9a147fe79d24935d0361fbdec3994efa8aaf7dd6858500a30fcb05aa003/test_mathlib.py new file mode 100644 index 0000000000000000000000000000000000000000..c28c651297d572452582d0f37ded4f3a36cf6e41 --- /dev/null +++ b/shared/package-files/33/3393c9a147fe79d24935d0361fbdec3994efa8aaf7dd6858500a30fcb05aa003/test_mathlib.py @@ -0,0 +1,756 @@ +import itertools +import math +import re +import sys +import unittest +import warnings + +import numpy as np + +from numba import njit, types +from numba.tests.support import TestCase +from numba.np import numpy_support +from numba.core.utils import PYVERSION + + +def sin(x): + return math.sin(x) + + +def cos(x): + return math.cos(x) + + +def tan(x): + return math.tan(x) + + +def sinh(x): + return math.sinh(x) + + +def cosh(x): + return math.cosh(x) + + +def tanh(x): + return math.tanh(x) + + +def asin(x): + return math.asin(x) + + +def acos(x): + return math.acos(x) + + +def atan(x): + return math.atan(x) + + +def atan2(y, x): + return math.atan2(y, x) + + +def asinh(x): + return math.asinh(x) + + +def acosh(x): + return math.acosh(x) + + +def atanh(x): + return math.atanh(x) + + +def sqrt(x): + return math.sqrt(x) + + +def npy_sqrt(x): + return np.sqrt(x) + + +def exp(x): + return math.exp(x) + +def exp2(x): + return math.exp2(x) + +def expm1(x): + return math.expm1(x) + + +def log(x): + return math.log(x) + + +def log1p(x): + return math.log1p(x) + + +def log10(x): + return math.log10(x) + + +def log2(x): + return math.log2(x) + + +def floor(x): + return math.floor(x) + + +def ceil(x): + return math.ceil(x) + + +def trunc(x): + return math.trunc(x) + + +def isnan(x): + return math.isnan(x) + + +def isinf(x): + return math.isinf(x) + + +def isfinite(x): + return math.isfinite(x) + + +def hypot(x, y): + return math.hypot(x, y) + + +def nextafter(x, y): + return math.nextafter(x, y) + + +def degrees(x): + return math.degrees(x) + + +def radians(x): + return math.radians(x) + + +def erf(x): + return math.erf(x) + + +def erfc(x): + return math.erfc(x) + + +def gamma(x): + return math.gamma(x) + + +def lgamma(x): + return math.lgamma(x) + + +def pow(x, y): + return math.pow(x, y) + +def gcd(x, y): + return math.gcd(x, y) + +def copysign(x, y): + return math.copysign(x, y) + + +def frexp(x): + return math.frexp(x) + + +def ldexp(x, e): + return math.ldexp(x, e) + + +def frexp_ldexp_roundtrip(x): + m, e = math.frexp(x) + return math.ldexp(m, e) + + +def np_ldexp(x, e): + return np.ldexp(x, e) + + +# IEEE-754 double corners, named for readability in TestFrexpLdexp. +DBL_TRUE_MIN = 5e-324 # smallest positive subnormal +DBL_MIN = 2.2250738585072014e-308 # smallest positive normal +DBL_MAX = 1.7976931348623157e308 + + +def get_constants(): + return math.pi, math.e + + +class TestMathLib(TestCase): + + def test_constants(self): + cfunc = njit(get_constants) + self.assertPreciseEqual(cfunc(), cfunc.py_func()) + + def run_unary(self, pyfunc, x_types, x_values, prec='exact', **kwargs): + cfunc = njit(pyfunc) + for tx, vx in zip(x_types, x_values): + got = cfunc(vx) + expected = pyfunc(vx) + actual_prec = 'single' if tx is types.float32 else prec + msg = 'for input %r' % (vx,) + self.assertPreciseEqual(got, expected, prec=actual_prec, msg=msg, + **kwargs) + + def run_binary(self, pyfunc, x_types, x_values, y_values, prec='exact'): + cfunc = njit(pyfunc) + for ty, x, y in zip(x_types, x_values, y_values): + got = cfunc(x, y) + expected = pyfunc(x, y) + actual_prec = 'single' if ty is types.float32 else prec + msg = 'for inputs (%r, %r)' % (x, y) + self.assertPreciseEqual(got, expected, prec=actual_prec, msg=msg) + + def check_predicate_func(self, pyfunc): + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float32, types.float32, + types.float64, types.float64, types.float64] + x_values = [0, 0, 0, 0, 0, 0, + float('inf'), 0.0, float('nan'), + float('inf'), 0.0, float('nan')] + self.run_unary(pyfunc, x_types, x_values) + + def test_sin(self): + pyfunc = sin + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + @unittest.skipIf(sys.platform == 'win32', + "not exactly equal on win32 (issue #597)") + def test_cos(self): + pyfunc = cos + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_tan(self): + pyfunc = tan + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_sqrt(self): + pyfunc = sqrt + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [2, 1, 2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_npy_sqrt(self): + pyfunc = npy_sqrt + x_values = [2, 1, 2, 2, 1, 2, .1, .2] + # XXX poor precision for int16 inputs + x_types = [types.int16, types.uint16] + self.run_unary(pyfunc, x_types, x_values, prec='single') + x_types = [types.int32, types.int64, + types.uint32, types.uint64, + types.float32, types.float64] + self.run_unary(pyfunc, x_types, x_values) + + def test_exp(self): + pyfunc = exp + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + @unittest.skipUnless(PYVERSION >= (3, 11), "needs Python 3.11+") + def test_exp2(self): + pyfunc = exp2 + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_expm1(self): + pyfunc = expm1 + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_log(self): + pyfunc = log + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 10, 100, 1000, 100000, 1000000, 0.1, 1.1] + self.run_unary(pyfunc, x_types, x_values) + + def test_log1p(self): + pyfunc = log1p + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 10, 100, 1000, 100000, 1000000, 0.1, 1.1] + self.run_unary(pyfunc, x_types, x_values) + + def test_log10(self): + pyfunc = log10 + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 10, 100, 1000, 100000, 1000000, 0.1, 1.1] + self.run_unary(pyfunc, x_types, x_values) + + def test_log2(self): + pyfunc = log2 + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 10, 100, 1000, 100000, 1000000, 0.1, 1.1] + self.run_unary(pyfunc, x_types, x_values) + + def test_asin(self): + pyfunc = asin + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_acos(self): + pyfunc = acos + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_atan(self): + pyfunc = atan + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_atan2(self): + pyfunc = atan2 + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + y_values = [x * 2 for x in x_values] + self.run_binary(pyfunc, x_types, x_values, y_values) + + def test_asinh(self): + pyfunc = asinh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values, prec='double') + + def test_acosh(self): + pyfunc = acosh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_atanh(self): + pyfunc = atanh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [0, 0, 0, 0, 0, 0, 0.1, 0.1] + self.run_unary(pyfunc, x_types, x_values, prec='double') + + def test_sinh(self): + pyfunc = sinh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_cosh(self): + pyfunc = cosh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_tanh(self): + pyfunc = tanh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [0, 0, 0, 0, 0, 0, 0.1, 0.1] + self.run_unary(pyfunc, x_types, x_values) + + def test_floor(self): + pyfunc = floor + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [0, 0, 0, 0, 0, 0, 0.1, 1.9] + self.run_unary(pyfunc, x_types, x_values) + + def test_ceil(self): + pyfunc = ceil + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [0, 0, 0, 0, 0, 0, 0.1, 1.9] + self.run_unary(pyfunc, x_types, x_values) + + def test_trunc(self): + pyfunc = trunc + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [0, 0, 0, 0, 0, 0, 0.1, 1.9] + self.run_unary(pyfunc, x_types, x_values) + + def test_isnan(self): + self.check_predicate_func(isnan) + + def test_isinf(self): + self.check_predicate_func(isinf) + + def test_isfinite(self): + self.check_predicate_func(isfinite) + + def test_hypot(self): + pyfunc = hypot + x_types = [types.int64, types.uint64, + types.float32, types.float64] + x_values = [1, 2, 3, 4, 5, 6, .21, .34] + y_values = [x + 2 for x in x_values] + # Issue #563: precision issues with math.hypot() under Windows. + prec = 'single' + self.run_binary(pyfunc, x_types, x_values, y_values, prec) + # Check that values that overflow in naive implementations do not + # in the numba impl + + def naive_hypot(x, y): + return math.sqrt(x * x + y * y) + + cfunc = njit(pyfunc) + for fltty in (types.float32, types.float64): + dt = numpy_support.as_dtype(fltty).type + val = dt(np.finfo(dt).max / 30.) + nb_ans = cfunc(val, val) + self.assertPreciseEqual(nb_ans, pyfunc(val, val), prec='single') + self.assertTrue(np.isfinite(nb_ans)) + + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + self.assertRaisesRegex(RuntimeWarning, + 'overflow encountered in .*scalar', + naive_hypot, val, val) + + def test_nextafter(self): + pyfunc = nextafter + x_types = [types.float32, types.float64, + types.int32, types.int64, + types.uint32, types.uint64] + x_values = [0.0, .21, .34, 1005382.042, -25.328] + y1_values = [x + 2 for x in x_values] + y2_values = [x - 2 for x in x_values] + + self.run_binary(pyfunc, x_types, x_values, y1_values) + self.run_binary(pyfunc, x_types, x_values, y2_values) + + # Test using pos/neg inf + self.run_binary(pyfunc, x_types, [0.0, -.5, .5], [math.inf]*3) + self.run_binary(pyfunc, x_types, [0.0, -.5, .5], [-math.inf]*3) + + # if both args to nextafter are equal, then it is returned unchanged. + self.run_binary(pyfunc, x_types, x_values, x_values) + + def test_degrees(self): + pyfunc = degrees + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_radians(self): + pyfunc = radians + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_erf(self): + pyfunc = erf + x_values = [1., 1., -1., -0.0, 0.0, 0.5, 5, float('inf')] + x_types = [types.float32, types.float64] * (len(x_values) // 2) + self.run_unary(pyfunc, x_types, x_values, prec='double', ulps=2) + + def test_erfc(self): + pyfunc = erfc + x_values = [1., 1., -1., -0.0, 0.0, 0.5, 5, float('inf')] + x_types = [types.float32, types.float64] * (len(x_values) // 2) + self.run_unary(pyfunc, x_types, x_values, prec='double', ulps=4) + + def test_gamma(self): + pyfunc = gamma + x_values = [1., -0.9, -0.5, 0.5] + x_types = [types.float32, types.float64] * (len(x_values) // 2) + self.run_unary(pyfunc, x_types, x_values, prec='double', ulps=3) + x_values = [-0.1, 0.1, 2.5, 10.1, 50., float('inf')] + x_types = [types.float64] * len(x_values) + self.run_unary(pyfunc, x_types, x_values, prec='double', ulps=8) + + def test_lgamma(self): + pyfunc = lgamma + x_values = [1., -0.9, -0.1, 0.1, 200., 1e10, 1e30, float('inf')] + x_types = [types.float32, types.float64] * (len(x_values) // 2) + self.run_unary(pyfunc, x_types, x_values, prec='double') + + def test_pow(self): + pyfunc = pow + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + y_values = [x * 2 for x in x_values] + self.run_binary(pyfunc, x_types, x_values, y_values) + + def test_gcd(self): + from itertools import product, repeat, chain + pyfunc = gcd + signed_args = product( + sorted(types.signed_domain), *repeat((-2, -1, 0, 1, 2, 7, 10), 2) + ) + unsigned_args = product( + sorted(types.unsigned_domain), *repeat((0, 1, 2, 7, 9, 16), 2) + ) + x_types, x_values, y_values = zip(*chain(signed_args, unsigned_args)) + self.run_binary(pyfunc, x_types, x_values, y_values) + + def test_copysign(self): + pyfunc = copysign + value_types = [types.float32, types.float64] + values = [-2, -1, -0.0, 0.0, 1, 2, float('-inf'), float('inf'), + float('nan')] + x_types, x_values, y_values = list(zip( + *itertools.product(value_types, values, values))) + self.run_binary(pyfunc, x_types, x_values, y_values) + + def test_frexp(self): + pyfunc = frexp + x_types = [types.float32, types.float64] + x_values = [-2.5, -0.0, 0.0, 3.5, + float('-inf'), float('inf'), float('nan')] + self.run_unary(pyfunc, x_types, x_values, prec='exact') + + def test_ldexp(self): + pyfunc = ldexp + cfunc = njit(pyfunc) + for fltty in (types.float32, types.float64): + for args in [(2.5, -2), (2.5, 1), (0.0, 0), (0.0, 1), + (-0.0, 0), (-0.0, 1), + (float('inf'), 0), (float('-inf'), 0), + (float('nan'), 0)]: + msg = 'for input %r' % (args,) + self.assertPreciseEqual(cfunc(*args), pyfunc(*args)) + + +class TestFrexpLdexp(TestCase): + def test_frexp_wide_range(self): + pyfunc = frexp + cfunc = njit(pyfunc) + x_values = [1.0, -1.0, 0.5, -0.5, 2.5, -2.5, math.pi, + 123456789.0, 1e300, -1e300, 1e-300, + DBL_MIN, -DBL_MIN, DBL_TRUE_MIN, -DBL_TRUE_MIN, + DBL_MAX, -DBL_MAX, + 0.0, -0.0, float('inf'), float('-inf'), float('nan')] + for x in x_values: + self.assertPreciseEqual(cfunc(x), pyfunc(x), + msg='for input %r' % (x,)) + + def test_frexp_exponent_over_full_double_range(self): + # Walk every exponent a double can produce, subnormals included. + cfunc = njit(frexp) + for e in range(-1073, 1025): + x = math.ldexp(0.75, e) + if x == 0.0 or math.isinf(x): + continue + self.assertEqual(cfunc(x)[1], math.frexp(x)[1], + msg='for exponent %d' % (e,)) + + def test_frexp_float32(self): + # Exercises the float32 helper, numba_frexpf. + cfunc = njit(frexp) + for v in [1.0, -1.0, 2.5, -2.5, 0.5, 1e30, -1e30, 1e-30, + 0.0, -0.0, float('inf'), float('-inf'), float('nan')]: + x = np.float32(v) + got_m, got_e = cfunc(x) + expected_m, expected_e = math.frexp(float(x)) + self.assertPreciseEqual(got_m, np.float32(expected_m), + msg='mantissa for input %r' % (v,)) + self.assertEqual(got_e, expected_e, + msg='exponent for input %r' % (v,)) + + def test_ldexp_normal_range(self): + pyfunc = ldexp + cfunc = njit(pyfunc) + x_values = [1.0, -1.0, 0.5, -0.5, 2.5, -2.5, math.pi, -math.pi, + 0.7071067811865476, 1.9999999999999998, 1e100, 1e-100] + exponents = [-200, -64, -53, -10, -3, -1, 0, 1, 3, 10, 53, 64, 200] + for x in x_values: + for n in exponents: + self.assertPreciseEqual(cfunc(x, n), pyfunc(x, n), + msg='for input (%r, %r)' % (x, n)) + + def test_ldexp_special_values(self): + pyfunc = ldexp + cfunc = njit(pyfunc) + for x in [0.0, -0.0, float('inf'), float('-inf'), float('nan')]: + for n in [-1000, -1, 0, 1, 1000]: + self.assertPreciseEqual(cfunc(x, n), pyfunc(x, n), + msg='for input (%r, %r)' % (x, n)) + + def test_ldexp_overflows_to_inf(self): + # Numba saturates like C's ldexp; CPython raises OverflowError. + # Pin that intentional divergence. + cfunc = njit(ldexp) + for x in [1.0, -1.0, DBL_MAX, -DBL_MAX]: + for n in [1200, 2000, 2100, 2101, 100000, 2 ** 31 - 1]: + self.assertPreciseEqual(cfunc(x, n), + math.copysign(float('inf'), x), + msg='for input (%r, %r)' % (x, n)) + with self.assertRaises(OverflowError): + math.ldexp(x, n) + + def test_ldexp_underflows_to_signed_zero(self): + cfunc = njit(ldexp) + for x in [1.0, -1.0, DBL_MIN, -DBL_MIN, DBL_TRUE_MIN, -DBL_TRUE_MIN]: + for n in [-1200, -2000, -2100, -2101, -100000, -(2 ** 31)]: + self.assertPreciseEqual(cfunc(x, n), math.copysign(0.0, x), + msg='for input (%r, %r)' % (x, n)) + + def test_ldexp_huge_exponent_saturates(self): + # An exponent large enough to cross the entire double range must + # saturate rather than return a finite, wrong value. + cfunc = njit(ldexp) + self.assertPreciseEqual(cfunc(DBL_TRUE_MIN, 2100), float('inf')) + self.assertPreciseEqual(cfunc(-DBL_TRUE_MIN, 2100), float('-inf')) + self.assertPreciseEqual(cfunc(DBL_MAX, -2100), 0.0) + self.assertPreciseEqual(cfunc(-DBL_MAX, -2100), -0.0) + + def test_ldexp_frexp_roundtrip(self): + # A corrupted exponent on either side breaks the identity. + pyfunc = frexp_ldexp_roundtrip + cfunc = njit(pyfunc) + x_values = [1.0, -1.0, 2.5, -2.5, math.pi, 1e300, -1e300, 1e-300, + DBL_MIN, DBL_MAX, DBL_TRUE_MIN, 3 * DBL_TRUE_MIN, + 11 * DBL_TRUE_MIN, 0.0, -0.0, + float('inf'), float('-inf'), float('nan')] + for x in x_values: + self.assertPreciseEqual(cfunc(x), x, msg='for input %r' % (x,)) + + def test_ldexp_subnormal_results_are_correctly_rounded(self): + # Results landing in the subnormal range must be rounded once, + # the way math.ldexp rounds them. Scaling by repeated halving + # rounds again at every step once the value is subnormal, so + # these inputs detect the accumulated double-rounding error. + cfunc = njit(ldexp) + cases = [(4.359607055276148e-151, -574), + (-6.853580717782567e-197, -423), + (7.162365283163292e-228, -319), + (1.5259499737847772e-83, -796), + (6.458979912260433e-06, -1048)] + for x, n in cases: + self.assertPreciseEqual(cfunc(x, n), math.ldexp(x, n), + msg='for input (%r, %r)' % (x, n)) + + def test_ldexp_float32(self): + cfunc = njit(ldexp) + for v in [1.0, -1.0, 2.5, -2.5, 0.5, 1e20, 1e-20]: + for n in [-40, -10, -1, 0, 1, 10, 40]: + x = np.float32(v) + self.assertPreciseEqual( + cfunc(x, n), np.float32(math.ldexp(float(x), n)), + msg='for input (%r, %r)' % (v, n)) + + def test_ldexp_declaration_has_signext_exponent(self): + # See issue #8489. The declaration is target-independent, so + # this checks the signext on any host. Both lowerings + # (math.ldexp, np.ldexp) times both helper symbols; the + # trailing \( in the pattern below keeps numba_ldexp from + # matching numba_ldexpf. + cases = [(ldexp, 2.5, 'numba_ldexp'), + (ldexp, np.float32(2.5), 'numba_ldexpf'), + (np_ldexp, 2.5, 'numba_ldexp'), + (np_ldexp, np.float32(2.5), 'numba_ldexpf')] + # np.int32, not a plain int: on Windows with NumPy < 2.0 the + # np.ldexp ufunc has no int64 exponent loop, and ufunc typing + # requires a safe cast, so int64 resolves to no loop at all. + # See the IS_WIN32 remap in numba/np/ufunc_db.py. + for pyfunc, x, symbol in cases: + cfunc = njit(pyfunc) + cfunc(x, np.int32(3)) + llvm_ir = '\n'.join(cfunc.inspect_llvm().values()) + match = re.search( + r'declare[^@\n]*@%s\(([^)]*)\)' % (symbol,), llvm_ir) + self.assertIsNotNone( + match, + msg='no %s declaration for %r' % (symbol, pyfunc)) + params = [p.strip() for p in match.group(1).split(',')] + self.assertEqual(len(params), 2, msg=match.group(0)) + self.assertIn('signext', params[1], msg=match.group(0)) + + def test_np_ldexp_matches_numpy(self): + # np.ldexp goes through a separate copy of the extern call, in + # numba/np/math/mathimpl.py. Cover it so the two cannot drift. + cfunc = njit(np_ldexp) + + # np.int32 exponents: see + # test_ldexp_declaration_has_signext_exponent. + for v in [1.0, -1.0, 2.5, -2.5, math.pi, 1e100, 1e-100]: + for n in [-200, -53, -10, -1, 0, 1, 10, 53, 200]: + self.assertPreciseEqual(cfunc(v, np.int32(n)), + float(np.ldexp(v, n)), + msg='for input (%r, %r)' % (v, n)) + + # Subnormal results must be correctly rounded here too. + for v, n in [(4.359607055276148e-151, -574), + (-6.853580717782567e-197, -423), + (7.162365283163292e-228, -319), + (1.5259499737847772e-83, -796), + (6.458979912260433e-06, -1048)]: + self.assertPreciseEqual(cfunc(v, np.int32(n)), + float(np.ldexp(v, n)), + msg='for input (%r, %r)' % (v, n)) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/33/339426e6e4552e419463e21ff8e348709f2f0b3021da1e895a0769ac70498571/lme03.csv b/shared/package-files/33/339426e6e4552e419463e21ff8e348709f2f0b3021da1e895a0769ac70498571/lme03.csv new file mode 100644 index 0000000000000000000000000000000000000000..a55bf82b98247acc529c2bd7d3d521e331b537f9 --- /dev/null +++ b/shared/package-files/33/339426e6e4552e419463e21ff8e348709f2f0b3021da1e895a0769ac70498571/lme03.csv @@ -0,0 +1,230 @@ +groups,endog,exog_fe_0,exog_fe_1,exog_re_0 +0.000,0.896,-1.659,0.537,1.000 +1.000,-1.499,-0.203,-0.225,1.000 +2.000,-3.643,-0.615,-1.157,1.000 +2.000,0.699,0.441,0.143,1.000 +3.000,2.919,-1.589,0.708,1.000 +3.000,0.916,-0.396,0.729,1.000 +4.000,-0.242,-1.445,0.732,1.000 +5.000,1.059,-1.102,0.009,1.000 +5.000,-3.304,0.785,-2.154,1.000 +5.000,-5.862,3.576,0.770,1.000 +6.000,0.222,-0.489,0.753,1.000 +7.000,-2.700,0.679,-0.605,1.000 +7.000,0.351,-0.309,0.357,1.000 +7.000,2.115,0.202,0.752,1.000 +7.000,0.962,0.995,-0.275,1.000 +8.000,-1.274,-0.089,0.455,1.000 +8.000,-2.722,0.424,-0.704,1.000 +8.000,-0.580,0.171,0.188,1.000 +8.000,-2.023,0.806,-0.704,1.000 +9.000,0.330,-1.884,-0.250,1.000 +9.000,-0.750,0.241,-0.030,1.000 +10.000,-0.380,0.185,1.472,1.000 +10.000,0.113,-0.028,0.557,1.000 +11.000,4.264,0.023,0.414,1.000 +12.000,1.558,0.368,0.341,1.000 +12.000,-3.011,1.417,-0.091,1.000 +12.000,1.173,-0.464,-0.015,1.000 +13.000,1.898,0.680,1.220,1.000 +13.000,-2.742,0.991,-0.618,1.000 +13.000,0.632,0.194,-0.752,1.000 +13.000,-1.512,0.368,0.247,1.000 +14.000,-1.465,-0.268,0.043,1.000 +14.000,2.018,-1.565,0.311,1.000 +15.000,0.986,0.398,-0.094,1.000 +15.000,0.778,0.378,1.167,1.000 +16.000,-1.643,0.469,1.175,1.000 +16.000,0.047,0.121,0.920,1.000 +16.000,-0.174,-0.546,-0.092,1.000 +16.000,1.584,-1.750,-1.095,1.000 +17.000,2.642,-1.545,-0.046,1.000 +17.000,4.356,-1.481,1.012,1.000 +17.000,4.753,0.816,-0.030,1.000 +17.000,1.643,0.651,-0.104,1.000 +18.000,2.506,-2.309,-0.814,1.000 +18.000,-2.066,1.571,-1.079,1.000 +18.000,-2.262,-1.279,0.181,1.000 +19.000,-1.682,0.128,0.839,1.000 +19.000,1.634,-1.319,-0.425,1.000 +19.000,-3.570,1.727,-1.531,1.000 +20.000,-0.385,-0.173,-0.767,1.000 +20.000,1.443,-1.916,1.464,1.000 +20.000,-2.247,-1.168,-1.333,1.000 +21.000,1.245,1.483,0.413,1.000 +21.000,-0.081,-0.610,0.718,1.000 +21.000,0.294,0.146,0.042,1.000 +21.000,2.983,-0.463,-0.352,1.000 +22.000,0.548,-1.322,0.716,1.000 +22.000,-2.133,1.215,0.020,1.000 +22.000,0.268,0.133,0.181,1.000 +23.000,-0.098,1.765,0.948,1.000 +23.000,-1.042,2.070,-0.115,1.000 +24.000,-0.899,-1.315,-0.318,1.000 +24.000,2.123,-0.119,1.215,1.000 +24.000,4.608,-0.597,1.929,1.000 +24.000,-0.514,1.038,-0.758,1.000 +25.000,-2.524,0.862,-1.144,1.000 +25.000,3.373,-0.401,1.374,1.000 +25.000,-0.960,0.043,-0.829,1.000 +25.000,-2.333,2.060,0.044,1.000 +26.000,0.546,0.243,-0.203,1.000 +27.000,1.103,-0.957,1.450,1.000 +28.000,1.061,-0.221,1.518,1.000 +29.000,3.441,-0.162,1.235,1.000 +29.000,-1.087,-0.302,-1.481,1.000 +29.000,3.334,-1.092,-0.339,1.000 +30.000,5.416,0.069,0.124,1.000 +30.000,4.293,-0.233,-1.247,1.000 +31.000,0.660,1.083,-0.361,1.000 +32.000,0.434,0.123,1.387,1.000 +33.000,0.432,0.771,0.253,1.000 +34.000,1.816,-0.892,1.608,1.000 +35.000,-1.419,1.386,-0.805,1.000 +35.000,0.716,0.551,-0.136,1.000 +36.000,-0.680,0.932,0.340,1.000 +37.000,-0.221,-0.724,-0.907,1.000 +38.000,1.402,0.112,3.245,1.000 +38.000,-2.095,0.810,-1.237,1.000 +38.000,-1.490,-0.060,-1.298,1.000 +39.000,2.287,-0.688,1.280,1.000 +39.000,-2.591,-0.499,-1.673,1.000 +40.000,1.140,-1.291,0.599,1.000 +41.000,-5.446,0.511,-1.338,1.000 +41.000,2.751,-1.685,0.481,1.000 +41.000,-1.602,1.219,-0.333,1.000 +42.000,5.675,-0.676,1.235,1.000 +43.000,1.229,-0.846,0.070,1.000 +43.000,-0.651,0.381,0.359,1.000 +43.000,-1.527,-0.316,-0.275,1.000 +44.000,-1.291,1.864,-0.548,1.000 +44.000,-1.953,0.944,1.798,1.000 +45.000,1.646,-0.602,1.462,1.000 +45.000,-3.746,-0.749,-2.052,1.000 +45.000,-5.442,2.733,0.193,1.000 +45.000,2.974,-1.392,2.903,1.000 +46.000,-0.325,-0.544,0.486,1.000 +46.000,4.702,-2.130,0.525,1.000 +46.000,-1.292,0.896,-0.585,1.000 +47.000,-2.663,1.043,-0.138,1.000 +47.000,-1.549,-1.495,-0.105,1.000 +48.000,0.411,0.288,0.703,1.000 +48.000,-6.470,1.120,0.653,1.000 +48.000,5.630,-2.713,1.562,1.000 +49.000,2.308,-2.690,0.866,1.000 +49.000,-2.982,0.096,0.306,1.000 +49.000,-0.079,-1.311,0.038,1.000 +49.000,-1.818,0.610,-0.358,1.000 +50.000,1.608,-1.717,-0.034,1.000 +51.000,-0.825,-0.267,0.487,1.000 +51.000,0.579,-0.213,-0.075,1.000 +51.000,-5.529,1.209,-1.972,1.000 +51.000,-3.270,2.479,0.672,1.000 +52.000,2.812,0.297,0.309,1.000 +52.000,-0.419,0.905,-1.172,1.000 +53.000,-1.949,-0.344,0.397,1.000 +54.000,2.353,0.924,0.468,1.000 +54.000,1.791,-2.778,-0.178,1.000 +54.000,4.525,-0.217,0.070,1.000 +55.000,0.980,-0.066,0.581,1.000 +55.000,3.972,-1.004,-0.100,1.000 +56.000,0.664,-0.769,-0.828,1.000 +56.000,-2.819,0.316,-1.447,1.000 +56.000,-1.988,0.041,-1.980,1.000 +56.000,-2.958,-0.464,-1.141,1.000 +57.000,-0.356,0.216,2.159,1.000 +57.000,0.259,0.219,-0.244,1.000 +58.000,1.200,0.331,-0.887,1.000 +58.000,7.956,-1.618,1.002,1.000 +58.000,-0.523,0.728,1.085,1.000 +59.000,2.565,-0.210,0.142,1.000 +59.000,-0.574,-0.775,-0.315,1.000 +59.000,-0.214,-1.694,-0.918,1.000 +60.000,1.968,-0.424,1.760,1.000 +60.000,3.931,-0.354,1.994,1.000 +61.000,-3.132,0.925,-0.764,1.000 +62.000,-0.298,-1.081,-0.132,1.000 +62.000,2.318,1.789,0.407,1.000 +62.000,1.677,-0.163,0.103,1.000 +62.000,-1.831,-0.046,-0.662,1.000 +63.000,-1.954,-0.928,-0.260,1.000 +63.000,-0.339,-1.324,-0.620,1.000 +63.000,-5.099,0.818,-0.744,1.000 +63.000,-5.013,0.016,-1.138,1.000 +64.000,-2.670,0.984,0.731,1.000 +65.000,2.345,1.160,-0.184,1.000 +65.000,0.710,1.722,0.206,1.000 +65.000,-3.464,2.988,0.018,1.000 +66.000,-3.057,2.216,0.315,1.000 +66.000,-1.738,0.384,-0.117,1.000 +67.000,1.764,0.228,-0.203,1.000 +67.000,-2.503,-0.455,-1.452,1.000 +67.000,-4.189,-0.153,0.219,1.000 +68.000,-1.165,0.070,0.059,1.000 +68.000,3.491,-0.239,0.239,1.000 +68.000,-1.288,-0.615,-0.062,1.000 +68.000,-0.837,0.493,-0.186,1.000 +69.000,1.221,-0.101,-0.573,1.000 +69.000,0.947,1.015,0.334,1.000 +69.000,2.886,0.287,1.636,1.000 +69.000,-0.707,0.012,-1.563,1.000 +70.000,-0.378,1.317,0.627,1.000 +71.000,-0.778,-0.461,0.564,1.000 +71.000,3.638,-0.855,-0.315,1.000 +71.000,2.361,-0.541,1.132,1.000 +72.000,-0.072,1.684,-0.807,1.000 +72.000,2.311,1.657,-0.254,1.000 +72.000,1.366,0.624,-1.171,1.000 +72.000,-0.266,-0.498,1.167,1.000 +73.000,2.208,-0.356,0.669,1.000 +74.000,0.589,1.113,-0.049,1.000 +75.000,1.824,0.016,0.798,1.000 +75.000,-1.998,1.758,1.491,1.000 +76.000,1.101,-1.502,0.166,1.000 +77.000,-0.902,-0.150,0.016,1.000 +77.000,-0.681,-0.017,1.283,1.000 +77.000,0.457,-1.734,-0.794,1.000 +77.000,-0.948,-0.110,-1.428,1.000 +78.000,-1.267,0.264,0.015,1.000 +78.000,-1.259,0.593,-3.032,1.000 +78.000,-0.704,-0.606,-0.331,1.000 +79.000,1.007,-0.791,0.357,1.000 +79.000,1.739,0.841,-0.429,1.000 +79.000,0.691,0.701,1.153,1.000 +80.000,-0.275,-1.660,-0.263,1.000 +80.000,-3.283,1.375,2.109,1.000 +81.000,-1.913,0.428,-0.707,1.000 +82.000,-0.322,0.457,0.423,1.000 +82.000,-0.780,-0.572,-2.861,1.000 +82.000,-2.724,-0.350,0.290,1.000 +82.000,1.602,-0.136,2.437,1.000 +83.000,-3.147,1.116,-1.956,1.000 +84.000,1.396,0.455,-0.582,1.000 +84.000,1.654,0.853,0.383,1.000 +84.000,1.438,1.338,1.451,1.000 +85.000,-1.257,0.335,-1.031,1.000 +85.000,-0.524,-0.736,-1.034,1.000 +86.000,7.604,-1.610,0.960,1.000 +87.000,-2.649,0.589,-0.687,1.000 +87.000,-0.415,-0.634,-2.428,1.000 +87.000,-1.182,-0.618,-0.847,1.000 +88.000,4.074,-1.670,0.072,1.000 +88.000,-1.084,-1.018,-0.150,1.000 +89.000,3.981,-0.789,0.976,1.000 +89.000,-5.208,2.187,-0.973,1.000 +90.000,-0.824,0.118,-1.090,1.000 +90.000,0.797,-1.498,1.407,1.000 +91.000,4.016,-1.043,0.911,1.000 +91.000,-1.655,0.638,-0.149,1.000 +91.000,3.831,-0.871,1.270,1.000 +91.000,3.299,0.221,0.765,1.000 +92.000,0.307,-1.345,-0.100,1.000 +93.000,1.757,0.144,0.624,1.000 +93.000,0.946,-2.669,-0.322,1.000 +94.000,4.008,-0.818,1.751,1.000 +95.000,-3.451,-0.114,0.345,1.000 +96.000,0.941,-0.258,0.887,1.000 +97.000,1.638,-0.639,-0.620,1.000 +98.000,-1.325,0.379,-0.282,1.000 +99.000,-1.543,-0.330,1.297,1.000 +99.000,0.157,-0.484,1.422,1.000 diff --git a/shared/package-files/33/33943f56f5b3fbb2c0368a8aee5f32cac95fd7c8cda2e1b681a5fb41956d689d/test_lapack.py b/shared/package-files/33/33943f56f5b3fbb2c0368a8aee5f32cac95fd7c8cda2e1b681a5fb41956d689d/test_lapack.py new file mode 100644 index 0000000000000000000000000000000000000000..86555d6c19916c8ae1f6a796fb009a6b803b2159 --- /dev/null +++ b/shared/package-files/33/33943f56f5b3fbb2c0368a8aee5f32cac95fd7c8cda2e1b681a5fb41956d689d/test_lapack.py @@ -0,0 +1,3508 @@ +# +# Created by: Pearu Peterson, September 2002 +# + +from functools import reduce +import random + +from numpy.testing import (assert_equal, assert_array_almost_equal, assert_, + assert_allclose, assert_almost_equal, + assert_array_equal) +import pytest +from pytest import raises as assert_raises + +import numpy as np +from numpy import (eye, ones, zeros, zeros_like, triu, tril, tril_indices, + triu_indices) + +from numpy.random import rand, randint, seed + +from scipy.linalg import (_flapack as flapack, lapack, inv, svd, cholesky, + solve, ldl, norm, block_diag, qr, eigh, qz) + +from scipy.linalg.lapack import _compute_lwork +from scipy.stats import ortho_group, unitary_group + +import scipy.sparse as sps +try: + from scipy.__config__ import CONFIG +except ImportError: + CONFIG = None + +try: + from scipy.linalg import _clapack as clapack +except ImportError: + clapack = None +from scipy.linalg.lapack import get_lapack_funcs +from scipy.linalg.blas import get_blas_funcs + +REAL_DTYPES = [np.float32, np.float64] +COMPLEX_DTYPES = [np.complex64, np.complex128] +DTYPES = REAL_DTYPES + COMPLEX_DTYPES + +blas_provider = blas_version = None +if CONFIG is not None: + blas_provider = CONFIG['Build Dependencies']['blas']['name'] + blas_version = CONFIG['Build Dependencies']['blas']['version'] + + +def generate_random_dtype_array(shape, dtype, rng): + # generates a random matrix of desired data type of shape + if dtype in COMPLEX_DTYPES: + return (rng.rand(*shape) + + rng.rand(*shape)*1.0j).astype(dtype) + return rng.rand(*shape).astype(dtype) + + +def test_lapack_documented(): + """Test that all entries are in the doc.""" + if lapack.__doc__ is None: # just in case there is a python -OO + pytest.skip('lapack.__doc__ is None') + names = set(lapack.__doc__.split()) + ignore_list = { + "absolute_import", + "clapack", + "division", + "find_best_lapack_type", + "flapack", + "print_function", + "HAS_ILP64", + "np", + } + missing = list() + for name in dir(lapack): + if (not name.startswith('_') and name not in ignore_list and + name not in names): + missing.append(name) + assert missing == [], 'Name(s) missing from lapack.__doc__ or ignore_list' + + +class TestFlapackSimple: + + def test_gebal(self): + a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + a1 = [[1, 0, 0, 3e-4], + [4, 0, 0, 2e-3], + [7, 1, 0, 0], + [0, 1, 0, 0]] + for p in 'sdzc': + f = getattr(flapack, p+'gebal', None) + if f is None: + continue + ba, lo, hi, pivscale, info = f(a) + assert_(not info, repr(info)) + assert_array_almost_equal(ba, a) + assert_equal((lo, hi), (0, len(a[0])-1)) + assert_array_almost_equal(pivscale, np.ones(len(a))) + + ba, lo, hi, pivscale, info = f(a1, permute=1, scale=1) + assert_(not info, repr(info)) + # print(a1) + # print(ba, lo, hi, pivscale) + + def test_gehrd(self): + a = [[-149, -50, -154], + [537, 180, 546], + [-27, -9, -25]] + for p in 'd': + f = getattr(flapack, p+'gehrd', None) + if f is None: + continue + ht, tau, info = f(a) + assert_(not info, repr(info)) + + def test_trsyl(self): + a = np.array([[1, 2], [0, 4]]) + b = np.array([[5, 6], [0, 8]]) + c = np.array([[9, 10], [11, 12]]) + trans = 'T' + + # Test single and double implementations, including most + # of the options + for dtype in 'fdFD': + a1, b1, c1 = a.astype(dtype), b.astype(dtype), c.astype(dtype) + trsyl, = get_lapack_funcs(('trsyl',), (a1,)) + if dtype.isupper(): # is complex dtype + a1[0] += 1j + trans = 'C' + + x, scale, info = trsyl(a1, b1, c1) + assert_array_almost_equal(np.dot(a1, x) + np.dot(x, b1), + scale * c1) + + x, scale, info = trsyl(a1, b1, c1, trana=trans, tranb=trans) + assert_array_almost_equal( + np.dot(a1.conjugate().T, x) + np.dot(x, b1.conjugate().T), + scale * c1, decimal=4) + + x, scale, info = trsyl(a1, b1, c1, isgn=-1) + assert_array_almost_equal(np.dot(a1, x) - np.dot(x, b1), + scale * c1, decimal=4) + + def test_lange(self): + a = np.array([ + [-149, -50, -154], + [537, 180, 546], + [-27, -9, -25]]) + + for dtype in 'fdFD': + for norm_str in 'Mm1OoIiFfEe': + a1 = a.astype(dtype) + if dtype.isupper(): + # is complex dtype + a1[0, 0] += 1j + + lange, = get_lapack_funcs(('lange',), (a1,)) + value = lange(norm_str, a1) + + if norm_str in 'FfEe': + if dtype in 'Ff': + decimal = 3 + else: + decimal = 7 + ref = np.sqrt(np.sum(np.square(np.abs(a1)))) + assert_almost_equal(value, ref, decimal) + else: + if norm_str in 'Mm': + ref = np.max(np.abs(a1)) + elif norm_str in '1Oo': + ref = np.max(np.sum(np.abs(a1), axis=0)) + elif norm_str in 'Ii': + ref = np.max(np.sum(np.abs(a1), axis=1)) + + assert_equal(value, ref) + + +class TestLapack: + + def test_flapack(self): + if hasattr(flapack, 'empty_module'): + # flapack module is empty + pass + + def test_clapack(self): + if hasattr(clapack, 'empty_module'): + # clapack module is empty + pass + + +class TestLeastSquaresSolvers: + + def test_gels(self): + seed(1234) + # Test fat/tall matrix argument handling - gh-issue #8329 + for ind, dtype in enumerate(DTYPES): + m = 10 + n = 20 + nrhs = 1 + a1 = rand(m, n).astype(dtype) + b1 = rand(n).astype(dtype) + gls, glslw = get_lapack_funcs(('gels', 'gels_lwork'), dtype=dtype) + + # Request of sizes + lwork = _compute_lwork(glslw, m, n, nrhs) + _, _, info = gls(a1, b1, lwork=lwork) + assert_(info >= 0) + _, _, info = gls(a1, b1, trans='TTCC'[ind], lwork=lwork) + assert_(info >= 0) + + for dtype in REAL_DTYPES: + a1 = np.array([[1.0, 2.0], + [4.0, 5.0], + [7.0, 8.0]], dtype=dtype) + b1 = np.array([16.0, 17.0, 20.0], dtype=dtype) + gels, gels_lwork, geqrf = get_lapack_funcs( + ('gels', 'gels_lwork', 'geqrf'), (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + lwork = _compute_lwork(gels_lwork, m, n, nrhs) + + lqr, x, info = gels(a1, b1, lwork=lwork) + assert_allclose(x[:-1], np.array([-14.333333333333323, + 14.999999999999991], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + lqr_truth, _, _, _ = geqrf(a1) + assert_array_equal(lqr, lqr_truth) + + for dtype in COMPLEX_DTYPES: + a1 = np.array([[1.0+4.0j, 2.0], + [4.0+0.5j, 5.0-3.0j], + [7.0-2.0j, 8.0+0.7j]], dtype=dtype) + b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype) + gels, gels_lwork, geqrf = get_lapack_funcs( + ('gels', 'gels_lwork', 'geqrf'), (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + lwork = _compute_lwork(gels_lwork, m, n, nrhs) + + lqr, x, info = gels(a1, b1, lwork=lwork) + assert_allclose(x[:-1], + np.array([1.161753632288328-1.901075709391912j, + 1.735882340522193+1.521240901196909j], + dtype=dtype), rtol=25*np.finfo(dtype).eps) + lqr_truth, _, _, _ = geqrf(a1) + assert_array_equal(lqr, lqr_truth) + + def test_gelsd(self): + for dtype in REAL_DTYPES: + a1 = np.array([[1.0, 2.0], + [4.0, 5.0], + [7.0, 8.0]], dtype=dtype) + b1 = np.array([16.0, 17.0, 20.0], dtype=dtype) + gelsd, gelsd_lwork = get_lapack_funcs(('gelsd', 'gelsd_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, iwork, info = gelsd_lwork(m, n, nrhs, -1) + lwork = int(np.real(work)) + iwork_size = iwork + + x, s, rank, info = gelsd(a1, b1, lwork, iwork_size, + -1, False, False) + assert_allclose(x[:-1], np.array([-14.333333333333323, + 14.999999999999991], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + assert_allclose(s, np.array([12.596017180511966, + 0.583396253199685], dtype=dtype), + rtol=25*np.finfo(dtype).eps) + + for dtype in COMPLEX_DTYPES: + a1 = np.array([[1.0+4.0j, 2.0], + [4.0+0.5j, 5.0-3.0j], + [7.0-2.0j, 8.0+0.7j]], dtype=dtype) + b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype) + gelsd, gelsd_lwork = get_lapack_funcs(('gelsd', 'gelsd_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, rwork, iwork, info = gelsd_lwork(m, n, nrhs, -1) + lwork = int(np.real(work)) + rwork_size = int(rwork) + iwork_size = iwork + + x, s, rank, info = gelsd(a1, b1, lwork, rwork_size, iwork_size, + -1, False, False) + assert_allclose(x[:-1], + np.array([1.161753632288328-1.901075709391912j, + 1.735882340522193+1.521240901196909j], + dtype=dtype), rtol=25*np.finfo(dtype).eps) + assert_allclose(s, + np.array([13.035514762572043, 4.337666985231382], + dtype=dtype), rtol=25*np.finfo(dtype).eps) + + def test_gelss(self): + + for dtype in REAL_DTYPES: + a1 = np.array([[1.0, 2.0], + [4.0, 5.0], + [7.0, 8.0]], dtype=dtype) + b1 = np.array([16.0, 17.0, 20.0], dtype=dtype) + gelss, gelss_lwork = get_lapack_funcs(('gelss', 'gelss_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, info = gelss_lwork(m, n, nrhs, -1) + lwork = int(np.real(work)) + + v, x, s, rank, work, info = gelss(a1, b1, -1, lwork, False, False) + assert_allclose(x[:-1], np.array([-14.333333333333323, + 14.999999999999991], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + assert_allclose(s, np.array([12.596017180511966, + 0.583396253199685], dtype=dtype), + rtol=25*np.finfo(dtype).eps) + + for dtype in COMPLEX_DTYPES: + a1 = np.array([[1.0+4.0j, 2.0], + [4.0+0.5j, 5.0-3.0j], + [7.0-2.0j, 8.0+0.7j]], dtype=dtype) + b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype) + gelss, gelss_lwork = get_lapack_funcs(('gelss', 'gelss_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, info = gelss_lwork(m, n, nrhs, -1) + lwork = int(np.real(work)) + + v, x, s, rank, work, info = gelss(a1, b1, -1, lwork, False, False) + assert_allclose(x[:-1], + np.array([1.161753632288328-1.901075709391912j, + 1.735882340522193+1.521240901196909j], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + assert_allclose(s, np.array([13.035514762572043, + 4.337666985231382], dtype=dtype), + rtol=25*np.finfo(dtype).eps) + + def test_gelsy(self): + + for dtype in REAL_DTYPES: + a1 = np.array([[1.0, 2.0], + [4.0, 5.0], + [7.0, 8.0]], dtype=dtype) + b1 = np.array([16.0, 17.0, 20.0], dtype=dtype) + gelsy, gelsy_lwork = get_lapack_funcs(('gelsy', 'gelss_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, info = gelsy_lwork(m, n, nrhs, 10*np.finfo(dtype).eps) + lwork = int(np.real(work)) + + jptv = np.zeros((a1.shape[1], 1), dtype=np.int32) + v, x, j, rank, info = gelsy(a1, b1, jptv, np.finfo(dtype).eps, + lwork, False, False) + assert_allclose(x[:-1], np.array([-14.333333333333323, + 14.999999999999991], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + + for dtype in COMPLEX_DTYPES: + a1 = np.array([[1.0+4.0j, 2.0], + [4.0+0.5j, 5.0-3.0j], + [7.0-2.0j, 8.0+0.7j]], dtype=dtype) + b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype) + gelsy, gelsy_lwork = get_lapack_funcs(('gelsy', 'gelss_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, info = gelsy_lwork(m, n, nrhs, 10*np.finfo(dtype).eps) + lwork = int(np.real(work)) + + jptv = np.zeros((a1.shape[1], 1), dtype=np.int32) + v, x, j, rank, info = gelsy(a1, b1, jptv, np.finfo(dtype).eps, + lwork, False, False) + assert_allclose(x[:-1], + np.array([1.161753632288328-1.901075709391912j, + 1.735882340522193+1.521240901196909j], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + + +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('shape', [(3, 4), (5, 2), (2**18, 2**18)]) +def test_geqrf_lwork(dtype, shape): + geqrf_lwork = get_lapack_funcs(('geqrf_lwork'), dtype=dtype) + m, n = shape + lwork, info = geqrf_lwork(m=m, n=n) + assert_equal(info, 0) + + +class TestRegression: + + def test_ticket_1645(self): + # Check that RQ routines have correct lwork + for dtype in DTYPES: + a = np.zeros((300, 2), dtype=dtype) + + gerqf, = get_lapack_funcs(['gerqf'], [a]) + assert_raises(Exception, gerqf, a, lwork=2) + rq, tau, work, info = gerqf(a) + + if dtype in REAL_DTYPES: + orgrq, = get_lapack_funcs(['orgrq'], [a]) + assert_raises(Exception, orgrq, rq[-2:], tau, lwork=1) + orgrq(rq[-2:], tau, lwork=2) + elif dtype in COMPLEX_DTYPES: + ungrq, = get_lapack_funcs(['ungrq'], [a]) + assert_raises(Exception, ungrq, rq[-2:], tau, lwork=1) + ungrq(rq[-2:], tau, lwork=2) + + +class TestDpotr: + def test_gh_2691(self): + # 'lower' argument of dportf/dpotri + for lower in [True, False]: + for clean in [True, False]: + np.random.seed(42) + x = np.random.normal(size=(3, 3)) + a = x.dot(x.T) + + dpotrf, dpotri = get_lapack_funcs(("potrf", "potri"), (a, )) + + c, info = dpotrf(a, lower, clean=clean) + dpt = dpotri(c, lower)[0] + + if lower: + assert_allclose(np.tril(dpt), np.tril(inv(a))) + else: + assert_allclose(np.triu(dpt), np.triu(inv(a))) + + +class TestDlasd4: + def test_sing_val_update(self): + + sigmas = np.array([4., 3., 2., 0]) + m_vec = np.array([3.12, 5.7, -4.8, -2.2]) + + M = np.hstack((np.vstack((np.diag(sigmas[0:-1]), + np.zeros((1, len(m_vec) - 1)))), + m_vec[:, np.newaxis])) + SM = svd(M, full_matrices=False, compute_uv=False, overwrite_a=False, + check_finite=False) + + it_len = len(sigmas) + sgm = np.concatenate((sigmas[::-1], [sigmas[0] + it_len*norm(m_vec)])) + mvc = np.concatenate((m_vec[::-1], (0,))) + + lasd4 = get_lapack_funcs('lasd4', (sigmas,)) + + roots = [] + for i in range(0, it_len): + res = lasd4(i, sgm, mvc) + roots.append(res[1]) + + assert_((res[3] <= 0), "LAPACK root finding dlasd4 failed to find \ + the singular value %i" % i) + roots = np.array(roots)[::-1] + + assert_((not np.any(np.isnan(roots)), "There are NaN roots")) + assert_allclose(SM, roots, atol=100*np.finfo(np.float64).eps, + rtol=100*np.finfo(np.float64).eps) + + +class TestTbtrs: + + @pytest.mark.parametrize('dtype', DTYPES) + def test_nag_example_f07vef_f07vsf(self, dtype): + """Test real (f07vef) and complex (f07vsf) examples from NAG + + Examples available from: + * https://www.nag.com/numeric/fl/nagdoc_latest/html/f07/f07vef.html + * https://www.nag.com/numeric/fl/nagdoc_latest/html/f07/f07vsf.html + + """ + if dtype in REAL_DTYPES: + ab = np.array([[-4.16, 4.78, 6.32, 0.16], + [-2.25, 5.86, -4.82, 0]], + dtype=dtype) + b = np.array([[-16.64, -4.16], + [-13.78, -16.59], + [13.10, -4.94], + [-14.14, -9.96]], + dtype=dtype) + x_out = np.array([[4, 1], + [-1, -3], + [3, 2], + [2, -2]], + dtype=dtype) + elif dtype in COMPLEX_DTYPES: + ab = np.array([[-1.94+4.43j, 4.12-4.27j, 0.43-2.66j, 0.44+0.1j], + [-3.39+3.44j, -1.84+5.52j, 1.74 - 0.04j, 0], + [1.62+3.68j, -2.77-1.93j, 0, 0]], + dtype=dtype) + b = np.array([[-8.86 - 3.88j, -24.09 - 5.27j], + [-15.57 - 23.41j, -57.97 + 8.14j], + [-7.63 + 22.78j, 19.09 - 29.51j], + [-14.74 - 2.40j, 19.17 + 21.33j]], + dtype=dtype) + x_out = np.array([[2j, 1 + 5j], + [1 - 3j, -7 - 2j], + [-4.001887 - 4.988417j, 3.026830 + 4.003182j], + [1.996158 - 1.045105j, -6.103357 - 8.986653j]], + dtype=dtype) + else: + raise ValueError(f"Datatype {dtype} not understood.") + + tbtrs = get_lapack_funcs(('tbtrs'), dtype=dtype) + x, info = tbtrs(ab=ab, b=b, uplo='L') + assert_equal(info, 0) + assert_allclose(x, x_out, rtol=0, atol=1e-5) + + @pytest.mark.parametrize('dtype,trans', + [(dtype, trans) + for dtype in DTYPES for trans in ['N', 'T', 'C'] + if not (trans == 'C' and dtype in REAL_DTYPES)]) + @pytest.mark.parametrize('uplo', ['U', 'L']) + @pytest.mark.parametrize('diag', ['N', 'U']) + def test_random_matrices(self, dtype, trans, uplo, diag): + rng = np.random.RandomState(1724) + + # n, nrhs, kd are used to specify A and b. + # A is of shape n x n with kd super/sub-diagonals + # b is of shape n x nrhs matrix + n, nrhs, kd = 4, 3, 2 + tbtrs = get_lapack_funcs('tbtrs', dtype=dtype) + + is_upper = (uplo == 'U') + ku = kd * is_upper + kl = kd - ku + + # Construct the diagonal and kd super/sub diagonals of A with + # the corresponding offsets. + band_offsets = range(ku, -kl - 1, -1) + band_widths = [n - abs(x) for x in band_offsets] + bands = [generate_random_dtype_array((width,), dtype, rng) + for width in band_widths] + + if diag == 'U': # A must be unit triangular + bands[ku] = np.ones(n, dtype=dtype) + + # Construct the diagonal banded matrix A from the bands and offsets. + a = sps.diags(bands, band_offsets, format='dia') + + # Convert A into banded storage form + ab = np.zeros((kd + 1, n), dtype) + for row, k in enumerate(band_offsets): + ab[row, max(k, 0):min(n+k, n)] = a.diagonal(k) + + # The RHS values. + b = generate_random_dtype_array((n, nrhs), dtype, rng) + + x, info = tbtrs(ab=ab, b=b, uplo=uplo, trans=trans, diag=diag) + assert_equal(info, 0) + + if trans == 'N': + assert_allclose(a @ x, b, rtol=5e-5) + elif trans == 'T': + assert_allclose(a.T @ x, b, rtol=5e-5) + elif trans == 'C': + assert_allclose(a.T.conjugate() @ x, b, rtol=5e-5) + else: + raise ValueError('Invalid trans argument') + + @pytest.mark.parametrize('uplo,trans,diag', + [['U', 'N', 'Invalid'], + ['U', 'Invalid', 'N'], + ['Invalid', 'N', 'N']]) + def test_invalid_argument_raises_exception(self, uplo, trans, diag): + """Test if invalid values of uplo, trans and diag raise exceptions""" + # Argument checks occur independently of used datatype. + # This mean we must not parameterize all available datatypes. + tbtrs = get_lapack_funcs('tbtrs', dtype=np.float64) + ab = rand(4, 2) + b = rand(2, 4) + assert_raises(Exception, tbtrs, ab, b, uplo, trans, diag) + + def test_zero_element_in_diagonal(self): + """Test if a matrix with a zero diagonal element is singular + + If the i-th diagonal of A is zero, ?tbtrs should return `i` in `info` + indicating the provided matrix is singular. + + Note that ?tbtrs requires the matrix A to be stored in banded form. + In this form the diagonal corresponds to the last row.""" + ab = np.ones((3, 4), dtype=float) + b = np.ones(4, dtype=float) + tbtrs = get_lapack_funcs('tbtrs', dtype=float) + + ab[-1, 3] = 0 + _, info = tbtrs(ab=ab, b=b, uplo='U') + assert_equal(info, 4) + + @pytest.mark.parametrize('ldab,n,ldb,nrhs', [ + (5, 5, 0, 5), + (5, 5, 3, 5) + ]) + def test_invalid_matrix_shapes(self, ldab, n, ldb, nrhs): + """Test ?tbtrs fails correctly if shapes are invalid.""" + ab = np.ones((ldab, n), dtype=float) + b = np.ones((ldb, nrhs), dtype=float) + tbtrs = get_lapack_funcs('tbtrs', dtype=float) + assert_raises(Exception, tbtrs, ab, b) + + + +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('norm', ['I', '1', 'O']) +@pytest.mark.parametrize('uplo', ['U', 'L']) +@pytest.mark.parametrize('diag', ['N', 'U']) +@pytest.mark.parametrize('n', [3, 10]) +def test_trcon(dtype, norm, uplo, diag, n): + # Simple way to get deterministic (unlike `hash`) integer seed based on arguments + random.seed(f"{dtype}{norm}{uplo}{diag}{n}") + rng = np.random.default_rng(random.randint(0, 9999999999999)) + + A = rng.random(size=(n, n)) + rng.random(size=(n, n))*1j + # make the condition numbers more interesting + offset = rng.permuted(np.logspace(0, rng.integers(0, 10), n)) + A += offset + A = A.real if np.issubdtype(dtype, np.floating) else A + A = np.triu(A) if uplo == 'U' else np.tril(A) + if diag == 'U': + A /= np.diag(A)[:, np.newaxis] + A = A.astype(dtype) + + trcon = get_lapack_funcs('trcon', (A,)) + res, _ = trcon(A, norm=norm, uplo=uplo, diag=diag) + + if norm == 'I': + norm_A = np.linalg.norm(A, ord=np.inf) + norm_inv_A = np.linalg.norm(np.linalg.inv(A), ord=np.inf) + ref = 1 / (norm_A * norm_inv_A) + else: + anorm = np.abs(A).sum(axis=0).max() + gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,)) + lu, ipvt, info = getrf(A) + ref, _ = gecon(lu, anorm, norm=norm) + + # This is an estimate of reciprocal condition number; we just need order of + # magnitude. In testing, we observed that much smaller rtol is OK in almost + # all cases... but sometimes it isn't. + rtol = 1 # np.finfo(dtype).eps**0.75 + assert_allclose(res, ref, rtol=rtol) + + +def test_lartg(): + for dtype in 'fdFD': + lartg = get_lapack_funcs('lartg', dtype=dtype) + + f = np.array(3, dtype) + g = np.array(4, dtype) + + if np.iscomplexobj(g): + g *= 1j + + cs, sn, r = lartg(f, g) + + assert_allclose(cs, 3.0/5.0) + assert_allclose(r, 5.0) + + if np.iscomplexobj(g): + assert_allclose(sn, -4.0j/5.0) + assert_(isinstance(r, complex)) + assert_(isinstance(cs, float)) + else: + assert_allclose(sn, 4.0/5.0) + + +def test_rot(): + # srot, drot from blas and crot and zrot from lapack. + + for dtype in 'fdFD': + c = 0.6 + s = 0.8 + + u = np.full(4, 3, dtype) + v = np.full(4, 4, dtype) + atol = 10**-(np.finfo(dtype).precision-1) + + if dtype in 'fd': + rot = get_blas_funcs('rot', dtype=dtype) + f = 4 + else: + rot = get_lapack_funcs('rot', dtype=dtype) + s *= -1j + v *= 1j + f = 4j + + assert_allclose(rot(u, v, c, s), [[5, 5, 5, 5], + [0, 0, 0, 0]], atol=atol) + assert_allclose(rot(u, v, c, s, n=2), [[5, 5, 3, 3], + [0, 0, f, f]], atol=atol) + assert_allclose(rot(u, v, c, s, offx=2, offy=2), + [[3, 3, 5, 5], [f, f, 0, 0]], atol=atol) + assert_allclose(rot(u, v, c, s, incx=2, offy=2, n=2), + [[5, 3, 5, 3], [f, f, 0, 0]], atol=atol) + assert_allclose(rot(u, v, c, s, offx=2, incy=2, n=2), + [[3, 3, 5, 5], [0, f, 0, f]], atol=atol) + assert_allclose(rot(u, v, c, s, offx=2, incx=2, offy=2, incy=2, n=1), + [[3, 3, 5, 3], [f, f, 0, f]], atol=atol) + assert_allclose(rot(u, v, c, s, incx=-2, incy=-2, n=2), + [[5, 3, 5, 3], [0, f, 0, f]], atol=atol) + + a, b = rot(u, v, c, s, overwrite_x=1, overwrite_y=1) + assert_(a is u) + assert_(b is v) + assert_allclose(a, [5, 5, 5, 5], atol=atol) + assert_allclose(b, [0, 0, 0, 0], atol=atol) + + +def test_larfg_larf(): + np.random.seed(1234) + a0 = np.random.random((4, 4)) + a0 = a0.T.dot(a0) + + a0j = np.random.random((4, 4)) + 1j*np.random.random((4, 4)) + a0j = a0j.T.conj().dot(a0j) + + # our test here will be to do one step of reducing a hermetian matrix to + # tridiagonal form using householder transforms. + + for dtype in 'fdFD': + larfg, larf = get_lapack_funcs(['larfg', 'larf'], dtype=dtype) + + if dtype in 'FD': + a = a0j.copy() + else: + a = a0.copy() + + # generate a householder transform to clear a[2:,0] + alpha, x, tau = larfg(a.shape[0]-1, a[1, 0], a[2:, 0]) + + # create expected output + expected = np.zeros_like(a[:, 0]) + expected[0] = a[0, 0] + expected[1] = alpha + + # assemble householder vector + v = np.zeros_like(a[1:, 0]) + v[0] = 1.0 + v[1:] = x + + # apply transform from the left + a[1:, :] = larf(v, tau.conjugate(), a[1:, :], np.zeros(a.shape[1])) + + # apply transform from the right + a[:, 1:] = larf(v, tau, a[:, 1:], np.zeros(a.shape[0]), side='R') + + assert_allclose(a[:, 0], expected, atol=1e-5) + assert_allclose(a[0, :], expected, atol=1e-5) + + +def test_sgesdd_lwork_bug_workaround(): + # Test that SGESDD lwork is sufficiently large for LAPACK. + # + # This checks that _compute_lwork() correctly works around a bug in + # LAPACK versions older than 3.10.1. + + sgesdd_lwork = get_lapack_funcs('gesdd_lwork', dtype=np.float32, + ilp64='preferred') + n = 9537 + lwork = _compute_lwork(sgesdd_lwork, n, n, + compute_uv=True, full_matrices=True) + # If we called the Fortran function SGESDD directly with IWORK=-1, the + # LAPACK bug would result in lwork being 272929856, which was too small. + # (The result was returned in a single precision float, which does not + # have sufficient precision to represent the exact integer value that it + # computed internally.) The work-around implemented in _compute_lwork() + # will convert that to 272929888. If we are using LAPACK 3.10.1 or later + # (such as in OpenBLAS 0.3.21 or later), the work-around will return + # 272929920, because it does not know which version of LAPACK is being + # used, so it always applies the correction to whatever it is given. We + # will accept either 272929888 or 272929920. + # Note that the acceptable values are a LAPACK implementation detail. + # If a future version of LAPACK changes how SGESDD works, and therefore + # changes the required LWORK size, the acceptable values might have to + # be updated. + assert lwork == 272929888 or lwork == 272929920 + + +class TestSytrd: + @pytest.mark.parametrize('dtype', REAL_DTYPES) + def test_sytrd_with_zero_dim_array(self, dtype): + # Assert that a 0x0 matrix raises an error + A = np.zeros((0, 0), dtype=dtype) + sytrd = get_lapack_funcs('sytrd', (A,)) + assert_raises(ValueError, sytrd, A) + + @pytest.mark.parametrize('dtype', REAL_DTYPES) + @pytest.mark.parametrize('n', (1, 3)) + def test_sytrd(self, dtype, n): + A = np.zeros((n, n), dtype=dtype) + + sytrd, sytrd_lwork = \ + get_lapack_funcs(('sytrd', 'sytrd_lwork'), (A,)) + + # some upper triangular array + A[np.triu_indices_from(A)] = \ + np.arange(1, n*(n+1)//2+1, dtype=dtype) + + # query lwork + lwork, info = sytrd_lwork(n) + assert_equal(info, 0) + + # check lower=1 behavior (shouldn't do much since the matrix is + # upper triangular) + data, d, e, tau, info = sytrd(A, lower=1, lwork=lwork) + assert_equal(info, 0) + + assert_allclose(data, A, atol=5*np.finfo(dtype).eps, rtol=1.0) + assert_allclose(d, np.diag(A)) + assert_allclose(e, 0.0) + assert_allclose(tau, 0.0) + + # and now for the proper test (lower=0 is the default) + data, d, e, tau, info = sytrd(A, lwork=lwork) + assert_equal(info, 0) + + # assert Q^T*A*Q = tridiag(e, d, e) + + # build tridiagonal matrix + T = np.zeros_like(A, dtype=dtype) + k = np.arange(A.shape[0]) + T[k, k] = d + k2 = np.arange(A.shape[0]-1) + T[k2+1, k2] = e + T[k2, k2+1] = e + + # build Q + Q = np.eye(n, n, dtype=dtype) + for i in range(n-1): + v = np.zeros(n, dtype=dtype) + v[:i] = data[:i, i+1] + v[i] = 1.0 + H = np.eye(n, n, dtype=dtype) - tau[i] * np.outer(v, v) + Q = np.dot(H, Q) + + # Make matrix fully symmetric + i_lower = np.tril_indices(n, -1) + A[i_lower] = A.T[i_lower] + + QTAQ = np.dot(Q.T, np.dot(A, Q)) + + # disable rtol here since some values in QTAQ and T are very close + # to 0. + assert_allclose(QTAQ, T, atol=5*np.finfo(dtype).eps, rtol=1.0) + + +class TestHetrd: + @pytest.mark.parametrize('complex_dtype', COMPLEX_DTYPES) + def test_hetrd_with_zero_dim_array(self, complex_dtype): + # Assert that a 0x0 matrix raises an error + A = np.zeros((0, 0), dtype=complex_dtype) + hetrd = get_lapack_funcs('hetrd', (A,)) + assert_raises(ValueError, hetrd, A) + + @pytest.mark.parametrize('real_dtype,complex_dtype', + zip(REAL_DTYPES, COMPLEX_DTYPES)) + @pytest.mark.parametrize('n', (1, 3)) + def test_hetrd(self, n, real_dtype, complex_dtype): + A = np.zeros((n, n), dtype=complex_dtype) + hetrd, hetrd_lwork = \ + get_lapack_funcs(('hetrd', 'hetrd_lwork'), (A,)) + + # some upper triangular array + A[np.triu_indices_from(A)] = ( + np.arange(1, n*(n+1)//2+1, dtype=real_dtype) + + 1j * np.arange(1, n*(n+1)//2+1, dtype=real_dtype) + ) + np.fill_diagonal(A, np.real(np.diag(A))) + + # test query lwork + for x in [0, 1]: + _, info = hetrd_lwork(n, lower=x) + assert_equal(info, 0) + # lwork returns complex which segfaults hetrd call (gh-10388) + # use the safe and recommended option + lwork = _compute_lwork(hetrd_lwork, n) + + # check lower=1 behavior (shouldn't do much since the matrix is + # upper triangular) + data, d, e, tau, info = hetrd(A, lower=1, lwork=lwork) + assert_equal(info, 0) + + assert_allclose(data, A, atol=5*np.finfo(real_dtype).eps, rtol=1.0) + + assert_allclose(d, np.real(np.diag(A))) + assert_allclose(e, 0.0) + assert_allclose(tau, 0.0) + + # and now for the proper test (lower=0 is the default) + data, d, e, tau, info = hetrd(A, lwork=lwork) + assert_equal(info, 0) + + # assert Q^T*A*Q = tridiag(e, d, e) + + # build tridiagonal matrix + T = np.zeros_like(A, dtype=real_dtype) + k = np.arange(A.shape[0], dtype=int) + T[k, k] = d + k2 = np.arange(A.shape[0]-1, dtype=int) + T[k2+1, k2] = e + T[k2, k2+1] = e + + # build Q + Q = np.eye(n, n, dtype=complex_dtype) + for i in range(n-1): + v = np.zeros(n, dtype=complex_dtype) + v[:i] = data[:i, i+1] + v[i] = 1.0 + H = np.eye(n, n, dtype=complex_dtype) \ + - tau[i] * np.outer(v, np.conj(v)) + Q = np.dot(H, Q) + + # Make matrix fully Hermitian + i_lower = np.tril_indices(n, -1) + A[i_lower] = np.conj(A.T[i_lower]) + + QHAQ = np.dot(np.conj(Q.T), np.dot(A, Q)) + + # disable rtol here since some values in QTAQ and T are very close + # to 0. + assert_allclose( + QHAQ, T, atol=10*np.finfo(real_dtype).eps, rtol=1.0 + ) + + +def test_gglse(): + # Example data taken from NAG manual + for ind, dtype in enumerate(DTYPES): + # DTYPES = gglse + func, func_lwork = get_lapack_funcs(('gglse', 'gglse_lwork'), + dtype=dtype) + lwork = _compute_lwork(func_lwork, m=6, n=4, p=2) + # For gglse + if ind < 2: + a = np.array([[-0.57, -1.28, -0.39, 0.25], + [-1.93, 1.08, -0.31, -2.14], + [2.30, 0.24, 0.40, -0.35], + [-1.93, 0.64, -0.66, 0.08], + [0.15, 0.30, 0.15, -2.13], + [-0.02, 1.03, -1.43, 0.50]], dtype=dtype) + c = np.array([-1.50, -2.14, 1.23, -0.54, -1.68, 0.82], dtype=dtype) + d = np.array([0., 0.], dtype=dtype) + # For gglse + else: + a = np.array([[0.96-0.81j, -0.03+0.96j, -0.91+2.06j, -0.05+0.41j], + [-0.98+1.98j, -1.20+0.19j, -0.66+0.42j, -0.81+0.56j], + [0.62-0.46j, 1.01+0.02j, 0.63-0.17j, -1.11+0.60j], + [0.37+0.38j, 0.19-0.54j, -0.98-0.36j, 0.22-0.20j], + [0.83+0.51j, 0.20+0.01j, -0.17-0.46j, 1.47+1.59j], + [1.08-0.28j, 0.20-0.12j, -0.07+1.23j, 0.26+0.26j]]) + c = np.array([[-2.54+0.09j], + [1.65-2.26j], + [-2.11-3.96j], + [1.82+3.30j], + [-6.41+3.77j], + [2.07+0.66j]]) + d = np.zeros(2, dtype=dtype) + + b = np.array([[1., 0., -1., 0.], [0., 1., 0., -1.]], dtype=dtype) + + _, _, _, result, _ = func(a, b, c, d, lwork=lwork) + if ind < 2: + expected = np.array([0.48904455, + 0.99754786, + 0.48904455, + 0.99754786]) + else: + expected = np.array([1.08742917-1.96205783j, + -0.74093902+3.72973919j, + 1.08742917-1.96205759j, + -0.74093896+3.72973895j]) + assert_array_almost_equal(result, expected, decimal=4) + + +def test_sycon_hecon(): + seed(1234) + for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES): + # DTYPES + COMPLEX DTYPES = sycon + hecon + n = 10 + # For sycon + if ind < 4: + func_lwork = get_lapack_funcs('sytrf_lwork', dtype=dtype) + funcon, functrf = get_lapack_funcs(('sycon', 'sytrf'), dtype=dtype) + A = (rand(n, n)).astype(dtype) + # For hecon + else: + func_lwork = get_lapack_funcs('hetrf_lwork', dtype=dtype) + funcon, functrf = get_lapack_funcs(('hecon', 'hetrf'), dtype=dtype) + A = (rand(n, n) + rand(n, n)*1j).astype(dtype) + + # Since sycon only refers to upper/lower part, conj() is safe here. + A = (A + A.conj().T)/2 + 2*np.eye(n, dtype=dtype) + + anorm = norm(A, 1) + lwork = _compute_lwork(func_lwork, n) + ldu, ipiv, _ = functrf(A, lwork=lwork, lower=1) + rcond, _ = funcon(a=ldu, ipiv=ipiv, anorm=anorm, lower=1) + # The error is at most 1-fold + assert_(abs(1/rcond - np.linalg.cond(A, p=1))*rcond < 1) + + +def test_sygst(): + seed(1234) + for ind, dtype in enumerate(REAL_DTYPES): + # DTYPES = sygst + n = 10 + + potrf, sygst, syevd, sygvd = get_lapack_funcs(('potrf', 'sygst', + 'syevd', 'sygvd'), + dtype=dtype) + + A = rand(n, n).astype(dtype) + A = (A + A.T)/2 + # B must be positive definite + B = rand(n, n).astype(dtype) + B = (B + B.T)/2 + 2 * np.eye(n, dtype=dtype) + + # Perform eig (sygvd) + eig_gvd, _, info = sygvd(A, B) + assert_(info == 0) + + # Convert to std problem potrf + b, info = potrf(B) + assert_(info == 0) + a, info = sygst(A, b) + assert_(info == 0) + + eig, _, info = syevd(a) + assert_(info == 0) + assert_allclose(eig, eig_gvd, rtol=1.2e-4) + + +def test_hegst(): + seed(1234) + for ind, dtype in enumerate(COMPLEX_DTYPES): + # DTYPES = hegst + n = 10 + + potrf, hegst, heevd, hegvd = get_lapack_funcs(('potrf', 'hegst', + 'heevd', 'hegvd'), + dtype=dtype) + + A = rand(n, n).astype(dtype) + 1j * rand(n, n).astype(dtype) + A = (A + A.conj().T)/2 + # B must be positive definite + B = rand(n, n).astype(dtype) + 1j * rand(n, n).astype(dtype) + B = (B + B.conj().T)/2 + 2 * np.eye(n, dtype=dtype) + + # Perform eig (hegvd) + eig_gvd, _, info = hegvd(A, B) + assert_(info == 0) + + # Convert to std problem potrf + b, info = potrf(B) + assert_(info == 0) + a, info = hegst(A, b) + assert_(info == 0) + + eig, _, info = heevd(a) + assert_(info == 0) + assert_allclose(eig, eig_gvd, rtol=1e-4) + + +def test_tzrzf(): + """ + This test performs an RZ decomposition in which an m x n upper trapezoidal + array M (m <= n) is factorized as M = [R 0] * Z where R is upper triangular + and Z is unitary. + """ + rng = np.random.RandomState(1234) + m, n = 10, 15 + for ind, dtype in enumerate(DTYPES): + tzrzf, tzrzf_lw = get_lapack_funcs(('tzrzf', 'tzrzf_lwork'), + dtype=dtype) + lwork = _compute_lwork(tzrzf_lw, m, n) + + if ind < 2: + A = triu(rng.rand(m, n).astype(dtype)) + else: + A = triu((rng.rand(m, n) + rng.rand(m, n)*1j).astype(dtype)) + + # assert wrong shape arg, f2py returns generic error + assert_raises(Exception, tzrzf, A.T) + rz, tau, info = tzrzf(A, lwork=lwork) + # Check success + assert_(info == 0) + + # Get Z manually for comparison + R = np.hstack((rz[:, :m], np.zeros((m, n-m), dtype=dtype))) + V = np.hstack((np.eye(m, dtype=dtype), rz[:, m:])) + Id = np.eye(n, dtype=dtype) + ref = [Id-tau[x]*V[[x], :].T.dot(V[[x], :].conj()) for x in range(m)] + Z = reduce(np.dot, ref) + assert_allclose(R.dot(Z) - A, zeros_like(A, dtype=dtype), + atol=10*np.spacing(dtype(1.0).real), rtol=0.) + + +def test_tfsm(): + """ + Test for solving a linear system with the coefficient matrix is a + triangular array stored in Full Packed (RFP) format. + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A = triu(rng.rand(n, n) + rng.rand(n, n)*1j + eye(n)).astype(dtype) + trans = 'C' + else: + A = triu(rng.rand(n, n) + eye(n)).astype(dtype) + trans = 'T' + + trttf, tfttr, tfsm = get_lapack_funcs(('trttf', 'tfttr', 'tfsm'), + dtype=dtype) + + Afp, _ = trttf(A) + B = rng.rand(n, 2).astype(dtype) + soln = tfsm(-1, Afp, B) + assert_array_almost_equal(soln, solve(-A, B), + decimal=4 if ind % 2 == 0 else 6) + + soln = tfsm(-1, Afp, B, trans=trans) + assert_array_almost_equal(soln, solve(-A.conj().T, B), + decimal=4 if ind % 2 == 0 else 6) + + # Make A, unit diagonal + A[np.arange(n), np.arange(n)] = dtype(1.) + soln = tfsm(-1, Afp, B, trans=trans, diag='U') + assert_array_almost_equal(soln, solve(-A.conj().T, B), + decimal=4 if ind % 2 == 0 else 6) + + # Change side + B2 = rng.rand(3, n).astype(dtype) + soln = tfsm(-1, Afp, B2, trans=trans, diag='U', side='R') + assert_array_almost_equal(soln, solve(-A, B2.T).conj().T, + decimal=4 if ind % 2 == 0 else 6) + + +def test_ormrz_unmrz(): + """ + This test performs a matrix multiplication with an arbitrary m x n matrix C + and a unitary matrix Q without explicitly forming the array. The array data + is encoded in the rectangular part of A which is obtained from ?TZRZF. Q + size is inferred by m, n, side keywords. + """ + rng = np.random.RandomState(1234) + qm, qn, cn = 10, 15, 15 + for ind, dtype in enumerate(DTYPES): + tzrzf, tzrzf_lw = get_lapack_funcs(('tzrzf', 'tzrzf_lwork'), + dtype=dtype) + lwork_rz = _compute_lwork(tzrzf_lw, qm, qn) + + if ind < 2: + A = triu(rng.rand(qm, qn).astype(dtype)) + C = rng.rand(cn, cn).astype(dtype) + orun_mrz, orun_mrz_lw = get_lapack_funcs(('ormrz', 'ormrz_lwork'), + dtype=dtype) + else: + A = triu((rng.rand(qm, qn) + rng.rand(qm, qn)*1j).astype(dtype)) + C = (rng.rand(cn, cn) + rand(cn, cn)*1j).astype(dtype) + orun_mrz, orun_mrz_lw = get_lapack_funcs(('unmrz', 'unmrz_lwork'), + dtype=dtype) + + lwork_mrz = _compute_lwork(orun_mrz_lw, cn, cn) + rz, tau, info = tzrzf(A, lwork=lwork_rz) + + # Get Q manually for comparison + V = np.hstack((np.eye(qm, dtype=dtype), rz[:, qm:])) + Id = np.eye(qn, dtype=dtype) + ref = [Id-tau[x]*V[[x], :].T.dot(V[[x], :].conj()) for x in range(qm)] + Q = reduce(np.dot, ref) + + # Now that we have Q, we can test whether lapack results agree with + # each case of CQ, CQ^H, QC, and QC^H + trans = 'T' if ind < 2 else 'C' + tol = 10*np.spacing(dtype(1.0).real) + + cq, info = orun_mrz(rz, tau, C, lwork=lwork_mrz) + assert_(info == 0) + assert_allclose(cq - Q.dot(C), zeros_like(C), atol=tol, rtol=0.) + + cq, info = orun_mrz(rz, tau, C, trans=trans, lwork=lwork_mrz) + assert_(info == 0) + assert_allclose(cq - Q.conj().T.dot(C), zeros_like(C), atol=tol, + rtol=0.) + + cq, info = orun_mrz(rz, tau, C, side='R', lwork=lwork_mrz) + assert_(info == 0) + assert_allclose(cq - C.dot(Q), zeros_like(C), atol=tol, rtol=0.) + + cq, info = orun_mrz(rz, tau, C, side='R', trans=trans, lwork=lwork_mrz) + assert_(info == 0) + assert_allclose(cq - C.dot(Q.conj().T), zeros_like(C), atol=tol, + rtol=0.) + + +def test_tfttr_trttf(): + """ + Test conversion routines between the Rectangular Full Packed (RFP) format + and Standard Triangular Array (TR) + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A_full = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + transr = 'C' + else: + A_full = (rng.rand(n, n)).astype(dtype) + transr = 'T' + + trttf, tfttr = get_lapack_funcs(('trttf', 'tfttr'), dtype=dtype) + A_tf_U, info = trttf(A_full) + assert_(info == 0) + A_tf_L, info = trttf(A_full, uplo='L') + assert_(info == 0) + A_tf_U_T, info = trttf(A_full, transr=transr, uplo='U') + assert_(info == 0) + A_tf_L_T, info = trttf(A_full, transr=transr, uplo='L') + assert_(info == 0) + + # Create the RFP array manually (n is even!) + A_tf_U_m = zeros((n+1, n//2), dtype=dtype) + A_tf_U_m[:-1, :] = triu(A_full)[:, n//2:] + A_tf_U_m[n//2+1:, :] += triu(A_full)[:n//2, :n//2].conj().T + + A_tf_L_m = zeros((n+1, n//2), dtype=dtype) + A_tf_L_m[1:, :] = tril(A_full)[:, :n//2] + A_tf_L_m[:n//2, :] += tril(A_full)[n//2:, n//2:].conj().T + + assert_array_almost_equal(A_tf_U, A_tf_U_m.reshape(-1, order='F')) + assert_array_almost_equal(A_tf_U_T, + A_tf_U_m.conj().T.reshape(-1, order='F')) + + assert_array_almost_equal(A_tf_L, A_tf_L_m.reshape(-1, order='F')) + assert_array_almost_equal(A_tf_L_T, + A_tf_L_m.conj().T.reshape(-1, order='F')) + + # Get the original array from RFP + A_tr_U, info = tfttr(n, A_tf_U) + assert_(info == 0) + A_tr_L, info = tfttr(n, A_tf_L, uplo='L') + assert_(info == 0) + A_tr_U_T, info = tfttr(n, A_tf_U_T, transr=transr, uplo='U') + assert_(info == 0) + A_tr_L_T, info = tfttr(n, A_tf_L_T, transr=transr, uplo='L') + assert_(info == 0) + + assert_array_almost_equal(A_tr_U, triu(A_full)) + assert_array_almost_equal(A_tr_U_T, triu(A_full)) + assert_array_almost_equal(A_tr_L, tril(A_full)) + assert_array_almost_equal(A_tr_L_T, tril(A_full)) + + +def test_tpttr_trttp(): + """ + Test conversion routines between the Rectangular Full Packed (RFP) format + and Standard Triangular Array (TR) + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A_full = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + else: + A_full = (rng.rand(n, n)).astype(dtype) + + trttp, tpttr = get_lapack_funcs(('trttp', 'tpttr'), dtype=dtype) + A_tp_U, info = trttp(A_full) + assert_(info == 0) + A_tp_L, info = trttp(A_full, uplo='L') + assert_(info == 0) + + # Create the TP array manually + inds = tril_indices(n) + A_tp_U_m = zeros(n*(n+1)//2, dtype=dtype) + A_tp_U_m[:] = (triu(A_full).T)[inds] + + inds = triu_indices(n) + A_tp_L_m = zeros(n*(n+1)//2, dtype=dtype) + A_tp_L_m[:] = (tril(A_full).T)[inds] + + assert_array_almost_equal(A_tp_U, A_tp_U_m) + assert_array_almost_equal(A_tp_L, A_tp_L_m) + + # Get the original array from TP + A_tr_U, info = tpttr(n, A_tp_U) + assert_(info == 0) + A_tr_L, info = tpttr(n, A_tp_L, uplo='L') + assert_(info == 0) + + assert_array_almost_equal(A_tr_U, triu(A_full)) + assert_array_almost_equal(A_tr_L, tril(A_full)) + + +def test_pftrf(): + """ + Test Cholesky factorization of a positive definite Rectangular Full + Packed (RFP) format array + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + A = A + A.conj().T + n*eye(n) + else: + A = (rng.rand(n, n)).astype(dtype) + A = A + A.T + n*eye(n) + + pftrf, trttf, tfttr = get_lapack_funcs(('pftrf', 'trttf', 'tfttr'), + dtype=dtype) + + # Get the original array from TP + Afp, info = trttf(A) + Achol_rfp, info = pftrf(n, Afp) + assert_(info == 0) + A_chol_r, _ = tfttr(n, Achol_rfp) + Achol = cholesky(A) + assert_array_almost_equal(A_chol_r, Achol) + + +def test_pftri(): + """ + Test Cholesky factorization of a positive definite Rectangular Full + Packed (RFP) format array to find its inverse + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + A = A + A.conj().T + n*eye(n) + else: + A = (rng.rand(n, n)).astype(dtype) + A = A + A.T + n*eye(n) + + pftri, pftrf, trttf, tfttr = get_lapack_funcs(('pftri', + 'pftrf', + 'trttf', + 'tfttr'), + dtype=dtype) + + # Get the original array from TP + Afp, info = trttf(A) + A_chol_rfp, info = pftrf(n, Afp) + A_inv_rfp, info = pftri(n, A_chol_rfp) + assert_(info == 0) + A_inv_r, _ = tfttr(n, A_inv_rfp) + Ainv = inv(A) + assert_array_almost_equal(A_inv_r, triu(Ainv), + decimal=4 if ind % 2 == 0 else 6) + + +def test_pftrs(): + """ + Test Cholesky factorization of a positive definite Rectangular Full + Packed (RFP) format array and solve a linear system + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + A = A + A.conj().T + n*eye(n) + else: + A = (rng.rand(n, n)).astype(dtype) + A = A + A.T + n*eye(n) + + B = ones((n, 3), dtype=dtype) + Bf1 = ones((n+2, 3), dtype=dtype) + Bf2 = ones((n-2, 3), dtype=dtype) + pftrs, pftrf, trttf, tfttr = get_lapack_funcs(('pftrs', + 'pftrf', + 'trttf', + 'tfttr'), + dtype=dtype) + + # Get the original array from TP + Afp, info = trttf(A) + A_chol_rfp, info = pftrf(n, Afp) + # larger B arrays shouldn't segfault + soln, info = pftrs(n, A_chol_rfp, Bf1) + assert_(info == 0) + assert_raises(Exception, pftrs, n, A_chol_rfp, Bf2) + soln, info = pftrs(n, A_chol_rfp, B) + assert_(info == 0) + assert_array_almost_equal(solve(A, B), soln, + decimal=4 if ind % 2 == 0 else 6) + + +def test_sfrk_hfrk(): + """ + Test for performing a symmetric rank-k operation for matrix in RFP format. + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + A = A + A.conj().T + n*eye(n) + else: + A = (rng.rand(n, n)).astype(dtype) + A = A + A.T + n*eye(n) + + prefix = 's'if ind < 2 else 'h' + trttf, tfttr, shfrk = get_lapack_funcs(('trttf', 'tfttr', f'{prefix}frk'), + dtype=dtype) + + Afp, _ = trttf(A) + C = rng.rand(n, 2).astype(dtype) + Afp_out = shfrk(n, 2, -1, C, 2, Afp) + A_out, _ = tfttr(n, Afp_out) + assert_array_almost_equal(A_out, triu(-C.dot(C.conj().T) + 2*A), + decimal=4 if ind % 2 == 0 else 6) + + +def test_syconv(): + """ + Test for going back and forth between the returned format of he/sytrf to + L and D factors/permutations. + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 10 + + if ind > 1: + A = (rng.randint(-30, 30, (n, n)) + + rng.randint(-30, 30, (n, n))*1j).astype(dtype) + + A = A + A.conj().T + else: + A = rng.randint(-30, 30, (n, n)).astype(dtype) + A = A + A.T + n*eye(n) + + tol = 100*np.spacing(dtype(1.0).real) + syconv, trf, trf_lwork = get_lapack_funcs(('syconv', 'sytrf', + 'sytrf_lwork'), dtype=dtype) + lw = _compute_lwork(trf_lwork, n, lower=1) + L, D, perm = ldl(A, lower=1, hermitian=False) + lw = _compute_lwork(trf_lwork, n, lower=1) + ldu, ipiv, info = trf(A, lower=1, lwork=lw) + a, e, info = syconv(ldu, ipiv, lower=1) + assert_allclose(tril(a, -1,), tril(L[perm, :], -1), atol=tol, rtol=0.) + + # Test also upper + U, D, perm = ldl(A, lower=0, hermitian=False) + ldu, ipiv, info = trf(A, lower=0) + a, e, info = syconv(ldu, ipiv, lower=0) + assert_allclose(triu(a, 1), triu(U[perm, :], 1), atol=tol, rtol=0.) + + +class TestBlockedQR: + """ + Tests for the blocked QR factorization, namely through geqrt, gemqrt, tpqrt + and tpmqr. + """ + + def test_geqrt_gemqrt(self): + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + else: + A = (rng.rand(n, n)).astype(dtype) + + tol = 100*np.spacing(dtype(1.0).real) + geqrt, gemqrt = get_lapack_funcs(('geqrt', 'gemqrt'), dtype=dtype) + + a, t, info = geqrt(n, A) + assert info == 0 + + # Extract elementary reflectors from lower triangle, adding the + # main diagonal of ones. + v = np.tril(a, -1) + np.eye(n, dtype=dtype) + # Generate the block Householder transform I - VTV^H + Q = np.eye(n, dtype=dtype) - v @ t @ v.T.conj() + R = np.triu(a) + + # Test columns of Q are orthogonal + assert_allclose(Q.T.conj() @ Q, np.eye(n, dtype=dtype), atol=tol, + rtol=0.) + assert_allclose(Q @ R, A, atol=tol, rtol=0.) + + if ind > 1: + C = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + transpose = 'C' + else: + C = (rng.rand(n, n)).astype(dtype) + transpose = 'T' + + for side in ('L', 'R'): + for trans in ('N', transpose): + c, info = gemqrt(a, t, C, side=side, trans=trans) + assert info == 0 + + if trans == transpose: + q = Q.T.conj() + else: + q = Q + + if side == 'L': + qC = q @ C + else: + qC = C @ q + + assert_allclose(c, qC, atol=tol, rtol=0.) + + # Test default arguments + if (side, trans) == ('L', 'N'): + c_default, info = gemqrt(a, t, C) + assert info == 0 + assert_equal(c_default, c) + + # Test invalid side/trans + assert_raises(Exception, gemqrt, a, t, C, side='A') + assert_raises(Exception, gemqrt, a, t, C, trans='A') + + def test_tpqrt_tpmqrt(self): + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + B = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + else: + A = (rng.rand(n, n)).astype(dtype) + B = (rng.rand(n, n)).astype(dtype) + + tol = 100*np.spacing(dtype(1.0).real) + tpqrt, tpmqrt = get_lapack_funcs(('tpqrt', 'tpmqrt'), dtype=dtype) + + # Test for the range of pentagonal B, from square to upper + # triangular + for l in (0, n // 2, n): + a, b, t, info = tpqrt(l, n, A, B) + assert info == 0 + + # Check that lower triangular part of A has not been modified + assert_equal(np.tril(a, -1), np.tril(A, -1)) + # Check that elements not part of the pentagonal portion of B + # have not been modified. + assert_equal(np.tril(b, l - n - 1), np.tril(B, l - n - 1)) + + # Extract pentagonal portion of B + B_pent, b_pent = np.triu(B, l - n), np.triu(b, l - n) + + # Generate elementary reflectors + v = np.concatenate((np.eye(n, dtype=dtype), b_pent)) + # Generate the block Householder transform I - VTV^H + Q = np.eye(2 * n, dtype=dtype) - v @ t @ v.T.conj() + R = np.concatenate((np.triu(a), np.zeros_like(a))) + + # Test columns of Q are orthogonal + assert_allclose(Q.T.conj() @ Q, np.eye(2 * n, dtype=dtype), + atol=tol, rtol=0.) + assert_allclose(Q @ R, np.concatenate((np.triu(A), B_pent)), + atol=tol, rtol=0.) + + if ind > 1: + C = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + D = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + transpose = 'C' + else: + C = (rng.rand(n, n)).astype(dtype) + D = (rng.rand(n, n)).astype(dtype) + transpose = 'T' + + for side in ('L', 'R'): + for trans in ('N', transpose): + c, d, info = tpmqrt(l, b, t, C, D, side=side, + trans=trans) + assert info == 0 + + if trans == transpose: + q = Q.T.conj() + else: + q = Q + + if side == 'L': + cd = np.concatenate((c, d), axis=0) + CD = np.concatenate((C, D), axis=0) + qCD = q @ CD + else: + cd = np.concatenate((c, d), axis=1) + CD = np.concatenate((C, D), axis=1) + qCD = CD @ q + + assert_allclose(cd, qCD, atol=tol, rtol=0.) + + if (side, trans) == ('L', 'N'): + c_default, d_default, info = tpmqrt(l, b, t, C, D) + assert info == 0 + assert_equal(c_default, c) + assert_equal(d_default, d) + + # Test invalid side/trans + assert_raises(Exception, tpmqrt, l, b, t, C, D, side='A') + assert_raises(Exception, tpmqrt, l, b, t, C, D, trans='A') + + +def test_pstrf(): + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + # DTYPES = pstrf + n = 10 + r = 2 + pstrf = get_lapack_funcs('pstrf', dtype=dtype) + + # Create positive semidefinite A + if ind > 1: + A = rng.rand(n, n-r).astype(dtype) + 1j * rng.rand(n, n-r).astype(dtype) + A = A @ A.conj().T + else: + A = rng.rand(n, n-r).astype(dtype) + A = A @ A.T + + c, piv, r_c, info = pstrf(A) + U = triu(c) + U[r_c - n:, r_c - n:] = 0. + + assert_equal(info, 1) + # python-dbg 3.5.2 runs cause trouble with the following assertion. + # assert_equal(r_c, n - r) + single_atol = 1000 * np.finfo(np.float32).eps + double_atol = 1000 * np.finfo(np.float64).eps + atol = single_atol if ind in [0, 2] else double_atol + assert_allclose(A[piv-1][:, piv-1], U.conj().T @ U, rtol=0., atol=atol) + + c, piv, r_c, info = pstrf(A, lower=1) + L = tril(c) + L[r_c - n:, r_c - n:] = 0. + + assert_equal(info, 1) + # assert_equal(r_c, n - r) + single_atol = 1000 * np.finfo(np.float32).eps + double_atol = 1000 * np.finfo(np.float64).eps + atol = single_atol if ind in [0, 2] else double_atol + assert_allclose(A[piv-1][:, piv-1], L @ L.conj().T, rtol=0., atol=atol) + + +def test_pstf2(): + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + # DTYPES = pstf2 + n = 10 + r = 2 + pstf2 = get_lapack_funcs('pstf2', dtype=dtype) + + # Create positive semidefinite A + if ind > 1: + A = rng.rand(n, n-r).astype(dtype) + 1j * rng.rand(n, n-r).astype(dtype) + A = A @ A.conj().T + else: + A = rng.rand(n, n-r).astype(dtype) + A = A @ A.T + + c, piv, r_c, info = pstf2(A) + U = triu(c) + U[r_c - n:, r_c - n:] = 0. + + assert_equal(info, 1) + # python-dbg 3.5.2 runs cause trouble with the commented assertions. + # assert_equal(r_c, n - r) + single_atol = 1000 * np.finfo(np.float32).eps + double_atol = 1000 * np.finfo(np.float64).eps + atol = single_atol if ind in [0, 2] else double_atol + assert_allclose(A[piv-1][:, piv-1], U.conj().T @ U, rtol=0., atol=atol) + + c, piv, r_c, info = pstf2(A, lower=1) + L = tril(c) + L[r_c - n:, r_c - n:] = 0. + + assert_equal(info, 1) + # assert_equal(r_c, n - r) + single_atol = 1000 * np.finfo(np.float32).eps + double_atol = 1000 * np.finfo(np.float64).eps + atol = single_atol if ind in [0, 2] else double_atol + assert_allclose(A[piv-1][:, piv-1], L @ L.conj().T, rtol=0., atol=atol) + + +def test_geequ(): + desired_real = np.array([[0.6250, 1.0000, 0.0393, -0.4269], + [1.0000, -0.5619, -1.0000, -1.0000], + [0.5874, -1.0000, -0.0596, -0.5341], + [-1.0000, -0.5946, -0.0294, 0.9957]]) + + desired_cplx = np.array([[-0.2816+0.5359*1j, + 0.0812+0.9188*1j, + -0.7439-0.2561*1j], + [-0.3562-0.2954*1j, + 0.9566-0.0434*1j, + -0.0174+0.1555*1j], + [0.8607+0.1393*1j, + -0.2759+0.7241*1j, + -0.1642-0.1365*1j]]) + + for ind, dtype in enumerate(DTYPES): + if ind < 2: + # Use examples from the NAG documentation + A = np.array([[1.80e+10, 2.88e+10, 2.05e+00, -8.90e+09], + [5.25e+00, -2.95e+00, -9.50e-09, -3.80e+00], + [1.58e+00, -2.69e+00, -2.90e-10, -1.04e+00], + [-1.11e+00, -6.60e-01, -5.90e-11, 8.00e-01]]) + A = A.astype(dtype) + else: + A = np.array([[-1.34e+00, 0.28e+10, -6.39e+00], + [-1.70e+00, 3.31e+10, -0.15e+00], + [2.41e-10, -0.56e+00, -0.83e-10]], dtype=dtype) + A += np.array([[2.55e+00, 3.17e+10, -2.20e+00], + [-1.41e+00, -0.15e+10, 1.34e+00], + [0.39e-10, 1.47e+00, -0.69e-10]])*1j + + A = A.astype(dtype) + + geequ = get_lapack_funcs('geequ', dtype=dtype) + r, c, rowcnd, colcnd, amax, info = geequ(A) + + if ind < 2: + assert_allclose(desired_real.astype(dtype), r[:, None]*A*c, + rtol=0, atol=1e-4) + else: + assert_allclose(desired_cplx.astype(dtype), r[:, None]*A*c, + rtol=0, atol=1e-4) + + +def test_syequb(): + desired_log2s = np.array([0, 0, 0, 0, 0, 0, -1, -1, -2, -3]) + + for ind, dtype in enumerate(DTYPES): + A = np.eye(10, dtype=dtype) + alpha = dtype(1. if ind < 2 else 1.j) + d = np.array([alpha * 2.**x for x in range(-5, 5)], dtype=dtype) + A += np.rot90(np.diag(d)) + + syequb = get_lapack_funcs('syequb', dtype=dtype) + s, scond, amax, info = syequb(A) + + assert_equal(np.log2(s).astype(int), desired_log2s) + + +@pytest.mark.skipif(True, + reason="Failing on some OpenBLAS version, see gh-12276") +def test_heequb(): + # zheequb has a bug for versions =< LAPACK 3.9.0 + # See Reference-LAPACK gh-61 and gh-408 + # Hence the zheequb test is customized accordingly to avoid + # work scaling. + A = np.diag([2]*5 + [1002]*5) + np.diag(np.ones(9), k=1)*1j + s, scond, amax, info = lapack.zheequb(A) + assert_equal(info, 0) + assert_allclose(np.log2(s), [0., -1.]*2 + [0.] + [-4]*5) + + A = np.diag(2**np.abs(np.arange(-5, 6)) + 0j) + A[5, 5] = 1024 + A[5, 0] = 16j + s, scond, amax, info = lapack.cheequb(A.astype(np.complex64), lower=1) + assert_equal(info, 0) + assert_allclose(np.log2(s), [-2, -1, -1, 0, 0, -5, 0, -1, -1, -2, -2]) + + +def test_getc2_gesc2(): + rng = np.random.RandomState(42) + n = 10 + desired_real = rng.rand(n) + desired_cplx = rng.rand(n) + rng.rand(n)*1j + + for ind, dtype in enumerate(DTYPES): + if ind < 2: + A = rng.rand(n, n) + A = A.astype(dtype) + b = A @ desired_real + b = b.astype(dtype) + else: + A = rng.rand(n, n) + rng.rand(n, n)*1j + A = A.astype(dtype) + b = A @ desired_cplx + b = b.astype(dtype) + + getc2 = get_lapack_funcs('getc2', dtype=dtype) + gesc2 = get_lapack_funcs('gesc2', dtype=dtype) + lu, ipiv, jpiv, info = getc2(A, overwrite_a=0) + x, scale = gesc2(lu, b, ipiv, jpiv, overwrite_rhs=0) + + if ind < 2: + assert_array_almost_equal(desired_real.astype(dtype), + x/scale, decimal=4) + else: + assert_array_almost_equal(desired_cplx.astype(dtype), + x/scale, decimal=4) + + +@pytest.mark.parametrize('size', [(6, 5), (5, 5)]) +@pytest.mark.parametrize('dtype', REAL_DTYPES) +@pytest.mark.parametrize('joba', range(6)) # 'C', 'E', 'F', 'G', 'A', 'R' +@pytest.mark.parametrize('jobu', range(4)) # 'U', 'F', 'W', 'N' +@pytest.mark.parametrize('jobv', range(4)) # 'V', 'J', 'W', 'N' +@pytest.mark.parametrize('jobr', [0, 1]) +@pytest.mark.parametrize('jobp', [0, 1]) +def test_gejsv_general(size, dtype, joba, jobu, jobv, jobr, jobp, jobt=0): + """Test the lapack routine ?gejsv. + + This function tests that a singular value decomposition can be performed + on the random M-by-N matrix A. The test performs the SVD using ?gejsv + then performs the following checks: + + * ?gejsv exist successfully (info == 0) + * The returned singular values are correct + * `A` can be reconstructed from `u`, `SIGMA`, `v` + * Ensure that u.T @ u is the identity matrix + * Ensure that v.T @ v is the identity matrix + * The reported matrix rank + * The reported number of singular values + * If denormalized floats are required + + Notes + ----- + joba specifies several choices effecting the calculation's accuracy + Although all arguments are tested, the tests only check that the correct + solution is returned - NOT that the prescribed actions are performed + internally. + + jobt is, as of v3.9.0, still experimental and removed to cut down number of + test cases. However keyword itself is tested externally. + """ + rng = np.random.RandomState(42) + + # Define some constants for later use: + m, n = size + atol = 100 * np.finfo(dtype).eps + A = generate_random_dtype_array(size, dtype, rng) + gejsv = get_lapack_funcs('gejsv', dtype=dtype) + + # Set up checks for invalid job? combinations + # if an invalid combination occurs we set the appropriate + # exit status. + lsvec = jobu < 2 # Calculate left singular vectors + rsvec = jobv < 2 # Calculate right singular vectors + l2tran = (jobt == 1) and (m == n) + is_complex = np.iscomplexobj(A) + + invalid_real_jobv = (jobv == 1) and (not lsvec) and (not is_complex) + invalid_cplx_jobu = (jobu == 2) and not (rsvec and l2tran) and is_complex + invalid_cplx_jobv = (jobv == 2) and not (lsvec and l2tran) and is_complex + + # Set the exit status to the expected value. + # Here we only check for invalid combinations, not individual + # parameters. + if invalid_cplx_jobu: + exit_status = -2 + elif invalid_real_jobv or invalid_cplx_jobv: + exit_status = -3 + else: + exit_status = 0 + + if (jobu > 1) and (jobv == 1): + assert_raises(Exception, gejsv, A, joba, jobu, jobv, jobr, jobt, jobp) + else: + sva, u, v, work, iwork, info = gejsv(A, + joba=joba, + jobu=jobu, + jobv=jobv, + jobr=jobr, + jobt=jobt, + jobp=jobp) + + # Check that ?gejsv exited successfully/as expected + assert_equal(info, exit_status) + + # If exit_status is non-zero the combination of jobs is invalid. + # We test this above but no calculations are performed. + if not exit_status: + + # Check the returned singular values + sigma = (work[0] / work[1]) * sva[:n] + assert_allclose(sigma, svd(A, compute_uv=False), atol=atol) + + if jobu == 1: + # If JOBU = 'F', then u contains the M-by-M matrix of + # the left singular vectors, including an ONB of the orthogonal + # complement of the Range(A) + # However, to recalculate A we are concerned about the + # first n singular values and so can ignore the latter. + # TODO: Add a test for ONB? + u = u[:, :n] + + if lsvec and rsvec: + assert_allclose(u @ np.diag(sigma) @ v.conj().T, A, atol=atol) + if lsvec: + assert_allclose(u.conj().T @ u, np.identity(n), atol=atol) + if rsvec: + assert_allclose(v.conj().T @ v, np.identity(n), atol=atol) + + assert_equal(iwork[0], np.linalg.matrix_rank(A)) + assert_equal(iwork[1], np.count_nonzero(sigma)) + # iwork[2] is non-zero if requested accuracy is not warranted for + # the data. This should never occur for these tests. + assert_equal(iwork[2], 0) + + +@pytest.mark.parametrize('dtype', REAL_DTYPES) +def test_gejsv_edge_arguments(dtype): + """Test edge arguments return expected status""" + gejsv = get_lapack_funcs('gejsv', dtype=dtype) + + # scalar A + sva, u, v, work, iwork, info = gejsv(1.) + assert_equal(info, 0) + assert_equal(u.shape, (1, 1)) + assert_equal(v.shape, (1, 1)) + assert_equal(sva, np.array([1.], dtype=dtype)) + + # 1d A + A = np.ones((1,), dtype=dtype) + sva, u, v, work, iwork, info = gejsv(A) + assert_equal(info, 0) + assert_equal(u.shape, (1, 1)) + assert_equal(v.shape, (1, 1)) + assert_equal(sva, np.array([1.], dtype=dtype)) + + # 2d empty A + A = np.ones((1, 0), dtype=dtype) + sva, u, v, work, iwork, info = gejsv(A) + assert_equal(info, 0) + assert_equal(u.shape, (1, 0)) + assert_equal(v.shape, (1, 0)) + assert_equal(sva, np.array([], dtype=dtype)) + + # make sure "overwrite_a" is respected - user reported in gh-13191 + A = np.sin(np.arange(100).reshape(10, 10)).astype(dtype) + A = np.asfortranarray(A + A.T) # make it symmetric and column major + Ac = A.copy('A') + _ = gejsv(A) + assert_allclose(A, Ac) + + +@pytest.mark.parametrize(('kwargs'), + ({'joba': 9}, + {'jobu': 9}, + {'jobv': 9}, + {'jobr': 9}, + {'jobt': 9}, + {'jobp': 9}) + ) +def test_gejsv_invalid_job_arguments(kwargs): + """Test invalid job arguments raise an Exception""" + A = np.ones((2, 2), dtype=float) + gejsv = get_lapack_funcs('gejsv', dtype=float) + assert_raises(Exception, gejsv, A, **kwargs) + + +@pytest.mark.parametrize("A,sva_expect,u_expect,v_expect", + [(np.array([[2.27, -1.54, 1.15, -1.94], + [0.28, -1.67, 0.94, -0.78], + [-0.48, -3.09, 0.99, -0.21], + [1.07, 1.22, 0.79, 0.63], + [-2.35, 2.93, -1.45, 2.30], + [0.62, -7.39, 1.03, -2.57]]), + np.array([9.9966, 3.6831, 1.3569, 0.5000]), + np.array([[0.2774, -0.6003, -0.1277, 0.1323], + [0.2020, -0.0301, 0.2805, 0.7034], + [0.2918, 0.3348, 0.6453, 0.1906], + [-0.0938, -0.3699, 0.6781, -0.5399], + [-0.4213, 0.5266, 0.0413, -0.0575], + [0.7816, 0.3353, -0.1645, -0.3957]]), + np.array([[0.1921, -0.8030, 0.0041, -0.5642], + [-0.8794, -0.3926, -0.0752, 0.2587], + [0.2140, -0.2980, 0.7827, 0.5027], + [-0.3795, 0.3351, 0.6178, -0.6017]]))]) +def test_gejsv_NAG(A, sva_expect, u_expect, v_expect): + """ + This test implements the example found in the NAG manual, f08khf. + An example was not found for the complex case. + """ + # NAG manual provides accuracy up to 4 decimals + atol = 1e-4 + gejsv = get_lapack_funcs('gejsv', dtype=A.dtype) + + sva, u, v, work, iwork, info = gejsv(A) + + assert_allclose(sva_expect, sva, atol=atol) + assert_allclose(u_expect, u, atol=atol) + assert_allclose(v_expect, v, atol=atol) + + +@pytest.mark.parametrize("dtype", DTYPES) +def test_gttrf_gttrs(dtype): + # The test uses ?gttrf and ?gttrs to solve a random system for each dtype, + # tests that the output of ?gttrf define LU matrices, that input + # parameters are unmodified, transposal options function correctly, that + # incompatible matrix shapes raise an error, and singular matrices return + # non zero info. + + rng = np.random.RandomState(42) + n = 10 + atol = 100 * np.finfo(dtype).eps + + # create the matrix in accordance with the data type + du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + d = generate_random_dtype_array((n,), dtype=dtype, rng=rng) + dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + + diag_cpy = [dl.copy(), d.copy(), du.copy()] + + A = np.diag(d) + np.diag(dl, -1) + np.diag(du, 1) + x = np.random.rand(n) + b = A @ x + + gttrf, gttrs = get_lapack_funcs(('gttrf', 'gttrs'), dtype=dtype) + + _dl, _d, _du, du2, ipiv, info = gttrf(dl, d, du) + # test to assure that the inputs of ?gttrf are unmodified + assert_array_equal(dl, diag_cpy[0]) + assert_array_equal(d, diag_cpy[1]) + assert_array_equal(du, diag_cpy[2]) + + # generate L and U factors from ?gttrf return values + # L/U are lower/upper triangular by construction (initially and at end) + U = np.diag(_d, 0) + np.diag(_du, 1) + np.diag(du2, 2) + L = np.eye(n, dtype=dtype) + + for i, m in enumerate(_dl): + # L is given in a factored form. + # See + # www.hpcavf.uclan.ac.uk/softwaredoc/sgi_scsl_html/sgi_html/ch03.html + piv = ipiv[i] - 1 + # right multiply by permutation matrix + L[:, [i, piv]] = L[:, [piv, i]] + # right multiply by Li, rank-one modification of identity + L[:, i] += L[:, i+1]*m + + # one last permutation + i, piv = -1, ipiv[-1] - 1 + # right multiply by final permutation matrix + L[:, [i, piv]] = L[:, [piv, i]] + + # check that the outputs of ?gttrf define an LU decomposition of A + assert_allclose(A, L @ U, atol=atol) + + b_cpy = b.copy() + x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b) + # test that the inputs of ?gttrs are unmodified + assert_array_equal(b, b_cpy) + # test that the result of ?gttrs matches the expected input + assert_allclose(x, x_gttrs, atol=atol) + + # test that ?gttrf and ?gttrs work with transposal options + if dtype in REAL_DTYPES: + trans = "T" + b_trans = A.T @ x + else: + trans = "C" + b_trans = A.conj().T @ x + + x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b_trans, trans=trans) + assert_allclose(x, x_gttrs, atol=atol) + + # test that ValueError is raised with incompatible matrix shapes + with assert_raises(ValueError): + gttrf(dl[:-1], d, du) + with assert_raises(ValueError): + gttrf(dl, d[:-1], du) + with assert_raises(ValueError): + gttrf(dl, d, du[:-1]) + + # test that matrix of size n=2 raises exception + with assert_raises(ValueError): + gttrf(dl[0], d[:1], du[0]) + + # test that singular (row of all zeroes) matrix fails via info + du[0] = 0 + d[0] = 0 + __dl, __d, __du, _du2, _ipiv, _info = gttrf(dl, d, du) + np.testing.assert_(__d[info - 1] == 0, (f"?gttrf: _d[info-1] is {__d[info - 1]}," + " not the illegal value :0.")) + + +@pytest.mark.parametrize("du, d, dl, du_exp, d_exp, du2_exp, ipiv_exp, b, x", + [(np.array([2.1, -1.0, 1.9, 8.0]), + np.array([3.0, 2.3, -5.0, -.9, 7.1]), + np.array([3.4, 3.6, 7.0, -6.0]), + np.array([2.3, -5, -.9, 7.1]), + np.array([3.4, 3.6, 7, -6, -1.015373]), + np.array([-1, 1.9, 8]), + np.array([2, 3, 4, 5, 5]), + np.array([[2.7, 6.6], + [-0.5, 10.8], + [2.6, -3.2], + [0.6, -11.2], + [2.7, 19.1] + ]), + np.array([[-4, 5], + [7, -4], + [3, -3], + [-4, -2], + [-3, 1]])), + ( + np.array([2 - 1j, 2 + 1j, -1 + 1j, 1 - 1j]), + np.array([-1.3 + 1.3j, -1.3 + 1.3j, + -1.3 + 3.3j, - .3 + 4.3j, + -3.3 + 1.3j]), + np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j]), + # du exp + np.array([-1.3 + 1.3j, -1.3 + 3.3j, + -0.3 + 4.3j, -3.3 + 1.3j]), + np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j, + -1.3399 + 0.2875j]), + np.array([2 + 1j, -1 + 1j, 1 - 1j]), + np.array([2, 3, 4, 5, 5]), + np.array([[2.4 - 5j, 2.7 + 6.9j], + [3.4 + 18.2j, - 6.9 - 5.3j], + [-14.7 + 9.7j, - 6 - .6j], + [31.9 - 7.7j, -3.9 + 9.3j], + [-1 + 1.6j, -3 + 12.2j]]), + np.array([[1 + 1j, 2 - 1j], + [3 - 1j, 1 + 2j], + [4 + 5j, -1 + 1j], + [-1 - 2j, 2 + 1j], + [1 - 1j, 2 - 2j]]) + )]) +def test_gttrf_gttrs_NAG_f07cdf_f07cef_f07crf_f07csf(du, d, dl, du_exp, d_exp, + du2_exp, ipiv_exp, b, x): + # test to assure that wrapper is consistent with NAG Library Manual Mark 26 + # example problems: f07cdf and f07cef (real) + # examples: f07crf and f07csf (complex) + # (Links may expire, so search for "NAG Library Manual Mark 26" online) + + gttrf, gttrs = get_lapack_funcs(('gttrf', "gttrs"), (du[0], du[0])) + + _dl, _d, _du, du2, ipiv, info = gttrf(dl, d, du) + assert_allclose(du2, du2_exp) + assert_allclose(_du, du_exp) + assert_allclose(_d, d_exp, atol=1e-4) # NAG examples provide 4 decimals. + assert_allclose(ipiv, ipiv_exp) + + x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b) + + assert_allclose(x_gttrs, x) + + +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('norm', ['1', 'I', 'O']) +@pytest.mark.parametrize('n', [3, 10]) +def test_gtcon(dtype, norm, n): + rng = np.random.default_rng(23498324) + + d = rng.random(n) + rng.random(n)*1j + dl = rng.random(n - 1) + rng.random(n - 1)*1j + du = rng.random(n - 1) + rng.random(n - 1)*1j + A = np.diag(d) + np.diag(dl, -1) + np.diag(du, 1) + if np.issubdtype(dtype, np.floating): + A, d, dl, du = A.real, d.real, dl.real, du.real + A, d, dl, du = A.astype(dtype), d.astype(dtype), dl.astype(dtype), du.astype(dtype) + + anorm = np.abs(A).sum(axis=0).max() + + gttrf, gtcon = get_lapack_funcs(('gttrf', 'gtcon'), (A,)) + dl, d, du, du2, ipiv, info = gttrf(dl, d, du) + res, _ = gtcon(dl, d, du, du2, ipiv, anorm, norm=norm) + + gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,)) + lu, ipvt, info = getrf(A) + ref, _ = gecon(lu, anorm, norm=norm) + + rtol = np.finfo(dtype).eps**0.75 + assert_allclose(res, ref, rtol=rtol) + + +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('shape', [(3, 7), (7, 3), (2**18, 2**18)]) +def test_geqrfp_lwork(dtype, shape): + geqrfp_lwork = get_lapack_funcs(('geqrfp_lwork'), dtype=dtype) + m, n = shape + lwork, info = geqrfp_lwork(m=m, n=n) + assert_equal(info, 0) + + +@pytest.mark.parametrize("ddtype,dtype", + zip(REAL_DTYPES + REAL_DTYPES, DTYPES)) +def test_pttrf_pttrs(ddtype, dtype): + rng = np.random.RandomState(42) + # set test tolerance appropriate for dtype + atol = 100*np.finfo(dtype).eps + # n is the length diagonal of A + n = 10 + # create diagonals according to size and dtype + + # diagonal d should always be real. + # add 4 to d so it will be dominant for all dtypes + d = generate_random_dtype_array((n,), ddtype, rng) + 4 + # diagonal e may be real or complex. + e = generate_random_dtype_array((n-1,), dtype, rng) + + # assemble diagonals together into matrix + A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1) + # store a copy of diagonals to later verify + diag_cpy = [d.copy(), e.copy()] + + pttrf = get_lapack_funcs('pttrf', dtype=dtype) + + _d, _e, info = pttrf(d, e) + # test to assure that the inputs of ?pttrf are unmodified + assert_array_equal(d, diag_cpy[0]) + assert_array_equal(e, diag_cpy[1]) + assert_equal(info, 0, err_msg=f"pttrf: info = {info}, should be 0") + + # test that the factors from pttrf can be recombined to make A + L = np.diag(_e, -1) + np.diag(np.ones(n)) + D = np.diag(_d) + + assert_allclose(A, L@D@L.conjugate().T, atol=atol) + + # generate random solution x + x = generate_random_dtype_array((n,), dtype, rng) + # determine accompanying b to get soln x + b = A@x + + # determine _x from pttrs + pttrs = get_lapack_funcs('pttrs', dtype=dtype) + _x, info = pttrs(_d, _e.conj(), b) + assert_equal(info, 0, err_msg=f"pttrs: info = {info}, should be 0") + + # test that _x from pttrs matches the expected x + assert_allclose(x, _x, atol=atol) + + +@pytest.mark.parametrize("ddtype,dtype", + zip(REAL_DTYPES + REAL_DTYPES, DTYPES)) +def test_pttrf_pttrs_errors_incompatible_shape(ddtype, dtype): + n = 10 + rng = np.random.RandomState(1234) + pttrf = get_lapack_funcs('pttrf', dtype=dtype) + d = generate_random_dtype_array((n,), ddtype, rng) + 2 + e = generate_random_dtype_array((n-1,), dtype, rng) + # test that ValueError is raised with incompatible matrix shapes + assert_raises(ValueError, pttrf, d[:-1], e) + assert_raises(ValueError, pttrf, d, e[:-1]) + + +@pytest.mark.parametrize("ddtype,dtype", + zip(REAL_DTYPES + REAL_DTYPES, DTYPES)) +def test_pttrf_pttrs_errors_singular_nonSPD(ddtype, dtype): + n = 10 + rng = np.random.RandomState(42) + pttrf = get_lapack_funcs('pttrf', dtype=dtype) + d = generate_random_dtype_array((n,), ddtype, rng) + 2 + e = generate_random_dtype_array((n-1,), dtype, rng) + # test that singular (row of all zeroes) matrix fails via info + d[0] = 0 + e[0] = 0 + _d, _e, info = pttrf(d, e) + assert_equal(_d[info - 1], 0, + f"?pttrf: _d[info-1] is {_d[info - 1]}, not the illegal value :0.") + + # test with non-spd matrix + d = generate_random_dtype_array((n,), ddtype, rng) + _d, _e, info = pttrf(d, e) + assert_(info != 0, "?pttrf should fail with non-spd matrix, but didn't") + + +@pytest.mark.parametrize(("d, e, d_expect, e_expect, b, x_expect"), [ + (np.array([4, 10, 29, 25, 5]), + np.array([-2, -6, 15, 8]), + np.array([4, 9, 25, 16, 1]), + np.array([-.5, -.6667, .6, .5]), + np.array([[6, 10], [9, 4], [2, 9], [14, 65], + [7, 23]]), + np.array([[2.5, 2], [2, -1], [1, -3], [-1, 6], + [3, -5]]) + ), ( + np.array([16, 41, 46, 21]), + np.array([16 + 16j, 18 - 9j, 1 - 4j]), + np.array([16, 9, 1, 4]), + np.array([1+1j, 2-1j, 1-4j]), + np.array([[64+16j, -16-32j], [93+62j, 61-66j], + [78-80j, 71-74j], [14-27j, 35+15j]]), + np.array([[2+1j, -3-2j], [1+1j, 1+1j], [1-2j, 1-2j], + [1-1j, 2+1j]]) + )]) +def test_pttrf_pttrs_NAG(d, e, d_expect, e_expect, b, x_expect): + # test to assure that wrapper is consistent with NAG Manual Mark 26 + # example problems: f07jdf and f07jef (real) + # examples: f07jrf and f07csf (complex) + # NAG examples provide 4 decimals. + # (Links expire, so please search for "NAG Library Manual Mark 26" online) + + atol = 1e-4 + pttrf = get_lapack_funcs('pttrf', dtype=e[0]) + _d, _e, info = pttrf(d, e) + assert_allclose(_d, d_expect, atol=atol) + assert_allclose(_e, e_expect, atol=atol) + + pttrs = get_lapack_funcs('pttrs', dtype=e[0]) + _x, info = pttrs(_d, _e.conj(), b) + assert_allclose(_x, x_expect, atol=atol) + + # also test option `lower` + if e.dtype in COMPLEX_DTYPES: + _x, info = pttrs(_d, _e, b, lower=1) + assert_allclose(_x, x_expect, atol=atol) + + +def pteqr_get_d_e_A_z(dtype, realtype, n, compute_z): + # used by ?pteqr tests to build parameters + # returns tuple of (d, e, A, z) + rng = np.random.RandomState(42) + if compute_z == 1: + # build Hermitian A from Q**T * tri * Q = A by creating Q and tri + A_eig = generate_random_dtype_array((n, n), dtype, rng) + A_eig = A_eig + np.diag(np.zeros(n) + 4*n) + A_eig = (A_eig + A_eig.conj().T) / 2 + # obtain right eigenvectors (orthogonal) + vr = eigh(A_eig)[1] + # create tridiagonal matrix + d = generate_random_dtype_array((n,), realtype, rng) + 4 + e = generate_random_dtype_array((n-1,), realtype, rng) + tri = np.diag(d) + np.diag(e, 1) + np.diag(e, -1) + # Build A using these factors that sytrd would: (Q**T * tri * Q = A) + A = vr @ tri @ vr.conj().T + # vr is orthogonal + z = vr + + else: + # d and e are always real per lapack docs. + d = generate_random_dtype_array((n,), realtype, rng) + e = generate_random_dtype_array((n-1,), realtype, rng) + + # make SPD + d = d + 4 + A = np.diag(d) + np.diag(e, 1) + np.diag(e, -1) + z = np.diag(d) + np.diag(e, -1) + np.diag(e, 1) + return (d, e, A, z) + + +@pytest.mark.parametrize("dtype,realtype", + zip(DTYPES, REAL_DTYPES + REAL_DTYPES)) +@pytest.mark.parametrize("compute_z", range(3)) +def test_pteqr(dtype, realtype, compute_z): + ''' + Tests the ?pteqr lapack routine for all dtypes and compute_z parameters. + It generates random SPD matrix diagonals d and e, and then confirms + correct eigenvalues with scipy.linalg.eig. With applicable compute_z=2 it + tests that z can reform A. + ''' + seed(42) + atol = 1000*np.finfo(dtype).eps + pteqr = get_lapack_funcs(('pteqr'), dtype=dtype) + + n = 10 + + d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z) + + d_pteqr, e_pteqr, z_pteqr, info = pteqr(d=d, e=e, z=z, compute_z=compute_z) + assert_equal(info, 0, f"info = {info}, should be 0.") + + # compare the routine's eigenvalues with scipy.linalg.eig's. + assert_allclose(np.sort(eigh(A)[0]), np.sort(d_pteqr), atol=atol) + + if compute_z: + # verify z_pteqr as orthogonal + assert_allclose(z_pteqr @ np.conj(z_pteqr).T, np.identity(n), + atol=atol) + # verify that z_pteqr recombines to A + assert_allclose(z_pteqr @ np.diag(d_pteqr) @ np.conj(z_pteqr).T, + A, atol=atol) + + +@pytest.mark.parametrize("dtype,realtype", + zip(DTYPES, REAL_DTYPES + REAL_DTYPES)) +@pytest.mark.parametrize("compute_z", range(3)) +def test_pteqr_error_non_spd(dtype, realtype, compute_z): + seed(42) + pteqr = get_lapack_funcs(('pteqr'), dtype=dtype) + + n = 10 + d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z) + + # test with non-spd matrix + d_pteqr, e_pteqr, z_pteqr, info = pteqr(d - 4, e, z=z, compute_z=compute_z) + assert info > 0 + + +@pytest.mark.parametrize("dtype,realtype", + zip(DTYPES, REAL_DTYPES + REAL_DTYPES)) +@pytest.mark.parametrize("compute_z", range(3)) +def test_pteqr_raise_error_wrong_shape(dtype, realtype, compute_z): + seed(42) + pteqr = get_lapack_funcs(('pteqr'), dtype=dtype) + n = 10 + d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z) + # test with incorrect/incompatible array sizes + assert_raises(ValueError, pteqr, d[:-1], e, z=z, compute_z=compute_z) + assert_raises(ValueError, pteqr, d, e[:-1], z=z, compute_z=compute_z) + if compute_z: + assert_raises(ValueError, pteqr, d, e, z=z[:-1], compute_z=compute_z) + + +@pytest.mark.parametrize("dtype,realtype", + zip(DTYPES, REAL_DTYPES + REAL_DTYPES)) +@pytest.mark.parametrize("compute_z", range(3)) +def test_pteqr_error_singular(dtype, realtype, compute_z): + seed(42) + pteqr = get_lapack_funcs(('pteqr'), dtype=dtype) + n = 10 + d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z) + # test with singular matrix + d[0] = 0 + e[0] = 0 + d_pteqr, e_pteqr, z_pteqr, info = pteqr(d, e, z=z, compute_z=compute_z) + assert info > 0 + + +@pytest.mark.parametrize("compute_z,d,e,d_expect,z_expect", + [(2, # "I" + np.array([4.16, 5.25, 1.09, .62]), + np.array([3.17, -.97, .55]), + np.array([8.0023, 1.9926, 1.0014, 0.1237]), + np.array([[0.6326, 0.6245, -0.4191, 0.1847], + [0.7668, -0.4270, 0.4176, -0.2352], + [-0.1082, 0.6071, 0.4594, -0.6393], + [-0.0081, 0.2432, 0.6625, 0.7084]])), + ]) +def test_pteqr_NAG_f08jgf(compute_z, d, e, d_expect, z_expect): + ''' + Implements real (f08jgf) example from NAG Manual Mark 26. + Tests for correct outputs. + ''' + # the NAG manual has 4 decimals accuracy + atol = 1e-4 + pteqr = get_lapack_funcs(('pteqr'), dtype=d.dtype) + + z = np.diag(d) + np.diag(e, 1) + np.diag(e, -1) + _d, _e, _z, info = pteqr(d=d, e=e, z=z, compute_z=compute_z) + assert_allclose(_d, d_expect, atol=atol) + assert_allclose(np.abs(_z), np.abs(z_expect), atol=atol) + + +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('matrix_size', [(3, 4), (7, 6), (6, 6)]) +def test_geqrfp(dtype, matrix_size): + # Tests for all dytpes, tall, wide, and square matrices. + # Using the routine with random matrix A, Q and R are obtained and then + # tested such that R is upper triangular and non-negative on the diagonal, + # and Q is an orthogonal matrix. Verifies that A=Q@R. It also + # tests against a matrix that for which the linalg.qr method returns + # negative diagonals, and for error messaging. + + # set test tolerance appropriate for dtype + rng = np.random.RandomState(42) + rtol = 250*np.finfo(dtype).eps + atol = 100*np.finfo(dtype).eps + # get appropriate ?geqrfp for dtype + geqrfp = get_lapack_funcs(('geqrfp'), dtype=dtype) + gqr = get_lapack_funcs(("orgqr"), dtype=dtype) + + m, n = matrix_size + + # create random matrix of dimensions m x n + A = generate_random_dtype_array((m, n), dtype=dtype, rng=rng) + # create qr matrix using geqrfp + qr_A, tau, info = geqrfp(A) + + # obtain r from the upper triangular area + r = np.triu(qr_A) + + # obtain q from the orgqr lapack routine + # based on linalg.qr's extraction strategy of q with orgqr + + if m > n: + # this adds an extra column to the end of qr_A + # let qqr be an empty m x m matrix + qqr = np.zeros((m, m), dtype=dtype) + # set first n columns of qqr to qr_A + qqr[:, :n] = qr_A + # determine q from this qqr + # note that m is a sufficient for lwork based on LAPACK documentation + q = gqr(qqr, tau=tau, lwork=m)[0] + else: + q = gqr(qr_A[:, :m], tau=tau, lwork=m)[0] + + # test that q and r still make A + assert_allclose(q@r, A, rtol=rtol) + # ensure that q is orthogonal (that q @ transposed q is the identity) + assert_allclose(np.eye(q.shape[0]), q@(q.conj().T), rtol=rtol, + atol=atol) + # ensure r is upper tri by comparing original r to r as upper triangular + assert_allclose(r, np.triu(r), rtol=rtol) + # make sure diagonals of r are positive for this random solution + assert_(np.all(np.diag(r) > np.zeros(len(np.diag(r))))) + # ensure that info is zero for this success + assert_(info == 0) + + # test that this routine gives r diagonals that are positive for a + # matrix that returns negatives in the diagonal with scipy.linalg.rq + A_negative = generate_random_dtype_array((n, m), dtype=dtype, rng=rng) * -1 + r_rq_neg, q_rq_neg = qr(A_negative) + rq_A_neg, tau_neg, info_neg = geqrfp(A_negative) + # assert that any of the entries on the diagonal from linalg.qr + # are negative and that all of geqrfp are positive. + assert_(np.any(np.diag(r_rq_neg) < 0) and + np.all(np.diag(r) > 0)) + + +def test_geqrfp_errors_with_empty_array(): + # check that empty array raises good error message + A_empty = np.array([]) + geqrfp = get_lapack_funcs('geqrfp', dtype=A_empty.dtype) + assert_raises(Exception, geqrfp, A_empty) + + +@pytest.mark.parametrize("driver", ['ev', 'evd', 'evr', 'evx']) +@pytest.mark.parametrize("pfx", ['sy', 'he']) +def test_standard_eigh_lworks(pfx, driver): + n = 1200 # Some sufficiently big arbitrary number + dtype = REAL_DTYPES if pfx == 'sy' else COMPLEX_DTYPES + sc_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[0]) + dz_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[1]) + try: + _compute_lwork(sc_dlw, n, lower=1) + _compute_lwork(dz_dlw, n, lower=1) + except Exception as e: + pytest.fail(f"{pfx+driver}_lwork raised unexpected exception: {e}") + + +@pytest.mark.parametrize("driver", ['gv', 'gvx']) +@pytest.mark.parametrize("pfx", ['sy', 'he']) +def test_generalized_eigh_lworks(pfx, driver): + n = 1200 # Some sufficiently big arbitrary number + dtype = REAL_DTYPES if pfx == 'sy' else COMPLEX_DTYPES + sc_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[0]) + dz_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[1]) + # Shouldn't raise any exceptions + try: + _compute_lwork(sc_dlw, n, uplo="L") + _compute_lwork(dz_dlw, n, uplo="L") + except Exception as e: + pytest.fail(f"{pfx+driver}_lwork raised unexpected exception: {e}") + + +@pytest.mark.parametrize("dtype_", DTYPES) +@pytest.mark.parametrize("m", [1, 10, 100, 1000]) +def test_orcsd_uncsd_lwork(dtype_, m): + seed(1234) + p = randint(0, m) + q = m - p + pfx = 'or' if dtype_ in REAL_DTYPES else 'un' + dlw = pfx + 'csd_lwork' + lw = get_lapack_funcs(dlw, dtype=dtype_) + lwval = _compute_lwork(lw, m, p, q) + lwval = lwval if pfx == 'un' else (lwval,) + assert all([x > 0 for x in lwval]) + + +@pytest.mark.parametrize("dtype_", DTYPES) +def test_orcsd_uncsd(dtype_): + m, p, q = 250, 80, 170 + + pfx = 'or' if dtype_ in REAL_DTYPES else 'un' + X = ortho_group.rvs(m) if pfx == 'or' else unitary_group.rvs(m) + + drv, dlw = get_lapack_funcs((pfx + 'csd', pfx + 'csd_lwork'), dtype=dtype_) + lwval = _compute_lwork(dlw, m, p, q) + lwvals = {'lwork': lwval} if pfx == 'or' else dict(zip(['lwork', + 'lrwork'], lwval)) + + cs11, cs12, cs21, cs22, theta, u1, u2, v1t, v2t, info =\ + drv(X[:p, :q], X[:p, q:], X[p:, :q], X[p:, q:], **lwvals) + + assert info == 0 + + U = block_diag(u1, u2) + VH = block_diag(v1t, v2t) + r = min(min(p, q), min(m-p, m-q)) + n11 = min(p, q) - r + n12 = min(p, m-q) - r + n21 = min(m-p, q) - r + n22 = min(m-p, m-q) - r + + S = np.zeros((m, m), dtype=dtype_) + one = dtype_(1.) + for i in range(n11): + S[i, i] = one + for i in range(n22): + S[p+i, q+i] = one + for i in range(n12): + S[i+n11+r, i+n11+r+n21+n22+r] = -one + for i in range(n21): + S[p+n22+r+i, n11+r+i] = one + + for i in range(r): + S[i+n11, i+n11] = np.cos(theta[i]) + S[p+n22+i, i+r+n21+n22] = np.cos(theta[i]) + + S[i+n11, i+n11+n21+n22+r] = -np.sin(theta[i]) + S[p+n22+i, i+n11] = np.sin(theta[i]) + + Xc = U @ S @ VH + assert_allclose(X, Xc, rtol=0., atol=1e4*np.finfo(dtype_).eps) + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("trans_bool", [False, True]) +@pytest.mark.parametrize("fact", ["F", "N"]) +def test_gtsvx(dtype, trans_bool, fact): + """ + These tests uses ?gtsvx to solve a random Ax=b system for each dtype. + It tests that the outputs define an LU matrix, that inputs are unmodified, + transposal options, incompatible shapes, singular matrices, and + singular factorizations. It parametrizes DTYPES and the 'fact' value along + with the fact related inputs. + """ + rng = np.random.RandomState(42) + # set test tolerance appropriate for dtype + atol = 100 * np.finfo(dtype).eps + # obtain routine + gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype) + # Generate random tridiagonal matrix A + n = 10 + dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + d = generate_random_dtype_array((n,), dtype=dtype, rng=rng) + du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1) + # generate random solution x + x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + # create b from x for equation Ax=b + trans = ("T" if dtype in REAL_DTYPES else "C") if trans_bool else "N" + b = (A.conj().T if trans_bool else A) @ x + + # store a copy of the inputs to check they haven't been modified later + inputs_cpy = [dl.copy(), d.copy(), du.copy(), b.copy()] + + # set these to None if fact = 'N', or the output of gttrf is fact = 'F' + dlf_, df_, duf_, du2f_, ipiv_, info_ = \ + gttrf(dl, d, du) if fact == 'F' else [None]*6 + + gtsvx_out = gtsvx(dl, d, du, b, fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out + assert_(info == 0, f"?gtsvx info = {info}, should be zero") + + # assure that inputs are unmodified + assert_array_equal(dl, inputs_cpy[0]) + assert_array_equal(d, inputs_cpy[1]) + assert_array_equal(du, inputs_cpy[2]) + assert_array_equal(b, inputs_cpy[3]) + + # test that x_soln matches the expected x + assert_allclose(x, x_soln, atol=atol) + + # assert that the outputs are of correct type or shape + # rcond should be a scalar + assert_(hasattr(rcond, "__len__") is not True, + f"rcond should be scalar but is {rcond}") + # ferr should be length of # of cols in x + assert_(ferr.shape[0] == b.shape[1], (f"ferr.shape is {ferr.shape[0]} but should" + f" be {b.shape[1]}")) + # berr should be length of # of cols in x + assert_(berr.shape[0] == b.shape[1], (f"berr.shape is {berr.shape[0]} but should" + f" be {b.shape[1]}")) + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("trans_bool", [0, 1]) +@pytest.mark.parametrize("fact", ["F", "N"]) +def test_gtsvx_error_singular(dtype, trans_bool, fact): + rng = np.random.RandomState(42) + # obtain routine + gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype) + # Generate random tridiagonal matrix A + n = 10 + dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + d = generate_random_dtype_array((n,), dtype=dtype, rng=rng) + du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1) + # generate random solution x + x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + # create b from x for equation Ax=b + trans = "T" if dtype in REAL_DTYPES else "C" + b = (A.conj().T if trans_bool else A) @ x + + # set these to None if fact = 'N', or the output of gttrf is fact = 'F' + dlf_, df_, duf_, du2f_, ipiv_, info_ = \ + gttrf(dl, d, du) if fact == 'F' else [None]*6 + + gtsvx_out = gtsvx(dl, d, du, b, fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out + # test with singular matrix + # no need to test inputs with fact "F" since ?gttrf already does. + if fact == "N": + # Construct a singular example manually + d[-1] = 0 + dl[-1] = 0 + # solve using routine + gtsvx_out = gtsvx(dl, d, du, b) + dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out + # test for the singular matrix. + assert info > 0, "info should be > 0 for singular matrix" + + elif fact == 'F': + # assuming that a singular factorization is input + df_[-1] = 0 + duf_[-1] = 0 + du2f_[-1] = 0 + + gtsvx_out = gtsvx(dl, d, du, b, fact=fact, dlf=dlf_, df=df_, duf=duf_, + du2=du2f_, ipiv=ipiv_) + dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out + # info should not be zero and should provide index of illegal value + assert info > 0, "info should be > 0 for singular matrix" + + +@pytest.mark.parametrize("dtype", DTYPES*2) +@pytest.mark.parametrize("trans_bool", [False, True]) +@pytest.mark.parametrize("fact", ["F", "N"]) +def test_gtsvx_error_incompatible_size(dtype, trans_bool, fact): + rng = np.random.RandomState(42) + # obtain routine + gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype) + # Generate random tridiagonal matrix A + n = 10 + dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + d = generate_random_dtype_array((n,), dtype=dtype, rng=rng) + du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1) + # generate random solution x + x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + # create b from x for equation Ax=b + trans = "T" if dtype in REAL_DTYPES else "C" + b = (A.conj().T if trans_bool else A) @ x + + # set these to None if fact = 'N', or the output of gttrf is fact = 'F' + dlf_, df_, duf_, du2f_, ipiv_, info_ = \ + gttrf(dl, d, du) if fact == 'F' else [None]*6 + + if fact == "N": + assert_raises(ValueError, gtsvx, dl[:-1], d, du, b, + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + assert_raises(ValueError, gtsvx, dl, d[:-1], du, b, + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + assert_raises(ValueError, gtsvx, dl, d, du[:-1], b, + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + assert_raises(Exception, gtsvx, dl, d, du, b[:-1], + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + else: + assert_raises(ValueError, gtsvx, dl, d, du, b, + fact=fact, trans=trans, dlf=dlf_[:-1], df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + assert_raises(ValueError, gtsvx, dl, d, du, b, + fact=fact, trans=trans, dlf=dlf_, df=df_[:-1], + duf=duf_, du2=du2f_, ipiv=ipiv_) + assert_raises(ValueError, gtsvx, dl, d, du, b, + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_[:-1], du2=du2f_, ipiv=ipiv_) + assert_raises(ValueError, gtsvx, dl, d, du, b, + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_[:-1], ipiv=ipiv_) + + +@pytest.mark.parametrize("du,d,dl,b,x", + [(np.array([2.1, -1.0, 1.9, 8.0]), + np.array([3.0, 2.3, -5.0, -0.9, 7.1]), + np.array([3.4, 3.6, 7.0, -6.0]), + np.array([[2.7, 6.6], [-.5, 10.8], [2.6, -3.2], + [.6, -11.2], [2.7, 19.1]]), + np.array([[-4, 5], [7, -4], [3, -3], [-4, -2], + [-3, 1]])), + (np.array([2 - 1j, 2 + 1j, -1 + 1j, 1 - 1j]), + np.array([-1.3 + 1.3j, -1.3 + 1.3j, -1.3 + 3.3j, + -.3 + 4.3j, -3.3 + 1.3j]), + np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j]), + np.array([[2.4 - 5j, 2.7 + 6.9j], + [3.4 + 18.2j, -6.9 - 5.3j], + [-14.7 + 9.7j, -6 - .6j], + [31.9 - 7.7j, -3.9 + 9.3j], + [-1 + 1.6j, -3 + 12.2j]]), + np.array([[1 + 1j, 2 - 1j], [3 - 1j, 1 + 2j], + [4 + 5j, -1 + 1j], [-1 - 2j, 2 + 1j], + [1 - 1j, 2 - 2j]]))]) +def test_gtsvx_NAG(du, d, dl, b, x): + # Test to ensure wrapper is consistent with NAG Manual Mark 26 + # example problems: real (f07cbf) and complex (f07cpf) + gtsvx = get_lapack_funcs('gtsvx', dtype=d.dtype) + + gtsvx_out = gtsvx(dl, d, du, b) + dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out + + assert_array_almost_equal(x, x_soln) + + +@pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES + + REAL_DTYPES)) +@pytest.mark.parametrize("fact,df_de_lambda", + [("F", + lambda d, e: get_lapack_funcs('pttrf', + dtype=e.dtype)(d, e)), + ("N", lambda d, e: (None, None, None))]) +def test_ptsvx(dtype, realtype, fact, df_de_lambda): + ''' + This tests the ?ptsvx lapack routine wrapper to solve a random system + Ax = b for all dtypes and input variations. Tests for: unmodified + input parameters, fact options, incompatible matrix shapes raise an error, + and singular matrices return info of illegal value. + ''' + rng = np.random.RandomState(42) + # set test tolerance appropriate for dtype + atol = 100 * np.finfo(dtype).eps + ptsvx = get_lapack_funcs('ptsvx', dtype=dtype) + n = 5 + # create diagonals according to size and dtype + d = generate_random_dtype_array((n,), realtype, rng) + 4 + e = generate_random_dtype_array((n-1,), dtype, rng) + A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1) + x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + b = A @ x_soln + + # use lambda to determine what df, ef are + df, ef, info = df_de_lambda(d, e) + + # create copy to later test that they are unmodified + diag_cpy = [d.copy(), e.copy(), b.copy()] + + # solve using routine + df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b, fact=fact, + df=df, ef=ef) + # d, e, and b should be unmodified + assert_array_equal(d, diag_cpy[0]) + assert_array_equal(e, diag_cpy[1]) + assert_array_equal(b, diag_cpy[2]) + assert_(info == 0, f"info should be 0 but is {info}.") + assert_array_almost_equal(x_soln, x) + + # test that the factors from ptsvx can be recombined to make A + L = np.diag(ef, -1) + np.diag(np.ones(n)) + D = np.diag(df) + assert_allclose(A, L@D@(np.conj(L).T), atol=atol) + + # assert that the outputs are of correct type or shape + # rcond should be a scalar + assert not hasattr(rcond, "__len__"), \ + f"rcond should be scalar but is {rcond}" + # ferr should be length of # of cols in x + assert_(ferr.shape == (2,), (f"ferr.shape is {ferr.shape} but should be " + "({x_soln.shape[1]},)")) + # berr should be length of # of cols in x + assert_(berr.shape == (2,), (f"berr.shape is {berr.shape} but should be " + "({x_soln.shape[1]},)")) + + +@pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES + + REAL_DTYPES)) +@pytest.mark.parametrize("fact,df_de_lambda", + [("F", + lambda d, e: get_lapack_funcs('pttrf', + dtype=e.dtype)(d, e)), + ("N", lambda d, e: (None, None, None))]) +def test_ptsvx_error_raise_errors(dtype, realtype, fact, df_de_lambda): + rng = np.random.RandomState(42) + ptsvx = get_lapack_funcs('ptsvx', dtype=dtype) + n = 5 + # create diagonals according to size and dtype + d = generate_random_dtype_array((n,), realtype, rng) + 4 + e = generate_random_dtype_array((n-1,), dtype, rng) + A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1) + x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + b = A @ x_soln + + # use lambda to determine what df, ef are + df, ef, info = df_de_lambda(d, e) + + # test with malformatted array sizes + assert_raises(ValueError, ptsvx, d[:-1], e, b, fact=fact, df=df, ef=ef) + assert_raises(ValueError, ptsvx, d, e[:-1], b, fact=fact, df=df, ef=ef) + assert_raises(Exception, ptsvx, d, e, b[:-1], fact=fact, df=df, ef=ef) + + +@pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES + + REAL_DTYPES)) +@pytest.mark.parametrize("fact,df_de_lambda", + [("F", + lambda d, e: get_lapack_funcs('pttrf', + dtype=e.dtype)(d, e)), + ("N", lambda d, e: (None, None, None))]) +def test_ptsvx_non_SPD_singular(dtype, realtype, fact, df_de_lambda): + rng = np.random.RandomState(42) + ptsvx = get_lapack_funcs('ptsvx', dtype=dtype) + n = 5 + # create diagonals according to size and dtype + d = generate_random_dtype_array((n,), realtype, rng) + 4 + e = generate_random_dtype_array((n-1,), dtype, rng) + A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1) + x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + b = A @ x_soln + + # use lambda to determine what df, ef are + df, ef, info = df_de_lambda(d, e) + + if fact == "N": + d[3] = 0 + # obtain new df, ef + df, ef, info = df_de_lambda(d, e) + # solve using routine + df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b) + # test for the singular matrix. + assert info > 0 and info <= n + + # non SPD matrix + d = generate_random_dtype_array((n,), realtype, rng) + df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b) + assert info > 0 and info <= n + else: + # assuming that someone is using a singular factorization + df, ef, info = df_de_lambda(d, e) + df[0] = 0 + ef[0] = 0 + df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b, fact=fact, + df=df, ef=ef) + assert info > 0 + + +@pytest.mark.parametrize('d,e,b,x', + [(np.array([4, 10, 29, 25, 5]), + np.array([-2, -6, 15, 8]), + np.array([[6, 10], [9, 4], [2, 9], [14, 65], + [7, 23]]), + np.array([[2.5, 2], [2, -1], [1, -3], + [-1, 6], [3, -5]])), + (np.array([16, 41, 46, 21]), + np.array([16 + 16j, 18 - 9j, 1 - 4j]), + np.array([[64 + 16j, -16 - 32j], + [93 + 62j, 61 - 66j], + [78 - 80j, 71 - 74j], + [14 - 27j, 35 + 15j]]), + np.array([[2 + 1j, -3 - 2j], + [1 + 1j, 1 + 1j], + [1 - 2j, 1 - 2j], + [1 - 1j, 2 + 1j]]))]) +def test_ptsvx_NAG(d, e, b, x): + # test to assure that wrapper is consistent with NAG Manual Mark 26 + # example problems: f07jbf, f07jpf + # (Links expire, so please search for "NAG Library Manual Mark 26" online) + + # obtain routine with correct type based on e.dtype + ptsvx = get_lapack_funcs('ptsvx', dtype=e.dtype) + # solve using routine + df, ef, x_ptsvx, rcond, ferr, berr, info = ptsvx(d, e, b) + # determine ptsvx's solution and x are the same. + assert_array_almost_equal(x, x_ptsvx) + + +@pytest.mark.parametrize('lower', [False, True]) +@pytest.mark.parametrize('dtype', DTYPES) +def test_pptrs_pptri_pptrf_ppsv_ppcon(dtype, lower): + rng = np.random.RandomState(1234) + atol = np.finfo(dtype).eps*100 + # Manual conversion to/from packed format is feasible here. + n, nrhs = 10, 4 + a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + b = generate_random_dtype_array([n, nrhs], dtype=dtype, rng=rng) + + a = a.conj().T + a + np.eye(n, dtype=dtype) * dtype(5.) + if lower: + inds = ([x for y in range(n) for x in range(y, n)], + [y for y in range(n) for x in range(y, n)]) + else: + inds = ([x for y in range(1, n+1) for x in range(y)], + [y-1 for y in range(1, n+1) for x in range(y)]) + ap = a[inds] + ppsv, pptrf, pptrs, pptri, ppcon = get_lapack_funcs( + ('ppsv', 'pptrf', 'pptrs', 'pptri', 'ppcon'), + dtype=dtype, + ilp64="preferred") + + ul, info = pptrf(n, ap, lower=lower) + assert_equal(info, 0) + aul = cholesky(a, lower=lower)[inds] + assert_allclose(ul, aul, rtol=0, atol=atol) + + uli, info = pptri(n, ul, lower=lower) + assert_equal(info, 0) + auli = inv(a)[inds] + assert_allclose(uli, auli, rtol=0, atol=atol) + + x, info = pptrs(n, ul, b, lower=lower) + assert_equal(info, 0) + bx = solve(a, b) + assert_allclose(x, bx, rtol=0, atol=atol) + + xv, info = ppsv(n, ap, b, lower=lower) + assert_equal(info, 0) + assert_allclose(xv, bx, rtol=0, atol=atol) + + anorm = np.linalg.norm(a, 1) + rcond, info = ppcon(n, ap, anorm=anorm, lower=lower) + assert_equal(info, 0) + assert_(abs(1/rcond - np.linalg.cond(a, p=1))*rcond < 1) + + +@pytest.mark.parametrize('dtype', DTYPES) +def test_gees_trexc(dtype): + rng = np.random.RandomState(1234) + atol = np.finfo(dtype).eps*100 + + n = 10 + a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + + gees, trexc = get_lapack_funcs(('gees', 'trexc'), dtype=dtype) + + result = gees(lambda x: None, a, overwrite_a=False) + assert_equal(result[-1], 0) + + t = result[0] + z = result[-3] + + d2 = t[6, 6] + + if dtype in COMPLEX_DTYPES: + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol) + + result = trexc(t, z, 7, 1) + assert_equal(result[-1], 0) + + t = result[0] + z = result[-2] + + if dtype in COMPLEX_DTYPES: + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol) + + assert_allclose(t[0, 0], d2, rtol=0, atol=atol) + + +@pytest.mark.parametrize( + "t, expect, ifst, ilst", + [(np.array([[0.80, -0.11, 0.01, 0.03], + [0.00, -0.10, 0.25, 0.35], + [0.00, -0.65, -0.10, 0.20], + [0.00, 0.00, 0.00, -0.10]]), + np.array([[-0.1000, -0.6463, 0.0874, 0.2010], + [0.2514, -0.1000, 0.0927, 0.3505], + [0.0000, 0.0000, 0.8000, -0.0117], + [0.0000, 0.0000, 0.0000, -0.1000]]), + 2, 1), + (np.array([[-6.00 - 7.00j, 0.36 - 0.36j, -0.19 + 0.48j, 0.88 - 0.25j], + [0.00 + 0.00j, -5.00 + 2.00j, -0.03 - 0.72j, -0.23 + 0.13j], + [0.00 + 0.00j, 0.00 + 0.00j, 8.00 - 1.00j, 0.94 + 0.53j], + [0.00 + 0.00j, 0.00 + 0.00j, 0.00 + 0.00j, 3.00 - 4.00j]]), + np.array([[-5.0000 + 2.0000j, -0.1574 + 0.7143j, + 0.1781 - 0.1913j, 0.3950 + 0.3861j], + [0.0000 + 0.0000j, 8.0000 - 1.0000j, + 1.0742 + 0.1447j, 0.2515 - 0.3397j], + [0.0000 + 0.0000j, 0.0000 + 0.0000j, + 3.0000 - 4.0000j, 0.2264 + 0.8962j], + [0.0000 + 0.0000j, 0.0000 + 0.0000j, + 0.0000 + 0.0000j, -6.0000 - 7.0000j]]), + 1, 4)]) +def test_trexc_NAG(t, ifst, ilst, expect): + """ + This test implements the example found in the NAG manual, + f08qfc, f08qtc, f08qgc, f08quc. + """ + # NAG manual provides accuracy up to 4 decimals + atol = 1e-4 + trexc = get_lapack_funcs('trexc', dtype=t.dtype) + + result = trexc(t, t, ifst, ilst, wantq=0) + assert_equal(result[-1], 0) + + t = result[0] + assert_allclose(expect, t, atol=atol) + + +@pytest.mark.parametrize('dtype', DTYPES) +def test_gges_tgexc(dtype): + rng = np.random.RandomState(1234) + atol = np.finfo(dtype).eps*100 + + n = 10 + a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + b = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + + gges, tgexc = get_lapack_funcs(('gges', 'tgexc'), dtype=dtype) + + result = gges(lambda x: None, a, b, overwrite_a=False, overwrite_b=False) + assert_equal(result[-1], 0) + + s = result[0] + t = result[1] + q = result[-4] + z = result[-3] + + d1 = s[0, 0] / t[0, 0] + d2 = s[6, 6] / t[6, 6] + + if dtype in COMPLEX_DTYPES: + assert_allclose(s, np.triu(s), rtol=0, atol=atol) + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol) + assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol) + + result = tgexc(s, t, q, z, 7, 1) + assert_equal(result[-1], 0) + + s = result[0] + t = result[1] + q = result[2] + z = result[3] + + if dtype in COMPLEX_DTYPES: + assert_allclose(s, np.triu(s), rtol=0, atol=atol) + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol) + assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol) + + assert_allclose(s[0, 0] / t[0, 0], d2, rtol=0, atol=atol) + assert_allclose(s[1, 1] / t[1, 1], d1, rtol=0, atol=atol) + + +@pytest.mark.parametrize('dtype', DTYPES) +def test_gees_trsen(dtype): + rng = np.random.RandomState(1234) + atol = np.finfo(dtype).eps*100 + + n = 10 + a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + + gees, trsen, trsen_lwork = get_lapack_funcs( + ('gees', 'trsen', 'trsen_lwork'), dtype=dtype) + + result = gees(lambda x: None, a, overwrite_a=False) + assert_equal(result[-1], 0) + + t = result[0] + z = result[-3] + + d2 = t[6, 6] + + if dtype in COMPLEX_DTYPES: + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol) + + select = np.zeros(n) + select[6] = 1 + + lwork = _compute_lwork(trsen_lwork, select, t) + + if dtype in COMPLEX_DTYPES: + result = trsen(select, t, z, lwork=lwork) + else: + result = trsen(select, t, z, lwork=lwork, liwork=lwork[1]) + assert_equal(result[-1], 0) + + t = result[0] + z = result[1] + + if dtype in COMPLEX_DTYPES: + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol) + + assert_allclose(t[0, 0], d2, rtol=0, atol=atol) + + +@pytest.mark.parametrize( + "t, q, expect, select, expect_s, expect_sep", + [(np.array([[0.7995, -0.1144, 0.0060, 0.0336], + [0.0000, -0.0994, 0.2478, 0.3474], + [0.0000, -0.6483, -0.0994, 0.2026], + [0.0000, 0.0000, 0.0000, -0.1007]]), + np.array([[0.6551, 0.1037, 0.3450, 0.6641], + [0.5236, -0.5807, -0.6141, -0.1068], + [-0.5362, -0.3073, -0.2935, 0.7293], + [0.0956, 0.7467, -0.6463, 0.1249]]), + np.array([[0.3500, 0.4500, -0.1400, -0.1700], + [0.0900, 0.0700, -0.5399, 0.3500], + [-0.4400, -0.3300, -0.0300, 0.1700], + [0.2500, -0.3200, -0.1300, 0.1100]]), + np.array([1, 0, 0, 1]), + 1.75e+00, 3.22e+00), + (np.array([[-6.0004 - 6.9999j, 0.3637 - 0.3656j, + -0.1880 + 0.4787j, 0.8785 - 0.2539j], + [0.0000 + 0.0000j, -5.0000 + 2.0060j, + -0.0307 - 0.7217j, -0.2290 + 0.1313j], + [0.0000 + 0.0000j, 0.0000 + 0.0000j, + 7.9982 - 0.9964j, 0.9357 + 0.5359j], + [0.0000 + 0.0000j, 0.0000 + 0.0000j, + 0.0000 + 0.0000j, 3.0023 - 3.9998j]]), + np.array([[-0.8347 - 0.1364j, -0.0628 + 0.3806j, + 0.2765 - 0.0846j, 0.0633 - 0.2199j], + [0.0664 - 0.2968j, 0.2365 + 0.5240j, + -0.5877 - 0.4208j, 0.0835 + 0.2183j], + [-0.0362 - 0.3215j, 0.3143 - 0.5473j, + 0.0576 - 0.5736j, 0.0057 - 0.4058j], + [0.0086 + 0.2958j, -0.3416 - 0.0757j, + -0.1900 - 0.1600j, 0.8327 - 0.1868j]]), + np.array([[-3.9702 - 5.0406j, -4.1108 + 3.7002j, + -0.3403 + 1.0098j, 1.2899 - 0.8590j], + [0.3397 - 1.5006j, 1.5201 - 0.4301j, + 1.8797 - 5.3804j, 3.3606 + 0.6498j], + [3.3101 - 3.8506j, 2.4996 + 3.4504j, + 0.8802 - 1.0802j, 0.6401 - 1.4800j], + [-1.0999 + 0.8199j, 1.8103 - 1.5905j, + 3.2502 + 1.3297j, 1.5701 - 3.4397j]]), + np.array([1, 0, 0, 1]), + 1.02e+00, 1.82e-01)]) +def test_trsen_NAG(t, q, select, expect, expect_s, expect_sep): + """ + This test implements the example found in the NAG manual, + f08qgc, f08quc. + """ + # NAG manual provides accuracy up to 4 and 2 decimals + atol = 1e-4 + atol2 = 1e-2 + trsen, trsen_lwork = get_lapack_funcs( + ('trsen', 'trsen_lwork'), dtype=t.dtype) + + lwork = _compute_lwork(trsen_lwork, select, t) + + if t.dtype in COMPLEX_DTYPES: + result = trsen(select, t, q, lwork=lwork) + else: + result = trsen(select, t, q, lwork=lwork, liwork=lwork[1]) + assert_equal(result[-1], 0) + + t = result[0] + q = result[1] + if t.dtype in COMPLEX_DTYPES: + s = result[4] + sep = result[5] + else: + s = result[5] + sep = result[6] + + assert_allclose(expect, q @ t @ q.conj().T, atol=atol) + assert_allclose(expect_s, 1 / s, atol=atol2) + assert_allclose(expect_sep, 1 / sep, atol=atol2) + + +@pytest.mark.parametrize('dtype', DTYPES) +def test_gges_tgsen(dtype): + rng = np.random.RandomState(1234) + atol = np.finfo(dtype).eps*100 + + n = 10 + a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + b = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + + gges, tgsen, tgsen_lwork = get_lapack_funcs( + ('gges', 'tgsen', 'tgsen_lwork'), dtype=dtype) + + result = gges(lambda x: None, a, b, overwrite_a=False, overwrite_b=False) + assert_equal(result[-1], 0) + + s = result[0] + t = result[1] + q = result[-4] + z = result[-3] + + d1 = s[0, 0] / t[0, 0] + d2 = s[6, 6] / t[6, 6] + + if dtype in COMPLEX_DTYPES: + assert_allclose(s, np.triu(s), rtol=0, atol=atol) + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol) + assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol) + + select = np.zeros(n) + select[6] = 1 + + lwork = _compute_lwork(tgsen_lwork, select, s, t) + + # off-by-one error in LAPACK, see gh-issue #13397 + lwork = (lwork[0]+1, lwork[1]) + + result = tgsen(select, s, t, q, z, lwork=lwork) + assert_equal(result[-1], 0) + + s = result[0] + t = result[1] + q = result[-7] + z = result[-6] + + if dtype in COMPLEX_DTYPES: + assert_allclose(s, np.triu(s), rtol=0, atol=atol) + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol) + assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol) + + assert_allclose(s[0, 0] / t[0, 0], d2, rtol=0, atol=atol) + assert_allclose(s[1, 1] / t[1, 1], d1, rtol=0, atol=atol) + + +@pytest.mark.parametrize( + "a, b, c, d, e, f, rans, lans", + [(np.array([[4.0, 1.0, 1.0, 2.0], + [0.0, 3.0, 4.0, 1.0], + [0.0, 1.0, 3.0, 1.0], + [0.0, 0.0, 0.0, 6.0]]), + np.array([[1.0, 1.0, 1.0, 1.0], + [0.0, 3.0, 4.0, 1.0], + [0.0, 1.0, 3.0, 1.0], + [0.0, 0.0, 0.0, 4.0]]), + np.array([[-4.0, 7.0, 1.0, 12.0], + [-9.0, 2.0, -2.0, -2.0], + [-4.0, 2.0, -2.0, 8.0], + [-7.0, 7.0, -6.0, 19.0]]), + np.array([[2.0, 1.0, 1.0, 3.0], + [0.0, 1.0, 2.0, 1.0], + [0.0, 0.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 2.0]]), + np.array([[1.0, 1.0, 1.0, 2.0], + [0.0, 1.0, 4.0, 1.0], + [0.0, 0.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 1.0]]), + np.array([[-7.0, 5.0, 0.0, 7.0], + [-5.0, 1.0, -8.0, 0.0], + [-1.0, 2.0, -3.0, 5.0], + [-3.0, 2.0, 0.0, 5.0]]), + np.array([[1.0, 1.0, 1.0, 1.0], + [-1.0, 2.0, -1.0, -1.0], + [-1.0, 1.0, 3.0, 1.0], + [-1.0, 1.0, -1.0, 4.0]]), + np.array([[4.0, -1.0, 1.0, -1.0], + [1.0, 3.0, -1.0, 1.0], + [-1.0, 1.0, 2.0, -1.0], + [1.0, -1.0, 1.0, 1.0]]))]) +@pytest.mark.parametrize('dtype', REAL_DTYPES) +def test_tgsyl_NAG(a, b, c, d, e, f, rans, lans, dtype): + atol = 1e-4 + + tgsyl = get_lapack_funcs(('tgsyl'), dtype=dtype) + rout, lout, scale, dif, info = tgsyl(a, b, c, d, e, f) + + assert_equal(info, 0) + assert_allclose(scale, 1.0, rtol=0, atol=np.finfo(dtype).eps*100, + err_msg="SCALE must be 1.0") + assert_allclose(dif, 0.0, rtol=0, atol=np.finfo(dtype).eps*100, + err_msg="DIF must be nearly 0") + assert_allclose(rout, rans, atol=atol, + err_msg="Solution for R is incorrect") + assert_allclose(lout, lans, atol=atol, + err_msg="Solution for L is incorrect") + + +@pytest.mark.parametrize('dtype', REAL_DTYPES) +@pytest.mark.parametrize('trans', ('N', 'T')) +@pytest.mark.parametrize('ijob', [0, 1, 2, 3, 4]) +def test_tgsyl(dtype, trans, ijob): + + atol = 1e-3 if dtype == np.float32 else 1e-10 + rng = np.random.default_rng(1685779866898198) + m, n = 10, 15 + + a, d, *_ = qz(rng.uniform(-10, 10, [m, m]).astype(dtype), + rng.uniform(-10, 10, [m, m]).astype(dtype), + output='real') + + b, e, *_ = qz(rng.uniform(-10, 10, [n, n]).astype(dtype), + rng.uniform(-10, 10, [n, n]).astype(dtype), + output='real') + + c = rng.uniform(-2, 2, [m, n]).astype(dtype) + f = rng.uniform(-2, 2, [m, n]).astype(dtype) + + tgsyl = get_lapack_funcs(('tgsyl'), dtype=dtype) + rout, lout, scale, dif, info = tgsyl(a, b, c, d, e, f, + trans=trans, ijob=ijob) + + assert info == 0, "INFO is non-zero" + assert scale >= 0.0, "SCALE must be non-negative" + if ijob == 0: + assert_allclose(dif, 0.0, rtol=0, atol=np.finfo(dtype).eps*100, + err_msg="DIF must be 0 for ijob =0") + else: + assert dif >= 0.0, "DIF must be non-negative" + + # Only DIF is calculated for ijob = 3/4 + if ijob <= 2: + if trans == 'N': + lhs1 = a @ rout - lout @ b + rhs1 = scale*c + lhs2 = d @ rout - lout @ e + rhs2 = scale*f + elif trans == 'T': + lhs1 = np.transpose(a) @ rout + np.transpose(d) @ lout + rhs1 = scale*c + lhs2 = rout @ np.transpose(b) + lout @ np.transpose(e) + rhs2 = -1.0*scale*f + + assert_allclose(lhs1, rhs1, atol=atol, rtol=0., + err_msg='lhs1 and rhs1 do not match') + assert_allclose(lhs2, rhs2, atol=atol, rtol=0., + err_msg='lhs2 and rhs2 do not match') + + +@pytest.mark.parametrize('mtype', ['sy', 'he']) # matrix type +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('lower', (0, 1)) +def test_sy_hetrs(mtype, dtype, lower): + if mtype == 'he' and dtype in REAL_DTYPES: + pytest.skip("hetrs not for real dtypes.") + rng = np.random.default_rng(1723059677121834) + n, nrhs = 20, 5 + if dtype in COMPLEX_DTYPES: + A = (rng.uniform(size=(n, n)) + rng.uniform(size=(n, n))*1j).astype(dtype) + else: + A = rng.uniform(size=(n, n)).astype(dtype) + + A = A + A.T if mtype == 'sy' else A + A.conj().T + b = rng.uniform(size=(n, nrhs)).astype(dtype) + names = f'{mtype}trf', f'{mtype}trf_lwork', f'{mtype}trs' + trf, trf_lwork, trs = get_lapack_funcs(names, dtype=dtype) + lwork = trf_lwork(n, lower=lower) + ldu, ipiv, info = trf(A, lwork=lwork) + assert info == 0 + x, info = trs(a=ldu, ipiv=ipiv, b=b) + assert info == 0 + eps = np.finfo(dtype).eps + assert_allclose(A@x, b, atol=100*n*eps) + + +@pytest.mark.parametrize('norm', list('Mm1OoIiFfEe')) +@pytest.mark.parametrize('uplo, m, n', [('U', 5, 10), ('U', 10, 10), + ('L', 10, 5), ('L', 10, 10)]) +@pytest.mark.parametrize('diag', ['N', 'U']) +@pytest.mark.parametrize('dtype', DTYPES) +def test_lantr(norm, uplo, m, n, diag, dtype): + rng = np.random.default_rng(98426598246982456) + A = rng.random(size=(m, n)).astype(dtype) + lantr, lange = get_lapack_funcs(('lantr', 'lange'), (A,)) + res = lantr(norm, A, uplo=uplo, diag=diag) + + # now modify the matrix according to assumptions made by `lantr` + A = np.triu(A) if uplo == 'U' else np.tril(A) + if diag == 'U': + i = np.arange(min(m, n)) + A[i, i] = 1 + ref = lange(norm, A) + + assert_allclose(res, ref, rtol=2e-6) diff --git a/shared/package-files/33/339775a722d56e07e26739aa840bf09603eef0c1cebb971bd26727b279f8cf75/partitioners.py b/shared/package-files/33/339775a722d56e07e26739aa840bf09603eef0c1cebb971bd26727b279f8cf75/partitioners.py new file mode 100644 index 0000000000000000000000000000000000000000..dd8f86055da1d8420130e9caeb2ab59c27d2a385 --- /dev/null +++ b/shared/package-files/33/339775a722d56e07e26739aa840bf09603eef0c1cebb971bd26727b279f8cf75/partitioners.py @@ -0,0 +1,981 @@ +# mypy: ignore-errors + +from torch.fx.experimental.proxy_tensor import is_sym_node, py_sym_types +from torch.fx.experimental.sym_node import magic_methods, method_to_operator +from torch.fx.experimental.symbolic_shapes import ( + hint_int, free_symbols, is_symbol_binding_fx_node, find_symbol_binding_fx_nodes +) +from torch.fx.experimental._backward_state import BackwardState +import torch +import torch.fx as fx +import operator +import math +import torch.utils._pytree as pytree +import copy +import os +import itertools +import sympy +from collections import defaultdict +from torch.fx.passes import graph_drawer +from typing import List, Optional, Set, Tuple, Union +from .compile_utils import fx_graph_cse, get_aten_target +from . import config +import functools + + +AOT_PARTITIONER_DEBUG = config.debug_partitioner + + +def must_recompute(node): + return node.meta.get("recompute", False) + +def has_recomputable_ops(fx_g): + found = False + for node in fx_g.graph.nodes: + if must_recompute(node): + return True + return False + +def has_recomputable_rng_ops(fx_g): + for node in fx_g.graph.nodes: + if must_recompute(node) and hasattr(node.target, "tags") and torch.Tag.nondeterministic_seeded in node.target.tags: + return True + return False + +def sym_node_size(node): + if isinstance(node.meta["val"], (torch.SymInt, torch.SymBool)): + return 1 + assert isinstance(node.meta["val"], torch.SymFloat) + return 4 + +class InvalidNodeBase: + def __repr__(self): + return "Invalid Node" + + +InvalidNode = InvalidNodeBase() + + +def _extract_graph_with_inputs_outputs(joint_graph, inputs, outputs): + """ + Given a graph, extracts out a subgraph that takes the specified nodes as + inputs and returns the specified outputs. + + This includes specifying non-placeholder nodes as inputs. + + The general strategy is to initialize all inputs with proxies as we + encounter them, and trace through the graph, only keeping values which take + in valid proxies. Then, all dead code is eliminated. + """ + new_graph = fx.Graph() + env = {} + + # Add new placeholder nodes in the order specified by the inputs + for node in inputs: + new_node = new_graph.placeholder(node.name) + # Can't use node_copy here as we may be turning previous call_function into placeholders + new_node.meta = node.meta + env[node] = new_node + + for node in joint_graph.nodes: + if node in inputs: + continue + elif node.op == 'placeholder': + env[node] = InvalidNode + elif node.op == 'call_function': + all_args = pytree.arg_tree_leaves(*node.args, **node.kwargs) + all_args = [isinstance(env[x], InvalidNodeBase) for x in all_args if isinstance(x, fx.Node)] + if any(all_args): + env[node] = InvalidNode + continue + env[node] = new_graph.node_copy(node, lambda x: env[x]) + elif node.op == 'get_attr': + env[node] = new_graph.node_copy(node, lambda x: env[x]) + elif node.op == 'output': + pass + output_values = [] + for x in outputs: + if isinstance(x, fx.Node): + if x not in env: + raise RuntimeError(f"Node {x} couldn't be found in env") + assert not isinstance(env[x], InvalidNodeBase), f"Node {x} was invalid, but is output" + output_values.append(env[x]) + else: + output_values.append(x) + new_graph.output(output_values) + + new_graph.eliminate_dead_code() + new_graph.lint() + return new_graph + + +def _is_primal(node): + return ( + node.op == "placeholder" + and "tangents" not in node.target + and not _is_bwd_seed_offset(node) + and not _is_fwd_seed_offset(node) + ) + +def _is_tangent(node): + return node.op == "placeholder" and "tangents" in node.target + +def _is_bwd_seed_offset(node): + return node.op == "placeholder" and ("bwd_seed" in node.target or "bwd_base_offset" in node.target) + +def _is_fwd_seed_offset(node): + return node.op == "placeholder" and ("fwd_seed" in node.target or "fwd_base_offset" in node.target) + +def _is_backward_state(node): + return node.op == "placeholder" and isinstance(node.meta.get("val"), BackwardState) + + +def _extract_fwd_bwd_outputs(joint_module: fx.GraphModule, *, num_fwd_outputs): + outputs = pytree.arg_tree_leaves(*(node.args for node in joint_module.graph.nodes if node.op == 'output')) + fwd_outputs = outputs[:num_fwd_outputs] + bwd_outputs = outputs[num_fwd_outputs:] + return fwd_outputs, bwd_outputs + + +def _remove_by_name(saved_values, name): + for saved_value in saved_values: + if saved_value.name == name: + saved_values.remove(saved_value) + break + +def _placeholders(nodes): + # Avoid making an entire pass over the graph if we only care about the input placeholders + result = [] + for node in nodes: + if node.op == 'placeholder': + result.append(node) + else: + break # placeholders are all at the start of graph + return result + + +def _extract_fwd_bwd_modules(joint_module: fx.GraphModule, saved_values, saved_sym_nodes, *, num_fwd_outputs): + fwd_outputs, bwd_outputs = _extract_fwd_bwd_outputs(joint_module, num_fwd_outputs=num_fwd_outputs) + placeholders = _placeholders(joint_module.graph.nodes) + primal_inputs = [*filter(_is_primal, placeholders)] + tangent_inputs = [*filter(_is_tangent, placeholders)] + fwd_seed_offset_inputs = [*filter(_is_fwd_seed_offset, placeholders)] + bwd_seed_offset_inputs = [*filter(_is_bwd_seed_offset, placeholders)] + backward_state_inputs = [*filter(_is_backward_state, placeholders)] + + bwd_graph = _extract_graph_with_inputs_outputs( + joint_module.graph, + saved_sym_nodes + saved_values + tangent_inputs + bwd_seed_offset_inputs, + bwd_outputs + ) + + for node in _placeholders(bwd_graph.nodes): + assert node.op == 'placeholder' + # This is to filter out saved values that don't actually end up being used by the backwards pass + if not node.users: + _remove_by_name(saved_values, node.name) + _remove_by_name(saved_sym_nodes, node.name) + elif _is_backward_state(node): + # BackwardState is saved directly + _remove_by_name(saved_values, node.name) + assert backward_state_inputs + + + # Now that we have the finalized list of saved values, we need to ensure + # we propagate all symbols which are referenced by backwards inputs. + # These are not directly used in the graph but are required for downstream + # sizevar assignment + saved_symbols: Set[sympy.Symbol] = set() + saved_sym_nodes_binding = [] + saved_sym_nodes_derived = [] + + # Some symbols may already be bound in the directly saved_sym_nodes, + # keep track of them so we don't re-bind them + for node in saved_sym_nodes: + symbol = is_symbol_binding_fx_node(node) + if symbol: + saved_symbols.add(symbol) + saved_sym_nodes_binding.append(node) + else: + saved_sym_nodes_derived.append(node) + + # Now go through all of the prospective backward inputs and track any + # other symbols we need to bind + symbol_bindings = find_symbol_binding_fx_nodes(joint_module.graph) + for node in itertools.chain(saved_sym_nodes_derived, saved_values, tangent_inputs): + if "val" not in node.meta: + continue + new_symbols = free_symbols(node.meta["val"]) - saved_symbols + # NB: Deterministic order please! + for s in sorted(new_symbols, key=lambda s: s.name): + # NB: For well formed graphs, the symbol should always be present, + # but we also have ways to produce ill-formed graphs, e.g., direct + # make_fx usages, so don't choke in this case + if s not in symbol_bindings: + continue + saved_sym_nodes_binding.append(symbol_bindings[s]) + saved_symbols |= new_symbols + + + # Update saved_sym_nodes that are now reordered to have all bindings at + # front. This can also be used later on to figure out the position of saved + # sym nodes in the output of fwd graph. + saved_sym_nodes.clear() + saved_sym_nodes.extend(saved_sym_nodes_binding + saved_sym_nodes_derived) + + # Now, we re-generate the fwd/bwd graphs. + # NB: This might increase compilation time, but I doubt it matters + fwd_graph = _extract_graph_with_inputs_outputs( + joint_module.graph, + primal_inputs + fwd_seed_offset_inputs, + fwd_outputs + saved_values + saved_sym_nodes + ) + bwd_graph = _extract_graph_with_inputs_outputs( + joint_module.graph, + saved_sym_nodes + saved_values + tangent_inputs + bwd_seed_offset_inputs + backward_state_inputs, + bwd_outputs + ) + + fwd_module = fx._lazy_graph_module._make_graph_module(joint_module, fwd_graph) + bwd_module = fx._lazy_graph_module._make_graph_module(joint_module, bwd_graph) + return fwd_module, bwd_module + + +def default_partition( + joint_module: fx.GraphModule, _joint_inputs, *, num_fwd_outputs +) -> Tuple[fx.GraphModule, fx.GraphModule]: + """ + Partitions the :attr:`joint_module` in a manner that closely resembles the + behavior observed in the original ``.forward()`` and ``.backward()`` of the + callable, i.e., the resulting forward graph contains those operators that + are executed in the original ``.forward()`` callable passed to + :func:`aot_function`. + + The default partitioner collects the operators that are between the forward + inputs and the forward outputs. This helps in finding the tensors which have + to be stashed for the backward pass. These stashed tensors become the output + of the generated forward graph. The remaining operators are then placed in + the backward graph. + + .. warning:: + This API is experimental and likely to change. + + Args: + joint_module(fx.GraphModule): The joint forward and backward graph. This + is the result of AOT Autograd tracing. + + Returns: + Returns the generated forward and backward Fx graph modules. + """ + if has_recomputable_ops(joint_module): + return min_cut_rematerialization_partition(joint_module, _joint_inputs, num_fwd_outputs=num_fwd_outputs) + primal_inputs = list(filter(_is_primal, joint_module.graph.nodes)) + fwd_seed_offset_inputs = list(filter(_is_fwd_seed_offset, joint_module.graph.nodes)) + inputs = primal_inputs + fwd_seed_offset_inputs + fwd_outputs, bwd_outputs = _extract_fwd_bwd_outputs(joint_module, num_fwd_outputs=num_fwd_outputs) + forward_only_graph = _extract_graph_with_inputs_outputs(joint_module.graph, inputs, fwd_outputs) + forward_node_names = {node.name for node in forward_only_graph.nodes if node.op != 'output'} + saved_values = [] + saved_sym_nodes = [] + + for node in joint_module.graph.nodes: + if node.name not in forward_node_names: + continue + if is_sym_node(node): + # Symints must be kept separate from tensors so that PythonFunction only calls + # save_for_backward on tensors and stashes symints in autograd .ctx + saved_sym_nodes.append(node) + elif ( + 'tensor_meta' not in node.meta + and node.op == 'call_function' + ): + # Since we can't save tuple of tensor values, we need to flatten out what we're saving + users = node.users + assert all(user.target == operator.getitem for user in users) + saved_values.extend(users) + else: + backward_usages = [n for n in node.users if n.name not in forward_node_names] + if 'tensor_meta' in node.meta and all(is_sym_node(n) for n in backward_usages): + # If we have a tensor in the forward, where only its sizes/strides are needed in the backward, + # and not the actual tensor data, + # then it will be a lot cheaper to save only the sizes/strides, and not the actual tensor. + # + # Note that saving the tensor could also cause compilation problems: + # If the user mutated an input in the forward and uses its sizes/strides in the backward, + # then we would be obligated to clone the input before saving it to appease autograd. + # (This is how we originally found this bug). + saved_sym_nodes.extend(backward_usages) + else: + saved_values.append(node) + saved_values = list(dict.fromkeys(saved_values).keys()) + saved_sym_nodes = list(dict.fromkeys(saved_sym_nodes).keys()) + + return _extract_fwd_bwd_modules(joint_module, saved_values, saved_sym_nodes=saved_sym_nodes, num_fwd_outputs=num_fwd_outputs) + + +def _prod(x): + s = 1 + for i in x: + s *= i + return s + +def _tensor_nbytes(numel, dtype): + return numel * dtype.itemsize + +def _size_of(node: fx.Node) -> int: + if 'val' in node.meta: + val = node.meta['val'] + if isinstance(val, py_sym_types): + if isinstance(val, torch.SymInt): + return 1 + else: + return 999999 + # NB: The fallback values here are meaningless, maybe we should respect + # torch._inductor.config.unbacked_symint_fallback (but this is a + # layering violation) + elif isinstance(val, (list, tuple)): + return sum(_tensor_nbytes(hint_int(n.numel(), fallback=4098), n.dtype) for n in val if isinstance(n, torch.Tensor)) + elif isinstance(val, torch.Tensor): + return _tensor_nbytes(hint_int(val.numel(), fallback=4098), val.dtype) + + raise RuntimeError(f"Unknown metadata type {type(val)}") + + # Only needed since we don't always trace with fake tensors. + if 'tensor_meta' in node.meta: + metadata = node.meta['tensor_meta'] + # TODO: What is to_size_hint suppose to be? + numel = _prod(map(to_size_hint, metadata.shape)) # noqa: F821 + dtype = metadata.dtype + else: + return 0 + + return _tensor_nbytes(numel, dtype) + + +# Used for some investigative purposes +def _count_ops(graph): + from collections import defaultdict + cnt = defaultdict(int) + for node in graph.nodes: + if node.op == 'call_function': + cnt[node.target.__name__] += 1 + print(sorted(cnt.items(), key=lambda x: x[1], reverse=True)) + + +@functools.lru_cache(None) +def pointwise_ops(): + ops = [] + for attr_name in dir(torch.ops.aten): + opoverloadpacket = getattr(torch.ops.aten, attr_name) + if not isinstance(opoverloadpacket, torch._ops.OpOverloadPacket): + continue + + for overload in opoverloadpacket.overloads(): + op_overload = getattr(opoverloadpacket, overload) + if torch.Tag.pointwise in op_overload.tags: + # currently aot autograd uses packet not overload + ops.append(opoverloadpacket) + break + + return ops + +def get_depth(node, depth_map): + if node in depth_map: + return depth_map[node] + + # Base case + if node.op == "placeholder": + depth_map[node] = 0 + return depth_map[node] + + # Handle output node + if node.op == "output": + args = node.args[0] + for arg in args: + if isinstance(arg, torch.fx.node.Node): + get_depth(arg, depth_map) + return + + # Get the depth of args and set the depth of this node + arg_depths = [get_depth(arg, depth_map) for arg in node.all_input_nodes if isinstance(arg, torch.fx.node.Node)] + # factory ops like full, rand might not have any input args + if len(arg_depths) == 0: + arg_depths = [0] + depth_map[node] = max(arg_depths) + 1 + return depth_map[node] + + +def sort_depths(args, depth_map): + arg_depths = {arg: depth_map[arg] for arg in args if isinstance(arg, torch.fx.node.Node)} + return sorted(arg_depths.items(), key=lambda x: x[1], reverse=True) + + +def reordering_to_mimic_autograd_engine(gm): + """ + This pass finds the first bwd node in the graph (by looking at users of + tangents) and then reorders the graph by walking from this node to all the + way to the end of the graph. At each op in this traveral, we insert this op + in a new graph and try to bring only the relevant subgraph from the other + non-bwd edges relevant for this op. This closely mimics the behavior of + autograd engine. + + Why is this pass required in the first place? + + This is an artifact of how partitioners work today. The starting point of + partitioner is a joint graph, which is fwd and then bwd graph. In the case + of checkpointing, we keep portions of fwd graph in their original place in + the joint graph, while obtaining a bwd graph. As a result, the resulting bwd + graph has copies of recomputed fwd subgraphs followed by the original bwd + graph. If we run this naively, this leads to bad memory footprint, because + the fwd subgraphs are live for way longer duration than necessary. This pass + reorders the operations such that we prioritize the ops for the original bwd + graph while only realizing those ops from the fwd graph that are necessary + at any given point in the graph. + """ + + new_graph = fx.Graph() + env = {} + + # Add new placeholder nodes in the order specified by the inputs + for node in gm.graph.nodes: + if node.op == "placeholder": + new_node = new_graph.placeholder(node.name) + # Can't use node_copy here as we may be turning previous call_function into placeholders + new_node.meta = node.meta + env[node] = new_node + + + order = {} + for idx, node in enumerate(gm.graph.nodes): + order[node] = idx + + # Populate depth for the nodes. Depth is the distance from the inputs. + depths = {} + output_node = next(node for node in gm.graph.nodes if node.op == "output") + get_depth(output_node, depths) + + def insert_node_in_graph(node): + if node in env: + return env[node] + + # Bias traversal towards the nodes that have higher depth - prioritizes + # critical path first. + for arg, _ in sort_depths(node.all_input_nodes, depths): + env[arg] = insert_node_in_graph(arg) + env[node] = new_graph.node_copy(node, lambda x: env[x]) + return env[node] + + # Find first bwd node in the graph + tangent_inputs = list(filter(_is_tangent, gm.graph.nodes)) + first_node_in_bwd = None + minimum_order = math.inf + for tangent in tangent_inputs: + for user in tangent.users: + if order[user] < minimum_order: + minimum_order = order[user] + first_node_in_bwd = user + assert first_node_in_bwd is not None + + # Build the graph op-by-op by starting from the node all the way to the end + for node in list(gm.graph.nodes)[order[first_node_in_bwd]:]: + insert_node_in_graph(node) + + # The output node is already built by the traversal. + new_gm = torch.fx.GraphModule(gm, new_graph) + return new_gm + + +def functionalize_rng_ops(joint_module, fw_module, bw_module, num_sym_nodes): + # During user-driven activation checkpointing, we have to ensure that a rng + # op in fwd yields the same output as the recomputed rng op in the bwd. To + # do this, we use functionalize wrappers to wrap the random ops and share + # rng state between the fwd and bwd graphs. + + # There are 3 main steps to do this + # Step 1 - Construct a mapping of rng node between the fwd and its counterpart in bwd. + # Step 2 - Modify the fwd pass such that + # 1) Replace rand with run_and_save_rng_state wrapper + # 2) Replace the users of the original op with the output[1] of this op. + # 3) Collect all the rng_state - output[0] of each op, and make them + # output nodes. Special care needs to be taken here because fwd outputs + # has symints at the very end. + # Step 3 - Modify the bwd pass such that + # 1) Add the input nodes just before the tangents for the stashed rng states + # 2) Replace rand with run_with_save_rng_state wrappers + # 3) Use the stashed states as inputs to these ops + + # Unique id to generate name + uid = itertools.count() + + def get_rng_ops(gmod): + random_nodes = {} + for node in gmod.graph.nodes: + if ( + node.op == "call_function" + and hasattr(node.target, "tags") + and torch.Tag.nondeterministic_seeded in node.target.tags + ): + random_nodes[node.name] = node + return random_nodes + + def get_device(node): + """ + Check the example value of the node outputs to find the device type. + """ + if "val" not in node.meta: + return None + + candidates = node.meta["val"] + if not isinstance(candidates, tuple): + candidates = (candidates,) + + for candidate in candidates: + if isinstance(candidate, torch.Tensor): + if candidate.device.type == "cuda": + return "cuda" + + return "cpu" + + def get_sample_rng_state(device): + if device == "cuda": + return torch.cuda.get_rng_state() + return torch.get_rng_state() + + # Step 1 - Construct a mapping of rng node between the fwd and its counterpart in bwd. + joint_graph_rng_ops = get_rng_ops(joint_module) + fw_graph_rng_ops = get_rng_ops(fw_module) + bw_graph_rng_ops = get_rng_ops(bw_module) + recomputable_rng_ops_map = dict() + for node in joint_module.graph.nodes: + if ( + must_recompute(node) + and hasattr(node.target, "tags") + and torch.Tag.nondeterministic_seeded in node.target.tags + ): + base_node = joint_graph_rng_ops[node.name] + fw_node = fw_graph_rng_ops[node.name] + bw_node = bw_graph_rng_ops[node.name] + recomputable_rng_ops_map[base_node] = {"fwd": fw_node, "bwd": bw_node} + + run_and_save_rng = torch._prims.rng_prims.run_and_save_rng_state + run_with_rng_state = torch._prims.rng_prims.run_with_rng_state + + for node in bw_module.graph.nodes: + if node.op == "placeholder" and "tangent" in node.name: + bw_tangent_start_node = node + break + + + fw_rng_state_outputs = [] + for base_node, node_pair in recomputable_rng_ops_map.items(): + # Step 2 - Modify the fwd pass such that + fw_node = node_pair["fwd"] + bw_node = node_pair["bwd"] + fw_graph = fw_module.graph + with fw_graph.inserting_before(fw_node): + functional_fw_node = fw_graph.create_node( + "call_function", + run_and_save_rng, + args=(fw_node.target, *fw_node.args), + kwargs=fw_node.kwargs + ) + state = fw_graph.create_node("call_function", operator.getitem, args=(functional_fw_node, 0), kwargs={}) + rng_output = fw_graph.create_node("call_function", operator.getitem, args=(functional_fw_node, 1,), kwargs={}) + fw_node.replace_all_uses_with(rng_output) + fw_graph.erase_node(fw_node) + fw_rng_state_outputs.append(state) + + + # Step 3 - Modify the bwd pass such that + bw_graph = bw_module.graph + with bw_graph.inserting_before(bw_tangent_start_node): + state_name = f"rng_state_output_{next(uid)}" + bw_rng_state_node = bw_graph.placeholder(state_name) + bw_rng_state_node.meta["val"] = get_sample_rng_state(get_device(fw_node)) + + with bw_graph.inserting_before(bw_node): + rng_output = bw_graph.create_node( + "call_function", + run_with_rng_state, + args=(bw_rng_state_node, bw_node.target, *bw_node.args), + kwargs=bw_node.kwargs + ) + + bw_node.replace_all_uses_with(rng_output) + bw_graph.erase_node(bw_node) + + + # Add the rng states in the output of the fwd graph. AOT Autograd assumes + # that symints are at the end of forward graph outputs. So, insert the new + # rng states accordingly. + fw_output_node = next(node for node in fw_module.graph.nodes if node.op == "output") + fw_outputs = fw_output_node.args[0] + sym_node_start_idx = len(fw_outputs) - num_sym_nodes + outputs = fw_outputs[:sym_node_start_idx] + fw_rng_state_outputs + fw_outputs[sym_node_start_idx:] + fw_module.graph.output(outputs) + fw_module.graph.erase_node(fw_output_node) + fw_module.recompile() + bw_module.recompile() + return fw_module, bw_module + + +def cleanup_recompute_tags(joint_module): + """ + If there are two consecutive checkpointed blocks with no operator in + between, we would still want to stash the tensor at the boundary of + checkpointed blocks. The following pass makes the last output node + non-recomputable to allow for that. + """ + for node in joint_module.graph.nodes: + if must_recompute(node): + for user in node.users: + if must_recompute(user) and user.meta["recompute"] > node.meta["recompute"]: + node.meta["recompute"] = 0 + return joint_module + + +def min_cut_rematerialization_partition( + joint_module: fx.GraphModule, _joint_inputs, compiler="inductor", recomputable_ops=None, + *, num_fwd_outputs +) -> Tuple[fx.GraphModule, fx.GraphModule]: + """ + Partitions the joint graph such that the backward recomputes the forward. + Recomputing helps in trading off memory bandwidth with computation. + + To create the fwd and bwd graph, we copy the joint graph, manually set the + outputs to just original forward or backward outputs. And then we run the + resulting graphs through dead code elimination. + + .. warning:: + This API is experimental and likely to change. + + Args: + joint_module(fx.GraphModule): The joint forward and backward graph. This + is the result of AOT Autograd tracing. + _joint_inputs: The inputs to the joint graph. This is unused. + compiler: This option determines the default set of recomputable ops. + Currently, there are two options: ``nvfuser`` and ``inductor``. + recomputable_ops: This is an optional set of recomputable ops. If this + is not None, then this set of ops will be used instead of the + default set of ops. + num_fwd_outputs: The number of outputs from the forward graph. + + Returns: + Returns the generated forward and backward Fx graph modules. + """ + try: + import networkx as nx + except ImportError as e: + raise RuntimeError("Need networkx installed to perform smart recomputation " + "heuristics") from e + + joint_module.graph.eliminate_dead_code() + joint_module.recompile() + + fx_g = joint_module.graph + + # add the CSE pass + if config.cse: + cse_graph = fx_graph_cse(fx_g) + joint_module.graph = cse_graph + full_bw_graph = joint_module.graph + + graph_has_recomputable_ops = has_recomputable_ops(joint_module) + graph_has_recomputable_rng_ops = has_recomputable_rng_ops(joint_module) + if graph_has_recomputable_ops: + joint_module = cleanup_recompute_tags(joint_module) + + name_to_node = {} + for node in joint_module.graph.nodes: + name_to_node[node.name] = node + + def classify_nodes(joint_module): + required_bw_nodes = set() + for node in joint_module.graph.nodes: + if node.op == 'placeholder' and "tangents" in node.target: + required_bw_nodes.add(node) + if node in required_bw_nodes: + for user in node.users: + required_bw_nodes.add(user) + + primal_inputs = list(filter(_is_primal, joint_module.graph.nodes)) + fwd_seed_offset_inputs = list(filter(_is_fwd_seed_offset, joint_module.graph.nodes)) + inputs = primal_inputs + fwd_seed_offset_inputs + fwd_outputs, bwd_outputs = _extract_fwd_bwd_outputs(joint_module, num_fwd_outputs=num_fwd_outputs) + required_bw_nodes.update(o for o in bwd_outputs if o is not None) + forward_only_graph = _extract_graph_with_inputs_outputs(joint_module.graph, inputs, fwd_outputs) + required_fw_nodes = {name_to_node[node.name] for node in forward_only_graph.nodes + if node.op != 'output'} + unclaimed_nodes = {node for node in joint_module.graph.nodes + if node not in required_fw_nodes and node not in required_bw_nodes} + return fwd_outputs, required_fw_nodes, required_bw_nodes, unclaimed_nodes, inputs + + orig_fw_outputs, required_fw_nodes, required_bw_nodes, unclaimed_nodes, inputs = classify_nodes(joint_module) + + # networkx blows up on graphs with no required backward nodes + # Since there's nothing to partition anyway, and the default partitioner can "handle" + # this case, send our graph over to the default partitioner. + if len(required_bw_nodes) == 0: + return default_partition(joint_module, _joint_inputs, num_fwd_outputs=num_fwd_outputs) + + for node in reversed(joint_module.graph.nodes): + if node not in required_fw_nodes: + node.dist_from_bw = 0 + else: + node.dist_from_bw = int(1e9) + for user in node.users: + node.dist_from_bw = min(node.dist_from_bw, user.dist_from_bw + 1) + + aten = torch.ops.aten + prims = torch.ops.prims + + # compiler == "nvfuser" is the default set of recomputable ops + default_recomputable_ops = [aten.add, aten.sub, aten.div, aten.atan2, aten.mul, aten.max, aten.min, aten.pow, aten.remainder, aten.fmod, aten.__and__, aten.__or__, aten.__xor__, aten.__lshift__, aten.__rshift__, aten.eq, aten.ne, aten.ge, aten.gt, aten.le, aten.lt, aten.abs, aten.bitwise_not, aten.ceil, aten.floor, aten.frac, aten.neg, aten.relu, aten.round, aten.silu, aten.trunc, aten.log, aten.log10, aten.log1p, aten.log2, aten.lgamma, aten.exp, aten.expm1, aten.erf, aten.erfc, aten.cos, aten.acos, aten.cosh, aten.sin, aten.asin, aten.sinh, aten.tan, aten.atan, aten.tanh, aten.atanh, aten.sqrt, aten.rsqrt, aten.reciprocal, aten.sigmoid, aten.softplus, aten.threshold, aten.threshold_backward, aten.clamp, aten.where, aten.lerp, aten.addcmul, aten.gelu, aten.gelu_backward, aten.sum, aten.mean, aten._grad_sum_to_size, aten.sum_to_size, aten.amax, aten.to, aten.type_as, operator.getitem, aten.squeeze, aten.unsqueeze, aten.rsub, aten._to_copy] # noqa: E501,B950 + view_ops = [aten.squeeze, aten.unsqueeze, aten.alias] + if compiler == "inductor": + default_recomputable_ops += [prims.div, prims.convert_element_type, aten.clone, aten._to_copy, aten.full_like, prims.var, prims.sum, aten.var, aten.std, prims.broadcast_in_dim, aten.select, aten.permute, aten._unsafe_view, aten.view, aten.expand, aten.slice, aten.reshape, aten.broadcast_tensors, aten.scalar_tensor, aten.ones, aten.new_zeros, aten.lift_fresh_copy, aten.arange, aten.triu, aten.var_mean, aten.isinf, aten.any, aten.full, aten.as_strided, aten.zeros, aten.argmax, aten.maximum] # noqa: E501,B950 + view_ops += [aten.view, aten.slice, aten.permute, aten.t, prims.broadcast_in_dim, aten.expand, aten.as_strided] + # Natalia said that we should allow recomputing indexing :) + default_recomputable_ops += [aten.index] + default_recomputable_ops += view_ops + + default_recomputable_ops += pointwise_ops() + + default_recomputable_ops += [ + aten.zeros_like, + ] + + default_recomputable_ops += [ + method_to_operator(m) + for m in magic_methods + ] + + recomputable_ops = set(recomputable_ops) if recomputable_ops is not None else set(default_recomputable_ops) + + random_ops = [aten.native_dropout, aten.rand_like, aten.randn_like] + compute_intensive_ops = [aten.mm, aten.convolution, aten.convolution_backward, aten.bmm, aten.addmm, aten.upsample_bilinear2d, aten._softmax, aten._softmax_backward_data, aten.native_layer_norm, aten.native_layer_norm_backward, aten.native_batch_norm, aten.native_batch_norm_backward, aten._native_batch_norm_legit] # noqa: E501,B950 + + fusible_ops = recomputable_ops | set(random_ops) + if AOT_PARTITIONER_DEBUG: + joint_module_ops = { + str(node.target._overloadpacket) + for node in joint_module.graph.nodes + if node.op == "call_function" and hasattr(node.target, "_overloadpacket") + } + ops_ignored = joint_module_ops - {str(i) for i in recomputable_ops} + print("Ops banned from rematerialization: ", ops_ignored) + print() + + def is_materialized_backwards(node): + cur_nodes = {node} + while len(cur_nodes) > 0: + cur = cur_nodes.pop() + for user in cur.users: + if user not in required_fw_nodes and not is_fusible(cur, user): + return True + if user not in required_fw_nodes and get_aten_target(user) in view_ops: + cur_nodes.add(user) + + return False + + def ban_recomputation(node): + if "recompute" in node.meta: + return node.meta["recompute"] == 0 + elif config.aggressive_recomputation: + ignored_ops = random_ops + compute_intensive_ops + return (node.op == 'call_function' and get_aten_target(node) in ignored_ops) + else: + if node.op != 'call_function': + return False + if get_aten_target(node) not in recomputable_ops: + return True + if node.target == operator.getitem: + return False + if node.target in [aten.lift_fresh_copy.default, aten.lift_fresh.default]: + return False + + # If a node *must* be materialized in the backwards pass, then we + # should never recompute it. This is a pretty subtle point. In + # general, the assumption we make is that recomputing a node in the + # backwards pass is "free". However, if a node must be materialized + # in the backwards pass, then recomputing it is never free. + if is_materialized_backwards(node): + return True + + # Arbitrary hack that sometimes seems to help things. The above + # modification appears to have made this heuristic a lot less critical + # for performance. + # TODO: Investigate why this hack helps. + # TODO: Investigate the interaction with compiler assisted + # activation checkpointing. Removing the heuristic improves both + # memory footprint and speedup. + if not graph_has_recomputable_ops: + if compiler == "inductor" and node.dist_from_bw > config.max_dist_from_bw: + return True + # If the output of an op is 4x smaller (arbitrary choice), + # then we don't allow recomputation. + input_tensors_size = sum(_size_of(i) for i in node.args if isinstance(i, fx.Node)) + output_size = _size_of(node) + return (output_size * 4 < input_tensors_size) + + def is_fusible(a, b): + # We can perform "memory fusion" into a cat, but cat cannot be a + # producer to a fusion + if get_aten_target(b) == aten.cat: + return True + return get_aten_target(a) in fusible_ops and get_aten_target(b) in fusible_ops + + def is_materialized(node): + if node.op == 'placeholder': + return True + + return not all(is_fusible(node, user) for user in node.users) + + def get_node_weight(node) -> int: + mem_sz = _size_of(node) + + # Heuristic to bias towards nodes closer to the backwards pass + # Complete guess about current value + mem_sz = int(mem_sz * (1.1 ** max(min(node.dist_from_bw, 100), 1))) + # mem_sz = int(mem_sz + node.dist_from_bw) + + if is_materialized(node): + return mem_sz + else: + return mem_sz * 2 + + nx_graph = nx.DiGraph() + for node in full_bw_graph.nodes: + if node.op == 'output': + continue + + if node in required_bw_nodes: + if node not in inputs: + nx_graph.add_edge(node.name + "_in", "sink", capacity=math.inf) + continue + # If someone saves a input for backward as-is and backward + # returns that tensor as-is as a grad input, then the node x would + # be both a required_bw_node and an input. In this case we + # (1) connect x_in to to the source, (2) x_out to the sink, and + # (3) assign the proper weight to the x_in-x_out edge, so that + # x would be part of cut nodes. A case where this happens is if + # NestedTensor saves a offset tensor as part of the singleton int + # in sizes. + nx_graph.add_edge(node.name + "_out", "sink", capacity=math.inf) + + if _is_primal(node) or _is_fwd_seed_offset(node): + nx_graph.add_edge("source", node.name + "_in", capacity=math.inf) + + # If a node can't be recomputed (too expensive or involves randomness), + # we prevent it from being recomputed by adding an inf edge to the source + # We only need to ban nodes in the fw pass, as those are the only ones that would be recomputed. + if ban_recomputation(node) and node in required_fw_nodes: + nx_graph.add_edge("source", node.name + "_in", capacity=math.inf) + + # Checks if a node is actually a tuple. Can be simplified to just an isinstance check if we always use faketensors. + is_non_tensor_node = (('val' not in node.meta and 'tensor_meta' not in node.meta) or + ('val' in node.meta and not isinstance(node.meta['val'], torch.Tensor))) + + if is_sym_node(node): + weight = sym_node_size(node) + elif is_non_tensor_node: + weight = 0 if isinstance(node.meta.get("val"), BackwardState) else math.inf + else: + weight = get_node_weight(node) + + # Creates the weights on the "node" edge + nx_graph.add_edge(node.name + "_in", node.name + "_out", capacity=weight) + for user in node.users: + nx_graph.add_edge(node.name + "_out", user.name + "_in", capacity=math.inf) + + try: + cut_value, partition = nx.minimum_cut(nx_graph, "source", "sink") + except Exception: + print('Failed to compute min-cut on following graph:') + print('\n'.join(nx.readwrite.edgelist.generate_edgelist(nx_graph))) + raise + + reachable, non_reachable = partition + cutset = set() + for u, nbrs in ((n, nx_graph[n]) for n in reachable): + cutset.update((u, v) for v in nbrs if v in non_reachable) + + cut_nodes = set() + for node_in, node_out in cutset: + assert node_in[:-3] == node_out[:-4] + node_name = node_in[:-3] + cut_nodes.add(node_name) + + # To make this stuff deterministic + node_idx = {node: idx for idx, node in enumerate(joint_module.graph.nodes)} + saved_values = sorted((name_to_node[node] for node in cut_nodes), key=lambda x: node_idx[x]) + # save_for_backward on tensors and stashes symints in autograd .ctx + saved_sym_nodes = list(filter(is_sym_node, saved_values)) + saved_values = list(filter(lambda n: not is_sym_node(n), saved_values)) + # NB: saved_sym_nodes will be mutated to reflect the actual saved symbols + fw_module, bw_module = _extract_fwd_bwd_modules( + joint_module, saved_values, saved_sym_nodes=saved_sym_nodes, num_fwd_outputs=num_fwd_outputs) + + if graph_has_recomputable_ops: + if graph_has_recomputable_rng_ops: + fw_module, bw_module = functionalize_rng_ops( + joint_module, fw_module, bw_module, len(saved_sym_nodes) + ) + bw_module = reordering_to_mimic_autograd_engine(bw_module) + + if AOT_PARTITIONER_DEBUG: + print("Theoretical Activations Stored: ", sum([_size_of(i) for i in saved_values]) / 1e9) + fw_module_nodes = {node.name for node in fw_module.graph.nodes if node.op == 'call_function'} + bw_module_nodes = {node.name for node in bw_module.graph.nodes if node.op == 'call_function'} + remat_nodes = fw_module_nodes & bw_module_nodes + + counts = defaultdict(int) + for node in fw_module.graph.nodes: + if node.name in remat_nodes and hasattr(node.target, '_overloadpacket'): + counts[str(node.target._overloadpacket)] += 1 + print(f"# remat/fw/bw: {len(remat_nodes)}/{len(fw_module_nodes)}/{len(bw_module_nodes)}") + print("Count of Ops Rematerialized: ", sorted(counts.items(), key=lambda x: x[1], reverse=True)) + return fw_module, bw_module + + +def draw_graph( + traced: torch.fx.GraphModule, + fname: str, + figname: str = "fx_graph", + clear_meta: bool = True, + prog: Union[str, List[str]] = None, + parse_stack_trace: bool = False, + dot_graph_shape: Optional[str] = None, +) -> None: + if clear_meta: + new_graph = copy.deepcopy(traced.graph) + traced = fx.GraphModule(traced, new_graph) + for node in traced.graph.nodes: + node.meta = {} + base, ext = os.path.splitext(fname) + if not ext: + ext = ".svg" + print(f"Writing FX graph to file: {base}{ext}") + g = graph_drawer.FxGraphDrawer( + traced, + figname, + parse_stack_trace=parse_stack_trace, + dot_graph_shape=dot_graph_shape, + ) + x = g.get_main_dot_graph() + write_method = getattr(x, "write_" + ext.lstrip(".")) + fname = f"{base}{ext}" + if prog is None: + write_method(fname) + else: + write_method(fname, prog=prog) + + +def draw_joint_graph( + graph: torch.fx.GraphModule, + joint_inputs, + file_name: str = "full_graph.png", + dot_graph_shape: Optional[str] = None, +): + draw_graph(graph, file_name, dot_graph_shape=dot_graph_shape) + return default_partition(graph, joint_inputs) diff --git a/shared/package-files/33/33984413a0b0295265261ba1fb25c75d99f8d03b51c3a121b371a7b806fba64e/_spline.cpython-310-x86_64-linux-gnu.so b/shared/package-files/33/33984413a0b0295265261ba1fb25c75d99f8d03b51c3a121b371a7b806fba64e/_spline.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..c776c84deedabf62573fdee3f6b0bea1089d0092 Binary files /dev/null and b/shared/package-files/33/33984413a0b0295265261ba1fb25c75d99f8d03b51c3a121b371a7b806fba64e/_spline.cpython-310-x86_64-linux-gnu.so differ diff --git a/shared/package-files/33/3398b5ab6ce4a28c36a35aec9fba77d89c36da09d87120d0a3f5d79fbfc6bf41/test_ufuncs.py b/shared/package-files/33/3398b5ab6ce4a28c36a35aec9fba77d89c36da09d87120d0a3f5d79fbfc6bf41/test_ufuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..b9976aa6623adbc1fe8316ca42bf0ad97207df68 --- /dev/null +++ b/shared/package-files/33/3398b5ab6ce4a28c36a35aec9fba77d89c36da09d87120d0a3f5d79fbfc6bf41/test_ufuncs.py @@ -0,0 +1,1918 @@ +import functools +import itertools +import sys +import warnings +import threading +import operator + +import numpy as np + +import unittest +from numba import guvectorize, njit, typeof, vectorize +from numba.core import types +from numba.np.numpy_support import from_dtype +from numba.core.errors import LoweringError, TypingError +from numba.tests.support import TestCase, MemoryLeakMixin +from numba.core.typing.npydecl import supported_ufuncs +from numba.np import numpy_support +from numba.core.registry import cpu_target +from numba.core.base import BaseContext +from numba.np import ufunc_db + +is32bits = tuple.__itemsize__ == 4 +iswindows = sys.platform.startswith('win32') + + +def _unimplemented(func): + """An 'expectedFailure' like decorator that only expects compilation errors + caused by unimplemented functions that fail in no-python mode""" + @functools.wraps(func) + def wrapper(*args, **kwargs): + try: + func(*args, **kwargs) + except TypingError: + raise unittest._ExpectedFailure(sys.exc_info()) + raise unittest._UnexpectedSuccess + + +def _make_ufunc_usecase(ufunc): + ldict = {} + arg_str = ','.join(['a{0}'.format(i) for i in range(ufunc.nargs)]) + func_str = 'def fn({0}):\n np.{1}({0})'.format(arg_str, ufunc.__name__) + exec(func_str, globals(), ldict) + fn = ldict['fn'] + fn.__name__ = '{0}_usecase'.format(ufunc.__name__) + return fn + + +def _make_unary_ufunc_op_usecase(ufunc_op): + ldict = {} + exec("def fn(x):\n return {0}(x)".format(ufunc_op), globals(), ldict) + fn = ldict["fn"] + fn.__name__ = "usecase_{0}".format(hash(ufunc_op)) + return fn + + +def _make_binary_ufunc_op_usecase(ufunc_op): + ldict = {} + exec("def fn(x,y):\n return x{0}y".format(ufunc_op), globals(), ldict) + fn = ldict["fn"] + fn.__name__ = "usecase_{0}".format(hash(ufunc_op)) + return fn + + +def _make_inplace_ufunc_op_usecase(ufunc_op): + """Generates a function to be compiled that performs an inplace operation + + ufunc_op can be a string like '+=' or a function like operator.iadd + """ + if isinstance(ufunc_op, str): + ldict = {} + exec("def fn(x,y):\n x{0}y".format(ufunc_op), globals(), ldict) + fn = ldict["fn"] + fn.__name__ = "usecase_{0}".format(hash(ufunc_op)) + else: + def inplace_op(x, y): + ufunc_op(x, y) + fn = inplace_op + return fn + + +def _as_dtype_value(tyargs, args): + """Convert python values into numpy scalar objects. + """ + return [np.dtype(str(ty)).type(val) for ty, val in zip(tyargs, args)] + + +class BaseUFuncTest(MemoryLeakMixin): + + def setUp(self): + super(BaseUFuncTest, self).setUp() + self.inputs = [ + (np.uint32(0), types.uint32), + (np.uint32(1), types.uint32), + (np.int32(-1), types.int32), + (np.int32(0), types.int32), + (np.int32(1), types.int32), + (np.uint64(0), types.uint64), + (np.uint64(1), types.uint64), + (np.int64(-1), types.int64), + (np.int64(0), types.int64), + (np.int64(1), types.int64), + + (np.float32(-0.5), types.float32), + (np.float32(0.0), types.float32), + (np.float32(0.5), types.float32), + + (np.float64(-0.5), types.float64), + (np.float64(0.0), types.float64), + (np.float64(0.5), types.float64), + + (np.array([0,1], dtype='u4'), types.Array(types.uint32, 1, 'C')), + (np.array([0,1], dtype='u8'), types.Array(types.uint64, 1, 'C')), + (np.array([-1,0,1], dtype='i4'), types.Array(types.int32, 1, 'C')), + (np.array([-1,0,1], dtype='i8'), types.Array(types.int64, 1, 'C')), + (np.array([-0.5, 0.0, 0.5], dtype='f4'), + types.Array(types.float32, 1, 'C')), + (np.array([-0.5, 0.0, 0.5], dtype='f8'), + types.Array(types.float64, 1, 'C')), + + (np.array([0,1], dtype=np.int8), types.Array(types.int8, 1, 'C')), + (np.array([0,1], dtype=np.int16), types.Array(types.int16, 1, 'C')), + (np.array([0,1], dtype=np.uint8), types.Array(types.uint8, 1, 'C')), + (np.array([0,1], dtype=np.uint16), + types.Array(types.uint16, 1, 'C')), + ] + + @functools.lru_cache(maxsize=None) + def _compile(self, pyfunc, args, nrt=False): + # NOTE: to test the implementation of Numpy ufuncs, we disable + # rewriting of array expressions. + return njit(args, _nrt=nrt, no_rewrites=True)(pyfunc) + + def _determine_output_type(self, input_type, int_output_type=None, + float_output_type=None): + ty = input_type + if isinstance(ty, types.Array): + ndim = ty.ndim + ty = ty.dtype + else: + ndim = 1 + + if ty in types.signed_domain: + if int_output_type: + output_type = types.Array(int_output_type, ndim, 'C') + else: + output_type = types.Array(ty, ndim, 'C') + elif ty in types.unsigned_domain: + if int_output_type: + output_type = types.Array(int_output_type, ndim, 'C') + else: + output_type = types.Array(ty, ndim, 'C') + else: + if float_output_type: + output_type = types.Array(float_output_type, ndim, 'C') + else: + output_type = types.Array(ty, ndim, 'C') + return output_type + + +class BasicUFuncTest(BaseUFuncTest): + def _make_ufunc_usecase(self, ufunc): + return _make_ufunc_usecase(ufunc) + + def basic_ufunc_test(self, ufunc, skip_inputs=None, additional_inputs=None, + int_output_type=None, float_output_type=None, + kinds='ifc', positive_only=False): + + # Necessary to avoid some Numpy warnings being silenced, despite + # the simplefilter() call below. + if skip_inputs is None: + skip_inputs = [] + if additional_inputs is None: + additional_inputs = [] + self.reset_module_warnings(__name__) + + pyfunc = self._make_ufunc_usecase(ufunc) + + inputs = list(self.inputs) + additional_inputs + + for input_tuple in inputs: + input_operand = input_tuple[0] + input_type = input_tuple[1] + + is_tuple = isinstance(input_operand, tuple) + if is_tuple: + args = input_operand + else: + args = (input_operand,) * ufunc.nin + + if input_type in skip_inputs: + continue + if positive_only and np.any(args[0] < 0): + continue + + # Some ufuncs don't allow all kinds of arguments + if (args[0].dtype.kind not in kinds): + continue + + output_type = self._determine_output_type( + input_type, int_output_type, float_output_type) + + input_types = (input_type,) * ufunc.nin + output_types = (output_type,) * ufunc.nout + argtys = input_types + output_types + cfunc = self._compile(pyfunc, argtys) + + if isinstance(args[0], np.ndarray): + results = [ + np.zeros(args[0].shape, + dtype=out_ty.dtype.name) + for out_ty in output_types + ] + expected = [ + np.zeros(args[0].shape, dtype=out_ty.dtype.name) + for out_ty in output_types + ] + else: + results = [ + np.zeros(1, dtype=out_ty.dtype.name) + for out_ty in output_types + ] + expected = [ + np.zeros(1, dtype=out_ty.dtype.name) + for out_ty in output_types + ] + + invalid_flag = False + with warnings.catch_warnings(record=True) as warnlist: + warnings.simplefilter('always') + pyfunc(*args, *expected) + + warnmsg = "invalid value encountered" + for thiswarn in warnlist: + + if (issubclass(thiswarn.category, RuntimeWarning) + and str(thiswarn.message).startswith(warnmsg)): + invalid_flag = True + + cfunc(*args, *results) + + for expected_i, result_i in zip(expected, results): + msg = '\n'.join(["ufunc '{0}' failed", + "inputs ({1}):", "{2}", + "got({3})", "{4}", + "expected ({5}):", "{6}" + ]).format(ufunc.__name__, + input_type, input_operand, + output_type, result_i, + expected_i.dtype, expected_i) + try: + np.testing.assert_array_almost_equal( + expected_i, result_i, + decimal=5, + err_msg=msg) + except AssertionError: + if invalid_flag: + # Allow output to mismatch for invalid input + print("Output mismatch for invalid input", + input_tuple, result_i, expected_i) + else: + raise + + def signed_unsigned_cmp_test(self, comparison_ufunc): + self.basic_ufunc_test(comparison_ufunc) + + if numpy_support.numpy_version < (1, 25): + return + + # Test additional implementations that specifically handle signed / + # unsigned comparisons added in NumPy 1.25: + # https://github.com/numpy/numpy/pull/23713 + additional_inputs = ( + (np.int64(-1), np.uint64(0)), + (np.int64(-1), np.uint64(1)), + (np.int64(0), np.uint64(0)), + (np.int64(0), np.uint64(1)), + (np.int64(1), np.uint64(0)), + (np.int64(1), np.uint64(1)), + + (np.uint64(0), np.int64(-1)), + (np.uint64(0), np.int64(0)), + (np.uint64(0), np.int64(1)), + (np.uint64(1), np.int64(-1)), + (np.uint64(1), np.int64(0)), + (np.uint64(1), np.int64(1)), + + (np.array([-1, -1, 0, 0, 1, 1], dtype=np.int64), + np.array([0, 1, 0, 1, 0, 1], dtype=np.uint64)), + + (np.array([0, 1, 0, 1, 0, 1], dtype=np.uint64), + np.array([-1, -1, 0, 0, 1, 1], dtype=np.int64)) + ) + + pyfunc = self._make_ufunc_usecase(comparison_ufunc) + + for a, b in additional_inputs: + input_types = (typeof(a), typeof(b)) + output_type = types.Array(types.bool_, 1, 'C') + argtys = input_types + (output_type,) + cfunc = self._compile(pyfunc, argtys) + + if isinstance(a, np.ndarray): + result = np.zeros(a.shape, dtype=np.bool_) + else: + result = np.zeros(1, dtype=np.bool_) + + expected = np.zeros_like(result) + + pyfunc(a, b, expected) + cfunc(a, b, result) + np.testing.assert_equal(expected, result) + + +class TestUFuncs(BasicUFuncTest, TestCase): + def basic_int_ufunc_test(self, name=None): + skip_inputs = [ + types.float32, + types.float64, + types.Array(types.float32, 1, 'C'), + types.Array(types.float64, 1, 'C'), + ] + self.basic_ufunc_test(name, skip_inputs=skip_inputs) + + ############################################################################ + # Math operations + + def test_add_ufunc(self): + self.basic_ufunc_test(np.add) + + def test_subtract_ufunc(self): + self.basic_ufunc_test(np.subtract) + + def test_multiply_ufunc(self): + self.basic_ufunc_test(np.multiply) + + def test_divide_ufunc(self): + # Bear in mind that in python3 divide IS true_divide + # so the out type for int types will be a double + int_out_type = None + int_out_type = types.float64 + + self.basic_ufunc_test(np.divide, + int_output_type=int_out_type) + + def test_logaddexp_ufunc(self): + self.basic_ufunc_test(np.logaddexp, kinds='f') + + def test_logaddexp2_ufunc(self): + self.basic_ufunc_test(np.logaddexp2, kinds='f') + + def test_true_divide_ufunc(self): + self.basic_ufunc_test(np.true_divide, + int_output_type=types.float64) + + def test_floor_divide_ufunc(self): + self.basic_ufunc_test(np.floor_divide) + + def test_negative_ufunc(self): + # NumPy ufunc has bug with uint32 as input and int64 as output, + # so skip uint32 input. + skip_inputs = [types.Array(types.uint32, 1, 'C'), types.uint32] + self.basic_ufunc_test(np.negative, int_output_type=types.int64, + skip_inputs=skip_inputs) + + def test_positive_ufunc(self): + self.basic_ufunc_test(np.positive) + + def test_power_ufunc(self): + self.basic_ufunc_test(np.power, positive_only=True) + + def test_float_power_ufunc(self): + self.basic_ufunc_test(np.float_power, kinds="fc") + + def test_gcd_ufunc(self): + self.basic_ufunc_test(np.gcd, kinds="iu") + + def test_lcm_ufunc(self): + self.basic_ufunc_test(np.lcm, kinds="iu") + + def test_remainder_ufunc(self): + self.basic_ufunc_test(np.remainder) + + def test_mod_ufunc(self): + additional_inputs = [ + ((np.uint64(np.iinfo(np.uint64).max), np.uint64(16)), types.uint64) + ] + self.basic_ufunc_test(np.mod, kinds='ifcu', + additional_inputs=additional_inputs) + + def test_fmod_ufunc(self): + self.basic_ufunc_test(np.fmod) + + def test_abs_ufunc(self, ufunc=np.abs): + additional_inputs = [ + (np.uint32(np.iinfo(np.uint32).max), types.uint32), + (np.uint64(np.iinfo(np.uint64).max), types.uint64), + (np.float32(np.finfo(np.float32).min), types.float32), + (np.float64(np.finfo(np.float64).min), types.float64), + ] + self.basic_ufunc_test(ufunc, + additional_inputs=additional_inputs) + + def test_absolute_ufunc(self): + self.test_abs_ufunc(ufunc=np.absolute) + + def test_fabs_ufunc(self): + self.basic_ufunc_test(np.fabs, kinds='f') + + def test_rint_ufunc(self): + self.basic_ufunc_test(np.rint, kinds='cf') + + def test_sign_ufunc(self): + self.basic_ufunc_test(np.sign) + + def test_conj_ufunc(self): + self.basic_ufunc_test(np.conj) + + def test_exp_ufunc(self): + self.basic_ufunc_test(np.exp, kinds='cf') + + def test_exp2_ufunc(self): + self.basic_ufunc_test(np.exp2, kinds='cf') + + def test_log_ufunc(self): + self.basic_ufunc_test(np.log, kinds='cf') + + def test_log2_ufunc(self): + self.basic_ufunc_test(np.log2, kinds='cf') + + def test_log10_ufunc(self): + self.basic_ufunc_test(np.log10, kinds='cf') + + def test_expm1_ufunc(self): + self.basic_ufunc_test(np.expm1, kinds='cf') + + def test_log1p_ufunc(self): + self.basic_ufunc_test(np.log1p, kinds='cf') + + def test_sqrt_ufunc(self): + self.basic_ufunc_test(np.sqrt, kinds='cf') + + def test_square_ufunc(self): + self.basic_ufunc_test(np.square) + + def test_cbrt_ufunc(self): + self.basic_ufunc_test(np.cbrt, kinds='f') + + def test_reciprocal_ufunc(self): + # reciprocal for integers doesn't make much sense and is problematic + # in the case of division by zero, as an inf will overflow float to + # int conversions, which is undefined behavior. + to_skip = [types.Array(types.uint32, 1, 'C'), types.uint32, + types.Array(types.int32, 1, 'C'), types.int32, + types.Array(types.uint64, 1, 'C'), types.uint64, + types.Array(types.int64, 1, 'C'), types.int64] + self.basic_ufunc_test(np.reciprocal, skip_inputs=to_skip) + + def test_conjugate_ufunc(self): + self.basic_ufunc_test(np.conjugate) + + ############################################################################ + # Trigonometric Functions + + def test_sin_ufunc(self): + self.basic_ufunc_test(np.sin, kinds='cf') + + def test_cos_ufunc(self): + self.basic_ufunc_test(np.cos, kinds='cf') + + def test_tan_ufunc(self): + self.basic_ufunc_test(np.tan, kinds='cf') + + def test_arcsin_ufunc(self): + self.basic_ufunc_test(np.arcsin, kinds='cf') + + def test_arccos_ufunc(self): + self.basic_ufunc_test(np.arccos, kinds='cf') + + def test_arctan_ufunc(self): + self.basic_ufunc_test(np.arctan, kinds='cf') + + def test_arctan2_ufunc(self): + self.basic_ufunc_test(np.arctan2, kinds='cf') + + def test_hypot_ufunc(self): + self.basic_ufunc_test(np.hypot, kinds='f') + + def test_sinh_ufunc(self): + self.basic_ufunc_test(np.sinh, kinds='cf') + + def test_cosh_ufunc(self): + self.basic_ufunc_test(np.cosh, kinds='cf') + + def test_tanh_ufunc(self): + self.basic_ufunc_test(np.tanh, kinds='cf') + + def test_arcsinh_ufunc(self): + self.basic_ufunc_test(np.arcsinh, kinds='cf') + + def test_arccosh_ufunc(self): + self.basic_ufunc_test(np.arccosh, kinds='cf') + + def test_arctanh_ufunc(self): + # arctanh is only valid is only finite in the range ]-1, 1[ + # This means that for any of the integer types it will produce + # conversion from infinity/-infinity to integer. That's undefined + # behavior in C, so the results may vary from implementation to + # implementation. This means that the result from the compiler + # used to compile NumPy may differ from the result generated by + # llvm. Skipping the integer types in this test avoids failed + # tests because of this. + to_skip = [types.Array(types.uint32, 1, 'C'), types.uint32, + types.Array(types.int32, 1, 'C'), types.int32, + types.Array(types.uint64, 1, 'C'), types.uint64, + types.Array(types.int64, 1, 'C'), types.int64] + + self.basic_ufunc_test(np.arctanh, skip_inputs=to_skip, kinds='cf') + + def test_deg2rad_ufunc(self): + self.basic_ufunc_test(np.deg2rad, kinds='f') + + def test_rad2deg_ufunc(self): + self.basic_ufunc_test(np.rad2deg, kinds='f') + + def test_degrees_ufunc(self): + self.basic_ufunc_test(np.degrees, kinds='f') + + def test_radians_ufunc(self): + self.basic_ufunc_test(np.radians, kinds='f') + + ############################################################################ + # Bit-twiddling Functions + + def test_bitwise_and_ufunc(self): + self.basic_int_ufunc_test(np.bitwise_and) + + def test_bitwise_or_ufunc(self): + self.basic_int_ufunc_test(np.bitwise_or) + + def test_bitwise_xor_ufunc(self): + self.basic_int_ufunc_test(np.bitwise_xor) + + def test_invert_ufunc(self): + self.basic_int_ufunc_test(np.invert) + + def test_bitwise_not_ufunc(self): + self.basic_int_ufunc_test(np.bitwise_not) + + # Note: there is no entry for left_shift and right_shift as this harness + # is not valid for them. This is so because left_shift and right + # shift implementation in NumPy has undefined behavior (in C-parlance) + # when the second argument is a negative (or bigger than the number + # of bits) value. + # Also, right_shift for negative first arguments also relies on + # implementation defined behavior, although numba warantees "sane" + # behavior (arithmetic shifts on signed integers, logic shifts on + # unsigned integers). + + ############################################################################ + # Comparison functions + def test_greater_ufunc(self): + self.signed_unsigned_cmp_test(np.greater) + + def test_greater_equal_ufunc(self): + self.signed_unsigned_cmp_test(np.greater_equal) + + def test_less_ufunc(self): + self.signed_unsigned_cmp_test(np.less) + + def test_less_equal_ufunc(self): + self.signed_unsigned_cmp_test(np.less_equal) + + def test_not_equal_ufunc(self): + self.signed_unsigned_cmp_test(np.not_equal) + + def test_equal_ufunc(self): + self.signed_unsigned_cmp_test(np.equal) + + def test_logical_and_ufunc(self): + self.basic_ufunc_test(np.logical_and) + + def test_logical_or_ufunc(self): + self.basic_ufunc_test(np.logical_or) + + def test_logical_xor_ufunc(self): + self.basic_ufunc_test(np.logical_xor) + + def test_logical_not_ufunc(self): + self.basic_ufunc_test(np.logical_not) + + def test_maximum_ufunc(self): + self.basic_ufunc_test(np.maximum) + + def test_minimum_ufunc(self): + self.basic_ufunc_test(np.minimum) + + def test_fmax_ufunc(self): + self.basic_ufunc_test(np.fmax) + + def test_fmin_ufunc(self): + self.basic_ufunc_test(np.fmin) + + ############################################################################ + # Floating functions + + def bool_additional_inputs(self): + return [ + (np.array([True, False], dtype=np.bool_), + types.Array(types.bool_, 1, 'C')), + ] + + def test_isfinite_ufunc(self): + self.basic_ufunc_test( + np.isfinite, kinds='ifcb', + additional_inputs=self.bool_additional_inputs(), + ) + + def test_isinf_ufunc(self): + self.basic_ufunc_test( + np.isinf, kinds='ifcb', + additional_inputs=self.bool_additional_inputs(), + ) + + def test_isnan_ufunc(self): + self.basic_ufunc_test( + np.isnan, kinds='ifcb', + additional_inputs=self.bool_additional_inputs(), + ) + + def test_signbit_ufunc(self): + self.basic_ufunc_test(np.signbit) + + def test_copysign_ufunc(self): + self.basic_ufunc_test(np.copysign, kinds='f') + + def test_nextafter_ufunc(self): + self.basic_ufunc_test(np.nextafter, kinds='f') + + @_unimplemented + def test_modf_ufunc(self): + self.basic_ufunc_test(np.modf, kinds='f') + + # Note: there is no entry for ldexp as this harness isn't valid for this + # ufunc. this is so because ldexp requires heterogeneous inputs. + # However, this ufunc is tested by the TestLoopTypes test classes. + + @_unimplemented + def test_frexp_ufunc(self): + self.basic_ufunc_test(np.frexp, kinds='f') + + def test_floor_ufunc(self): + self.basic_ufunc_test(np.floor, kinds='f') + + def test_ceil_ufunc(self): + self.basic_ufunc_test(np.ceil, kinds='f') + + def test_trunc_ufunc(self): + self.basic_ufunc_test(np.trunc, kinds='f') + + def test_spacing_ufunc(self): + # additional input to check inf behaviour as Numba uses a different alg + # to NumPy + additional = [(np.array([np.inf, -np.inf], dtype=np.float64), + types.Array(types.float64, 1, 'C')),] + self.basic_ufunc_test(np.spacing, kinds='f', + additional_inputs=additional) + + ############################################################################ + # Other tests + + def binary_ufunc_mixed_types_test(self, ufunc): + ufunc_name = ufunc.__name__ + ufunc = _make_ufunc_usecase(ufunc) + inputs1 = [ + (1, types.uint64), + (-1, types.int64), + (0.5, types.float64), + + (np.array([0, 1], dtype='u8'), types.Array(types.uint64, 1, 'C')), + (np.array([-1, 1], dtype='i8'), types.Array(types.int64, 1, 'C')), + (np.array([-0.5, 0.5], dtype='f8'), + types.Array(types.float64, 1, 'C'))] + + inputs2 = inputs1 + + output_types = [types.Array(types.int64, 1, 'C'), + types.Array(types.float64, 1, 'C')] + + pyfunc = ufunc + + for vals in itertools.product(inputs1, inputs2, output_types): + input1, input2, output_type = vals + + input1_operand = input1[0] + input1_type = input1[1] + + input2_operand = input2[0] + input2_type = input2[1] + + # Skip division by unsigned int because of NumPy bugs + if ufunc_name == 'divide' and ( + input2_type == types.Array(types.uint32, 1, 'C') or + input2_type == types.Array(types.uint64, 1, 'C')): + continue + + # Skip some subtraction tests because of NumPy bugs + if (ufunc_name == 'subtract' + and input1_type == types.Array(types.uint32, 1, 'C') + and input2_type == types.uint32 + and types.Array(types.int64, 1, 'C')): + continue + if (ufunc_name == 'subtract' + and input1_type == types.Array(types.uint32, 1, 'C') + and input2_type == types.uint64 + and types.Array(types.int64, 1, 'C')): + continue + + if ((isinstance(input1_type, types.Array) or + isinstance(input2_type, types.Array)) and + not isinstance(output_type, types.Array)): + continue + + args = (input1_type, input2_type, output_type) + cfunc = self._compile(pyfunc, args) + + if isinstance(input1_operand, np.ndarray): + result = np.zeros(input1_operand.size, + dtype=output_type.dtype.name) + expected = np.zeros(input1_operand.size, + dtype=output_type.dtype.name) + elif isinstance(input2_operand, np.ndarray): + result = np.zeros(input2_operand.size, + dtype=output_type.dtype.name) + expected = np.zeros(input2_operand.size, + dtype=output_type.dtype.name) + else: + result = np.zeros(1, dtype=output_type.dtype.name) + expected = np.zeros(1, dtype=output_type.dtype.name) + + cfunc(input1_operand, input2_operand, result) + pyfunc(input1_operand, input2_operand, expected) + + scalar_type = getattr(output_type, 'dtype', output_type) + prec = ('single' + if scalar_type in (types.float32, types.complex64) + else 'double') + self.assertPreciseEqual(expected, result, prec=prec) + + def test_broadcasting(self): + + # Test unary ufunc + pyfunc = _make_ufunc_usecase(np.negative) + + input_operands = [ + np.arange(3, dtype='u8'), + np.arange(3, dtype='u8').reshape(3,1), + np.arange(3, dtype='u8').reshape(1,3), + np.arange(3, dtype='u8').reshape(3,1), + np.arange(3, dtype='u8').reshape(1,3), + np.arange(3 * 3, dtype='u8').reshape(3,3)] + + output_operands = [ + np.zeros(3 * 3, dtype='i8').reshape(3,3), + np.zeros(3 * 3, dtype='i8').reshape(3,3), + np.zeros(3 * 3, dtype='i8').reshape(3,3), + np.zeros(3 * 3 * 3, dtype='i8').reshape(3,3,3), + np.zeros(3 * 3 * 3, dtype='i8').reshape(3,3,3), + np.zeros(3 * 3 * 3, dtype='i8').reshape(3,3,3)] + + for x, result in zip(input_operands, output_operands): + + input_type = types.Array(types.uint64, x.ndim, 'C') + output_type = types.Array(types.int64, result.ndim, 'C') + args = (input_type, output_type) + + cfunc = self._compile(pyfunc, args) + + expected = np.zeros(result.shape, dtype=result.dtype) + np.negative(x, expected) + + cfunc(x, result) + + self.assertPreciseEqual(result, expected) + + # Test binary ufunc + pyfunc = _make_ufunc_usecase(np.add) + + input1_operands = [ + np.arange(3, dtype='u8'), + np.arange(3 * 3, dtype='u8').reshape(3,3), + np.arange(3 * 3 * 3, dtype='u8').reshape(3,3,3), + np.arange(3, dtype='u8').reshape(3,1), + np.arange(3, dtype='u8').reshape(1,3), + np.arange(3, dtype='u8').reshape(3,1,1), + np.arange(3 * 3, dtype='u8').reshape(3,3,1), + np.arange(3 * 3, dtype='u8').reshape(3,1,3), + np.arange(3 * 3, dtype='u8').reshape(1,3,3)] + + input2_operands = input1_operands + + for x, y in itertools.product(input1_operands, input2_operands): + + input1_type = types.Array(types.uint64, x.ndim, 'C') + input2_type = types.Array(types.uint64, y.ndim, 'C') + output_type = types.Array(types.uint64, max(x.ndim, y.ndim), 'C') + args = (input1_type, input2_type, output_type) + + cfunc = self._compile(pyfunc, args) + + expected = np.add(x, y) + result = np.zeros(expected.shape, dtype='u8') + + cfunc(x, y, result) + self.assertPreciseEqual(result, expected) + + def test_implicit_output_npm(self): + # Test for Issue #1078 (https://github.com/numba/numba/issues/1078) - + # ensures that the output of a ufunc is an array. + arr_ty = types.Array(types.uint64, 1, 'C') + sig = (arr_ty, arr_ty) + + @njit((arr_ty, arr_ty)) + def myadd(a0, a1): + return np.add(a0, a1) + + self.assertEqual(myadd.overloads[sig].signature.return_type, arr_ty) + + def test_broadcast_implicit_output_npm_nrt(self): + def pyfunc(a0, a1): + return np.add(a0, a1) + + input1_operands = [ + np.arange(3, dtype='u8'), + np.arange(3 * 3, dtype='u8').reshape(3,3), + np.arange(3 * 3 * 3, dtype='u8').reshape(3,3,3), + np.arange(3, dtype='u8').reshape(3,1), + np.arange(3, dtype='u8').reshape(1,3), + np.arange(3, dtype='u8').reshape(3,1,1), + np.arange(3 * 3, dtype='u8').reshape(3,3,1), + np.arange(3 * 3, dtype='u8').reshape(3,1,3), + np.arange(3 * 3, dtype='u8').reshape(1,3,3)] + + input2_operands = input1_operands + + for x, y in itertools.product(input1_operands, input2_operands): + + input1_type = types.Array(types.uint64, x.ndim, 'C') + input2_type = types.Array(types.uint64, y.ndim, 'C') + args = (input1_type, input2_type) + + cfunc = self._compile(pyfunc, args, nrt=True) + + expected = np.add(x, y) + result = cfunc(x, y) + np.testing.assert_array_equal(expected, result) + + def test_implicit_output_layout_binary(self): + def pyfunc(a0, a1): + return np.add(a0, a1) + + # C layout + X = np.linspace(0, 1, 20).reshape(4, 5) + # F layout + Y = np.array(X, order='F') + # A layout + Z = X.reshape(5, 4).T[0] + + Xty = typeof(X) + assert X.flags.c_contiguous and Xty.layout == 'C' + Yty = typeof(Y) + assert Y.flags.f_contiguous and Yty.layout == 'F' + Zty = typeof(Z) + assert Zty.layout == 'A' + assert not Z.flags.c_contiguous + assert not Z.flags.f_contiguous + + testcases = list(itertools.permutations([X, Y, Z], 2)) + testcases += [(X, X)] + testcases += [(Y, Y)] + testcases += [(Z, Z)] + + for arg0, arg1 in testcases: + args = (typeof(arg0), typeof(arg1)) + cfunc = self._compile(pyfunc, args, nrt=True) + expected = pyfunc(arg0, arg1) + result = cfunc(arg0, arg1) + + self.assertEqual(expected.flags.c_contiguous, + result.flags.c_contiguous) + self.assertEqual(expected.flags.f_contiguous, + result.flags.f_contiguous) + np.testing.assert_array_equal(expected, result) + + def test_implicit_output_layout_unary(self): + def pyfunc(a0): + return np.sqrt(a0) + + # C layout + X = np.linspace(0, 1, 20).reshape(4, 5) + # F layout + Y = np.array(X, order='F') + # A layout + Z = X.reshape(5, 4).T[0] + + Xty = typeof(X) + assert X.flags.c_contiguous and Xty.layout == 'C' + Yty = typeof(Y) + assert Y.flags.f_contiguous and Yty.layout == 'F' + Zty = typeof(Z) + assert Zty.layout == 'A' + assert not Z.flags.c_contiguous + assert not Z.flags.f_contiguous + + for arg0 in [X, Y, Z]: + args = (typeof(arg0),) + cfunc = self._compile(pyfunc, args, nrt=True) + expected = pyfunc(arg0) + result = cfunc(arg0) + + self.assertEqual(expected.flags.c_contiguous, + result.flags.c_contiguous) + self.assertEqual(expected.flags.f_contiguous, + result.flags.f_contiguous) + np.testing.assert_array_equal(expected, result) + + +class TestArrayOperators(BaseUFuncTest, TestCase): + + def _check_results(self, expected, got): + self.assertEqual(expected.dtype.kind, got.dtype.kind) + np.testing.assert_array_almost_equal(expected, got) + + def unary_op_test(self, operator, nrt=True, + skip_inputs=None, additional_inputs=None, + int_output_type=None, float_output_type=None): + if skip_inputs is None: + skip_inputs = [] + if additional_inputs is None: + additional_inputs = [] + operator_func = _make_unary_ufunc_op_usecase(operator) + inputs = list(self.inputs) + inputs.extend(additional_inputs) + pyfunc = operator_func + for input_tuple in inputs: + input_operand, input_type = input_tuple + + if ((input_type in skip_inputs) or + (not isinstance(input_type, types.Array))): + continue + + cfunc = self._compile(pyfunc, (input_type,), nrt=nrt) + expected = pyfunc(input_operand) + got = cfunc(input_operand) + self._check_results(expected, got) + + def binary_op_test(self, operator, nrt=True, + skip_inputs=None, additional_inputs=None, + int_output_type=None, float_output_type=None, + positive_rhs=False): + if skip_inputs is None: + skip_inputs = [] + if additional_inputs is None: + additional_inputs = [] + operator_func = _make_binary_ufunc_op_usecase(operator) + inputs = list(self.inputs) + inputs.extend(additional_inputs) + pyfunc = operator_func + # when generating arbitrary sequences, we use a fixed seed + # for deterministic testing + random_state = np.random.RandomState(1) + for input_tuple in inputs: + input_operand1, input_type = input_tuple + input_dtype = numpy_support.as_dtype( + getattr(input_type, "dtype", input_type)) + input_type1 = input_type + + if input_type in skip_inputs: + continue + + if positive_rhs: + zero = np.zeros(1, dtype=input_dtype)[0] + # If we only use two scalars, the code generator will not + # select the ufunctionalized operator, so we mix it up. + if isinstance(input_type, types.Array): + input_operand0 = input_operand1 + input_type0 = input_type + if positive_rhs and np.any(input_operand1 < zero): + continue + else: + input_operand0 = (random_state.uniform(0, 100, 10)).astype( + input_dtype) + input_type0 = typeof(input_operand0) + if positive_rhs and input_operand1 < zero: + continue + + args = (input_type0, input_type1) + cfunc = self._compile(pyfunc, args, nrt=nrt) + expected = pyfunc(input_operand0, input_operand1) + got = cfunc(input_operand0, input_operand1) + self._check_results(expected, got) + + def bitwise_additional_inputs(self): + # For bitwise operators, we want to check the results for boolean + # arrays (see #1813). + return [ + (True, types.boolean), + (False, types.boolean), + (np.array([True, False]), types.Array(types.boolean, 1, 'C')), + ] + + def binary_int_op_test(self, *args, **kws): + skip_inputs = kws.setdefault('skip_inputs', []) + skip_inputs += [ + types.float32, types.float64, + types.Array(types.float32, 1, 'C'), + types.Array(types.float64, 1, 'C'), + ] + return self.binary_op_test(*args, **kws) + + def binary_bitwise_op_test(self, *args, **kws): + additional_inputs = kws.setdefault('additional_inputs', []) + additional_inputs += self.bitwise_additional_inputs() + return self.binary_int_op_test(*args, **kws) + + def inplace_op_test(self, operator, lhs_values, rhs_values, + lhs_dtypes, rhs_dtypes, precise=True): + operator_func = _make_inplace_ufunc_op_usecase(operator) + pyfunc = operator_func + + if precise: + assertion = self.assertPreciseEqual + else: + assertion = np.testing.assert_allclose + + # The left operand can only be an array, while the right operand + # can be either an array or a scalar + lhs_inputs = [np.array(lhs_values, dtype=dtype) + for dtype in lhs_dtypes] + + rhs_arrays = [np.array(rhs_values, dtype=dtype) + for dtype in rhs_dtypes] + rhs_scalars = [dtype(v) for v in rhs_values for dtype in rhs_dtypes] + rhs_inputs = rhs_arrays + rhs_scalars + + for lhs, rhs in itertools.product(lhs_inputs, rhs_inputs): + lhs_type = typeof(lhs) + rhs_type = typeof(rhs) + args = (lhs_type, rhs_type) + cfunc = self._compile(pyfunc, args) + expected = lhs.copy() + pyfunc(expected, rhs) + got = lhs.copy() + cfunc(got, rhs) + assertion(got, expected) + + def inplace_float_op_test(self, operator, lhs_values, rhs_values, + precise=True): + # Also accept integer inputs for the right operand (they should + # be converted to float). + return self.inplace_op_test(operator, lhs_values, rhs_values, + (np.float32, np.float64), + (np.float32, np.float64, np.int64), + precise=precise) + + def inplace_int_op_test(self, operator, lhs_values, rhs_values): + self.inplace_op_test(operator, lhs_values, rhs_values, + (np.int16, np.int32, np.int64), + (np.int16, np.uint32)) + + def inplace_bitwise_op_test(self, operator, lhs_values, rhs_values): + self.inplace_int_op_test(operator, lhs_values, rhs_values) + self.inplace_op_test(operator, lhs_values, rhs_values, + (np.bool_,), (np.bool_, np.bool_)) + + # ____________________________________________________________ + # Unary operators + + def test_unary_positive_array_op(self): + self.unary_op_test('+') + + def test_unary_negative_array_op(self): + self.unary_op_test('-') + + def test_unary_invert_array_op(self): + self.unary_op_test('~', + skip_inputs=[types.float32, types.float64, + types.Array(types.float32, 1, 'C'), + types.Array(types.float64, 1, 'C')], + additional_inputs=self.bitwise_additional_inputs()) + + # ____________________________________________________________ + # Inplace operators + + def test_inplace_add(self): + self.inplace_float_op_test('+=', [-1, 1.5, 3], [-5, 0, 2.5]) + self.inplace_float_op_test(operator.iadd, [-1, 1.5, 3], [-5, 0, 2.5]) + + def test_inplace_sub(self): + self.inplace_float_op_test('-=', [-1, 1.5, 3], [-5, 0, 2.5]) + self.inplace_float_op_test(operator.isub, [-1, 1.5, 3], [-5, 0, 2.5]) + + def test_inplace_mul(self): + self.inplace_float_op_test('*=', [-1, 1.5, 3], [-5, 0, 2.5]) + self.inplace_float_op_test(operator.imul, [-1, 1.5, 3], [-5, 0, 2.5]) + + def test_inplace_floordiv(self): + self.inplace_float_op_test('//=', [-1, 1.5, 3], [-5, 1.25, 2.5]) + self.inplace_float_op_test(operator.ifloordiv, [-1, 1.5, 3], + [-5, 1.25, 2.5]) + + def test_inplace_div(self): + self.inplace_float_op_test('/=', [-1, 1.5, 3], [-5, 0, 2.5]) + self.inplace_float_op_test(operator.itruediv, [-1, 1.5, 3], + [-5, 1.25, 2.5]) + + def test_inplace_remainder(self): + self.inplace_float_op_test('%=', [-1, 1.5, 3], [-5, 2, 2.5]) + self.inplace_float_op_test(operator.imod, [-1, 1.5, 3], [-5, 2, 2.5]) + + def test_inplace_pow(self): + self.inplace_float_op_test('**=', [-1, 1.5, 3], [-5, 2, 2.5], + precise=False) + self.inplace_float_op_test(operator.ipow, [-1, 1.5, 3], [-5, 2, 2.5], + precise=False) + + def test_inplace_and(self): + self.inplace_bitwise_op_test('&=', [0, 1, 2, 3, 51], + [0, 13, 16, 42, 255]) + self.inplace_bitwise_op_test(operator.iand, [0, 1, 2, 3, 51], + [0, 13, 16, 42, 255]) + + def test_inplace_or(self): + self.inplace_bitwise_op_test('|=', [0, 1, 2, 3, 51], + [0, 13, 16, 42, 255]) + self.inplace_bitwise_op_test(operator.ior, [0, 1, 2, 3, 51], + [0, 13, 16, 42, 255]) + + def test_inplace_xor(self): + self.inplace_bitwise_op_test('^=', [0, 1, 2, 3, 51], + [0, 13, 16, 42, 255]) + self.inplace_bitwise_op_test(operator.ixor, [0, 1, 2, 3, 51], + [0, 13, 16, 42, 255]) + + def test_inplace_lshift(self): + self.inplace_int_op_test('<<=', [0, 5, -10, -51], [0, 1, 4, 14]) + self.inplace_int_op_test(operator.ilshift, [0, 5, -10, -51], + [0, 1, 4, 14]) + + def test_inplace_rshift(self): + self.inplace_int_op_test('>>=', [0, 5, -10, -51], [0, 1, 4, 14]) + self.inplace_int_op_test(operator.irshift, [0, 5, -10, -51], + [0, 1, 4, 14]) + + def test_unary_positive_array_op_2(self): + ''' + Verify that the unary positive operator copies values, and doesn't + just alias to the input array (mirrors normal Numpy/Python + interaction behavior). + ''' + # Test originally from @gmarkall + def f(a1): + a2 = +a1 + a1[0] = 3 + a2[1] = 4 + return a2 + + a1 = np.zeros(10) + a2 = f(a1) + self.assertTrue(a1[0] != a2[0] and a1[1] != a2[1]) + a3 = np.zeros(10) + a4 = njit(f)(a3) + self.assertTrue(a3[0] != a4[0] and a3[1] != a4[1]) + np.testing.assert_array_equal(a1, a3) + np.testing.assert_array_equal(a2, a4) + + # ____________________________________________________________ + # Binary operators + + def test_add_array_op(self): + self.binary_op_test('+') + + def test_subtract_array_op(self): + self.binary_op_test('-') + + def test_multiply_array_op(self): + self.binary_op_test('*') + + def test_divide_array_op(self): + int_out_type = None + int_out_type = types.float64 + self.binary_op_test('/', int_output_type=int_out_type) + + def test_floor_divide_array_op(self): + # Avoid floating-point zeros as x // 0.0 can have varying results + # depending on the algorithm (which changed across Numpy versions) + self.inputs = [ + (np.uint32(1), types.uint32), + (np.int32(-2), types.int32), + (np.int32(0), types.int32), + (np.uint64(4), types.uint64), + (np.int64(-5), types.int64), + (np.int64(0), types.int64), + + (np.float32(-0.5), types.float32), + (np.float32(1.5), types.float32), + + (np.float64(-2.5), types.float64), + (np.float64(3.5), types.float64), + + (np.array([1,2], dtype='u4'), types.Array(types.uint32, 1, 'C')), + (np.array([3,4], dtype='u8'), types.Array(types.uint64, 1, 'C')), + (np.array([-1,1,5], dtype='i4'), types.Array(types.int32, 1, 'C')), + (np.array([-1,1,6], dtype='i8'), types.Array(types.int64, 1, 'C')), + (np.array([-0.5, 1.5], dtype='f4'), + types.Array(types.float32, 1, 'C')), + (np.array([-2.5, 3.5], dtype='f8'), + types.Array(types.float64, 1, 'C')), + ] + self.binary_op_test('//') + + def test_remainder_array_op(self): + self.binary_op_test('%') + + def test_power_array_op(self): + self.binary_op_test('**', positive_rhs=True) + + def test_left_shift_array_op(self): + self.binary_int_op_test('<<', positive_rhs=True) + + def test_right_shift_array_op(self): + self.binary_int_op_test('>>', positive_rhs=True) + + def test_bitwise_and_array_op(self): + self.binary_bitwise_op_test('&') + + def test_bitwise_or_array_op(self): + self.binary_bitwise_op_test('|') + + def test_bitwise_xor_array_op(self): + self.binary_bitwise_op_test('^') + + def test_equal_array_op(self): + self.binary_op_test('==') + + def test_greater_array_op(self): + self.binary_op_test('>') + + def test_greater_equal_array_op(self): + self.binary_op_test('>=') + + def test_less_array_op(self): + self.binary_op_test('<') + + def test_less_equal_array_op(self): + self.binary_op_test('<=') + + def test_not_equal_array_op(self): + self.binary_op_test('!=') + + +class TestScalarUFuncs(TestCase): + """check the machinery of ufuncs works when the result is an scalar. + These are not exhaustive because: + - the machinery to support this case is the same for all the functions of a + given arity. + - the result of the inner function itself is already tested in TestUFuncs + """ + + def run_ufunc(self, pyfunc, arg_types, arg_values): + for tyargs, args in zip(arg_types, arg_values): + cfunc = njit(tyargs)(pyfunc) + got = cfunc(*args) + expected = pyfunc(*_as_dtype_value(tyargs, args)) + + msg = 'for args {0} typed {1}'.format(args, tyargs) + + # note: due to semantics of ufuncs, thing like adding a int32 to a + # uint64 results in doubles (as neither int32 can be cast safely + # to uint64 nor vice-versa, falling back to using the float version. + # Modify in those cases the expected value (the numpy version does + # not use typed integers as inputs so its result is an integer) + special = set([ + (types.int32, types.uint64), + (types.uint64, types.int32), + (types.int64, types.uint64), + (types.uint64, types.int64) + ]) + if tyargs in special: + expected = float(expected) + else: + # The numba version of scalar ufuncs return an actual value that + # gets converted to a Python type, instead of using NumPy + # scalars. although in python 2 NumPy scalars are considered + # and instance of the appropriate python type, in python 3 that + # is no longer the case. This is why the expected result is + # casted to the appropriate Python type (which is actually the + # expected behavior of the ufunc translation) + if np.issubdtype(expected.dtype, np.inexact): + expected = float(expected) + elif np.issubdtype(expected.dtype, np.integer): + expected = int(expected) + elif np.issubdtype(expected.dtype, np.bool_): + expected = bool(expected) + + alltypes = tyargs + (cfunc.overloads[tyargs].signature.return_type,) + + # select the appropriate precision for comparison: note that an + # argument typed at a lower precision can introduce precision + # problems. For this reason the argument types must be taken into + # account. + if any([t == types.float32 for t in alltypes]): + prec = 'single' + elif any([t == types.float64 for t in alltypes]): + prec = 'double' + else: + prec = 'exact' + + self.assertPreciseEqual(got, expected, msg=msg, prec=prec) + + def test_scalar_unary_ufunc(self): + def _func(x): + return np.sqrt(x) + + vals = [(2,), (2,), (1,), (2,), (.1,), (.2,)] + tys = [(types.int32,), (types.uint32,), + (types.int64,), (types.uint64,), + (types.float32,), (types.float64,)] + self.run_ufunc(_func, tys, vals) + + def test_scalar_binary_uniform_ufunc(self): + def _func(x,y): + return np.add(x,y) + + vals = [2, 2, 1, 2, .1, .2] + tys = [types.int32, types.uint32, + types.int64, types.uint64, types.float32, types.float64] + self.run_ufunc(_func, zip(tys, tys), zip(vals, vals)) + + def test_scalar_binary_mixed_ufunc(self): + def _func(x,y): + return np.add(x,y) + + vals = [2, 2, 1, 2, .1, .2] + tys = [types.int32, types.uint32, + types.int64, types.uint64, + types.float32, types.float64] + self.run_ufunc(_func, itertools.product(tys, tys), + itertools.product(vals, vals)) + + +class TestUfuncIssues(TestCase): + + def test_issue_651(self): + # Exercise the code path to make sure this does not fail + @vectorize(["(float64,float64)"]) + def foo(x1, x2): + return np.add(x1, x2) + np.add(x1, x2) + + a = np.arange(10, dtype='f8') + b = np.arange(10, dtype='f8') + self.assertPreciseEqual(foo(a, b), (a + b) + (a + b)) + + def test_issue_2006(self): + """ + should return float32, not float64. + """ + def foo(x, y): + return np.power(x, y) + pyfunc = foo + cfunc = njit(pyfunc) + + def check(x, y): + got = cfunc(x, y) + np.testing.assert_array_almost_equal(got, pyfunc(x, y)) + # Check the power operation conserved the input's dtype + # (this is different from Numpy, whose behaviour depends on + # the *values* of the arguments -- see PyArray_CanCastArrayTo). + self.assertEqual(got.dtype, x.dtype) + + xs = [np.float32([1, 2, 3]), np.complex64([1j, 2, 3 - 3j])] + for x in xs: + check(x, 3) + check(x, np.uint64(3)) + check(x, np.int64([2, 2, 3])) + + +class _LoopTypesTester(TestCase): + """Test code generation for the different loop types defined by ufunc. + + This test relies on class variables to configure the test. Subclasses + of this class can just override some of these variables to check other + ufuncs in a different compilation context. The variables supported are: + + _funcs: the ufuncs to test + _skip_types: letter types that force skipping the loop when testing + if present in the NumPy ufunc signature. + _supported_types: only test loops where all the types in the loop + signature are in this collection. If unset, all. + + Note that both, _skip_types and _supported_types must be met for a loop + to be tested. + + The NumPy ufunc signature has a form like 'ff->f' (for a binary ufunc + loop taking 2 floats and resulting in a float). In a NumPy ufunc object + you can get a list of supported signatures by accessing the attribute + 'types'. + """ + _skip_types = 'OegG' + + # Allowed deviation between Numpy and Numba results + _ulps = {('arccos', 'F'): 2, + ('arcsin', 'D'): 4, + ('arcsin', 'F'): 4, + ('log10', 'D'): 5, + ('tanh', 'F'): 2, + ('cbrt', 'd'): 2, + ('logaddexp2', 'd'): 2, + } + + def _arg_for_type(self, a_letter_type, index=0): + """return a suitable array argument for testing the letter type""" + # Note all possible arrays must have the same size, since they + # may be used as inputs to the same func. + if a_letter_type in 'bhilq': + # an integral + return np.array([1, 4, 0, -2], dtype=a_letter_type) + if a_letter_type in 'BHILQ': + return np.array([1, 2, 4, 0], dtype=a_letter_type) + elif a_letter_type in '?': + # a boolean + return np.array([True, False, False, True], dtype=a_letter_type) + elif a_letter_type[0] == 'm': + # timedelta64 + if len(a_letter_type) == 1: + a_letter_type = 'm8[D]' + return np.array([2, -3, 'NaT', 0], dtype=a_letter_type) + elif a_letter_type[0] == 'M': + # datetime64 + if len(a_letter_type) == 1: + a_letter_type = 'M8[D]' + return np.array(['Nat', 1, 25, 0], dtype=a_letter_type) + elif a_letter_type in 'fd': + # floating point + return np.array([1.5, -3.5, 0.0, float('nan')], + dtype=a_letter_type) + elif a_letter_type in 'FD': + # complex + if sys.platform != 'win32': + # Other platforms have better handling of negative zeros, + # test them + negzero = -(0.0 + 1.0j) + else: + negzero = 0.0 - 1.0j + return np.array([negzero, 1.5 + 1.5j, 1j * float('nan'), 0j], + dtype=a_letter_type) + else: + raise RuntimeError("type %r not understood" % (a_letter_type,)) + + def _check_loop(self, fn, ufunc, loop): + # the letter types for the args + letter_types = loop[:ufunc.nin] + loop[-ufunc.nout:] + + # ignore the loops containing an object argument. They will always + # fail in no python mode. Usually the last loop in ufuncs is an all + # object fallback + supported_types = getattr(self, '_supported_types', []) + if (supported_types and + any(l not in supported_types for l in letter_types)): + return + skip_types = getattr(self, '_skip_types', []) + if any(l in skip_types for l in letter_types): + return + # if the test case requires some types to be present, skip loops + # not involving any of those types. + required_types = getattr(self, '_required_types', []) + if required_types and not any(l in letter_types + for l in required_types): + return + + self._check_ufunc_with_dtypes(fn, ufunc, letter_types) + + def _check_ufunc_with_dtypes(self, fn, ufunc, dtypes): + # Arrays created with datetime and timedelta types (e.g. with np.array) + # will have units, so in order to ensure that the dtypes of arguments + # match the dtypes in the signature, we add units to unitless datetime + # and timedelta types. This corresponds with the addition of units in + # _arg_for_type() above. + dtypes_with_units = [] + for t in dtypes: + if t in ('m', 'M'): + t = t + '8[D]' + dtypes_with_units.append(t) + + arg_dty = [np.dtype(t) for t in dtypes_with_units] + arg_nbty = tuple([types.Array(from_dtype(t), 1, 'C') for t in arg_dty]) + cfunc = njit(arg_nbty)(fn) + + # Ensure a good mix of input values + c_args = [self._arg_for_type(t, index=index).repeat(2) + for index, t in enumerate(dtypes)] + for arr in c_args: + self.random.shuffle(arr) + py_args = [a.copy() for a in c_args] + + cfunc(*c_args) + fn(*py_args) + + # Check each array (including inputs, to ensure they weren't + # mutated). + for dtype, py_arg, c_arg in zip(arg_dty, py_args, c_args): + py_arg, c_arg = self._fixup_results(dtype, py_arg, c_arg) + typechar = c_arg.dtype.char + ulps = self._ulps.get((ufunc.__name__, typechar), 1) + prec = 'single' if typechar in 'fF' else 'exact' + prec = 'double' if typechar in 'dD' else prec + msg = '\n'.join(["ufunc '{0}' arrays differ ({1}):", + "args: {2}", "expected {3}", "got {4}"]) + msg = msg.format(ufunc.__name__, c_args, prec, py_arg, c_arg) + self.assertPreciseEqual(py_arg, c_arg, prec=prec, msg=msg, + ulps=ulps) + + def _fixup_results(self, dtype, py_arg, c_arg): + return py_arg, c_arg + + @classmethod + def _check_ufunc_loops(cls, ufunc): + for loop in ufunc.types: + cls._inject_test(ufunc, loop) + + @classmethod + def _inject_test(cls, ufunc, loop): + def test_template(self): + fn = _make_ufunc_usecase(ufunc) + self._check_loop(fn, ufunc, loop) + setattr(cls, "test_{0}_{1}".format(ufunc.__name__, + loop.replace('->', '_')), + test_template) + + @classmethod + def autogenerate(cls): + for ufunc in cls._ufuncs: + cls._check_ufunc_loops(ufunc) + + +class TestLoopTypesInt(_LoopTypesTester): + _ufuncs = supported_ufuncs[:] + # reciprocal and power need a special test due to issue #757 + _ufuncs.remove(np.power) + _ufuncs.remove(np.reciprocal) + _ufuncs.remove(np.left_shift) # has its own test class + _ufuncs.remove(np.right_shift) # has its own test class + # special test for bool subtract/negative + _ufuncs.remove(np.subtract) + _ufuncs.remove(np.negative) + _required_types = '?bBhHiIlLqQ' + _skip_types = 'fdFDmMO' + _LoopTypesTester._skip_types + + +TestLoopTypesInt.autogenerate() + + +class TestLoopTypesSubtractAndNegative(_LoopTypesTester): + _ufuncs = [np.subtract, np.negative] + _required_types = '?bBhHiIlLqQfdFD' + _skip_types = 'mMO' + _LoopTypesTester._skip_types + '?' + + +TestLoopTypesSubtractAndNegative.autogenerate() + + +class TestLoopTypesReciprocal(_LoopTypesTester): + _ufuncs = [np.reciprocal] # issue #757 + _required_types = 'bBhHiIlLqQfdFD' + _skip_types = 'mMO' + _LoopTypesTester._skip_types + + def _arg_for_type(self, a_letter_type, index=0): + res = super(self.__class__, self)._arg_for_type(a_letter_type, + index=index) + if a_letter_type in 'bBhHiIlLqQ': + # For integer reciprocal, avoid 0 as argument, as it triggers + # undefined behavior that may differ in results from Numba + # to the compiler used to compile NumPy. + res[res == 0] = 42 + return res + + +TestLoopTypesReciprocal.autogenerate() + + +class TestLoopTypesPower(_LoopTypesTester): + _ufuncs = [np.power] # issue #757 + _required_types = 'bBhHiIlLqQfdFD' + _skip_types = 'mMO' + _LoopTypesTester._skip_types + + def _arg_for_type(self, a_letter_type, index=0): + res = super(self.__class__, self)._arg_for_type(a_letter_type, + index=index) + if a_letter_type in 'bBhHiIlLqQ' and index == 1: + # For integer power, avoid a negative exponent, as it triggers + # undefined behavior that may differ in results from Numba + # to the compiler used to compile NumPy + res[res < 0] = 3 + return res + + +TestLoopTypesPower.autogenerate() + + +class TestLoopTypesIntLeftShift(_LoopTypesTester): + _ufuncs = [np.left_shift] + _required_types = 'bBhHiIlLqQ' + _skip_types = 'fdFDmMO' + _LoopTypesTester._skip_types + + def _arg_for_type(self, a_letter_type, index=0): + res = super(self.__class__, self)._arg_for_type(a_letter_type, + index=index) + # Shifting by a negative amount (argument with index 1) is undefined + # behavior in C. It is also undefined behavior in numba. In the same + # sense, it is also undefined behavior when the shift amount is larger + # than the number of bits in the shifted integer. + # To avoid problems in the test, the values are clamped (clipped) so + # that 0 <= shift_amount < bitcount(shifted_integer) + if index == 1: + bit_count = res.dtype.itemsize * 8 + res = np.clip(res, 0, bit_count - 1) + return res + + +TestLoopTypesIntLeftShift.autogenerate() + + +class TestLoopTypesIntRightShift(_LoopTypesTester): + _ufuncs = [np.right_shift] + _required_types = 'bBhHiIlLqQ' + _skip_types = 'fdFDmMO' + _LoopTypesTester._skip_types + + def _arg_for_type(self, a_letter_type, index=0): + res = super(self.__class__, self)._arg_for_type(a_letter_type, + index=index) + # Shifting by a negative amount (argument with index 1) is undefined + # behavior in C. It is also undefined behavior in numba. In the same + # sense, it is also undefined behavior when the shift amount is larger + # than the number of bits in the shifted integer. + # To avoid problems in the test, the values are clamped (clipped) so + # that 0 <= shift_amount < bitcount(shifted_integer) + if index == 1: + bit_count = res.dtype.itemsize * 8 + res = np.clip(res, 0, bit_count - 1) + + # Right shift has "implementation defined behavior" when the number + # shifted is negative (in C). In numba, right shift for signed integers + # is "arithmetic" while for unsigned integers is "logical". + # This test compares against the NumPy implementation, that relies + # on "implementation defined behavior", so the test could be a false + # failure if the compiler used to compile NumPy doesn't follow the same + # policy. + # Hint: do not rely on right shifting negative numbers in NumPy. + if index == 0: + res = np.abs(res) + return res + + +TestLoopTypesIntRightShift.autogenerate() + + +class TestLoopTypesFloorDivide(_LoopTypesTester): + _ufuncs = [np.floor_divide, np.remainder, np.divmod] + _required_types = 'bBhHiIlLqQfdFD' + _skip_types = 'mMO' + _LoopTypesTester._skip_types + + def _fixup_results(self, dtype, py_arg, c_arg): + if dtype.kind == 'f': + # Discrepancies on floating-point floor division and remainder: + # Numpy may return nan where Numba returns inf, e.g. 1. // 0. + pred = (np.isinf(c_arg) & np.isnan(py_arg)) + # Numpy and Numba may differ in signed zeros, e.g. -0. // -1. + pred |= (py_arg == 0.0) & (c_arg == 0.0) + c_arg[pred] = py_arg[pred] + return py_arg, c_arg + + +TestLoopTypesFloorDivide.autogenerate() + + +class TestLoopTypesFloat(_LoopTypesTester): + _ufuncs = supported_ufuncs[:] + if iswindows: + _ufuncs.remove(np.signbit) # TODO: fix issue #758 + _ufuncs.remove(np.floor_divide) # has its own test class + _ufuncs.remove(np.remainder) # has its own test class + _ufuncs.remove(np.divmod) # has its own test class + _ufuncs.remove(np.mod) # same as np.remainder + _required_types = 'fd' + _skip_types = 'FDmMO' + _LoopTypesTester._skip_types + + +TestLoopTypesFloat.autogenerate() + + +class TestLoopTypesComplex(_LoopTypesTester): + _ufuncs = supported_ufuncs[:] + + # Test complex types + # Every loop containing a complex argument must be tested + _required_types = 'FD' + _skip_types = 'mMO' + _LoopTypesTester._skip_types + + +TestLoopTypesComplex.autogenerate() + + +class TestLoopTypesDatetime(_LoopTypesTester): + _ufuncs = supported_ufuncs[:] + + _ufuncs.remove(np.divmod) # not implemented yet + + # NOTE: the full list of ufuncs supporting datetime64 and timedelta64 + # types in Numpy is: + # ['absolute', 'add', 'divide', 'equal', 'floor_divide', 'fmax', 'fmin', + # 'greater', 'greater_equal', 'less', 'less_equal', 'maximum', + # 'minimum', 'multiply', 'negative', 'not_equal', 'sign', 'subtract', + # 'true_divide'] + + # Test datetime64 and timedelta64 types. + _required_types = 'mM' + + # Test various units combinations (TestLoopTypes is only able to test + # homogeneous units). + + def test_add(self): + ufunc = np.add + fn = _make_ufunc_usecase(ufunc) + # heterogeneous inputs + self._check_ufunc_with_dtypes(fn, ufunc, ['m8[s]', 'm8[m]', 'm8[s]']) + self._check_ufunc_with_dtypes(fn, ufunc, ['m8[m]', 'm8[s]', 'm8[s]']) + # heterogeneous inputs, scaled output + self._check_ufunc_with_dtypes(fn, ufunc, ['m8[s]', 'm8[m]', 'm8[ms]']) + self._check_ufunc_with_dtypes(fn, ufunc, ['m8[m]', 'm8[s]', 'm8[ms]']) + # Cannot upscale result (Numpy would accept this) + with self.assertRaises(LoweringError): + self._check_ufunc_with_dtypes(fn, ufunc, + ['m8[m]', 'm8[s]', 'm8[m]']) + + def test_subtract(self): + ufunc = np.subtract + fn = _make_ufunc_usecase(ufunc) + # heterogeneous inputs + self._check_ufunc_with_dtypes(fn, ufunc, ['M8[s]', 'M8[m]', 'm8[s]']) + self._check_ufunc_with_dtypes(fn, ufunc, ['M8[m]', 'M8[s]', 'm8[s]']) + # heterogeneous inputs, scaled output + self._check_ufunc_with_dtypes(fn, ufunc, ['M8[s]', 'M8[m]', 'm8[ms]']) + self._check_ufunc_with_dtypes(fn, ufunc, ['M8[m]', 'M8[s]', 'm8[ms]']) + # Cannot upscale result (Numpy would accept this) + with self.assertRaises(LoweringError): + self._check_ufunc_with_dtypes(fn, ufunc, + ['M8[m]', 'M8[s]', 'm8[m]']) + + def test_multiply(self): + ufunc = np.multiply + fn = _make_ufunc_usecase(ufunc) + # scaled output + self._check_ufunc_with_dtypes(fn, ufunc, ['m8[s]', 'q', 'm8[us]']) + self._check_ufunc_with_dtypes(fn, ufunc, ['q', 'm8[s]', 'm8[us]']) + # Cannot upscale result (Numpy would accept this) + with self.assertRaises(LoweringError): + self._check_ufunc_with_dtypes(fn, ufunc, ['m8[s]', 'q', 'm8[m]']) + + def test_true_divide(self): + ufunc = np.true_divide + fn = _make_ufunc_usecase(ufunc) + # heterogeneous inputs + self._check_ufunc_with_dtypes(fn, ufunc, ['m8[m]', 'm8[s]', 'd']) + self._check_ufunc_with_dtypes(fn, ufunc, ['m8[s]', 'm8[m]', 'd']) + # scaled output + self._check_ufunc_with_dtypes(fn, ufunc, ['m8[m]', 'q', 'm8[s]']) + self._check_ufunc_with_dtypes(fn, ufunc, ['m8[m]', 'd', 'm8[s]']) + # Cannot upscale result (Numpy would accept this) + with self.assertRaises(LoweringError): + self._check_ufunc_with_dtypes(fn, ufunc, ['m8[s]', 'q', 'm8[m]']) + + def test_floor_divide(self): + ufunc = np.floor_divide + fn = _make_ufunc_usecase(ufunc) + # scaled output + self._check_ufunc_with_dtypes(fn, ufunc, ['m8[m]', 'q', 'm8[s]']) + self._check_ufunc_with_dtypes(fn, ufunc, ['m8[m]', 'd', 'm8[s]']) + # Cannot upscale result (Numpy would accept this) + with self.assertRaises(LoweringError): + self._check_ufunc_with_dtypes(fn, ufunc, ['m8[s]', 'q', 'm8[m]']) + + def _check_comparison(self, ufunc): + fn = _make_ufunc_usecase(ufunc) + # timedelta + self._check_ufunc_with_dtypes(fn, ufunc, ['m8[m]', 'm8[s]', '?']) + self._check_ufunc_with_dtypes(fn, ufunc, ['m8[s]', 'm8[m]', '?']) + # datetime + self._check_ufunc_with_dtypes(fn, ufunc, ['M8[m]', 'M8[s]', '?']) + self._check_ufunc_with_dtypes(fn, ufunc, ['M8[s]', 'M8[m]', '?']) + + def test_comparisons(self): + for ufunc in [np.equal, np.not_equal, np.less, np.less_equal, + np.greater, np.greater_equal]: + self._check_comparison(ufunc) + + +TestLoopTypesDatetime.autogenerate() + + +class TestUFuncBadArgs(TestCase): + def test_missing_args(self): + def func(x): + """error: np.add requires two args""" + result = np.add(x) + return result + + with self.assertRaises(TypingError): + njit([types.float64(types.float64)])(func) + + def test_too_many_args(self): + def func(x, out, out2): + """error: too many args""" + result = np.add(x, x, out, out2) + return result + + array_type = types.Array(types.float64, 1, 'C') + sig = array_type(array_type, array_type, array_type) + + with self.assertRaises(TypingError): + njit(sig)(func) + + def test_no_scalar_result_by_reference(self): + def func(x): + """error: scalar as a return value is not supported""" + y = 0 + np.add(x, x, y) + + with self.assertRaises(TypingError): + njit([types.float64(types.float64)])(func) + + +class TestUFuncCompilationThreadSafety(TestCase): + + def test_lock(self): + """ + Test that (lazy) compiling from several threads at once doesn't + produce errors (see issue #2403). + """ + errors = [] + + @vectorize + def foo(x): + return x + 1 + + def wrapper(): + try: + a = np.ones((10,), dtype=np.float64) + expected = np.ones((10,), dtype=np.float64) + 1. + np.testing.assert_array_equal(foo(a), expected) + except Exception as e: + errors.append(e) + + threads = [threading.Thread(target=wrapper) for i in range(16)] + for t in threads: + t.start() + for t in threads: + t.join() + self.assertFalse(errors) + + +class TestUfuncOnContext(TestCase): + def test_cpu_get_ufunc_info(self): + # The CPU context defines get_ufunc_info that is the same as + # ufunc_db.get_ufunc_info. + targetctx = cpu_target.target_context + # Check: get_ufunc_info returns a dict + add_info = targetctx.get_ufunc_info(np.add) + self.assertIsInstance(add_info, dict) + # Check: it is the same as ufunc_db.get_ufunc_info + expected = ufunc_db.get_ufunc_info(np.add) + self.assertEqual(add_info, expected) + # Check: KeyError raised on bad key + badkey = object() + with self.assertRaises(KeyError) as raises: + ufunc_db.get_ufunc_info(badkey) + self.assertEqual(raises.exception.args, (badkey,)) + + def test_base_get_ufunc_info(self): + # The BaseContext always raises NotImplementedError + targetctx = BaseContext(cpu_target.typing_context, 'cpu') + with self.assertRaises(NotImplementedError) as raises: + targetctx.get_ufunc_info(np.add) + self.assertRegex( + str(raises.exception), + r" does not support ufunc", + ) + + +class TestUfuncWriteInput(TestCase): + def test_write_input_arg(self): + @guvectorize(["void(float64[:], uint8[:])"], "(n)->(n)") + def func(x, out): + + for i in range(x.size): + # set every fourth element to 1 + if i % 4 == 0: + out[i] = 1 + + x = np.random.rand(10, 5) + out = np.zeros_like(x, dtype=np.int8) + + func(x, out) + np.testing.assert_array_equal( + np.array([True, False, False, False, True], dtype=np.bool_), + out.any(axis=0)) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/33/339e07a06cc19898f2372f2d6774b6f473e3e73e08900f602594ba6dc06f3efc/_foreach_pow_compositeexplicitautograd_dispatch.h b/shared/package-files/33/339e07a06cc19898f2372f2d6774b6f473e3e73e08900f602594ba6dc06f3efc/_foreach_pow_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f85c7d11c55a65cccaf4da98a4e7b102f1aaaa4c --- /dev/null +++ b/shared/package-files/33/339e07a06cc19898f2372f2d6774b6f473e3e73e08900f602594ba6dc06f3efc/_foreach_pow_compositeexplicitautograd_dispatch.h @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API void _foreach_pow_out(at::TensorList out, at::TensorList self, at::TensorList exponent); +TORCH_API void _foreach_pow_outf(at::TensorList self, at::TensorList exponent, at::TensorList out); +TORCH_API void _foreach_pow_out(at::TensorList out, at::TensorList self, const at::Scalar & exponent); +TORCH_API void _foreach_pow_outf(at::TensorList self, const at::Scalar & exponent, at::TensorList out); +TORCH_API void _foreach_pow_out(at::TensorList out, at::TensorList self, at::ArrayRef exponent); +TORCH_API void _foreach_pow_outf(at::TensorList self, at::ArrayRef exponent, at::TensorList out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/33/33a4c5f70a5b832c1042fb5e841a212d312bd9ff1eedcc3dd3d3d9dd7b24dcde/METADATA b/shared/package-files/33/33a4c5f70a5b832c1042fb5e841a212d312bd9ff1eedcc3dd3d3d9dd7b24dcde/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..f1d7204611ed8b8afcebac694988ff4546bf891a --- /dev/null +++ b/shared/package-files/33/33a4c5f70a5b832c1042fb5e841a212d312bd9ff1eedcc3dd3d3d9dd7b24dcde/METADATA @@ -0,0 +1,116 @@ +Metadata-Version: 2.1 +Name: beautifulsoup4 +Version: 4.12.2 +Summary: Screen-scraping library +Project-URL: Download, https://www.crummy.com/software/BeautifulSoup/bs4/download/ +Project-URL: Homepage, https://www.crummy.com/software/BeautifulSoup/bs4/ +Author-email: Leonard Richardson +License-Expression: MIT +License-File: AUTHORS +License-File: LICENSE +Keywords: HTML,XML,parse,soup +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Text Processing :: Markup :: HTML +Classifier: Topic :: Text Processing :: Markup :: SGML +Classifier: Topic :: Text Processing :: Markup :: XML +Requires-Python: >=3.6.0 +Requires-Dist: soupsieve>1.2 +Provides-Extra: html5lib +Requires-Dist: html5lib; extra == 'html5lib' +Provides-Extra: lxml +Requires-Dist: lxml; extra == 'lxml' +Description-Content-Type: text/markdown + +Beautiful Soup is a library that makes it easy to scrape information +from web pages. It sits atop an HTML or XML parser, providing Pythonic +idioms for iterating, searching, and modifying the parse tree. + +# Quick start + +``` +>>> from bs4 import BeautifulSoup +>>> soup = BeautifulSoup("

SomebadHTML") +>>> print(soup.prettify()) + + +

+ Some + + bad + + HTML + + +

+ + +>>> soup.find(text="bad") +'bad' +>>> soup.i +HTML +# +>>> soup = BeautifulSoup("SomebadXML", "xml") +# +>>> print(soup.prettify()) + + + Some + + bad + + XML + + +``` + +To go beyond the basics, [comprehensive documentation is available](https://www.crummy.com/software/BeautifulSoup/bs4/doc/). + +# Links + +* [Homepage](https://www.crummy.com/software/BeautifulSoup/bs4/) +* [Documentation](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) +* [Discussion group](https://groups.google.com/group/beautifulsoup/) +* [Development](https://code.launchpad.net/beautifulsoup/) +* [Bug tracker](https://bugs.launchpad.net/beautifulsoup/) +* [Complete changelog](https://bazaar.launchpad.net/~leonardr/beautifulsoup/bs4/view/head:/CHANGELOG) + +# Note on Python 2 sunsetting + +Beautiful Soup's support for Python 2 was discontinued on December 31, +2020: one year after the sunset date for Python 2 itself. From this +point onward, new Beautiful Soup development will exclusively target +Python 3. The final release of Beautiful Soup 4 to support Python 2 +was 4.9.3. + +# Supporting the project + +If you use Beautiful Soup as part of your professional work, please consider a +[Tidelift subscription](https://tidelift.com/subscription/pkg/pypi-beautifulsoup4?utm_source=pypi-beautifulsoup4&utm_medium=referral&utm_campaign=readme). +This will support many of the free software projects your organization +depends on, not just Beautiful Soup. + +If you use Beautiful Soup for personal projects, the best way to say +thank you is to read +[Tool Safety](https://www.crummy.com/software/BeautifulSoup/zine/), a zine I +wrote about what Beautiful Soup has taught me about software +development. + +# Building the documentation + +The bs4/doc/ directory contains full documentation in Sphinx +format. Run `make html` in that directory to create HTML +documentation. + +# Running the unit tests + +Beautiful Soup supports unit test discovery using Pytest: + +``` +$ pytest +``` + diff --git a/shared/package-files/33/33a7424b977be741737fd197ef1c8d91af92676c091422faeb2e63fa6a07870a/__init__.py b/shared/package-files/33/33a7424b977be741737fd197ef1c8d91af92676c091422faeb2e63fa6a07870a/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..245594bfdc9e72ff5cb3a4799e9055c7cd6b5a3e --- /dev/null +++ b/shared/package-files/33/33a7424b977be741737fd197ef1c8d91af92676c091422faeb2e63fa6a07870a/__init__.py @@ -0,0 +1,7 @@ +""" +Test files dedicated to individual (stand-alone) DataFrame methods + +Ideally these files/tests should correspond 1-to-1 with tests.series.methods + +These may also present opportunities for sharing/de-duplicating test code. +""" diff --git a/shared/package-files/33/33a8073afc6c632b6de1e28eb68ae0ed31dece856252766ac6a917a95203edff/tvi912c-p-2p b/shared/package-files/33/33a8073afc6c632b6de1e28eb68ae0ed31dece856252766ac6a917a95203edff/tvi912c-p-2p new file mode 100644 index 0000000000000000000000000000000000000000..af170f669105354c5f0217119ba6ebad9eb52d7c Binary files /dev/null and b/shared/package-files/33/33a8073afc6c632b6de1e28eb68ae0ed31dece856252766ac6a917a95203edff/tvi912c-p-2p differ diff --git a/shared/package-files/33/33ac546de38905af7117c80f2e1486ec020c0db2b87bd0756af84cd9e5cb5d75/DeviceUtils.cuh b/shared/package-files/33/33ac546de38905af7117c80f2e1486ec020c0db2b87bd0756af84cd9e5cb5d75/DeviceUtils.cuh new file mode 100644 index 0000000000000000000000000000000000000000..c0a2fc47c0069bed4e15beec249162a556f7dc3d --- /dev/null +++ b/shared/package-files/33/33ac546de38905af7117c80f2e1486ec020c0db2b87bd0756af84cd9e5cb5d75/DeviceUtils.cuh @@ -0,0 +1,121 @@ +#pragma once + +#include +#include +#include + +__device__ __forceinline__ unsigned int ACTIVE_MASK() +{ +#if !defined(USE_ROCM) + return __activemask(); +#else +// will be ignored anyway + return 0xffffffff; +#endif +} + +__device__ __forceinline__ void WARP_SYNC(unsigned mask = 0xffffffff) { +#if !defined(USE_ROCM) + return __syncwarp(mask); +#endif +} + +#if defined(USE_ROCM) +__device__ __forceinline__ unsigned long long int WARP_BALLOT(int predicate) +{ +return __ballot(predicate); +} +#else +__device__ __forceinline__ unsigned int WARP_BALLOT(int predicate, unsigned int mask = 0xffffffff) +{ +#if !defined(USE_ROCM) + return __ballot_sync(mask, predicate); +#else + return __ballot(predicate); +#endif +} +#endif + +template +__device__ __forceinline__ T WARP_SHFL_XOR(T value, int laneMask, int width = warpSize, unsigned int mask = 0xffffffff) +{ +#if !defined(USE_ROCM) + return __shfl_xor_sync(mask, value, laneMask, width); +#else + return __shfl_xor(value, laneMask, width); +#endif +} + +template +__device__ __forceinline__ T WARP_SHFL(T value, int srcLane, int width = warpSize, unsigned int mask = 0xffffffff) +{ +#if !defined(USE_ROCM) + return __shfl_sync(mask, value, srcLane, width); +#else + return __shfl(value, srcLane, width); +#endif +} + +template +__device__ __forceinline__ T WARP_SHFL_UP(T value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff) +{ +#if !defined(USE_ROCM) + return __shfl_up_sync(mask, value, delta, width); +#else + return __shfl_up(value, delta, width); +#endif +} + +template +__device__ __forceinline__ T WARP_SHFL_DOWN(T value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff) +{ +#if !defined(USE_ROCM) + return __shfl_down_sync(mask, value, delta, width); +#else + return __shfl_down(value, delta, width); +#endif +} + +#if defined(USE_ROCM) +template<> +__device__ __forceinline__ int64_t WARP_SHFL_DOWN(int64_t value, unsigned int delta, int width , unsigned int mask) +{ + //(HIP doesn't support int64_t). Trick from https://devblogs.nvidia.com/faster-parallel-reductions-kepler/ + int2 a = *reinterpret_cast(&value); + a.x = __shfl_down(a.x, delta); + a.y = __shfl_down(a.y, delta); + return *reinterpret_cast(&a); +} +#endif + +template<> +__device__ __forceinline__ c10::Half WARP_SHFL_DOWN(c10::Half value, unsigned int delta, int width, unsigned int mask) +{ + return c10::Half(WARP_SHFL_DOWN(value.x, delta, width, mask), c10::Half::from_bits_t{}); +} + +template +__device__ __forceinline__ c10::complex WARP_SHFL_DOWN(c10::complex value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff) +{ +#if !defined(USE_ROCM) + return c10::complex( + __shfl_down_sync(mask, value.real_, delta, width), + __shfl_down_sync(mask, value.imag_, delta, width)); +#else + return c10::complex( + __shfl_down(value.real_, delta, width), + __shfl_down(value.imag_, delta, width)); +#endif +} + +/** + * For CC 3.5+, perform a load using __ldg + */ +template +__device__ __forceinline__ T doLdg(const T* p) { +#if __CUDA_ARCH__ >= 350 && !defined(USE_ROCM) + return __ldg(p); +#else + return *p; +#endif +} diff --git a/shared/package-files/33/33acda08d1ad11a762760d2dc2948b50c660c1c048f02f48d75377acdded6bca/linalg_solve_ops.h b/shared/package-files/33/33acda08d1ad11a762760d2dc2948b50c660c1c048f02f48d75377acdded6bca/linalg_solve_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..a5beb0ed6e3181a7e8d9042a6910221b23989e02 --- /dev/null +++ b/shared/package-files/33/33acda08d1ad11a762760d2dc2948b50c660c1c048f02f48d75377acdded6bca/linalg_solve_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API linalg_solve { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::linalg_solve") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_solve(Tensor A, Tensor B, *, bool left=True) -> Tensor") + static at::Tensor call(const at::Tensor & A, const at::Tensor & B, bool left); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & A, const at::Tensor & B, bool left); +}; + +struct TORCH_API linalg_solve_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, bool, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::linalg_solve") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_solve.out(Tensor A, Tensor B, *, bool left=True, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & A, const at::Tensor & B, bool left, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & A, const at::Tensor & B, bool left, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/33/33aeeb6f840b33de7ae4d6ba08766729e96310eb5ca3355c85a44fd35d4e1bfd/AUTHORS.md b/shared/package-files/33/33aeeb6f840b33de7ae4d6ba08766729e96310eb5ca3355c85a44fd35d4e1bfd/AUTHORS.md new file mode 100644 index 0000000000000000000000000000000000000000..6f8b98dbad5b6b00b7d5090fa250adf02c0230ab --- /dev/null +++ b/shared/package-files/33/33aeeb6f840b33de7ae4d6ba08766729e96310eb5ca3355c85a44fd35d4e1bfd/AUTHORS.md @@ -0,0 +1,13 @@ +All of the people who have made at least one contribution to conda-content-trust. +Authors are sorted alphabetically. + +* Bianca Henderson +* Cheng H. Lee +* Conda Bot +* Daniel Holth +* Jannis Leidel +* Ken Odegard +* Mike Sarahan +* Sebastien Awwad +* dependabot[bot] +* pre-commit-ci[bot] diff --git a/shared/package-files/33/33af48e8c163687295a74dee653d92fe90c3ebf850e2357c04963c394ff59010/arccosh_compositeimplicitautograd_dispatch.h b/shared/package-files/33/33af48e8c163687295a74dee653d92fe90c3ebf850e2357c04963c394ff59010/arccosh_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..5646fa0d8641bd5abc6e9ff49b1ad333ca64228d --- /dev/null +++ b/shared/package-files/33/33af48e8c163687295a74dee653d92fe90c3ebf850e2357c04963c394ff59010/arccosh_compositeimplicitautograd_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor arccosh(const at::Tensor & self); +TORCH_API at::Tensor & arccosh_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & arccosh_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & arccosh_(at::Tensor & self); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/33/33b19575df80c4e87aa06c3acdf38d1004cb32cc402185b6cbd9113979e7f998/model.pyi b/shared/package-files/33/33b19575df80c4e87aa06c3acdf38d1004cb32cc402185b6cbd9113979e7f998/model.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d8f44b47c51b06b6752e0aea050037d089be010f --- /dev/null +++ b/shared/package-files/33/33b19575df80c4e87aa06c3acdf38d1004cb32cc402185b6cbd9113979e7f998/model.pyi @@ -0,0 +1 @@ +from pyexpat.model import * diff --git a/shared/package-files/33/33b1c5130ef2f4aa62eeda4bc8c0d99730e46c38cec7150eb5bb4ae66c1a4cf3/gufunc.pyi b/shared/package-files/33/33b1c5130ef2f4aa62eeda4bc8c0d99730e46c38cec7150eb5bb4ae66c1a4cf3/gufunc.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c68267f83f28a86be58cbae16fc92eee9b4d3ccc --- /dev/null +++ b/shared/package-files/33/33b1c5130ef2f4aa62eeda4bc8c0d99730e46c38cec7150eb5bb4ae66c1a4cf3/gufunc.pyi @@ -0,0 +1,152 @@ +from collections.abc import Callable +from typing import Any, TypeAlias, type_check_only + +from typing_extensions import ( + Concatenate, + Generic, + Never, + ParamSpec, + Self, + TypeVar, + override, +) + +from numba.core import serialize +from numba.core.compiler import CompileResult +from numba.core.types import Type +from numba.core.typing.templates import Signature +from numba.np import npyimpl + +from .ufunc_base import ( + UfuncBase, + UfuncLowererBase, + _AccumulateT_co, + _IdentityT_co, + _OuterT_co, + _ReduceAtT_co, + _ReduceT_co, +) + +### + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_Tss = ParamSpec("_Tss") +_CallT_co = TypeVar( + "_CallT_co", + bound=Callable[Concatenate[Never, ...], object], + default=Callable[Concatenate[Any, ...], Any], + covariant=True, +) +_AtT_co = TypeVar( + "_AtT_co", + bound=Callable[[Never, Never, Never], None], + default=Callable[[Any, Any, Any | None], None], + covariant=True, +) +_GUFuncT = TypeVar("_GUFuncT", bound=GUFunc) +_GUFuncT_co = TypeVar("_GUFuncT_co", bound=GUFunc, covariant=True) + +_ToSignature: TypeAlias = Signature | tuple[Type | Signature, ...] | str + +@type_check_only +class GUFuncKernel(npyimpl._Kernel, Generic[_GUFuncT_co]): + __name__: str + + dufunc: _GUFuncT_co # not a typo + + inner_sig: Signature | None + cres: CompileResult | None + +### + +def make_gufunc_kernel(_dufunc: _GUFuncT) -> type[GUFuncKernel[_GUFuncT]]: ... + +class GUFuncLowerer( + UfuncLowererBase[_GUFuncT_co, GUFuncKernel[_GUFuncT_co]], + Generic[_GUFuncT_co], +): + def __init__(self, gufunc: _GUFuncT_co) -> None: ... + +class GUFunc( + serialize.ReduceMixin, + UfuncBase[ + _AtT_co, + _ReduceT_co, + _ReduceAtT_co, + _AccumulateT_co, + _OuterT_co, + _IdentityT_co, + str, + ], + Generic[ + _CallT_co, + _AtT_co, + _ReduceT_co, + _ReduceAtT_co, + _AccumulateT_co, + _OuterT_co, + _IdentityT_co, + ], +): + __name__: str + __doc__: str | None + + def __init__( + self, + py_func: Callable[..., object], + signature: str, + identity: _IdentityT_co | None = None, + cache: bool | None = None, + is_dynamic: bool = False, + targetoptions: dict[str, Any] | None = None, + writable_args: tuple[int | str, ...] = ..., + ) -> None: ... + def __call__( + self: GUFunc[Callable[Concatenate[_T1, _Tss], _T]], + arg0: _T1, + /, + *args: _Tss.args, + **kws: _Tss.kwargs, + ) -> _T: ... + + # + def add(self, fty: _ToSignature) -> None: ... + def expected_ndims(self) -> tuple[tuple[int, ...], tuple[int, ...]]: ... + def build_ufunc(self) -> Self: ... + @override + def match_signature( # pyrefly:ignore[bad-override-mutable-attribute] + self, ewise_types: tuple[Type, ...], sig: Signature + ) -> bool: ... + + # + @property + def is_dynamic(self) -> bool: ... + + # `ReduceMixin` methods + @override + def _reduce_states(self) -> dict[str, Any]: ... + @classmethod + @override + def _rebuild( # type: ignore[override] # pyrefly:ignore[bad-override] + cls, + py_func: Callable[..., object], + signature: str, + identity: _T, + cache: bool, + is_dynamic: bool, + targetoptions: dict[str, Any] | None, + writable_args: tuple[int | str, ...], + typesigs: list[Signature], + frozen: bool, + ) -> GUFunc[ + _CallT_co, + _AtT_co, + _ReduceT_co, + _ReduceAtT_co, + _AccumulateT_co, + _OuterT_co, + _T, + ]: ... diff --git a/shared/package-files/33/33b2e4cc2a8e13fdab2c42e4e5f39c041964bb8ff51016dfa659a88475220458/set_data.h b/shared/package-files/33/33b2e4cc2a8e13fdab2c42e4e5f39c041964bb8ff51016dfa659a88475220458/set_data.h new file mode 100644 index 0000000000000000000000000000000000000000..c1b79d201b9a2bd732fbc48574ff519be4fb6461 --- /dev/null +++ b/shared/package-files/33/33b2e4cc2a8e13fdab2c42e4e5f39c041964bb8ff51016dfa659a88475220458/set_data.h @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + + +} diff --git a/shared/package-files/33/33b4a16a7ac94f1f9b00fef8d2c477b3b050ca961f9a1db79f5b51605282e14b/structuralholes.py b/shared/package-files/33/33b4a16a7ac94f1f9b00fef8d2c477b3b050ca961f9a1db79f5b51605282e14b/structuralholes.py new file mode 100644 index 0000000000000000000000000000000000000000..9f67f59ff659765b4686b503d3d67880834a7521 --- /dev/null +++ b/shared/package-files/33/33b4a16a7ac94f1f9b00fef8d2c477b3b050ca961f9a1db79f5b51605282e14b/structuralholes.py @@ -0,0 +1,279 @@ +"""Functions for computing measures of structural holes.""" + +import networkx as nx + +__all__ = ["constraint", "local_constraint", "effective_size"] + + +@nx._dispatch +def mutual_weight(G, u, v, weight=None): + """Returns the sum of the weights of the edge from `u` to `v` and + the edge from `v` to `u` in `G`. + + `weight` is the edge data key that represents the edge weight. If + the specified key is `None` or is not in the edge data for an edge, + that edge is assumed to have weight 1. + + Pre-conditions: `u` and `v` must both be in `G`. + + """ + try: + a_uv = G[u][v].get(weight, 1) + except KeyError: + a_uv = 0 + try: + a_vu = G[v][u].get(weight, 1) + except KeyError: + a_vu = 0 + return a_uv + a_vu + + +def normalized_mutual_weight(G, u, v, norm=sum, weight=None): + """Returns normalized mutual weight of the edges from `u` to `v` + with respect to the mutual weights of the neighbors of `u` in `G`. + + `norm` specifies how the normalization factor is computed. It must + be a function that takes a single argument and returns a number. + The argument will be an iterable of mutual weights + of pairs ``(u, w)``, where ``w`` ranges over each (in- and + out-)neighbor of ``u``. Commons values for `normalization` are + ``sum`` and ``max``. + + `weight` can be ``None`` or a string, if None, all edge weights + are considered equal. Otherwise holds the name of the edge + attribute used as weight. + + """ + scale = norm(mutual_weight(G, u, w, weight) for w in set(nx.all_neighbors(G, u))) + return 0 if scale == 0 else mutual_weight(G, u, v, weight) / scale + + +def effective_size(G, nodes=None, weight=None): + r"""Returns the effective size of all nodes in the graph ``G``. + + The *effective size* of a node's ego network is based on the concept + of redundancy. A person's ego network has redundancy to the extent + that her contacts are connected to each other as well. The + nonredundant part of a person's relationships it's the effective + size of her ego network [1]_. Formally, the effective size of a + node $u$, denoted $e(u)$, is defined by + + .. math:: + + e(u) = \sum_{v \in N(u) \setminus \{u\}} + \left(1 - \sum_{w \in N(v)} p_{uw} m_{vw}\right) + + where $N(u)$ is the set of neighbors of $u$ and $p_{uw}$ is the + normalized mutual weight of the (directed or undirected) edges + joining $u$ and $v$, for each vertex $u$ and $v$ [1]_. And $m_{vw}$ + is the mutual weight of $v$ and $w$ divided by $v$ highest mutual + weight with any of its neighbors. The *mutual weight* of $u$ and $v$ + is the sum of the weights of edges joining them (edge weights are + assumed to be one if the graph is unweighted). + + For the case of unweighted and undirected graphs, Borgatti proposed + a simplified formula to compute effective size [2]_ + + .. math:: + + e(u) = n - \frac{2t}{n} + + where `t` is the number of ties in the ego network (not including + ties to ego) and `n` is the number of nodes (excluding ego). + + Parameters + ---------- + G : NetworkX graph + The graph containing ``v``. Directed graphs are treated like + undirected graphs when computing neighbors of ``v``. + + nodes : container, optional + Container of nodes in the graph ``G`` to compute the effective size. + If None, the effective size of every node is computed. + + weight : None or string, optional + If None, all edge weights are considered equal. + Otherwise holds the name of the edge attribute used as weight. + + Returns + ------- + dict + Dictionary with nodes as keys and the effective size of the node as values. + + Notes + ----- + Burt also defined the related concept of *efficiency* of a node's ego + network, which is its effective size divided by the degree of that + node [1]_. So you can easily compute efficiency: + + >>> G = nx.DiGraph() + >>> G.add_edges_from([(0, 1), (0, 2), (1, 0), (2, 1)]) + >>> esize = nx.effective_size(G) + >>> efficiency = {n: v / G.degree(n) for n, v in esize.items()} + + See also + -------- + constraint + + References + ---------- + .. [1] Burt, Ronald S. + *Structural Holes: The Social Structure of Competition.* + Cambridge: Harvard University Press, 1995. + + .. [2] Borgatti, S. + "Structural Holes: Unpacking Burt's Redundancy Measures" + CONNECTIONS 20(1):35-38. + http://www.analytictech.com/connections/v20(1)/holes.htm + + """ + + def redundancy(G, u, v, weight=None): + nmw = normalized_mutual_weight + r = sum( + nmw(G, u, w, weight=weight) * nmw(G, v, w, norm=max, weight=weight) + for w in set(nx.all_neighbors(G, u)) + ) + return 1 - r + + effective_size = {} + if nodes is None: + nodes = G + # Use Borgatti's simplified formula for unweighted and undirected graphs + if not G.is_directed() and weight is None: + for v in nodes: + # Effective size is not defined for isolated nodes + if len(G[v]) == 0: + effective_size[v] = float("nan") + continue + E = nx.ego_graph(G, v, center=False, undirected=True) + effective_size[v] = len(E) - (2 * E.size()) / len(E) + else: + for v in nodes: + # Effective size is not defined for isolated nodes + if len(G[v]) == 0: + effective_size[v] = float("nan") + continue + effective_size[v] = sum( + redundancy(G, v, u, weight) for u in set(nx.all_neighbors(G, v)) + ) + return effective_size + + +def constraint(G, nodes=None, weight=None): + r"""Returns the constraint on all nodes in the graph ``G``. + + The *constraint* is a measure of the extent to which a node *v* is + invested in those nodes that are themselves invested in the + neighbors of *v*. Formally, the *constraint on v*, denoted `c(v)`, + is defined by + + .. math:: + + c(v) = \sum_{w \in N(v) \setminus \{v\}} \ell(v, w) + + where $N(v)$ is the subset of the neighbors of `v` that are either + predecessors or successors of `v` and $\ell(v, w)$ is the local + constraint on `v` with respect to `w` [1]_. For the definition of local + constraint, see :func:`local_constraint`. + + Parameters + ---------- + G : NetworkX graph + The graph containing ``v``. This can be either directed or undirected. + + nodes : container, optional + Container of nodes in the graph ``G`` to compute the constraint. If + None, the constraint of every node is computed. + + weight : None or string, optional + If None, all edge weights are considered equal. + Otherwise holds the name of the edge attribute used as weight. + + Returns + ------- + dict + Dictionary with nodes as keys and the constraint on the node as values. + + See also + -------- + local_constraint + + References + ---------- + .. [1] Burt, Ronald S. + "Structural holes and good ideas". + American Journal of Sociology (110): 349–399. + + """ + if nodes is None: + nodes = G + constraint = {} + for v in nodes: + # Constraint is not defined for isolated nodes + if len(G[v]) == 0: + constraint[v] = float("nan") + continue + constraint[v] = sum( + local_constraint(G, v, n, weight) for n in set(nx.all_neighbors(G, v)) + ) + return constraint + + +def local_constraint(G, u, v, weight=None): + r"""Returns the local constraint on the node ``u`` with respect to + the node ``v`` in the graph ``G``. + + Formally, the *local constraint on u with respect to v*, denoted + $\ell(v)$, is defined by + + .. math:: + + \ell(u, v) = \left(p_{uv} + \sum_{w \in N(v)} p_{uw} p_{wv}\right)^2, + + where $N(v)$ is the set of neighbors of $v$ and $p_{uv}$ is the + normalized mutual weight of the (directed or undirected) edges + joining $u$ and $v$, for each vertex $u$ and $v$ [1]_. The *mutual + weight* of $u$ and $v$ is the sum of the weights of edges joining + them (edge weights are assumed to be one if the graph is + unweighted). + + Parameters + ---------- + G : NetworkX graph + The graph containing ``u`` and ``v``. This can be either + directed or undirected. + + u : node + A node in the graph ``G``. + + v : node + A node in the graph ``G``. + + weight : None or string, optional + If None, all edge weights are considered equal. + Otherwise holds the name of the edge attribute used as weight. + + Returns + ------- + float + The constraint of the node ``v`` in the graph ``G``. + + See also + -------- + constraint + + References + ---------- + .. [1] Burt, Ronald S. + "Structural holes and good ideas". + American Journal of Sociology (110): 349–399. + + """ + nmw = normalized_mutual_weight + direct = nmw(G, u, v, weight=weight) + indirect = sum( + nmw(G, u, w, weight=weight) * nmw(G, w, v, weight=weight) + for w in set(nx.all_neighbors(G, u)) + ) + return (direct + indirect) ** 2 diff --git a/shared/package-files/33/33b8b851998e03b691ce8a0dd7f1da9aa55defc920b59e97c80dddc5597a9db5/utils.py b/shared/package-files/33/33b8b851998e03b691ce8a0dd7f1da9aa55defc920b59e97c80dddc5597a9db5/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..71d55eadc11c93a0cffaa78494f1598dc950f780 --- /dev/null +++ b/shared/package-files/33/33b8b851998e03b691ce8a0dd7f1da9aa55defc920b59e97c80dddc5597a9db5/utils.py @@ -0,0 +1,172 @@ +import ast +import itertools +import types +from collections import OrderedDict, Counter, defaultdict +from types import FrameType, TracebackType +from typing import ( + Iterator, List, Tuple, Iterable, Callable, Union, + TypeVar, Mapping, +) + +T = TypeVar('T') +R = TypeVar('R') + + +def truncate(seq, max_length: int, middle): + if len(seq) > max_length: + right = (max_length - len(middle)) // 2 + left = max_length - len(middle) - right + seq = seq[:left] + middle + seq[-right:] + return seq + + +def unique_in_order(it: Iterable[T]) -> List[T]: + return list(OrderedDict.fromkeys(it)) + + +def line_range(node: ast.AST) -> Tuple[int, int]: + """ + Returns a pair of numbers representing a half open range + (i.e. suitable as arguments to the `range()` builtin) + of line numbers of the given AST nodes. + """ + try: + return ( + node.first_token.start[0], + node.last_token.end[0] + 1, + ) + except AttributeError: + return ( + node.lineno, + getattr(node, "end_lineno", node.lineno) + 1, + ) + + +def highlight_unique(lst: List[T]) -> Iterator[Tuple[T, bool]]: + counts = Counter(lst) + + for is_common, group in itertools.groupby(lst, key=lambda x: counts[x] > 3): + if is_common: + group = list(group) + highlighted = [False] * len(group) + + def highlight_index(f): + try: + i = f() + except ValueError: + return None + highlighted[i] = True + return i + + for item in set(group): + first = highlight_index(lambda: group.index(item)) + if first is not None: + highlight_index(lambda: group.index(item, first + 1)) + highlight_index(lambda: -1 - group[::-1].index(item)) + else: + highlighted = itertools.repeat(True) + + yield from zip(group, highlighted) + + +def identity(x: T) -> T: + return x + + +def collapse_repeated(lst, *, collapser, mapper=identity, key=identity): + keyed = list(map(key, lst)) + for is_highlighted, group in itertools.groupby( + zip(lst, highlight_unique(keyed)), + key=lambda t: t[1][1], + ): + original_group, highlighted_group = zip(*group) + if is_highlighted: + yield from map(mapper, original_group) + else: + keyed_group, _ = zip(*highlighted_group) + yield collapser(list(original_group), list(keyed_group)) + + +def is_frame(frame_or_tb: Union[FrameType, TracebackType]) -> bool: + assert_(isinstance(frame_or_tb, (types.FrameType, types.TracebackType))) + return isinstance(frame_or_tb, (types.FrameType,)) + + +def iter_stack(frame_or_tb: Union[FrameType, TracebackType]) -> Iterator[Union[FrameType, TracebackType]]: + while frame_or_tb: + yield frame_or_tb + if is_frame(frame_or_tb): + frame_or_tb = frame_or_tb.f_back + else: + frame_or_tb = frame_or_tb.tb_next + + +def frame_and_lineno(frame_or_tb: Union[FrameType, TracebackType]) -> Tuple[FrameType, int]: + if is_frame(frame_or_tb): + return frame_or_tb, frame_or_tb.f_lineno + else: + return frame_or_tb.tb_frame, frame_or_tb.tb_lineno + + +def group_by_key_func(iterable: Iterable[T], key_func: Callable[[T], R]) -> Mapping[R, List[T]]: + # noinspection PyUnresolvedReferences + """ + Create a dictionary from an iterable such that the keys are the result of evaluating a key function on elements + of the iterable and the values are lists of elements all of which correspond to the key. + + >>> def si(d): return sorted(d.items()) + >>> si(group_by_key_func("a bb ccc d ee fff".split(), len)) + [(1, ['a', 'd']), (2, ['bb', 'ee']), (3, ['ccc', 'fff'])] + >>> si(group_by_key_func([-1, 0, 1, 3, 6, 8, 9, 2], lambda x: x % 2)) + [(0, [0, 6, 8, 2]), (1, [-1, 1, 3, 9])] + """ + result = defaultdict(list) + for item in iterable: + result[key_func(item)].append(item) + return result + + +class cached_property(object): + """ + A property that is only computed once per instance and then replaces itself + with an ordinary attribute. Deleting the attribute resets the property. + + Based on https://github.com/pydanny/cached-property/blob/master/cached_property.py + """ + + def __init__(self, func): + self.__doc__ = func.__doc__ + self.func = func + + def cached_property_wrapper(self, obj, _cls): + if obj is None: + return self + + value = obj.__dict__[self.func.__name__] = self.func(obj) + return value + + __get__ = cached_property_wrapper + + +def _pygmented_with_ranges(formatter, code, ranges): + import pygments + from pygments.lexers import get_lexer_by_name + + class MyLexer(type(get_lexer_by_name("python3"))): + def get_tokens(self, text): + length = 0 + for ttype, value in super().get_tokens(text): + if any(start <= length < end for start, end in ranges): + ttype = ttype.ExecutingNode + length += len(value) + yield ttype, value + + lexer = MyLexer(stripnl=False) + return pygments.highlight(code, lexer, formatter).splitlines() + + +def assert_(condition, error=""): + if not condition: + if isinstance(error, str): + error = AssertionError(error) + raise error diff --git a/shared/package-files/33/33b8d33788102115a9900ad0475ddb23b58de96716f8069bc4a82b38746f7de4/helper.py b/shared/package-files/33/33b8d33788102115a9900ad0475ddb23b58de96716f8069bc4a82b38746f7de4/helper.py new file mode 100644 index 0000000000000000000000000000000000000000..fcc7000c215f8a7605a2a59b5767b27b2fcd969d --- /dev/null +++ b/shared/package-files/33/33b8d33788102115a9900ad0475ddb23b58de96716f8069bc4a82b38746f7de4/helper.py @@ -0,0 +1,19 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.fftpack` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'fftshift', 'ifftshift', 'fftfreq', 'rfftfreq', 'next_fast_len' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="fftpack", module="helper", + private_modules=["_helper"], all=__all__, + attribute=name) diff --git a/shared/package-files/33/33b9313dd9efcd1d65c564b3a3067361ebe03de97b3727c5e8bdbbf062b116c9/add_native.h b/shared/package-files/33/33b9313dd9efcd1d65c564b3a3067361ebe03de97b3727c5e8bdbbf062b116c9/add_native.h new file mode 100644 index 0000000000000000000000000000000000000000..c3476cfbc1ec210307330e7a349b85f9f8ccf3d0 --- /dev/null +++ b/shared/package-files/33/33b9313dd9efcd1d65c564b3a3067361ebe03de97b3727c5e8bdbbf062b116c9/add_native.h @@ -0,0 +1,43 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_ufunc_add_CPU : public at::meta::structured_add_Tensor { +void impl(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha, const at::Tensor & out); +}; +struct TORCH_API structured_ufunc_add_CUDA : public at::meta::structured_add_Tensor { +void impl(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha, const at::Tensor & out); +}; +TORCH_API at::Tensor NestedTensor_add_Tensor(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha=1); +TORCH_API at::Tensor & NestedTensor_add__Tensor(at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha=1); +TORCH_API at::Tensor add_sparse(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha=1); +TORCH_API at::Tensor & add_out_sparse_cpu(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha, at::Tensor & out); +TORCH_API at::Tensor & add_sparse_(at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha=1); +TORCH_API at::Tensor & add_out_sparse_cuda(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha, at::Tensor & out); +TORCH_API at::Tensor add_sparse_csr(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha=1); +TORCH_API at::Tensor & add_out_sparse_compressed_cpu(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha, at::Tensor & out); +TORCH_API at::Tensor & add_sparse_csr_(at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha=1); +TORCH_API at::Tensor & add_out_sparse_compressed_cuda(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha, at::Tensor & out); +TORCH_API at::Tensor mkldnn_add(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha=1); +TORCH_API at::Tensor & mkldnn_add_out(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha, at::Tensor & out); +TORCH_API at::Tensor & mkldnn_add_(at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha=1); +TORCH_API at::Tensor add_zerotensor(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha=1); +TORCH_API at::Tensor add(const at::Tensor & self, const at::Scalar & other, const at::Scalar & alpha=1); +TORCH_API at::Tensor & add_Scalar_out(const at::Tensor & self, const at::Scalar & other, const at::Scalar & alpha, at::Tensor & out); +TORCH_API at::Tensor & add_(at::Tensor & self, const at::Scalar & other, const at::Scalar & alpha=1); +} // namespace native +} // namespace at diff --git a/shared/package-files/33/33b99bf55ddfe4952eb7cc9ff147cbdeb1b85cfafe2ebebdd831a3935391f5de/email_mime_text.pyi b/shared/package-files/33/33b99bf55ddfe4952eb7cc9ff147cbdeb1b85cfafe2ebebdd831a3935391f5de/email_mime_text.pyi new file mode 100644 index 0000000000000000000000000000000000000000..51e147387fa218e3269958debaae49027f390e43 --- /dev/null +++ b/shared/package-files/33/33b99bf55ddfe4952eb7cc9ff147cbdeb1b85cfafe2ebebdd831a3935391f5de/email_mime_text.pyi @@ -0,0 +1 @@ +from email.mime.text import * diff --git a/shared/package-files/33/33bac34d3d7d2b1a6e4fdd7ec4142b60a5fd9f75edefe3e55b18311dec5bd324/quantize_per_tensor_dynamic_ops.h b/shared/package-files/33/33bac34d3d7d2b1a6e4fdd7ec4142b60a5fd9f75edefe3e55b18311dec5bd324/quantize_per_tensor_dynamic_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..c0b2e1a0c1e471b062623f236811c9caa9fbbc8d --- /dev/null +++ b/shared/package-files/33/33bac34d3d7d2b1a6e4fdd7ec4142b60a5fd9f75edefe3e55b18311dec5bd324/quantize_per_tensor_dynamic_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API quantize_per_tensor_dynamic { + using schema = at::Tensor (const at::Tensor &, at::ScalarType, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::quantize_per_tensor_dynamic") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "quantize_per_tensor_dynamic(Tensor self, ScalarType dtype, bool reduce_range) -> Tensor") + static at::Tensor call(const at::Tensor & self, at::ScalarType dtype, bool reduce_range); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::ScalarType dtype, bool reduce_range); +}; + +struct TORCH_API quantize_per_tensor_dynamic_out { + using schema = at::Tensor & (const at::Tensor &, at::ScalarType, bool, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::quantize_per_tensor_dynamic") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "quantize_per_tensor_dynamic.out(Tensor self, ScalarType dtype, bool reduce_range, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::ScalarType dtype, bool reduce_range, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::ScalarType dtype, bool reduce_range, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/33/33be7b7e8fa4fd19b1760e1a8ed8a668bdab852c91b692dd41424bcb725a9fca/LICENSE b/shared/package-files/33/33be7b7e8fa4fd19b1760e1a8ed8a668bdab852c91b692dd41424bcb725a9fca/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7ec568c1136eb8ec86aa05cf7abacfb54c3e5ead --- /dev/null +++ b/shared/package-files/33/33be7b7e8fa4fd19b1760e1a8ed8a668bdab852c91b692dd41424bcb725a9fca/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Seth Michael Larson + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/shared/package-files/33/33c21552f0cae8e6b588bc942fbaca4525079f0570c6541cfba6130458fee33e/max_pool3d_native.h b/shared/package-files/33/33c21552f0cae8e6b588bc942fbaca4525079f0570c6541cfba6130458fee33e/max_pool3d_native.h new file mode 100644 index 0000000000000000000000000000000000000000..567d20779158cf2ecd6ba26885c85801be37f56e --- /dev/null +++ b/shared/package-files/33/33c21552f0cae8e6b588bc942fbaca4525079f0570c6541cfba6130458fee33e/max_pool3d_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor max_pool3d(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride={}, at::IntArrayRef padding=0, at::IntArrayRef dilation=1, bool ceil_mode=false); +} // namespace native +} // namespace at diff --git a/shared/package-files/33/33c2db3f3248bbd8e5f8a37698e1c14de9d2a89a4fe2bb3c7fb7f4775096af51/common_types.py b/shared/package-files/33/33c2db3f3248bbd8e5f8a37698e1c14de9d2a89a4fe2bb3c7fb7f4775096af51/common_types.py new file mode 100644 index 0000000000000000000000000000000000000000..884f739e27813a38e8364469bb9659c09ea410b3 --- /dev/null +++ b/shared/package-files/33/33c2db3f3248bbd8e5f8a37698e1c14de9d2a89a4fe2bb3c7fb7f4775096af51/common_types.py @@ -0,0 +1,42 @@ +from typing import TypeVar, Union, Tuple, Optional +from .. import Tensor + +# Create some useful type aliases + +# Template for arguments which can be supplied as a tuple, or which can be a scalar which PyTorch will internally +# broadcast to a tuple. +# Comes in several variants: A tuple of unknown size, and a fixed-size tuple for 1d, 2d, or 3d operations. +T = TypeVar('T') +_scalar_or_tuple_any_t = Union[T, Tuple[T, ...]] +_scalar_or_tuple_1_t = Union[T, Tuple[T]] +_scalar_or_tuple_2_t = Union[T, Tuple[T, T]] +_scalar_or_tuple_3_t = Union[T, Tuple[T, T, T]] +_scalar_or_tuple_4_t = Union[T, Tuple[T, T, T, T]] +_scalar_or_tuple_5_t = Union[T, Tuple[T, T, T, T, T]] +_scalar_or_tuple_6_t = Union[T, Tuple[T, T, T, T, T, T]] + +# For arguments which represent size parameters (eg, kernel size, padding) +_size_any_t = _scalar_or_tuple_any_t[int] +_size_1_t = _scalar_or_tuple_1_t[int] +_size_2_t = _scalar_or_tuple_2_t[int] +_size_3_t = _scalar_or_tuple_3_t[int] +_size_4_t = _scalar_or_tuple_4_t[int] +_size_5_t = _scalar_or_tuple_5_t[int] +_size_6_t = _scalar_or_tuple_6_t[int] + +# For arguments which represent optional size parameters (eg, adaptive pool parameters) +_size_any_opt_t = _scalar_or_tuple_any_t[Optional[int]] +_size_2_opt_t = _scalar_or_tuple_2_t[Optional[int]] +_size_3_opt_t = _scalar_or_tuple_3_t[Optional[int]] + +# For arguments that represent a ratio to adjust each dimension of an input with (eg, upsampling parameters) +_ratio_2_t = _scalar_or_tuple_2_t[float] +_ratio_3_t = _scalar_or_tuple_3_t[float] +_ratio_any_t = _scalar_or_tuple_any_t[float] + +_tensor_list_t = _scalar_or_tuple_any_t[Tensor] + +# For the return value of max pooling operations that may or may not return indices. +# With the proposed 'Literal' feature to Python typing, it might be possible to +# eventually eliminate this. +_maybe_indices_t = _scalar_or_tuple_2_t[Tensor] diff --git a/shared/package-files/33/33c6072a006ba4e9513d7b7fd3d08b1c745ca1079b6d796c36b2a5ae8e4ae02b/iso8859-13.enc b/shared/package-files/33/33c6072a006ba4e9513d7b7fd3d08b1c745ca1079b6d796c36b2a5ae8e4ae02b/iso8859-13.enc new file mode 100644 index 0000000000000000000000000000000000000000..b7edcaf38f42902061c0cf53d14afdaa712aabc0 --- /dev/null +++ b/shared/package-files/33/33c6072a006ba4e9513d7b7fd3d08b1c745ca1079b6d796c36b2a5ae8e4ae02b/iso8859-13.enc @@ -0,0 +1,20 @@ +# Encoding file: iso8859-13, single-byte +S +003F 0 1 +00 +0000000100020003000400050006000700080009000A000B000C000D000E000F +0010001100120013001400150016001700180019001A001B001C001D001E001F +0020002100220023002400250026002700280029002A002B002C002D002E002F +0030003100320033003400350036003700380039003A003B003C003D003E003F +0040004100420043004400450046004700480049004A004B004C004D004E004F +0050005100520053005400550056005700580059005A005B005C005D005E005F +0060006100620063006400650066006700680069006A006B006C006D006E006F +0070007100720073007400750076007700780079007A007B007C007D007E007F +0080008100820083008400850086008700880089008A008B008C008D008E008F +0090009100920093009400950096009700980099009A009B009C009D009E009F +00A0201D00A200A300A4201E00A600A700D800A9015600AB00AC00AD00AE00C6 +00B000B100B200B3201C00B500B600B700F800B9015700BB00BC00BD00BE00E6 +0104012E0100010600C400C501180112010C00C90179011601220136012A013B +01600143014500D3014C00D500D600D701720141015A016A00DC017B017D00DF +0105012F0101010700E400E501190113010D00E9017A011701230137012B013C +01610144014600F3014D00F500F600F701730142015B016B00FC017C017E2019 diff --git a/shared/package-files/33/33c6c4471664084bae63a40669ed01fc0895dce9f3858f7c85a64b121adeb925/poisson_weights_v2.do b/shared/package-files/33/33c6c4471664084bae63a40669ed01fc0895dce9f3858f7c85a64b121adeb925/poisson_weights_v2.do new file mode 100644 index 0000000000000000000000000000000000000000..c11ead7086ad24eeb1d095134ba1ce1e5242e42d --- /dev/null +++ b/shared/package-files/33/33c6c4471664084bae63a40669ed01fc0895dce9f3858f7c85a64b121adeb925/poisson_weights_v2.do @@ -0,0 +1,447 @@ +clear +tempname filename +local filename = "M:\josef_new\stata_work\results_glm_poisson_weights.py" + +insheet using M:\josef_new\eclipse_ws\statsmodels\statsmodels_py34_pr\statsmodels\datasets\cpunish\cpunish.csv +generate LN_VC100k96 = log(vc100k96) +generate var10 = 1 in 1 +replace var10 = 1 in 2 +replace var10 = 1 in 3 +replace var10 = 2 in 4 +replace var10 = 2 in 5 +replace var10 = 2 in 6 +replace var10 = 3 in 7 +replace var10 = 3 in 8 +replace var10 = 3 in 9 +replace var10 = 1 in 10 +replace var10 = 1 in 11 +replace var10 = 1 in 12 +replace var10 = 2 in 13 +replace var10 = 2 in 14 +replace var10 = 2 in 15 +replace var10 = 3 in 16 +replace var10 = 3 in 17 +label variable var10 "fweight" +rename var10 fweight +label variable LN_VC100k96 "LN_VC100k96" + +/* for checkin Poisson produces the same, poisson does not allow aweights */ +/*poisson executions income perpoverty perblack LN_VC100k96 south degree */ + + +glm executions income perpoverty perblack LN_VC100k96 south degree, family(poisson) + +/* copied from glm_logit_constrained.do */ +/*glm grade gpa tuce psi, family(binomial) constraints(2) */ + +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) +predict predict_mu, mu +predict predict_linpred_std, stdp +predict predict_hat, hat + +predict score_factor, score +predict resid_anscombe, anscombe +predict resid_deviance, deviance +predict resid_response, response +predict resid_pearson, pearson +predict resid_working, working + +local pred predict_mu predict_linpred_std predict_hat +local res score_factor resid_response resid_anscombe resid_deviance resid_pearson resid_working +mkmat `res', matrix(resids) +mkmat `pred', matrix(predicted) +estmat2nparray params_table cov infocrit predicted resids, saving(`filename') format("%16.0g") resname("poisson_none_nonrobust") replace +/*------------------*/ + +drop `pred' `res' + + +glm executions income perpoverty perblack LN_VC100k96 south degree [fweight=fweight], family(poisson) + +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) +predict predict_mu, mu +predict predict_linpred_std, stdp +predict predict_hat, hat + +predict score_factor, score +predict resid_anscombe, anscombe +predict resid_deviance, deviance +predict resid_response, response +predict resid_pearson, pearson +predict resid_working, working + +local pred predict_mu predict_linpred_std predict_hat +local res score_factor resid_response resid_anscombe resid_deviance resid_pearson resid_working +mkmat `res', matrix(resids) +mkmat `pred', matrix(predicted) +estmat2nparray params_table cov infocrit predicted resids, saving(`filename') format("%16.0g") resname("poisson_fweight_nonrobust") append + +/*------------------*/ + +drop `pred' `res' + +glm executions income perpoverty perblack LN_VC100k96 south degree [aweight=fweight], family(poisson) + +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) +predict predict_mu, mu +predict predict_linpred_std, stdp +predict predict_hat, hat + +predict score_factor, score +predict resid_anscombe, anscombe +predict resid_deviance, deviance +predict resid_response, response +predict resid_pearson, pearson +predict resid_working, working + +local pred predict_mu predict_linpred_std predict_hat +local res score_factor resid_response resid_anscombe resid_deviance resid_pearson resid_working +mkmat `res', matrix(resids) +mkmat `pred', matrix(predicted) +estmat2nparray params_table cov infocrit predicted resids, saving(`filename') format("%16.0g") resname("poisson_aweight_nonrobust") append +/*------------------*/ + + +drop `pred' `res' + +glm executions income perpoverty perblack LN_VC100k96 south degree [pweight=fweight], family(poisson) + +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) + +predict predict_mu, mu +predict predict_linpred_std, stdp +//predict predict_hat, hat not allowed after robust, pweights implies HC1 + +predict score_factor, score +predict resid_anscombe, anscombe +predict resid_deviance, deviance +predict resid_response, response +predict resid_pearson, pearson +predict resid_working, working + +local pred predict_mu predict_linpred_std //predict_hat +local res score_factor resid_response resid_anscombe resid_deviance resid_pearson resid_working +mkmat `res', matrix(resids) +mkmat `pred', matrix(predicted) +estmat2nparray params_table cov infocrit predicted resids, saving(`filename') format("%16.0g") resname("poisson_pweight_nonrobust") append +/*------------------*/ + +/*******************************************************************/ +/*********** next with robust = HC1, do not save resid and similar */ + +drop `pred' `res' +glm executions income perpoverty perblack LN_VC100k96 south degree, family(poisson) vce(robust) + +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) +predict predict_mu, mu +predict predict_linpred_std, stdp +//predict predict_hat, hat + +local pred predict_mu predict_linpred_std //predict_hat +mkmat `pred', matrix(predicted) +estmat2nparray params_table cov infocrit predicted, saving(`filename') format("%16.0g") resname("poisson_none_hc1") append +/*------------------*/ + +drop `pred' + +glm executions income perpoverty perblack LN_VC100k96 south degree [fweight=fweight], family(poisson) vce(robust) + +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) +predict predict_mu, mu +predict predict_linpred_std, stdp +//predict predict_hat, hat + +local pred predict_mu predict_linpred_std //predict_hat +mkmat `pred', matrix(predicted) +estmat2nparray params_table cov infocrit predicted, saving(`filename') format("%16.0g") resname("poisson_fweight_hc1") append +/*------------------*/ + +drop `pred' + +glm executions income perpoverty perblack LN_VC100k96 south degree [aweight=fweight], family(poisson) vce(robust) + +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) +predict predict_mu, mu +predict predict_linpred_std, stdp +//predict predict_hat, hat + +local pred predict_mu predict_linpred_std //predict_hat +mkmat `pred', matrix(predicted) +estmat2nparray params_table cov infocrit predicted, saving(`filename') format("%16.0g") resname("poisson_aweight_hc1") append +/*------------------*/ + + +drop `pred' + +glm executions income perpoverty perblack LN_VC100k96 south degree [pweight=fweight], family(poisson) vce(robust) + +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) +predict predict_mu, mu +predict predict_linpred_std, stdp +//predict predict_hat, hat + +local pred predict_mu predict_linpred_std //predict_hat +mkmat `pred', matrix(predicted) +estmat2nparray params_table cov infocrit predicted, saving(`filename') format("%16.0g") resname("poisson_pweight_hc1") append +/*------------------*/ + + + + +/*****************************************************************/ +/*************************** with cluster robust standard errors */ +gen id = (_n - mod(_n, 2)) / 2 + +drop `pred' +glm executions income perpoverty perblack LN_VC100k96 south degree, family(poisson) vce(cluster id) + +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) +predict predict_mu, mu +predict predict_linpred_std, stdp +//predict predict_hat, hat + +local pred predict_mu predict_linpred_std //predict_hat +mkmat `pred', matrix(predicted) +estmat2nparray params_table cov infocrit predicted, saving(`filename') format("%16.0g") resname("poisson_none_clu1") append +/*------------------*/ + +drop `pred' + +glm executions income perpoverty perblack LN_VC100k96 south degree [fweight=fweight], family(poisson) vce(cluster id) + +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) +predict predict_mu, mu +predict predict_linpred_std, stdp +//predict predict_hat, hat + +local pred predict_mu predict_linpred_std //predict_hat +mkmat `pred', matrix(predicted) +estmat2nparray params_table cov infocrit predicted, saving(`filename') format("%16.0g") resname("poisson_fweight_clu1") append +/*------------------*/ + +drop `pred' + +glm executions income perpoverty perblack LN_VC100k96 south degree [aweight=fweight], family(poisson) vce(cluster id) + +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) +predict predict_mu, mu +predict predict_linpred_std, stdp +//predict predict_hat, hat + +local pred predict_mu predict_linpred_std //predict_hat +mkmat `pred', matrix(predicted) +estmat2nparray params_table cov infocrit predicted, saving(`filename') format("%16.0g") resname("poisson_aweight_clu1") append +/*------------------*/ + + +drop `pred' + +glm executions income perpoverty perblack LN_VC100k96 south degree [pweight=fweight], family(poisson) vce(cluster id) + +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) +predict predict_mu, mu +predict predict_linpred_std, stdp +//predict predict_hat, hat + +local pred predict_mu predict_linpred_std //predict_hat +mkmat `pred', matrix(predicted) +estmat2nparray params_table cov infocrit predicted, saving(`filename') format("%16.0g") resname("poisson_pweight_clu1") append +/*------------------*/ + + + +/*****************************************************************/ +/* +gen idn = _n +glm executions income perpoverty perblack LN_VC100k96 south degree, family(poisson) vce(cluster idn) +*/ + +/* +glm grade gpa tuce psi, family(binomial) constraints(2) vce(robust) +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) +estmat2nparray params_table cov infocrit, saving(`filename') format("%16.0g") resname("constraint2_robust") append +/*------------------*/ + + +capture drop fittedvalues fittedvalues_se +predict fittedvalues, xb +predict fittedvalues_se, stdp +outsheet fittedvalues fittedvalues_se using theil_predict.csv, comma replace +/*------------------*/ + +glm executions income perpoverty perblack LN_VC100k96 south degree [aweight=fweight], family(poisson) +predict resid_deviance_aw, deviance + + +*/ + +/*------------------*/ + +drop `pred' + +regress executions income perpoverty perblack LN_VC100k96 south degree [aweight=fweight], vce(robust) + +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) +predict predict_mu, xb +predict predict_std, stdp +//predict predict_stf, stdf +//predict predict_str, stdr +//predict predict_hat, hat + +local pred predict_mu predict_std //predict_stf predict_str predict_hat +mkmat `pred', matrix(predicted) +estmat2nparray params_table cov infocrit predicted, saving(`filename') format("%16.0g") resname("wls_aweight_robust") append +/*------------------*/ + +drop `pred' + +regress executions income perpoverty perblack LN_VC100k96 south degree [aweight=fweight], vce(cluster id) + +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) +predict predict_mu, xb +predict predict_std, stdp +//predict predict_stf, stdf +//predict predict_str, stdr +//predict predict_hat, hat + +local pred predict_mu predict_std //predict_stf predict_str predict_hat +mkmat `pred', matrix(predicted) +estmat2nparray params_table cov infocrit predicted, saving(`filename') format("%16.0g") resname("wls_aweight_clu1") append +/*------------------*/ + + +drop `pred' + +regress executions income perpoverty perblack LN_VC100k96 south degree [fweight=fweight], vce(cluster id) + +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) +predict predict_mu, xb +predict predict_std, stdp +//predict predict_stf, stdf +//predict predict_str, stdr +//predict predict_hat, hat + +local pred predict_mu predict_std //predict_stf predict_str predict_hat +mkmat `pred', matrix(predicted) +estmat2nparray params_table cov infocrit predicted, saving(`filename') format("%16.0g") resname("wls_fweight_clu1") append +/*------------------*/ + +drop `pred' + +regress executions income perpoverty perblack LN_VC100k96 south degree [pweight=fweight], vce(cluster id) + +/* boiler plate, add matrices if needed */ +tempname cov +tempname params_table +matrix cov = e(V) +matrix params_table = r(table)' +estat ic +matrix infocrit = r(S) +predict predict_mu, xb +predict predict_std, stdp +//predict predict_stf, stdf +//predict predict_str, stdr +//predict predict_hat, hat + +local pred predict_mu predict_std //predict_stf predict_str predict_hat +mkmat `pred', matrix(predicted) +estmat2nparray params_table cov infocrit predicted, saving(`filename') format("%16.0g") resname("wls_pweight_clu1") append +/*------------------*/ + +drop `pred' diff --git a/shared/package-files/33/33d0fec1b11c7512f13f1c7e6700a1a8a5f1f5323584be4614b8a97d86d11d76/THCP.h b/shared/package-files/33/33d0fec1b11c7512f13f1c7e6700a1a8a5f1f5323584be4614b8a97d86d11d76/THCP.h new file mode 100644 index 0000000000000000000000000000000000000000..697a66dc3ee91a22ae2503852db04dbba2fc74d4 --- /dev/null +++ b/shared/package-files/33/33d0fec1b11c7512f13f1c7e6700a1a8a5f1f5323584be4614b8a97d86d11d76/THCP.h @@ -0,0 +1,10 @@ +#ifndef THCP_H +#define THCP_H + +#include +#include +#include +#include +#include + +#endif diff --git a/shared/package-files/33/33d1f3f8b0878376a965596fa5de1c42dc01f45c3240f088b588591a4d938138/EmbeddingBag.h b/shared/package-files/33/33d1f3f8b0878376a965596fa5de1c42dc01f45c3240f088b588591a4d938138/EmbeddingBag.h new file mode 100644 index 0000000000000000000000000000000000000000..c2e61f280bf5922e911cdbc180a3503d75d8a06f --- /dev/null +++ b/shared/package-files/33/33d1f3f8b0878376a965596fa5de1c42dc01f45c3240f088b588591a4d938138/EmbeddingBag.h @@ -0,0 +1,139 @@ +#include +#include +#include + +#ifdef USE_FBGEMM +#include +#endif + +namespace at::native { + +void check_arguments( + const Tensor& weight, + const Tensor& indices, + const Tensor& offsets, + const int64_t mode, + const c10::optional& per_sample_weights, + bool include_last_offset); + +void make_bag_size_out( + Tensor& bag_size_out, + const Tensor& offsets, + const Tensor& indices, + const int64_t mode, + const bool include_last_offset, + const bool requires_grad); + +void make_max_indices_out( + Tensor& max_indices_out, + const Tensor& weight, + const Tensor& indices, + const Tensor& offsets, + const Tensor& bag_size, + const int64_t mode, + bool include_last_offset); + +void make_offset2bag_out( + Tensor& offset2bag, + Tensor& output, + const Tensor& weight, + const Tensor& indices, + const Tensor& offsets, + const int64_t mode, + const c10::optional& per_sample_weights, + const int64_t padding_idx = -1); + +#ifdef USE_FBGEMM + +template +struct _CallbackAndBlockSize { + using TCallback = typename fbgemm::EmbeddingSpMDMKernelSignature::Type; + + int64_t blockSize = -1; + TCallback callback = nullptr; + + static TCallback generateCallback(int64_t block_size) { + return fbgemm::GenerateEmbeddingSpMDM( + block_size, + has_weight, + /* normalize_by_lengths */false, + /* prefetch */16, + /* is_weight_positional */false, + /* use_offsets */true); + } + + _CallbackAndBlockSize() = default; + + explicit _CallbackAndBlockSize(c10::optional maybe_block_size) + : blockSize(maybe_block_size.value_or(-1)) + , callback(maybe_block_size.has_value() ? generateCallback(maybe_block_size.value()) : nullptr) + {} +}; + +template +struct _EmbeddingBagKernelCacheImpl : private StorageMixins... { + + _EmbeddingBagKernelCacheImpl() = default; + // use each of the mixins to store corresponding kernel and block size + explicit _EmbeddingBagKernelCacheImpl(c10::optional maybe_block_size) + : StorageMixins(maybe_block_size)... + {} + + // this method is thread safe (call sites may call from different threads) + template + typename _CallbackAndBlockSize::TCallback + getCallback(int64_t block_size) const { + // if the cache doesn't store the kernel for the incoming block size + // (so it is different from the one stored in corresponding mixin) + // regenerate the kernel (not writing it into the cache so we avoid locks) + if (block_size != _CallbackAndBlockSize::blockSize) { + return _CallbackAndBlockSize::generateCallback(block_size); + } + // else retrieve the cached kernel from the corresponding mixin + return _CallbackAndBlockSize::callback; + } +}; + +// instantiate the cache with the list of storage mixins +// for each of the 8 _EmbeddingBagKernelCache* usages in the EmbeddingBag.cpp impl file +using _EmbeddingBagKernelCache = _EmbeddingBagKernelCacheImpl< + _CallbackAndBlockSize, + _CallbackAndBlockSize, + _CallbackAndBlockSize, + _CallbackAndBlockSize, + _CallbackAndBlockSize, + _CallbackAndBlockSize, + _CallbackAndBlockSize, + _CallbackAndBlockSize>; +#else +struct _EmbeddingBagKernelCache { + explicit _EmbeddingBagKernelCache(c10::optional /* maybe_block_size */) {} +}; +#endif + +void _embedding_bag_cpu_impl_out(Tensor& output, Tensor& offset2bag, + Tensor& bag_size, Tensor* max_indices, + const Tensor &weight, const Tensor &indices, + const Tensor &offsets, const int64_t mode = 0, + const c10::optional& per_sample_weights = c10::nullopt, + bool include_last_offset = false, + int64_t padding_idx = -1, + _EmbeddingBagKernelCache* fbgemm_kernel_cache = nullptr); + +void _embedding_bag_cpu_out( + at::Tensor& output, + at::Tensor& offset2bag, + at::Tensor& bag_size, + at::Tensor* p_max_indices, + const at::Tensor& weight, + const at::Tensor& indices, + const at::Tensor& offsets, + const bool scale_grad_by_freq, + const int64_t mode, + const bool sparse, + const c10::optional& per_sample_weights, + const bool include_last_offset, + const c10::optional& padding_idx, + _EmbeddingBagKernelCache* fbgemm_kernel_cache = nullptr); + +} // namespace at::native diff --git a/shared/package-files/33/33d39e477f65dfe0c625206bf382159a760ca4cb3fdf155f0a049247cbbb9be9/test_sas.py b/shared/package-files/33/33d39e477f65dfe0c625206bf382159a760ca4cb3fdf155f0a049247cbbb9be9/test_sas.py new file mode 100644 index 0000000000000000000000000000000000000000..1e38baf4fc4093879b850f03d746ae5e67b477ee --- /dev/null +++ b/shared/package-files/33/33d39e477f65dfe0c625206bf382159a760ca4cb3fdf155f0a049247cbbb9be9/test_sas.py @@ -0,0 +1,34 @@ +from io import StringIO + +import pytest + +from pandas import read_sas +import pandas._testing as tm + + +class TestSas: + def test_sas_buffer_format(self): + # see gh-14947 + b = StringIO("") + + msg = ( + "If this is a buffer object rather than a string " + "name, you must specify a format string" + ) + with pytest.raises(ValueError, match=msg): + read_sas(b) + + def test_sas_read_no_format_or_extension(self): + # see gh-24548 + msg = "unable to infer format of SAS file.+" + with tm.ensure_clean("test_file_no_extension") as path: + with pytest.raises(ValueError, match=msg): + read_sas(path) + + +def test_sas_archive(datapath): + fname_uncompressed = datapath("io", "sas", "data", "airline.sas7bdat") + df_uncompressed = read_sas(fname_uncompressed) + fname_compressed = datapath("io", "sas", "data", "airline.sas7bdat.gz") + df_compressed = read_sas(fname_compressed, format="sas7bdat") + tm.assert_frame_equal(df_uncompressed, df_compressed) diff --git a/shared/package-files/33/33d3edc009158d1bf1353165440929e8403935776c16bfaa775f97466f8a8ac3/msvc9compiler.py b/shared/package-files/33/33d3edc009158d1bf1353165440929e8403935776c16bfaa775f97466f8a8ac3/msvc9compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..a7976fbe3ed924efda902f221899e35147e6c5ec --- /dev/null +++ b/shared/package-files/33/33d3edc009158d1bf1353165440929e8403935776c16bfaa775f97466f8a8ac3/msvc9compiler.py @@ -0,0 +1,788 @@ +"""distutils.msvc9compiler + +Contains MSVCCompiler, an implementation of the abstract CCompiler class +for the Microsoft Visual Studio 2008. + +The module is compatible with VS 2005 and VS 2008. You can find legacy support +for older versions of VS in distutils.msvccompiler. +""" + +# Written by Perry Stoll +# hacked by Robin Becker and Thomas Heller to do a better job of +# finding DevStudio (through the registry) +# ported to VS2005 and VS 2008 by Christian Heimes + +import os +import subprocess +import sys +import re + +from distutils.errors import DistutilsExecError, DistutilsPlatformError, \ + CompileError, LibError, LinkError +from distutils.ccompiler import CCompiler, gen_lib_options +from distutils import log +from distutils.util import get_platform + +import winreg + +RegOpenKeyEx = winreg.OpenKeyEx +RegEnumKey = winreg.EnumKey +RegEnumValue = winreg.EnumValue +RegError = winreg.error + +HKEYS = (winreg.HKEY_USERS, + winreg.HKEY_CURRENT_USER, + winreg.HKEY_LOCAL_MACHINE, + winreg.HKEY_CLASSES_ROOT) + +NATIVE_WIN64 = (sys.platform == 'win32' and sys.maxsize > 2**32) +if NATIVE_WIN64: + # Visual C++ is a 32-bit application, so we need to look in + # the corresponding registry branch, if we're running a + # 64-bit Python on Win64 + VS_BASE = r"Software\Wow6432Node\Microsoft\VisualStudio\%0.1f" + WINSDK_BASE = r"Software\Wow6432Node\Microsoft\Microsoft SDKs\Windows" + NET_BASE = r"Software\Wow6432Node\Microsoft\.NETFramework" +else: + VS_BASE = r"Software\Microsoft\VisualStudio\%0.1f" + WINSDK_BASE = r"Software\Microsoft\Microsoft SDKs\Windows" + NET_BASE = r"Software\Microsoft\.NETFramework" + +# A map keyed by get_platform() return values to values accepted by +# 'vcvarsall.bat'. Note a cross-compile may combine these (eg, 'x86_amd64' is +# the param to cross-compile on x86 targeting amd64.) +PLAT_TO_VCVARS = { + 'win32' : 'x86', + 'win-amd64' : 'amd64', +} + +class Reg: + """Helper class to read values from the registry + """ + + def get_value(cls, path, key): + for base in HKEYS: + d = cls.read_values(base, path) + if d and key in d: + return d[key] + raise KeyError(key) + get_value = classmethod(get_value) + + def read_keys(cls, base, key): + """Return list of registry keys.""" + try: + handle = RegOpenKeyEx(base, key) + except RegError: + return None + L = [] + i = 0 + while True: + try: + k = RegEnumKey(handle, i) + except RegError: + break + L.append(k) + i += 1 + return L + read_keys = classmethod(read_keys) + + def read_values(cls, base, key): + """Return dict of registry keys and values. + + All names are converted to lowercase. + """ + try: + handle = RegOpenKeyEx(base, key) + except RegError: + return None + d = {} + i = 0 + while True: + try: + name, value, type = RegEnumValue(handle, i) + except RegError: + break + name = name.lower() + d[cls.convert_mbcs(name)] = cls.convert_mbcs(value) + i += 1 + return d + read_values = classmethod(read_values) + + def convert_mbcs(s): + dec = getattr(s, "decode", None) + if dec is not None: + try: + s = dec("mbcs") + except UnicodeError: + pass + return s + convert_mbcs = staticmethod(convert_mbcs) + +class MacroExpander: + + def __init__(self, version): + self.macros = {} + self.vsbase = VS_BASE % version + self.load_macros(version) + + def set_macro(self, macro, path, key): + self.macros["$(%s)" % macro] = Reg.get_value(path, key) + + def load_macros(self, version): + self.set_macro("VCInstallDir", self.vsbase + r"\Setup\VC", "productdir") + self.set_macro("VSInstallDir", self.vsbase + r"\Setup\VS", "productdir") + self.set_macro("FrameworkDir", NET_BASE, "installroot") + try: + if version >= 8.0: + self.set_macro("FrameworkSDKDir", NET_BASE, + "sdkinstallrootv2.0") + else: + raise KeyError("sdkinstallrootv2.0") + except KeyError: + raise DistutilsPlatformError( + """Python was built with Visual Studio 2008; +extensions must be built with a compiler than can generate compatible binaries. +Visual Studio 2008 was not found on this system. If you have Cygwin installed, +you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""") + + if version >= 9.0: + self.set_macro("FrameworkVersion", self.vsbase, "clr version") + self.set_macro("WindowsSdkDir", WINSDK_BASE, "currentinstallfolder") + else: + p = r"Software\Microsoft\NET Framework Setup\Product" + for base in HKEYS: + try: + h = RegOpenKeyEx(base, p) + except RegError: + continue + key = RegEnumKey(h, 0) + d = Reg.get_value(base, r"%s\%s" % (p, key)) + self.macros["$(FrameworkVersion)"] = d["version"] + + def sub(self, s): + for k, v in self.macros.items(): + s = s.replace(k, v) + return s + +def get_build_version(): + """Return the version of MSVC that was used to build Python. + + For Python 2.3 and up, the version number is included in + sys.version. For earlier versions, assume the compiler is MSVC 6. + """ + prefix = "MSC v." + i = sys.version.find(prefix) + if i == -1: + return 6 + i = i + len(prefix) + s, rest = sys.version[i:].split(" ", 1) + majorVersion = int(s[:-2]) - 6 + if majorVersion >= 13: + # v13 was skipped and should be v14 + majorVersion += 1 + minorVersion = int(s[2:3]) / 10.0 + # I don't think paths are affected by minor version in version 6 + if majorVersion == 6: + minorVersion = 0 + if majorVersion >= 6: + return majorVersion + minorVersion + # else we don't know what version of the compiler this is + return None + +def normalize_and_reduce_paths(paths): + """Return a list of normalized paths with duplicates removed. + + The current order of paths is maintained. + """ + # Paths are normalized so things like: /a and /a/ aren't both preserved. + reduced_paths = [] + for p in paths: + np = os.path.normpath(p) + # XXX(nnorwitz): O(n**2), if reduced_paths gets long perhaps use a set. + if np not in reduced_paths: + reduced_paths.append(np) + return reduced_paths + +def removeDuplicates(variable): + """Remove duplicate values of an environment variable. + """ + oldList = variable.split(os.pathsep) + newList = [] + for i in oldList: + if i not in newList: + newList.append(i) + newVariable = os.pathsep.join(newList) + return newVariable + +def find_vcvarsall(version): + """Find the vcvarsall.bat file + + At first it tries to find the productdir of VS 2008 in the registry. If + that fails it falls back to the VS90COMNTOOLS env var. + """ + vsbase = VS_BASE % version + try: + productdir = Reg.get_value(r"%s\Setup\VC" % vsbase, + "productdir") + except KeyError: + log.debug("Unable to find productdir in registry") + productdir = None + + if not productdir or not os.path.isdir(productdir): + toolskey = "VS%0.f0COMNTOOLS" % version + toolsdir = os.environ.get(toolskey, None) + + if toolsdir and os.path.isdir(toolsdir): + productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC") + productdir = os.path.abspath(productdir) + if not os.path.isdir(productdir): + log.debug("%s is not a valid directory" % productdir) + return None + else: + log.debug("Env var %s is not set or invalid" % toolskey) + if not productdir: + log.debug("No productdir found") + return None + vcvarsall = os.path.join(productdir, "vcvarsall.bat") + if os.path.isfile(vcvarsall): + return vcvarsall + log.debug("Unable to find vcvarsall.bat") + return None + +def query_vcvarsall(version, arch="x86"): + """Launch vcvarsall.bat and read the settings from its environment + """ + vcvarsall = find_vcvarsall(version) + interesting = {"include", "lib", "libpath", "path"} + result = {} + + if vcvarsall is None: + raise DistutilsPlatformError("Unable to find vcvarsall.bat") + log.debug("Calling 'vcvarsall.bat %s' (version=%s)", arch, version) + popen = subprocess.Popen('"%s" %s & set' % (vcvarsall, arch), + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + try: + stdout, stderr = popen.communicate() + if popen.wait() != 0: + raise DistutilsPlatformError(stderr.decode("mbcs")) + + stdout = stdout.decode("mbcs") + for line in stdout.split("\n"): + line = Reg.convert_mbcs(line) + if '=' not in line: + continue + line = line.strip() + key, value = line.split('=', 1) + key = key.lower() + if key in interesting: + if value.endswith(os.pathsep): + value = value[:-1] + result[key] = removeDuplicates(value) + + finally: + popen.stdout.close() + popen.stderr.close() + + if len(result) != len(interesting): + raise ValueError(str(list(result.keys()))) + + return result + +# More globals +VERSION = get_build_version() +if VERSION < 8.0: + raise DistutilsPlatformError("VC %0.1f is not supported by this module" % VERSION) +# MACROS = MacroExpander(VERSION) + +class MSVCCompiler(CCompiler) : + """Concrete class that implements an interface to Microsoft Visual C++, + as defined by the CCompiler abstract class.""" + + compiler_type = 'msvc' + + # Just set this so CCompiler's constructor doesn't barf. We currently + # don't use the 'set_executables()' bureaucracy provided by CCompiler, + # as it really isn't necessary for this sort of single-compiler class. + # Would be nice to have a consistent interface with UnixCCompiler, + # though, so it's worth thinking about. + executables = {} + + # Private class data (need to distinguish C from C++ source for compiler) + _c_extensions = ['.c'] + _cpp_extensions = ['.cc', '.cpp', '.cxx'] + _rc_extensions = ['.rc'] + _mc_extensions = ['.mc'] + + # Needed for the filename generation methods provided by the + # base class, CCompiler. + src_extensions = (_c_extensions + _cpp_extensions + + _rc_extensions + _mc_extensions) + res_extension = '.res' + obj_extension = '.obj' + static_lib_extension = '.lib' + shared_lib_extension = '.dll' + static_lib_format = shared_lib_format = '%s%s' + exe_extension = '.exe' + + def __init__(self, verbose=0, dry_run=0, force=0): + CCompiler.__init__ (self, verbose, dry_run, force) + self.__version = VERSION + self.__root = r"Software\Microsoft\VisualStudio" + # self.__macros = MACROS + self.__paths = [] + # target platform (.plat_name is consistent with 'bdist') + self.plat_name = None + self.__arch = None # deprecated name + self.initialized = False + + def initialize(self, plat_name=None): + # multi-init means we would need to check platform same each time... + assert not self.initialized, "don't init multiple times" + if plat_name is None: + plat_name = get_platform() + # sanity check for platforms to prevent obscure errors later. + ok_plats = 'win32', 'win-amd64' + if plat_name not in ok_plats: + raise DistutilsPlatformError("--plat-name must be one of %s" % + (ok_plats,)) + + if "DISTUTILS_USE_SDK" in os.environ and "MSSdk" in os.environ and self.find_exe("cl.exe"): + # Assume that the SDK set up everything alright; don't try to be + # smarter + self.cc = "cl.exe" + self.linker = "link.exe" + self.lib = "lib.exe" + self.rc = "rc.exe" + self.mc = "mc.exe" + else: + # On x86, 'vcvars32.bat amd64' creates an env that doesn't work; + # to cross compile, you use 'x86_amd64'. + # On AMD64, 'vcvars32.bat amd64' is a native build env; to cross + # compile use 'x86' (ie, it runs the x86 compiler directly) + if plat_name == get_platform() or plat_name == 'win32': + # native build or cross-compile to win32 + plat_spec = PLAT_TO_VCVARS[plat_name] + else: + # cross compile from win32 -> some 64bit + plat_spec = PLAT_TO_VCVARS[get_platform()] + '_' + \ + PLAT_TO_VCVARS[plat_name] + + vc_env = query_vcvarsall(VERSION, plat_spec) + + self.__paths = vc_env['path'].split(os.pathsep) + os.environ['lib'] = vc_env['lib'] + os.environ['include'] = vc_env['include'] + + if len(self.__paths) == 0: + raise DistutilsPlatformError("Python was built with %s, " + "and extensions need to be built with the same " + "version of the compiler, but it isn't installed." + % self.__product) + + self.cc = self.find_exe("cl.exe") + self.linker = self.find_exe("link.exe") + self.lib = self.find_exe("lib.exe") + self.rc = self.find_exe("rc.exe") # resource compiler + self.mc = self.find_exe("mc.exe") # message compiler + #self.set_path_env_var('lib') + #self.set_path_env_var('include') + + # extend the MSVC path with the current path + try: + for p in os.environ['path'].split(';'): + self.__paths.append(p) + except KeyError: + pass + self.__paths = normalize_and_reduce_paths(self.__paths) + os.environ['path'] = ";".join(self.__paths) + + self.preprocess_options = None + if self.__arch == "x86": + self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', + '/DNDEBUG'] + self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', + '/Z7', '/D_DEBUG'] + else: + # Win64 + self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', '/GS-' , + '/DNDEBUG'] + self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GS-', + '/Z7', '/D_DEBUG'] + + self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO'] + if self.__version >= 7: + self.ldflags_shared_debug = [ + '/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG' + ] + self.ldflags_static = [ '/nologo'] + + self.initialized = True + + # -- Worker methods ------------------------------------------------ + + def object_filenames(self, + source_filenames, + strip_dir=0, + output_dir=''): + # Copied from ccompiler.py, extended to return .res as 'object'-file + # for .rc input file + if output_dir is None: output_dir = '' + obj_names = [] + for src_name in source_filenames: + (base, ext) = os.path.splitext (src_name) + base = os.path.splitdrive(base)[1] # Chop off the drive + base = base[os.path.isabs(base):] # If abs, chop off leading / + if ext not in self.src_extensions: + # Better to raise an exception instead of silently continuing + # and later complain about sources and targets having + # different lengths + raise CompileError ("Don't know how to compile %s" % src_name) + if strip_dir: + base = os.path.basename (base) + if ext in self._rc_extensions: + obj_names.append (os.path.join (output_dir, + base + self.res_extension)) + elif ext in self._mc_extensions: + obj_names.append (os.path.join (output_dir, + base + self.res_extension)) + else: + obj_names.append (os.path.join (output_dir, + base + self.obj_extension)) + return obj_names + + + def compile(self, sources, + output_dir=None, macros=None, include_dirs=None, debug=0, + extra_preargs=None, extra_postargs=None, depends=None): + + if not self.initialized: + self.initialize() + compile_info = self._setup_compile(output_dir, macros, include_dirs, + sources, depends, extra_postargs) + macros, objects, extra_postargs, pp_opts, build = compile_info + + compile_opts = extra_preargs or [] + compile_opts.append ('/c') + if debug: + compile_opts.extend(self.compile_options_debug) + else: + compile_opts.extend(self.compile_options) + + for obj in objects: + try: + src, ext = build[obj] + except KeyError: + continue + if debug: + # pass the full pathname to MSVC in debug mode, + # this allows the debugger to find the source file + # without asking the user to browse for it + src = os.path.abspath(src) + + if ext in self._c_extensions: + input_opt = "/Tc" + src + elif ext in self._cpp_extensions: + input_opt = "/Tp" + src + elif ext in self._rc_extensions: + # compile .RC to .RES file + input_opt = src + output_opt = "/fo" + obj + try: + self.spawn([self.rc] + pp_opts + + [output_opt] + [input_opt]) + except DistutilsExecError as msg: + raise CompileError(msg) + continue + elif ext in self._mc_extensions: + # Compile .MC to .RC file to .RES file. + # * '-h dir' specifies the directory for the + # generated include file + # * '-r dir' specifies the target directory of the + # generated RC file and the binary message resource + # it includes + # + # For now (since there are no options to change this), + # we use the source-directory for the include file and + # the build directory for the RC file and message + # resources. This works at least for win32all. + h_dir = os.path.dirname(src) + rc_dir = os.path.dirname(obj) + try: + # first compile .MC to .RC and .H file + self.spawn([self.mc] + + ['-h', h_dir, '-r', rc_dir] + [src]) + base, _ = os.path.splitext (os.path.basename (src)) + rc_file = os.path.join (rc_dir, base + '.rc') + # then compile .RC to .RES file + self.spawn([self.rc] + + ["/fo" + obj] + [rc_file]) + + except DistutilsExecError as msg: + raise CompileError(msg) + continue + else: + # how to handle this file? + raise CompileError("Don't know how to compile %s to %s" + % (src, obj)) + + output_opt = "/Fo" + obj + try: + self.spawn([self.cc] + compile_opts + pp_opts + + [input_opt, output_opt] + + extra_postargs) + except DistutilsExecError as msg: + raise CompileError(msg) + + return objects + + + def create_static_lib(self, + objects, + output_libname, + output_dir=None, + debug=0, + target_lang=None): + + if not self.initialized: + self.initialize() + (objects, output_dir) = self._fix_object_args(objects, output_dir) + output_filename = self.library_filename(output_libname, + output_dir=output_dir) + + if self._need_link(objects, output_filename): + lib_args = objects + ['/OUT:' + output_filename] + if debug: + pass # XXX what goes here? + try: + self.spawn([self.lib] + lib_args) + except DistutilsExecError as msg: + raise LibError(msg) + else: + log.debug("skipping %s (up-to-date)", output_filename) + + + def link(self, + target_desc, + objects, + output_filename, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug=0, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None): + + if not self.initialized: + self.initialize() + (objects, output_dir) = self._fix_object_args(objects, output_dir) + fixed_args = self._fix_lib_args(libraries, library_dirs, + runtime_library_dirs) + (libraries, library_dirs, runtime_library_dirs) = fixed_args + + if runtime_library_dirs: + self.warn ("I don't know what to do with 'runtime_library_dirs': " + + str (runtime_library_dirs)) + + lib_opts = gen_lib_options(self, + library_dirs, runtime_library_dirs, + libraries) + if output_dir is not None: + output_filename = os.path.join(output_dir, output_filename) + + if self._need_link(objects, output_filename): + if target_desc == CCompiler.EXECUTABLE: + if debug: + ldflags = self.ldflags_shared_debug[1:] + else: + ldflags = self.ldflags_shared[1:] + else: + if debug: + ldflags = self.ldflags_shared_debug + else: + ldflags = self.ldflags_shared + + export_opts = [] + for sym in (export_symbols or []): + export_opts.append("/EXPORT:" + sym) + + ld_args = (ldflags + lib_opts + export_opts + + objects + ['/OUT:' + output_filename]) + + # The MSVC linker generates .lib and .exp files, which cannot be + # suppressed by any linker switches. The .lib files may even be + # needed! Make sure they are generated in the temporary build + # directory. Since they have different names for debug and release + # builds, they can go into the same directory. + build_temp = os.path.dirname(objects[0]) + if export_symbols is not None: + (dll_name, dll_ext) = os.path.splitext( + os.path.basename(output_filename)) + implib_file = os.path.join( + build_temp, + self.library_filename(dll_name)) + ld_args.append ('/IMPLIB:' + implib_file) + + self.manifest_setup_ldargs(output_filename, build_temp, ld_args) + + if extra_preargs: + ld_args[:0] = extra_preargs + if extra_postargs: + ld_args.extend(extra_postargs) + + self.mkpath(os.path.dirname(output_filename)) + try: + self.spawn([self.linker] + ld_args) + except DistutilsExecError as msg: + raise LinkError(msg) + + # embed the manifest + # XXX - this is somewhat fragile - if mt.exe fails, distutils + # will still consider the DLL up-to-date, but it will not have a + # manifest. Maybe we should link to a temp file? OTOH, that + # implies a build environment error that shouldn't go undetected. + mfinfo = self.manifest_get_embed_info(target_desc, ld_args) + if mfinfo is not None: + mffilename, mfid = mfinfo + out_arg = '-outputresource:%s;%s' % (output_filename, mfid) + try: + self.spawn(['mt.exe', '-nologo', '-manifest', + mffilename, out_arg]) + except DistutilsExecError as msg: + raise LinkError(msg) + else: + log.debug("skipping %s (up-to-date)", output_filename) + + def manifest_setup_ldargs(self, output_filename, build_temp, ld_args): + # If we need a manifest at all, an embedded manifest is recommended. + # See MSDN article titled + # "How to: Embed a Manifest Inside a C/C++ Application" + # (currently at http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx) + # Ask the linker to generate the manifest in the temp dir, so + # we can check it, and possibly embed it, later. + temp_manifest = os.path.join( + build_temp, + os.path.basename(output_filename) + ".manifest") + ld_args.append('/MANIFESTFILE:' + temp_manifest) + + def manifest_get_embed_info(self, target_desc, ld_args): + # If a manifest should be embedded, return a tuple of + # (manifest_filename, resource_id). Returns None if no manifest + # should be embedded. See http://bugs.python.org/issue7833 for why + # we want to avoid any manifest for extension modules if we can. + for arg in ld_args: + if arg.startswith("/MANIFESTFILE:"): + temp_manifest = arg.split(":", 1)[1] + break + else: + # no /MANIFESTFILE so nothing to do. + return None + if target_desc == CCompiler.EXECUTABLE: + # by default, executables always get the manifest with the + # CRT referenced. + mfid = 1 + else: + # Extension modules try and avoid any manifest if possible. + mfid = 2 + temp_manifest = self._remove_visual_c_ref(temp_manifest) + if temp_manifest is None: + return None + return temp_manifest, mfid + + def _remove_visual_c_ref(self, manifest_file): + try: + # Remove references to the Visual C runtime, so they will + # fall through to the Visual C dependency of Python.exe. + # This way, when installed for a restricted user (e.g. + # runtimes are not in WinSxS folder, but in Python's own + # folder), the runtimes do not need to be in every folder + # with .pyd's. + # Returns either the filename of the modified manifest or + # None if no manifest should be embedded. + manifest_f = open(manifest_file) + try: + manifest_buf = manifest_f.read() + finally: + manifest_f.close() + pattern = re.compile( + r"""|)""", + re.DOTALL) + manifest_buf = re.sub(pattern, "", manifest_buf) + pattern = r"\s*" + manifest_buf = re.sub(pattern, "", manifest_buf) + # Now see if any other assemblies are referenced - if not, we + # don't want a manifest embedded. + pattern = re.compile( + r"""|)""", re.DOTALL) + if re.search(pattern, manifest_buf) is None: + return None + + manifest_f = open(manifest_file, 'w') + try: + manifest_f.write(manifest_buf) + return manifest_file + finally: + manifest_f.close() + except OSError: + pass + + # -- Miscellaneous methods ----------------------------------------- + # These are all used by the 'gen_lib_options() function, in + # ccompiler.py. + + def library_dir_option(self, dir): + return "/LIBPATH:" + dir + + def runtime_library_dir_option(self, dir): + raise DistutilsPlatformError( + "don't know how to set runtime library search path for MSVC++") + + def library_option(self, lib): + return self.library_filename(lib) + + + def find_library_file(self, dirs, lib, debug=0): + # Prefer a debugging library if found (and requested), but deal + # with it if we don't have one. + if debug: + try_names = [lib + "_d", lib] + else: + try_names = [lib] + for dir in dirs: + for name in try_names: + libfile = os.path.join(dir, self.library_filename (name)) + if os.path.exists(libfile): + return libfile + else: + # Oops, didn't find it in *any* of 'dirs' + return None + + # Helper methods for using the MSVC registry settings + + def find_exe(self, exe): + """Return path to an MSVC executable program. + + Tries to find the program in several places: first, one of the + MSVC program search paths from the registry; next, the directories + in the PATH environment variable. If any of those work, return an + absolute path that is known to exist. If none of them work, just + return the original program name, 'exe'. + """ + for p in self.__paths: + fn = os.path.join(os.path.abspath(p), exe) + if os.path.isfile(fn): + return fn + + # didn't find it; try existing path + for p in os.environ['Path'].split(';'): + fn = os.path.join(os.path.abspath(p),exe) + if os.path.isfile(fn): + return fn + + return exe diff --git a/shared/package-files/33/33d641c50fd82487bf95614bcabd0092f824232d1c875ae19d99bb24d213d8b1/headerregistry.pyi b/shared/package-files/33/33d641c50fd82487bf95614bcabd0092f824232d1c875ae19d99bb24d213d8b1/headerregistry.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4ccb4d312203eea488ae786fca81ed56c1ae7768 --- /dev/null +++ b/shared/package-files/33/33d641c50fd82487bf95614bcabd0092f824232d1c875ae19d99bb24d213d8b1/headerregistry.pyi @@ -0,0 +1,90 @@ +from datetime import datetime as _datetime +from email.errors import MessageDefect +from email.policy import Policy +from typing import Any, Dict, Mapping, Optional, Tuple, Union + +class BaseHeader(str): + @property + def name(self) -> str: ... + @property + def defects(self) -> Tuple[MessageDefect, ...]: ... + @property + def max_count(self) -> Optional[int]: ... + def __new__(cls, name: str, value: Any) -> BaseHeader: ... + def init(self, *args: Any, **kw: Any) -> None: ... + def fold(self, *, policy: Policy) -> str: ... + +class UnstructuredHeader: + @classmethod + def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + +class UniqueUnstructuredHeader(UnstructuredHeader): ... + +class DateHeader: + datetime: _datetime + @classmethod + def parse(cls, string: Union[str, _datetime], kwds: Dict[str, Any]) -> None: ... + +class UniqueDateHeader(DateHeader): ... + +class AddressHeader: + groups: Tuple[Group, ...] + addresses: Tuple[Address, ...] + @classmethod + def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + +class UniqueAddressHeader(AddressHeader): ... + +class SingleAddressHeader(AddressHeader): + @property + def address(self) -> Address: ... + +class UniqueSingleAddressHeader(SingleAddressHeader): ... + +class MIMEVersionHeader: + version: Optional[str] + major: Optional[int] + minor: Optional[int] + @classmethod + def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + +class ParameterizedMIMEHeader: + params: Mapping[str, Any] + @classmethod + def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + +class ContentTypeHeader(ParameterizedMIMEHeader): + content_type: str + maintype: str + subtype: str + +class ContentDispositionHeader(ParameterizedMIMEHeader): + content_disposition: str + +class ContentTransferEncodingHeader: + cte: str + @classmethod + def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + +class HeaderRegistry: + def __init__(self, base_class: BaseHeader = ..., default_class: BaseHeader = ..., use_default_map: bool = ...) -> None: ... + def map_to_type(self, name: str, cls: BaseHeader) -> None: ... + def __getitem__(self, name: str) -> BaseHeader: ... + def __call__(self, name: str, value: Any) -> BaseHeader: ... + +class Address: + display_name: str + username: str + domain: str + @property + def addr_spec(self) -> str: ... + def __init__( + self, display_name: str = ..., username: Optional[str] = ..., domain: Optional[str] = ..., addr_spec: Optional[str] = ... + ) -> None: ... + def __str__(self) -> str: ... + +class Group: + display_name: Optional[str] + addresses: Tuple[Address, ...] + def __init__(self, display_name: Optional[str] = ..., addresses: Optional[Tuple[Address, ...]] = ...) -> None: ... + def __str__(self) -> str: ... diff --git a/shared/package-files/33/33d79491545c4d9257a52756a935379a68f1225907ef342e08bc6114f5588e26/arrayref_tensor.h b/shared/package-files/33/33d79491545c4d9257a52756a935379a68f1225907ef342e08bc6114f5588e26/arrayref_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..a864dbf45bf4bdbaf593fd443bc18291d3273b09 --- /dev/null +++ b/shared/package-files/33/33d79491545c4d9257a52756a935379a68f1225907ef342e08bc6114f5588e26/arrayref_tensor.h @@ -0,0 +1,367 @@ +#pragma once + +#include + +#include +#include +#include + +namespace torch { +namespace aot_inductor { + +// Can't use c10::ArrayRef because it's not truly header-only and +// pulls in other c10 headers. This is (sadly) copy-pasted and +// adapted. +template +class MiniArrayRef final { + public: + using iterator = T*; + using const_iterator = const T*; + using size_type = size_t; + using value_type = T; + + using reverse_iterator = std::reverse_iterator; + + private: + /// The start of the array, in an external buffer. + T* Data; + + /// The number of elements. + size_type Length; + + public: + /// @name Constructors + /// @{ + + /// Construct an empty MiniArrayRef. + /* implicit */ constexpr MiniArrayRef() : Data(nullptr), Length(0) {} + + /// Construct an MiniArrayRef from a single element. + // TODO Make this explicit + constexpr MiniArrayRef(const T& OneElt) : Data(&OneElt), Length(1) {} + + /// Construct an MiniArrayRef from a pointer and length. + constexpr MiniArrayRef(T* data, size_t length) : Data(data), Length(length) {} + + /// Construct an MiniArrayRef from a range. + constexpr MiniArrayRef(T* begin, T* end) : Data(begin), Length(end - begin) {} + + template < + typename Container, + typename = std::enable_if_t().data())>, + T*>::value>> + /* implicit */ MiniArrayRef(Container& container) + : Data(container.data()), Length(container.size()) {} + + /// Construct an MiniArrayRef from a std::vector. + // The enable_if stuff here makes sure that this isn't used for + // std::vector, because MiniArrayRef can't work on a std::vector + // bitfield. + template + /* implicit */ MiniArrayRef(const std::vector& Vec) + : Data(Vec.data()), Length(Vec.size()) { + static_assert( + !std::is_same::value, + "MiniArrayRef cannot be constructed from a std::vector bitfield."); + } + + /// Construct an MiniArrayRef from a std::array + template + /* implicit */ constexpr MiniArrayRef(std::array& Arr) + : Data(Arr.data()), Length(N) {} + + /// Construct an MiniArrayRef from a C array. + template + /* implicit */ constexpr MiniArrayRef(T (&Arr)[N]) : Data(Arr), Length(N) {} + + /// Construct an MiniArrayRef from a std::initializer_list. + /* implicit */ constexpr MiniArrayRef(const std::initializer_list& Vec) + : Data( + std::begin(Vec) == std::end(Vec) ? static_cast(nullptr) + : std::begin(Vec)), + Length(Vec.size()) {} + + /// @} + /// @name Simple Operations + /// @{ + + constexpr iterator begin() const { + return Data; + } + constexpr iterator end() const { + return Data + Length; + } + + // These are actually the same as iterator, since MiniArrayRef only + // gives you const iterators. + constexpr const_iterator cbegin() const { + return Data; + } + constexpr const_iterator cend() const { + return Data + Length; + } + + constexpr reverse_iterator rbegin() const { + return reverse_iterator(end()); + } + constexpr reverse_iterator rend() const { + return reverse_iterator(begin()); + } + + /// empty - Check if the array is empty. + constexpr bool empty() const { + return Length == 0; + } + + constexpr T* data() const { + return Data; + } + + /// size - Get the array size. + constexpr size_t size() const { + return Length; + } + + /// equals - Check for element-wise equality. + constexpr bool equals(MiniArrayRef RHS) const { + return Length == RHS.Length && std::equal(begin(), end(), RHS.begin()); + } + + /// @} + /// @name Operator Overloads + /// @{ + constexpr const T& operator[](size_t Index) const { + return Data[Index]; + } + + /// Disallow accidental assignment from a temporary. + /// + /// The declaration here is extra complicated so that "arrayRef = {}" + /// continues to select the move assignment operator. + template + typename std::enable_if::value, MiniArrayRef>::type& + operator=(U&& Temporary) = delete; + + /// Disallow accidental assignment from a temporary. + /// + /// The declaration here is extra complicated so that "arrayRef = {}" + /// continues to select the move assignment operator. + template + typename std::enable_if::value, MiniArrayRef>::type& + operator=(std::initializer_list) = delete; +}; + +using MiniIntArrayRef = MiniArrayRef; + +inline bool is_contiguous_strides_for_shape( + int64_t ndim, + const int64_t* strides_ptr, + const int64_t* sizes_ptr) { + int64_t z = 1; + for (int64_t d = ndim - 1; d >= 0; d--) { + const auto& size_d = sizes_ptr[d]; + if (size_d != 1) { + if (strides_ptr[d] == z) { + z *= size_d; + } else { + return false; + } + } + } + return true; +} + +// Shim for AOTI generated code to pretend a raw array works like an +// AtenTensorHandle. +template +class ArrayRefTensor { + public: + ArrayRefTensor() = default; + + explicit ArrayRefTensor( + MiniArrayRef arr, + MiniArrayRef sizes, + MiniArrayRef strides, + int32_t device_type, + int32_t device_idx) + : arrayRef_(arr), + sizes_(sizes), + strides_(strides), + device_type_(device_type), + device_idx_(device_idx), + numel_(arr.size()) { + assert(sizes.size() == strides.size()); + assert(is_contiguous_strides_for_shape( + sizes.size(), strides.data(), sizes.data())); + } + + AtenTensorHandle expensiveCopyToTensor() const { + AtenTensorHandle result; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_empty_strided( + sizes_.size(), + sizes_.data(), + strides_.data(), + aoti_torch_dtype>(), + device_type_, + device_idx_, + &result)); + void* dataPtr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_data_ptr(result, &dataPtr)); + std::memcpy(dataPtr, data(), numel() * sizeof(T)); + return result; + } + + // We need to look the same as RAIIAtenTensorHandle, which returns + // an owning AtenTensorHandle from release(). So, we allocate one! + AtenTensorHandle release() { + return expensiveCopyToTensor(); + } + + // We don't need to free any memory. + void reset() {} + + auto sizes() const { + return sizes_; + } + + auto strides() const { + return strides_; + } + + auto device_type() const { + return device_type_; + } + + auto device_idx() const { + return device_idx_; + } + + T* data() const { + return arrayRef_.data(); + } + + auto numel() const { + return numel_; + } + + void set_arrayref(MiniArrayRef new_arrayref) { + arrayRef_ = new_arrayref; + } + + private: + MiniArrayRef arrayRef_; + // We expect generated code to have statically available sizes & + // strides for us. + MiniArrayRef sizes_; + MiniArrayRef strides_; + int32_t device_type_ = 0; + int32_t device_idx_ = 0; + int32_t numel_ = 0; +}; + +inline AtenTensorHandle reinterpret_tensor_wrapper( + AtenTensorHandle self, + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + int64_t storage_offset) { + AtenTensorHandle result; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch__reinterpret_tensor( + self, ndim, sizes_ptr, strides_ptr, storage_offset, &result)); + return result; +} + +template +inline ArrayRefTensor reinterpret_tensor_wrapper( + const ArrayRefTensor& self, + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + int64_t storage_offset) { + // REVIEW: we should add a way to build the DSO in debug mode during + // tests so we can have checks like this! + assert(is_contiguous_strides_for_shape(ndim, strides_ptr, sizes_ptr)); + return ArrayRefTensor( + MiniArrayRef( + self.data() + storage_offset, self.numel() - storage_offset), + MiniArrayRef(sizes_ptr, ndim), + MiniArrayRef(strides_ptr, ndim), + self.device_type(), + self.device_idx()); +} + +inline void* get_data_ptr_wrapper(AtenTensorHandle tensor) { + void* result; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_data_ptr(tensor, &result)); + return result; +} + +template +inline T* get_data_ptr_wrapper(ArrayRefTensor& tensor) { + return tensor.data(); +} + +template +inline T* get_data_ptr_wrapper(const MiniArrayRef& arr) { + return arr.data(); +} + +inline AtenTensorHandle unwrap_raii_handle_if_needed( + const RAIIAtenTensorHandle& handle) { + return handle.get(); +} + +template +inline const ArrayRefTensor& unwrap_raii_handle_if_needed( + const ArrayRefTensor& tensor) { + return tensor; +} + +template +inline ArrayRefTensor& unwrap_raii_handle_if_needed( + ArrayRefTensor& tensor) { + return tensor; +} + +inline RAIIAtenTensorHandle wrap_with_raii_handle_if_needed( + AtenTensorHandle handle) { + return RAIIAtenTensorHandle(handle); +} + +template +inline const ArrayRefTensor& wrap_with_raii_handle_if_needed( + const ArrayRefTensor& tensor) { + return tensor; +} + +template +inline ArrayRefTensor& wrap_with_raii_handle_if_needed( + ArrayRefTensor& tensor) { + return tensor; +} + +template +inline RAIIAtenTensorHandle expensive_copy_to_tensor_if_needed( + const ArrayRefTensor& tensor) { + return tensor.expensiveCopyToTensor(); +} + +inline AtenTensorHandle expensive_copy_to_tensor_if_needed( + AtenTensorHandle handle) { + return handle; +} + +template +const T& convert_arrayref_tensor_to_tensor(const T& t) { + return t; +} + +template +RAIIAtenTensorHandle convert_arrayref_tensor_to_tensor( + const ArrayRefTensor& art) { + return art.expensiveCopyToTensor(); +} + +} // namespace aot_inductor +} // namespace torch diff --git a/shared/package-files/33/33d99f8f9a6825ef997b06f2dd2095162ba877a48ea4b3b86fc462fc0f8ca7c1/_flash_attention_backward_cuda_dispatch.h b/shared/package-files/33/33d99f8f9a6825ef997b06f2dd2095162ba877a48ea4b3b86fc462fc0f8ca7c1/_flash_attention_backward_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..d30703ae48b2ca53de43771d3183d6bf922eda16 --- /dev/null +++ b/shared/package-files/33/33d99f8f9a6825ef997b06f2dd2095162ba877a48ea4b3b86fc462fc0f8ca7c1/_flash_attention_backward_cuda_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::tuple _flash_attention_backward(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, bool is_causal, const at::Tensor & philox_seed, const at::Tensor & philox_offset, c10::optional scale=c10::nullopt); +TORCH_API ::std::tuple _flash_attention_backward_symint(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, c10::SymInt max_q, c10::SymInt max_k, double dropout_p, bool is_causal, const at::Tensor & philox_seed, const at::Tensor & philox_offset, c10::optional scale=c10::nullopt); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/33/33dbcdd5a21e13c8205ac956dadf982eba311dd56cd3e02987afecaf0011d995/expand_ops.h b/shared/package-files/33/33dbcdd5a21e13c8205ac956dadf982eba311dd56cd3e02987afecaf0011d995/expand_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..4a0b82a7fa315eb6e8bba6fea18731d1c7bc590b --- /dev/null +++ b/shared/package-files/33/33dbcdd5a21e13c8205ac956dadf982eba311dd56cd3e02987afecaf0011d995/expand_ops.h @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API expand { + using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::expand") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "expand(Tensor(a) self, SymInt[] size, *, bool implicit=False) -> Tensor(a)") + static at::Tensor call(const at::Tensor & self, c10::SymIntArrayRef size, bool implicit); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef size, bool implicit); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/33/33e131a273dcc7a5bef33fd32d368fd7a0c9b5e95255e40764a3b569639b4ae0/test_core_functionalities.py b/shared/package-files/33/33e131a273dcc7a5bef33fd32d368fd7a0c9b5e95255e40764a3b569639b4ae0/test_core_functionalities.py new file mode 100644 index 0000000000000000000000000000000000000000..8dc80c5cc0e0eadbe792e114d48593d95df17907 --- /dev/null +++ b/shared/package-files/33/33e131a273dcc7a5bef33fd32d368fd7a0c9b5e95255e40764a3b569639b4ae0/test_core_functionalities.py @@ -0,0 +1,106 @@ +import numpy as np +import pytest + +from pandas import DataFrame +import pandas._testing as tm +from pandas.tests.copy_view.util import get_array + + +def test_assigning_to_same_variable_removes_references(using_copy_on_write): + df = DataFrame({"a": [1, 2, 3]}) + df = df.reset_index() + if using_copy_on_write: + assert df._mgr._has_no_reference(1) + arr = get_array(df, "a") + df.iloc[0, 1] = 100 # Write into a + + assert np.shares_memory(arr, get_array(df, "a")) + + +def test_setitem_dont_track_unnecessary_references(using_copy_on_write): + df = DataFrame({"a": [1, 2, 3], "b": 1, "c": 1}) + + df["b"] = 100 + arr = get_array(df, "a") + # We split the block in setitem, if we are not careful the new blocks will + # reference each other triggering a copy + df.iloc[0, 0] = 100 + assert np.shares_memory(arr, get_array(df, "a")) + + +def test_setitem_with_view_copies(using_copy_on_write, warn_copy_on_write): + df = DataFrame({"a": [1, 2, 3], "b": 1, "c": 1}) + view = df[:] + expected = df.copy() + + df["b"] = 100 + arr = get_array(df, "a") + with tm.assert_cow_warning(warn_copy_on_write): + df.iloc[0, 0] = 100 # Check that we correctly track reference + if using_copy_on_write: + assert not np.shares_memory(arr, get_array(df, "a")) + tm.assert_frame_equal(view, expected) + + +def test_setitem_with_view_invalidated_does_not_copy( + using_copy_on_write, warn_copy_on_write, request +): + df = DataFrame({"a": [1, 2, 3], "b": 1, "c": 1}) + view = df[:] + + df["b"] = 100 + arr = get_array(df, "a") + view = None # noqa: F841 + # TODO(CoW-warn) false positive? -> block gets split because of `df["b"] = 100` + # which introduces additional refs, even when those of `view` go out of scopes + with tm.assert_cow_warning(warn_copy_on_write): + df.iloc[0, 0] = 100 + if using_copy_on_write: + # Setitem split the block. Since the old block shared data with view + # all the new blocks are referencing view and each other. When view + # goes out of scope, they don't share data with any other block, + # so we should not trigger a copy + mark = pytest.mark.xfail( + reason="blk.delete does not track references correctly" + ) + request.applymarker(mark) + assert np.shares_memory(arr, get_array(df, "a")) + + +def test_out_of_scope(using_copy_on_write): + def func(): + df = DataFrame({"a": [1, 2], "b": 1.5, "c": 1}) + # create some subset + result = df[["a", "b"]] + return result + + result = func() + if using_copy_on_write: + assert not result._mgr.blocks[0].refs.has_reference() + assert not result._mgr.blocks[1].refs.has_reference() + + +def test_delete(using_copy_on_write): + df = DataFrame( + np.random.default_rng(2).standard_normal((4, 3)), columns=["a", "b", "c"] + ) + del df["b"] + if using_copy_on_write: + assert not df._mgr.blocks[0].refs.has_reference() + assert not df._mgr.blocks[1].refs.has_reference() + + df = df[["a"]] + if using_copy_on_write: + assert not df._mgr.blocks[0].refs.has_reference() + + +def test_delete_reference(using_copy_on_write): + df = DataFrame( + np.random.default_rng(2).standard_normal((4, 3)), columns=["a", "b", "c"] + ) + x = df[:] + del df["b"] + if using_copy_on_write: + assert df._mgr.blocks[0].refs.has_reference() + assert df._mgr.blocks[1].refs.has_reference() + assert x._mgr.blocks[0].refs.has_reference() diff --git a/shared/package-files/33/33e2b5f49cd41015e17907674bd9b5c45b0c5d5e0f668974816dca056eee0442/test_async_helpers.py b/shared/package-files/33/33e2b5f49cd41015e17907674bd9b5c45b0c5d5e0f668974816dca056eee0442/test_async_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..48e31231906f286a2a8b49c0db26863e1c8912d3 --- /dev/null +++ b/shared/package-files/33/33e2b5f49cd41015e17907674bd9b5c45b0c5d5e0f668974816dca056eee0442/test_async_helpers.py @@ -0,0 +1,325 @@ +""" +Test for async helpers. + +Should only trigger on python 3.5+ or will have syntax errors. +""" +from itertools import chain, repeat +from textwrap import dedent, indent +from typing import TYPE_CHECKING +from unittest import TestCase + +import pytest + +from IPython.core.async_helpers import _should_be_async +from IPython.testing.decorators import skip_without + +if TYPE_CHECKING: + from IPython import get_ipython + + ip = get_ipython() + + +def iprc(x): + return ip.run_cell(dedent(x)).raise_error() + + +def iprc_nr(x): + return ip.run_cell(dedent(x)) + + +class AsyncTest(TestCase): + def test_should_be_async(self): + self.assertFalse(_should_be_async("False")) + self.assertTrue(_should_be_async("await bar()")) + self.assertTrue(_should_be_async("x = await bar()")) + self.assertFalse( + _should_be_async( + dedent( + """ + async def awaitable(): + pass + """ + ) + ) + ) + + def _get_top_level_cases(self): + # These are test cases that should be valid in a function + # but invalid outside of a function. + test_cases = [] + test_cases.append(('basic', "{val}")) + + # Note, in all conditional cases, I use True instead of + # False so that the peephole optimizer won't optimize away + # the return, so CPython will see this as a syntax error: + # + # while True: + # break + # return + # + # But not this: + # + # while False: + # return + # + # See https://bugs.python.org/issue1875 + + test_cases.append(('if', dedent(""" + if True: + {val} + """))) + + test_cases.append(('while', dedent(""" + while True: + {val} + break + """))) + + test_cases.append(('try', dedent(""" + try: + {val} + except: + pass + """))) + + test_cases.append(('except', dedent(""" + try: + pass + except: + {val} + """))) + + test_cases.append(('finally', dedent(""" + try: + pass + except: + pass + finally: + {val} + """))) + + test_cases.append(('for', dedent(""" + for _ in range(4): + {val} + """))) + + + test_cases.append(('nested', dedent(""" + if True: + while True: + {val} + break + """))) + + test_cases.append(('deep-nested', dedent(""" + if True: + while True: + break + for x in range(3): + if True: + while True: + for x in range(3): + {val} + """))) + + return test_cases + + def _get_ry_syntax_errors(self): + # This is a mix of tests that should be a syntax error if + # return or yield whether or not they are in a function + + test_cases = [] + + test_cases.append(('class', dedent(""" + class V: + {val} + """))) + + test_cases.append(('nested-class', dedent(""" + class V: + class C: + {val} + """))) + + return test_cases + + + def test_top_level_return_error(self): + tl_err_test_cases = self._get_top_level_cases() + tl_err_test_cases.extend(self._get_ry_syntax_errors()) + + vals = ('return', 'yield', 'yield from (_ for _ in range(3))', + dedent(''' + def f(): + pass + return + '''), + ) + + for test_name, test_case in tl_err_test_cases: + # This example should work if 'pass' is used as the value + with self.subTest((test_name, 'pass')): + iprc(test_case.format(val='pass')) + + # It should fail with all the values + for val in vals: + with self.subTest((test_name, val)): + msg = "Syntax error not raised for %s, %s" % (test_name, val) + with self.assertRaises(SyntaxError, msg=msg): + iprc(test_case.format(val=val)) + + def test_in_func_no_error(self): + # Test that the implementation of top-level return/yield + # detection isn't *too* aggressive, and works inside a function + func_contexts = [] + + func_contexts.append(('func', False, dedent(""" + def f():"""))) + + func_contexts.append(('method', False, dedent(""" + class MyClass: + def __init__(self): + """))) + + func_contexts.append(('async-func', True, dedent(""" + async def f():"""))) + + func_contexts.append(('async-method', True, dedent(""" + class MyClass: + async def f(self):"""))) + + func_contexts.append(('closure', False, dedent(""" + def f(): + def g(): + """))) + + def nest_case(context, case): + # Detect indentation + lines = context.strip().splitlines() + prefix_len = 0 + for c in lines[-1]: + if c != ' ': + break + prefix_len += 1 + + indented_case = indent(case, ' ' * (prefix_len + 4)) + return context + '\n' + indented_case + + # Gather and run the tests + + # yield is allowed in async functions, starting in Python 3.6, + # and yield from is not allowed in any version + vals = ('return', 'yield', 'yield from (_ for _ in range(3))') + + success_tests = zip(self._get_top_level_cases(), repeat(False)) + failure_tests = zip(self._get_ry_syntax_errors(), repeat(True)) + + tests = chain(success_tests, failure_tests) + + for context_name, async_func, context in func_contexts: + for (test_name, test_case), should_fail in tests: + nested_case = nest_case(context, test_case) + + for val in vals: + test_id = (context_name, test_name, val) + cell = nested_case.format(val=val) + + with self.subTest(test_id): + if should_fail: + msg = ("SyntaxError not raised for %s" % + str(test_id)) + with self.assertRaises(SyntaxError, msg=msg): + iprc(cell) + + print(cell) + else: + iprc(cell) + + def test_nonlocal(self): + # fails if outer scope is not a function scope or if var not defined + with self.assertRaises(SyntaxError): + iprc("nonlocal x") + iprc(""" + x = 1 + def f(): + nonlocal x + x = 10000 + yield x + """) + iprc(""" + def f(): + def g(): + nonlocal x + x = 10000 + yield x + """) + + # works if outer scope is a function scope and var exists + iprc(""" + def f(): + x = 20 + def g(): + nonlocal x + x = 10000 + yield x + """) + + + def test_execute(self): + iprc(""" + import asyncio + await asyncio.sleep(0.001) + """ + ) + + def test_autoawait(self): + iprc("%autoawait False") + iprc("%autoawait True") + iprc(""" + from asyncio import sleep + await sleep(0.1) + """ + ) + + def test_memory_error(self): + """ + The pgen parser in 3.8 or before use to raise MemoryError on too many + nested parens anymore""" + + iprc("(" * 200 + ")" * 200) + + @pytest.mark.xfail(reason="fail on curio 1.6 and before on Python 3.12") + @pytest.mark.skip( + reason="skip_without(curio) fails on 3.12 for now even with other skip so must uncond skip" + ) + # @skip_without("curio") + def test_autoawait_curio(self): + iprc("%autoawait curio") + + @skip_without('trio') + def test_autoawait_trio(self): + iprc("%autoawait trio") + + @skip_without('trio') + def test_autoawait_trio_wrong_sleep(self): + iprc("%autoawait trio") + res = iprc_nr(""" + import asyncio + await asyncio.sleep(0) + """) + with self.assertRaises(TypeError): + res.raise_error() + + @skip_without('trio') + def test_autoawait_asyncio_wrong_sleep(self): + iprc("%autoawait asyncio") + res = iprc_nr(""" + import trio + await trio.sleep(0) + """) + with self.assertRaises(RuntimeError): + res.raise_error() + + + def tearDown(self): + ip.loop_runner = "asyncio" diff --git a/shared/package-files/33/33e2facd36b62b0a347b1dc3c6c2e830541e06291b2140121a2864cb91050749/metrics.py b/shared/package-files/33/33e2facd36b62b0a347b1dc3c6c2e830541e06291b2140121a2864cb91050749/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..c9a2fcca5f2fb9bbb2118b5b833be61670ee6d3d --- /dev/null +++ b/shared/package-files/33/33e2facd36b62b0a347b1dc3c6c2e830541e06291b2140121a2864cb91050749/metrics.py @@ -0,0 +1,419 @@ +from __future__ import annotations + +import csv +import inspect +import os +import re +from dataclasses import dataclass +from functools import lru_cache + +from typing import Dict, List, Set, Tuple, TYPE_CHECKING, Union + +from torch._inductor import config +from torch._inductor.utils import get_benchmark_name + +# Prevent circular import +if TYPE_CHECKING: + from torch._inductor.scheduler import ( + BaseSchedulerNode, + ExternKernelSchedulerNode, + NopKernelSchedulerNode, + SchedulerNode, + ) + +# counter for tracking how many kernels have been generated +generated_kernel_count = 0 +generated_cpp_vec_kernel_count = 0 +num_bytes_accessed = 0 +nodes_num_elem: List[ + Tuple[ + Union[NopKernelSchedulerNode, SchedulerNode, ExternKernelSchedulerNode], + int, + ] +] = [] +node_runtimes: List[Tuple[BaseSchedulerNode, float]] = [] + +# counters for tracking fusions +ir_nodes_pre_fusion = 0 + +# counters for tracking to_dtype inserted +cpp_to_dtype_count = 0 + +# counters for tracking cpp_wrapper disabled +disable_cpp_wrapper = 0 + + +# reset all counters +def reset(): + global generated_kernel_count + global generated_cpp_vec_kernel_count + global num_bytes_accessed, nodes_num_elem + global ir_nodes_pre_fusion + global cpp_to_dtype_count + global disable_cpp_wrapper + + generated_kernel_count = 0 + generated_cpp_vec_kernel_count = 0 + num_bytes_accessed = 0 + nodes_num_elem.clear() + node_runtimes.clear() + ir_nodes_pre_fusion = 0 + cpp_to_dtype_count = 0 + disable_cpp_wrapper = 0 + + +@dataclass +class CachedMetricsDeltas: + """ + The subset of metrics we want update across cache hits, e.g., the + FxGraphCache. + """ + + generated_kernel_count: int + generated_cpp_vec_kernel_count: int + ir_nodes_pre_fusion: int + cpp_to_dtype_count: int + + +class CachedMetricsHelper: + """ + A helper class to help calculate and apply counter deltas for those + metrics we want to save with cache entries (e.g., FxGraphCache) and + apply on a cache hit. + """ + + def __init__(self): + global generated_kernel_count + global generated_cpp_vec_kernel_count + global ir_nodes_pre_fusion + global cpp_to_dtype_count + + self.generated_kernel_count = generated_kernel_count + self.generated_cpp_vec_kernel_count = generated_cpp_vec_kernel_count + self.ir_nodes_pre_fusion = ir_nodes_pre_fusion + self.cpp_to_dtype_count = cpp_to_dtype_count + + def get_deltas(self) -> CachedMetricsDeltas: + global generated_kernel_count + global generated_cpp_vec_kernel_count + global ir_nodes_pre_fusion + global cpp_to_dtype_count + + return CachedMetricsDeltas( + generated_kernel_count - self.generated_kernel_count, + generated_cpp_vec_kernel_count - self.generated_cpp_vec_kernel_count, + ir_nodes_pre_fusion - self.ir_nodes_pre_fusion, + cpp_to_dtype_count - self.cpp_to_dtype_count, + ) + + @staticmethod + def apply_deltas(delta: CachedMetricsDeltas): + global generated_kernel_count + global generated_cpp_vec_kernel_count + global ir_nodes_pre_fusion + global cpp_to_dtype_count + + generated_kernel_count += delta.generated_kernel_count + generated_cpp_vec_kernel_count += delta.generated_cpp_vec_kernel_count + ir_nodes_pre_fusion += delta.ir_nodes_pre_fusion + cpp_to_dtype_count += delta.cpp_to_dtype_count + + +REGISTERED_METRIC_TABLES: Dict[str, MetricTable] = {} + + +@dataclass +class MetricTable: + table_name: str + column_names: List[str] + + num_rows_added: int = 0 + + def add_row(self, row_fn): + if self.table_name not in enabled_metric_tables(): + return + + row_dict = row_fn() + assert len(self.column_names) == len( + row_dict + ), f"{len(self.column_names)} v.s. {len(row_dict)}" + assert set(self.column_names) == set( + row_dict.keys() + ), f"{set(self.column_names)} v.s. {set(row_dict.keys())}" + + row = [ + get_benchmark_name(), + ] + row += [row_dict[column_name] for column_name in self.column_names] + self._write_row(row) + + def output_filename(self): + return f"metric_table_{self.table_name}.csv" + + def write_header(self): + filename = self.output_filename() + with open(filename, "w") as fd: + writer = csv.writer(fd, lineterminator="\n") + writer.writerow(["model_name"] + self.column_names) + + def _write_row(self, row): + filename = self.output_filename() + if self.num_rows_added == 0 and not os.path.exists(filename): + self.write_header() + + self.num_rows_added += 1 + + for idx, orig_val in enumerate(row): + if isinstance(orig_val, float): + new_val = f"{orig_val:.6f}" + elif orig_val is None: + new_val = "" + else: + new_val = orig_val + row[idx] = new_val + + with open(filename, "a") as fd: + writer = csv.writer(fd, lineterminator="\n") + writer.writerow(row) + + @staticmethod + def register_table(name, column_names): + table = MetricTable(name, column_names) + REGISTERED_METRIC_TABLES[name] = table + + +MetricTable.register_table( + "slow_fusion", + [ + "kernel1_path", + "kernel1_latency", + "kernel2_path", + "kernel2_latency", + "fused_kernel_path", + "fused_kernel_latency", + "slow_down_ratio", + ], +) + +# track the fusion statistics for each graph +MetricTable.register_table( + "graph_stats", + [ + "graph_id", + "num_nodes_before_fusion", + "num_nodes_after_fusion", + ], +) + +# track the perf difference between persistent reduction and non-persistent +# reductions +MetricTable.register_table( + "persistent_red_perf", + [ + "kernel1_name", + "kernel2_name", + "kernel1_latency", + "kernel2_latency", + "size_hints", + "reduction_hint", + "speedup", + ], +) + +# Log metadata for pointwise/reduction kernels. E.g., model name, kernel path, numel, rnumel, reduction hint +MetricTable.register_table( + "kernel_metadata", + [ + "kernel_name", + "kernel_path", + "kernel_category", # pointwise/reduction/foreach etc. + "size_hints", + "reduction_hint", + "line_of_code", + "num_load", + "num_store", + "num_for_loop", + "num_atomic_add", + "num_args", + # xyz numel can be different to size_hints since size_hints are rounded + # up to the nearest power of 2. + # Inductor kernel will burn in the xyz numel in kernel code for static + # shape kernels. + # Logging them will be helpful to find unaligned shape for reduction + "xnumel", + "ynumel", + "rnumel", + "kernel_args_num_gb", + ], +) + + +def _parse_kernel_fn_code(kernel_module_code): + """ + The kernel_module_code is the python module that contains kernel function code. + kernel function is the proper triton kernel function annotated with + @triton.jit + """ + from .codecache import PyCodeCache + from .wrapper_benchmark import get_triton_kernel + + mod = PyCodeCache.load(kernel_module_code) + kernel = get_triton_kernel(mod) + # kernel is a CachingAutotune; kernel.fn is the JITFunction; + # kernel.fn.fn is the function being decorate by triton.jit + return inspect.getsource(kernel.fn.fn) + + +def _parse_kernel_line_of_code(proper_kernel_fn_code): + """ + Return the line of code for the kernel excluding the decorators. + """ + return len(proper_kernel_fn_code.splitlines()) + + +def _parse_size_hints(kernel_module_code, kernel_category): + if kernel_category == "foreach": + # foreach kernel does not have size_hints + return None + m = re.search(r"size_hints=(\[[0-9, ]*\]),", kernel_module_code) + assert m, "size_hints missing!" + return m.group(1) + + +def _parse_reduction_hint(kernel_category, kernel_module_code): + if kernel_category not in ("reduction", "persistent_reduction"): + return None + m = re.search(r"reduction_hint=ReductionHint\.(\w*),", kernel_module_code) + assert m, "reduction_hint not found in kernel source code!" + return m.group(1) + + +def _count_pattern(proper_kernel_fn_code, pattern): + return proper_kernel_fn_code.count(pattern) + + +def _count_args(proper_kernel_fn_code): + def_line = proper_kernel_fn_code.splitlines()[0] + assert def_line.startswith("def ") + start_idx = def_line.index("(") + end_idx = def_line.index("):") + decl_csv = def_line[start_idx + 1 : end_idx] + comps = decl_csv.split(",") + return len(comps) + + +def _parse_proper_kernel_fn_code(kernel_fn_code): + """ + Skip decorators. + """ + start_pos = kernel_fn_code.index("def ") + return kernel_fn_code[start_pos:] + + +def _parse_numel(proper_kernel_fn_code, numel_arg_name): + m = re.search(f"{numel_arg_name} = ([\\d]+)", proper_kernel_fn_code) + if m: + return int(m.group(1)) + else: + return None + + +def _parse_kernel_args_num_gb(kernel_fn_code, kernel_category): + """ + inductor meta looks like: + inductor_meta={... 'mutated_arg_names': [], 'no_x_dim': False, 'kernel_num_gb': 2.0}, + """ + m = re.search(r".kernel_num_gb.:\s*([0-9.]+)", kernel_fn_code) + if m: + return float(m.group(1)) + else: + """ + There are a few cases that kernel_num_gdb field can be missing: + 1. the field will be missing if config.benchmark_kernel and + config.profile_bandwidth are false + 2. even if config.benchmark_kernel or config.profile_bandwidth is true. + foreach kernel does not have kernel_num_gb field in the metadata + """ + return None + + +def log_kernel_metadata(kernel_name, kernel_path, kernel_module_code): + """ + An utility to log kernel metadata. We may parse metadata from kernel source code here. + + It's fine to parse the generated kernel code here since the logging is + disabled by default. It would hurt compilation time. + """ + from .wrapper_benchmark import get_kernel_category_by_source_code + + kernel_category = get_kernel_category_by_source_code(kernel_module_code) + reduction_hint = _parse_reduction_hint(kernel_category, kernel_module_code) + size_hints = _parse_size_hints(kernel_module_code, kernel_category) + kernel_fn_code = _parse_kernel_fn_code(kernel_module_code) + + proper_kernel_fn_code = _parse_proper_kernel_fn_code(kernel_fn_code) + + # the line of code excluding the decortors + kernel_line_of_code = _parse_kernel_line_of_code(proper_kernel_fn_code) + + get_metric_table("kernel_metadata").add_row( + lambda: { + "kernel_name": kernel_name, + "kernel_path": kernel_path, + "kernel_category": kernel_category, + "size_hints": size_hints, + "reduction_hint": reduction_hint, + "line_of_code": kernel_line_of_code, + "num_load": _count_pattern(proper_kernel_fn_code, "tl.load"), + "num_store": _count_pattern(proper_kernel_fn_code, "tl.store"), + "num_for_loop": _count_pattern(proper_kernel_fn_code, "for "), + "num_atomic_add": _count_pattern(proper_kernel_fn_code, "tl.atomic_add"), + "num_args": _count_args(proper_kernel_fn_code), + "xnumel": _parse_numel(proper_kernel_fn_code, "xnumel"), + "ynumel": _parse_numel(proper_kernel_fn_code, "ynumel"), + "rnumel": _parse_numel(proper_kernel_fn_code, "rnumel"), + "kernel_args_num_gb": _parse_kernel_args_num_gb( + kernel_fn_code, kernel_category + ), + } + ) + + +def purge_old_log_files(): + """ + Purge the old log file at the beginning when the benchmark script runs. + Should do it in the parent process rather than the child processes running + each individual model. + """ + for name, table in REGISTERED_METRIC_TABLES.items(): + if name in enabled_metric_tables(): + filename = table.output_filename() + if os.path.exists(filename): + os.unlink(filename) + + table.write_header() + + +@lru_cache +def enabled_metric_tables() -> Set[str]: + config_str = config.enabled_metric_tables + + enabled = set() + for name in config_str.split(","): + name = name.strip() + if not name: + continue + assert ( + name in REGISTERED_METRIC_TABLES + ), f"Metric table name {name} is not registered" + enabled.add(name) + return enabled + + +def is_metric_table_enabled(name): + return name in enabled_metric_tables() + + +def get_metric_table(name): + assert name in REGISTERED_METRIC_TABLES, f"Metric table {name} is not defined" + return REGISTERED_METRIC_TABLES[name] diff --git a/shared/package-files/33/33e412b364b1445858c0654c257152d8a4d68205322882cb4b7b3fb02dbfa49e/clamp_cpu_dispatch.h b/shared/package-files/33/33e412b364b1445858c0654c257152d8a4d68205322882cb4b7b3fb02dbfa49e/clamp_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..86e69da0fe82f3e354c34d186d04b41ca64fd350 --- /dev/null +++ b/shared/package-files/33/33e412b364b1445858c0654c257152d8a4d68205322882cb4b7b3fb02dbfa49e/clamp_cpu_dispatch.h @@ -0,0 +1,30 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor clamp(const at::Tensor & self, const c10::optional & min, const c10::optional & max=c10::nullopt); +TORCH_API at::Tensor & clamp_out(at::Tensor & out, const at::Tensor & self, const c10::optional & min, const c10::optional & max=c10::nullopt); +TORCH_API at::Tensor & clamp_outf(const at::Tensor & self, const c10::optional & min, const c10::optional & max, at::Tensor & out); +TORCH_API at::Tensor & clamp_(at::Tensor & self, const c10::optional & min, const c10::optional & max=c10::nullopt); +TORCH_API at::Tensor clamp(const at::Tensor & self, const c10::optional & min={}, const c10::optional & max={}); +TORCH_API at::Tensor & clamp_out(at::Tensor & out, const at::Tensor & self, const c10::optional & min={}, const c10::optional & max={}); +TORCH_API at::Tensor & clamp_outf(const at::Tensor & self, const c10::optional & min, const c10::optional & max, at::Tensor & out); +TORCH_API at::Tensor & clamp_(at::Tensor & self, const c10::optional & min={}, const c10::optional & max={}); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/33/33e64cb7e0d1520c9979dfc8d608a4c446d260424bc22ee6c298ddfbf885282f/traversal.py b/shared/package-files/33/33e64cb7e0d1520c9979dfc8d608a4c446d260424bc22ee6c298ddfbf885282f/traversal.py new file mode 100644 index 0000000000000000000000000000000000000000..0615c221a5386514eeec83278d6f5857acc1e1b8 --- /dev/null +++ b/shared/package-files/33/33e64cb7e0d1520c9979dfc8d608a4c446d260424bc22ee6c298ddfbf885282f/traversal.py @@ -0,0 +1,306 @@ +from .basic import Basic +from .sorting import ordered +from .sympify import sympify +from sympy.utilities.iterables import iterable + + + +def iterargs(expr): + """Yield the args of a Basic object in a breadth-first traversal. + Depth-traversal stops if `arg.args` is either empty or is not + an iterable. + + Examples + ======== + + >>> from sympy import Integral, Function + >>> from sympy.abc import x + >>> f = Function('f') + >>> from sympy.core.traversal import iterargs + >>> list(iterargs(Integral(f(x), (f(x), 1)))) + [Integral(f(x), (f(x), 1)), f(x), (f(x), 1), x, f(x), 1, x] + + See Also + ======== + iterfreeargs, preorder_traversal + """ + args = [expr] + for i in args: + yield i + try: + args.extend(i.args) + except TypeError: + pass # for cases like f being an arg + + +def iterfreeargs(expr, _first=True): + """Yield the args of a Basic object in a breadth-first traversal. + Depth-traversal stops if `arg.args` is either empty or is not + an iterable. The bound objects of an expression will be returned + as canonical variables. + + Examples + ======== + + >>> from sympy import Integral, Function + >>> from sympy.abc import x + >>> f = Function('f') + >>> from sympy.core.traversal import iterfreeargs + >>> list(iterfreeargs(Integral(f(x), (f(x), 1)))) + [Integral(f(x), (f(x), 1)), 1] + + See Also + ======== + iterargs, preorder_traversal + """ + args = [expr] + for i in args: + yield i + if _first and hasattr(i, 'bound_symbols'): + void = i.canonical_variables.values() + for i in iterfreeargs(i.as_dummy(), _first=False): + if not i.has(*void): + yield i + try: + args.extend(i.args) + except TypeError: + pass # for cases like f being an arg + + +class preorder_traversal: + """ + Do a pre-order traversal of a tree. + + This iterator recursively yields nodes that it has visited in a pre-order + fashion. That is, it yields the current node then descends through the + tree breadth-first to yield all of a node's children's pre-order + traversal. + + + For an expression, the order of the traversal depends on the order of + .args, which in many cases can be arbitrary. + + Parameters + ========== + node : SymPy expression + The expression to traverse. + keys : (default None) sort key(s) + The key(s) used to sort args of Basic objects. When None, args of Basic + objects are processed in arbitrary order. If key is defined, it will + be passed along to ordered() as the only key(s) to use to sort the + arguments; if ``key`` is simply True then the default keys of ordered + will be used. + + Yields + ====== + subtree : SymPy expression + All of the subtrees in the tree. + + Examples + ======== + + >>> from sympy import preorder_traversal, symbols + >>> x, y, z = symbols('x y z') + + The nodes are returned in the order that they are encountered unless key + is given; simply passing key=True will guarantee that the traversal is + unique. + + >>> list(preorder_traversal((x + y)*z, keys=None)) # doctest: +SKIP + [z*(x + y), z, x + y, y, x] + >>> list(preorder_traversal((x + y)*z, keys=True)) + [z*(x + y), z, x + y, x, y] + + """ + def __init__(self, node, keys=None): + self._skip_flag = False + self._pt = self._preorder_traversal(node, keys) + + def _preorder_traversal(self, node, keys): + yield node + if self._skip_flag: + self._skip_flag = False + return + if isinstance(node, Basic): + if not keys and hasattr(node, '_argset'): + # LatticeOp keeps args as a set. We should use this if we + # don't care about the order, to prevent unnecessary sorting. + args = node._argset + else: + args = node.args + if keys: + if keys != True: + args = ordered(args, keys, default=False) + else: + args = ordered(args) + for arg in args: + yield from self._preorder_traversal(arg, keys) + elif iterable(node): + for item in node: + yield from self._preorder_traversal(item, keys) + + def skip(self): + """ + Skip yielding current node's (last yielded node's) subtrees. + + Examples + ======== + + >>> from sympy import preorder_traversal, symbols + >>> x, y, z = symbols('x y z') + >>> pt = preorder_traversal((x + y*z)*z) + >>> for i in pt: + ... print(i) + ... if i == x + y*z: + ... pt.skip() + z*(x + y*z) + z + x + y*z + """ + self._skip_flag = True + + def __next__(self): + return next(self._pt) + + def __iter__(self): + return self + + +def use(expr, func, level=0, args=(), kwargs={}): + """ + Use ``func`` to transform ``expr`` at the given level. + + Examples + ======== + + >>> from sympy import use, expand + >>> from sympy.abc import x, y + + >>> f = (x + y)**2*x + 1 + + >>> use(f, expand, level=2) + x*(x**2 + 2*x*y + y**2) + 1 + >>> expand(f) + x**3 + 2*x**2*y + x*y**2 + 1 + + """ + def _use(expr, level): + if not level: + return func(expr, *args, **kwargs) + else: + if expr.is_Atom: + return expr + else: + level -= 1 + _args = [_use(arg, level) for arg in expr.args] + return expr.__class__(*_args) + + return _use(sympify(expr), level) + + +def walk(e, *target): + """Iterate through the args that are the given types (target) and + return a list of the args that were traversed; arguments + that are not of the specified types are not traversed. + + Examples + ======== + + >>> from sympy.core.traversal import walk + >>> from sympy import Min, Max + >>> from sympy.abc import x, y, z + >>> list(walk(Min(x, Max(y, Min(1, z))), Min)) + [Min(x, Max(y, Min(1, z)))] + >>> list(walk(Min(x, Max(y, Min(1, z))), Min, Max)) + [Min(x, Max(y, Min(1, z))), Max(y, Min(1, z)), Min(1, z)] + + See Also + ======== + + bottom_up + """ + if isinstance(e, target): + yield e + for i in e.args: + yield from walk(i, *target) + + +def bottom_up(rv, F, atoms=False, nonbasic=False): + """Apply ``F`` to all expressions in an expression tree from the + bottom up. If ``atoms`` is True, apply ``F`` even if there are no args; + if ``nonbasic`` is True, try to apply ``F`` to non-Basic objects. + """ + args = getattr(rv, 'args', None) + if args is not None: + if args: + args = tuple([bottom_up(a, F, atoms, nonbasic) for a in args]) + if args != rv.args: + rv = rv.func(*args) + rv = F(rv) + elif atoms: + rv = F(rv) + else: + if nonbasic: + try: + rv = F(rv) + except TypeError: + pass + + return rv + + +def postorder_traversal(node, keys=None): + """ + Do a postorder traversal of a tree. + + This generator recursively yields nodes that it has visited in a postorder + fashion. That is, it descends through the tree depth-first to yield all of + a node's children's postorder traversal before yielding the node itself. + + Parameters + ========== + + node : SymPy expression + The expression to traverse. + keys : (default None) sort key(s) + The key(s) used to sort args of Basic objects. When None, args of Basic + objects are processed in arbitrary order. If key is defined, it will + be passed along to ordered() as the only key(s) to use to sort the + arguments; if ``key`` is simply True then the default keys of + ``ordered`` will be used (node count and default_sort_key). + + Yields + ====== + subtree : SymPy expression + All of the subtrees in the tree. + + Examples + ======== + + >>> from sympy import postorder_traversal + >>> from sympy.abc import w, x, y, z + + The nodes are returned in the order that they are encountered unless key + is given; simply passing key=True will guarantee that the traversal is + unique. + + >>> list(postorder_traversal(w + (x + y)*z)) # doctest: +SKIP + [z, y, x, x + y, z*(x + y), w, w + z*(x + y)] + >>> list(postorder_traversal(w + (x + y)*z, keys=True)) + [w, z, x, y, x + y, z*(x + y), w + z*(x + y)] + + + """ + if isinstance(node, Basic): + args = node.args + if keys: + if keys != True: + args = ordered(args, keys, default=False) + else: + args = ordered(args) + for arg in args: + yield from postorder_traversal(arg, keys) + elif iterable(node): + for item in node: + yield from postorder_traversal(item, keys) + yield node diff --git a/shared/package-files/33/33e6a36056667d40e26f195c14371567470f53324c3fec43aec29e09d7d2a60b/CREDITS.txt b/shared/package-files/33/33e6a36056667d40e26f195c14371567470f53324c3fec43aec29e09d7d2a60b/CREDITS.txt new file mode 100644 index 0000000000000000000000000000000000000000..4a42af586a4a9e55567977bd012969b420fb4a2f --- /dev/null +++ b/shared/package-files/33/33e6a36056667d40e26f195c14371567470f53324c3fec43aec29e09d7d2a60b/CREDITS.txt @@ -0,0 +1,47 @@ +Guido van Rossum, as well as being the creator of the Python language, is the +original creator of IDLE. Other contributors prior to Version 0.8 include +Mark Hammond, Jeremy Hylton, Tim Peters, and Moshe Zadka. + +Until Python 2.3, IDLE's development was carried out in the SF IDLEfork project. The +objective was to develop a version of IDLE which had an execution environment +which could be initialized prior to each run of user code. +IDLefork was merged into the Python code base in 2003. + +The IDLEfork project was initiated by David Scherer, with some help from Peter +Schneider-Kamp and Nicholas Riley. David wrote the first version of the RPC +code and designed a fast turn-around environment for VPython. Guido developed +the RPC code and Remote Debugger currently integrated in IDLE. Bruce Sherwood +contributed considerable time testing and suggesting improvements. + +Besides David and Guido, the main developers who were active on IDLEfork +are Stephen M. Gava, who implemented the configuration GUI, the new +configuration system, and the About dialog, and Kurt B. Kaiser, who completed +the integration of the RPC and remote debugger, implemented the threaded +subprocess, and made a number of usability enhancements. + +Other contributors include Raymond Hettinger, Tony Lownds (Mac integration), +Neal Norwitz (code check and clean-up), Ronald Oussoren (Mac integration), +Noam Raphael (Code Context, Call Tips, many other patches), and Chui Tey (RPC +integration, debugger integration and persistent breakpoints). + +Scott David Daniels, Tal Einat, Hernan Foffani, Christos Georgiou, +Jim Jewett, Martin v. Löwis, Jason Orendorff, Guilherme Polo, Josh Robb, +Nigel Rowe, Bruce Sherwood, Jeff Shute, and Weeble have submitted useful +patches. Thanks, guys! + +Major contributors since 2005: + +- 2005: Tal Einat +- 2010: Terry Jan Reedy (current maintainer) +- 2013: Roger Serwys +- 2014: Saimadhav Heblikar +- 2015: Mark Roseman +- 2017: Louie Lu, Cheryl Sabella, and Serhiy Storchaka + +For additional details refer to NEWS.txt and Changelog. + +Please contact the IDLE maintainer (kbk@shore.net) to have yourself included +here if you are one of those we missed! + + + diff --git a/shared/package-files/33/33e72112fe1bb674ad113fbac434c6f4b3d164d97dd57a4caa95ad6e88828fd3/_upsample_nearest_exact2d_compositeimplicitautograd_dispatch.h b/shared/package-files/33/33e72112fe1bb674ad113fbac434c6f4b3d164d97dd57a4caa95ad6e88828fd3/_upsample_nearest_exact2d_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..a4080f54e05d4b36f33cc8c839f791053189fc65 --- /dev/null +++ b/shared/package-files/33/33e72112fe1bb674ad113fbac434c6f4b3d164d97dd57a4caa95ad6e88828fd3/_upsample_nearest_exact2d_compositeimplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor _upsample_nearest_exact2d(const at::Tensor & input, at::OptionalIntArrayRef output_size, c10::optional> scale_factors); +TORCH_API at::Tensor _upsample_nearest_exact2d_symint(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, c10::optional> scale_factors); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/33/33eea45d86d97f7de97c190cf7cc94941f43fdf17e6bd4c7498d21bc172e6c9b/conv_serialization.h b/shared/package-files/33/33eea45d86d97f7de97c190cf7cc94941f43fdf17e6bd4c7498d21bc172e6c9b/conv_serialization.h new file mode 100644 index 0000000000000000000000000000000000000000..9f452a1cc72137beedbbdc0273b7ce87addb4740 --- /dev/null +++ b/shared/package-files/33/33eea45d86d97f7de97c190cf7cc94941f43fdf17e6bd4c7498d21bc172e6c9b/conv_serialization.h @@ -0,0 +1,414 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#if !defined(__s390x__) && !defined(__powerpc__) +#include +#endif + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + + +#include + +/* Convolution prepacked parameters serialization. + * + * Version 1 + * + * - Fields: + * 1. weight + * 2. bias + * 3. stride x kSpatialDim + * 4. padding x kSpatialDim + * 5. dilation x kSpatialDim + * 6. groups + * + * Version 2 + * + * - Fields: + * 0. version (string) + * 1. list of non-optional tensors + * 0: packed parameters (int16_t) + * - kSpatialDim + * - stride x kSpatialDim + * - padding x kSpatialDim + * - dilation x kSpatialDim + * - output_padding x kSpatialDim + * - groups + * - transpose (0 or 1) + * 1: weight + * 2. list of optional tensors + * 0: bias + * + * Version 3 + * + * - Fields: + * 0. version (int64_t) + * 1. list of int64_t configuration values + * - kSpatialDim + * - stride x kSpatialDim + * - padding x kSpatialDim + * - dilation x kSpatialDim + * - output_padding x kSpatialDim + * - groups + * - flags (bitmask) + * - (1 << 0) transpose (1 = yes) + * 2. list of optional tensors + * 0: None (helps with type inference) + * 1: weight (this must be present) + * 2: bias + */ + +using ConvParamsSerializationTypeV2 = std::tuple< + // version, for versions 2 and up + std::string, + // non-optional tensors + std::vector, + // optional tensors + std::vector>>; + +using ConvParamsSerializationTypeV3 = std::tuple< + // version, int for versions 3 and up + int64_t, + // configuration values + std::vector, + // optional tensors + std::vector>>; + +// Parses any historical conv packed params format into +// the current format. +template +ConvParamsSerializationTypeV3 parse_conv_serialized_state(c10::IValue v) { + + // determine the version based on IValue contents + int version = -1; + if (v.isTuple()) { + const auto& elements = v.toTupleRef().elements(); + if (!elements.empty()) { + auto firstElement = elements[0]; + if (firstElement.isTensor()) { + version = 1; + } else if (firstElement.isString()) { + const std::string& version_str = firstElement.toStringRef(); + // note: not parsing the string to automatically handle bad + // inputs + if (version_str == "2") { + version = 2; + } + } else if (firstElement.isInt()) { + auto raw_version = firstElement.toInt(); + if (raw_version == 3) { + version = 3; + } + } + } + } + TORCH_INTERNAL_ASSERT(version != -1, "Unable to parse serialization version"); + + if (version == 1) { + // version 1 - convert to version 3 manually + + const auto& elements = v.toTupleRef().elements(); + + at::Tensor weight = elements[0].toTensor(); + c10::optional bias = elements[1].toOptional(); + torch::List stride_x_kSpatialDim = elements[2].toTensorList(); + torch::List padding_x_kSpatialDim = elements[3].toTensorList(); + torch::List dilation_x_kSpatialDim = elements[4].toTensorList(); + at::Tensor groups = elements[5].toTensor(); + + std::vector config_vals; + config_vals.reserve( + stride_x_kSpatialDim.size() + padding_x_kSpatialDim.size() + + dilation_x_kSpatialDim.size() + kSpatialDim + 3); + config_vals.push_back(kSpatialDim); + for (const auto i : c10::irange(stride_x_kSpatialDim.size())) { + auto stride = stride_x_kSpatialDim.get(i); + config_vals.push_back(stride[0].item()); + } + for (const auto i : c10::irange(padding_x_kSpatialDim.size())) { + auto padding = padding_x_kSpatialDim.get(i); + config_vals.push_back(padding[0].item()); + } + for (const auto i : c10::irange(dilation_x_kSpatialDim.size())) { + auto dilation = dilation_x_kSpatialDim.get(i); + config_vals.push_back(dilation[0].item()); + } + // output_padding does not exist in v1, so we fill in a default value + for (C10_UNUSED const auto i : c10::irange(kSpatialDim)) { + config_vals.push_back(0); + } + config_vals.push_back(groups[0].item()); + // transpose does not exist in v1, so we fill in a default value + config_vals.push_back(0); + + std::vector> tensors; + tensors.emplace_back(); + tensors.emplace_back(weight); + tensors.emplace_back(bias); + + int64_t version = 3; + return std::tie(version, config_vals, tensors); + } else if (version == 2) { + // version 2 + const auto& elements = v.toTupleRef().elements(); + std::vector non_optional = elements[1].toTensorList().vec(); + std::vector> optional; + + if (elements[2].isTensorList()) { + for (const auto& elem : elements[2].toTensorList()) { + optional.emplace_back(static_cast(elem)); + } + } else { + for (const auto& elem : elements[2].toList()) { + optional.emplace_back(static_cast(elem).toOptional()); + } + } + // create default optional value for bias + if (optional.empty()) { + optional.emplace_back(); + } + + auto config_a = non_optional[0].accessor(); + std::vector config_vals; + config_vals.reserve(config_a.size(0)); + for (const auto i : c10::irange(config_a.size(0))) { + config_vals.emplace_back(config_a[i]); + } + + auto weight = non_optional[1]; + auto bias = optional[0]; + + std::vector> tensors; + tensors.emplace_back(); + tensors.emplace_back(weight); + tensors.emplace_back(bias); + + int64_t version = 3; + return std::tie(version, config_vals, tensors); + } else if (version == 3) { + return v.to(); + } else { + TORCH_INTERNAL_ASSERT(false, "Unexpected serialized qconv version: ", + version); + } +} + +#define QCONV_SERIALIZATION_VERSION 2 + +#if QCONV_SERIALIZATION_VERSION == 2 +using ConvParamsSerializationType = ConvParamsSerializationTypeV2; + +template +ConvParamsSerializationTypeV2 serialize_conv( + const c10::intrusive_ptr>& params) { + + std::string version = "2"; + std::vector non_optional; + std::vector> optional; + + // create a packed int8_t tensor for conv params + std::vector params_vec; + params_vec.push_back(kSpatialDim); + auto stride = params->stride().vec(); + params_vec.insert(params_vec.end(), stride.begin(), stride.end()); + auto padding = params->padding().vec(); + params_vec.insert(params_vec.end(), padding.begin(), padding.end()); + auto dilation = params->dilation().vec(); + params_vec.insert(params_vec.end(), dilation.begin(), dilation.end()); + auto output_padding = params->output_padding().vec(); + params_vec.insert(params_vec.end(), output_padding.begin(), + output_padding.end()); + params_vec.push_back(params->groups()); + params_vec.push_back(params->transpose()); + int64_t vec_size = params_vec.size(); + at::Tensor params_tensor = at::from_blob( + params_vec.data(), {vec_size}, + at::TensorOptions().dtype(at::kShort)) + // clone to retain ownership of the data + .clone(); + + auto [weight, bias] = params->unpack(); + + non_optional.emplace_back(std::move(params_tensor)); + non_optional.emplace_back(std::move(weight)); + optional.emplace_back(std::move(bias)); + + return std::tie(version, non_optional, optional); +} + +#elif QCONV_SERIALIZATION_VERSION == 3 +using ConvParamsSerializationType = ConvParamsSerializationTypeV3; + +template +ConvParamsSerializationTypeV3 serialize_conv( + const c10::intrusive_ptr>& params) { + std::vector config_vals; + config_vals.push_back(kSpatialDim); + auto stride = params->stride().vec(); + config_vals.insert(config_vals.end(), stride.begin(), stride.end()); + auto padding = params->padding().vec(); + config_vals.insert(config_vals.end(), padding.begin(), padding.end()); + auto dilation = params->dilation().vec(); + config_vals.insert(config_vals.end(), dilation.begin(), dilation.end()); + auto output_padding = params->output_padding().vec(); + config_vals.insert(config_vals.end(), output_padding.begin(), + output_padding.end()); + config_vals.push_back(params->groups()); + config_vals.push_back(params->transpose()); + + auto [weight, bias] = params->unpack(); + + std::vector> tensors; + tensors.emplace_back(); + tensors.emplace_back(weight); + tensors.emplace_back(bias); + + int64_t version = 3; + return std::tie(version, config_vals, tensors); +} + +#else +#error "Invalid qconv serialization version." +#endif + +template +c10::intrusive_ptr> deserialize_conv( + ConvParamsSerializationTypeV3 state) { + auto [version, config_vals, tensors] = state; + TORCH_INTERNAL_ASSERT(version == 3, "Unexpected serialized qconv version: ", version); + + TORCH_CHECK(tensors.size() == 3, "Wrong number of tensors", tensors.size()); + c10::optional weight = tensors[1]; + c10::optional bias = tensors[2]; + TORCH_INTERNAL_ASSERT(weight, "Weight should always be present in serialized qconv."); + + torch::List stride, padding, output_padding, dilation; + // skip kSpatialDim + int idx = 1; + for (C10_UNUSED const auto i : c10::irange(kSpatialDim)) { + stride.emplace_back(config_vals.at(idx)); + idx++; + } + for (C10_UNUSED const auto i : c10::irange(kSpatialDim)) { + padding.emplace_back(config_vals.at(idx)); + idx++; + } + for (C10_UNUSED const auto i : c10::irange(kSpatialDim)) { + dilation.emplace_back(config_vals.at(idx)); + idx++; + } + for (C10_UNUSED const auto i : c10::irange(kSpatialDim)) { + TORCH_INTERNAL_ASSERT(idx < static_cast(config_vals.size()), + "Unexpected index = ", idx, " for config_vals of size ", + config_vals.size()); + output_padding.emplace_back(config_vals.at(idx)); + idx++; + } + int64_t groups = config_vals.at(idx); + idx++; + int64_t flags = config_vals.at(idx); + idx++; + TORCH_INTERNAL_ASSERT(idx == static_cast(config_vals.size()), + "Unexpected length of config_vals, expected ", + idx, + " got ", + config_vals.size()); + + bool transpose = flags & (1 << 0); + + int64_t other_flags = flags & ~(1 << 0); + TORCH_INTERNAL_ASSERT(other_flags == 0, "Unexpected flags set in ", flags, "."); + + auto& ctx = at::globalContext(); + +#ifdef USE_FBGEMM + if (ctx.qEngine() == at::QEngine::X86) { +#if AT_MKLDNN_ENABLED() + bool use_onednn = onednn_utils::should_use_onednn_quant( + weight.value(), transpose, groups, output_padding); + if (use_onednn) { + return PackedConvWeightsOnednn::prepack( + weight.value(), + bias, + stride, + padding, + output_padding, + dilation, + groups, + transpose + ); + } +#endif + return PackedConvWeight::prepack( + weight.value(), + bias, + stride, + padding, + output_padding, + dilation, + groups, + transpose + ); + } // x86 +#endif + +#ifdef USE_FBGEMM + if (ctx.qEngine() == at::QEngine::FBGEMM) { + return PackedConvWeight::prepack( + weight.value(), + bias, + stride, + padding, + output_padding, + dilation, + groups, + transpose + ); + } +#endif // USE_FBGEMM +#ifdef USE_PYTORCH_QNNPACK + if (ctx.qEngine() == at::QEngine::QNNPACK) { + TORCH_CHECK( + kSpatialDim == 2, + "prepack/__setstate__: QNNPACK only supports Conv2d " + "now."); + return PackedConvWeightsQnnp::prepack( + weight.value(), + bias, + stride, + padding, + output_padding, + dilation, + groups, + transpose + ); + } +#endif // USE_PYTORCH_QNNPACK +#if AT_MKLDNN_ENABLED() + if (ctx.qEngine() == at::QEngine::ONEDNN) { + return PackedConvWeightsOnednn::prepack( + weight.value(), + bias, + stride, + padding, + output_padding, + dilation, + groups, + transpose + ); + } +#endif // AT_MKLDNN_ENABLED() +TORCH_CHECK( + false, + "Didn't find engine for when deserializing ConvPackedParams: ", + toString(ctx.qEngine())); +} diff --git a/shared/package-files/33/33eee347c02ac8fbbcb935dbc3820d2dbf51b192ab3e66653ceed3eccb2443ff/azurefs.h b/shared/package-files/33/33eee347c02ac8fbbcb935dbc3820d2dbf51b192ab3e66653ceed3eccb2443ff/azurefs.h new file mode 100644 index 0000000000000000000000000000000000000000..ee0956afdd7a982769fdb5035db02e17fac3f2cb --- /dev/null +++ b/shared/package-files/33/33eee347c02ac8fbbcb935dbc3820d2dbf51b192ab3e66653ceed3eccb2443ff/azurefs.h @@ -0,0 +1,373 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/filesystem/filesystem.h" +#include "arrow/util/macros.h" +#include "arrow/util/uri.h" + +namespace Azure::Core::Credentials { +class TokenCredential; +} + +namespace Azure::Storage { +class StorageSharedKeyCredential; +} + +namespace Azure::Storage::Blobs { +class BlobServiceClient; +} + +namespace Azure::Storage::Files::DataLake { +class DataLakeFileSystemClient; +class DataLakeServiceClient; +} // namespace Azure::Storage::Files::DataLake + +namespace arrow::fs { + +class TestAzureFileSystem; +class TestAzureOptions; + +/// Options for the AzureFileSystem implementation. +/// +/// By default, authentication is handled by the Azure SDK's credential chain +/// which may read from multiple environment variables, such as: +/// - `AZURE_TENANT_ID` +/// - `AZURE_CLIENT_ID` +/// - `AZURE_CLIENT_SECRET` +/// - `AZURE_AUTHORITY_HOST` +/// - `AZURE_CLIENT_CERTIFICATE_PATH` +/// - `AZURE_FEDERATED_TOKEN_FILE` +/// +/// Functions are provided for explicit configuration of credentials if that is preferred. +struct ARROW_EXPORT AzureOptions { + friend class TestAzureOptions; + + /// \brief The name of the Azure Storage Account being accessed. + /// + /// All service URLs will be constructed using this storage account name. + /// `ConfigureAccountKeyCredential` assumes the user wants to authenticate + /// this account. + std::string account_name; + + /// \brief hostname[:port] of the Azure Blob Storage Service. + /// + /// If the hostname is a relative domain name (one that starts with a '.'), then storage + /// account URLs will be constructed by prepending the account name to the hostname. + /// If the hostname is a fully qualified domain name, then the hostname will be used + /// as-is and the account name will follow the hostname in the URL path. + /// + /// Default: ".blob.core.windows.net" + std::string blob_storage_authority = ".blob.core.windows.net"; + + /// \brief hostname[:port] of the Azure Data Lake Storage Gen 2 Service. + /// + /// If the hostname is a relative domain name (one that starts with a '.'), then storage + /// account URLs will be constructed by prepending the account name to the hostname. + /// If the hostname is a fully qualified domain name, then the hostname will be used + /// as-is and the account name will follow the hostname in the URL path. + /// + /// Default: ".dfs.core.windows.net" + std::string dfs_storage_authority = ".dfs.core.windows.net"; + + /// \brief Azure Blob Storage connection transport. + /// + /// Default: "https" + std::string blob_storage_scheme = "https"; + + /// \brief Azure Data Lake Storage Gen 2 connection transport. + /// + /// Default: "https" + std::string dfs_storage_scheme = "https"; + + // TODO(GH-38598): Add support for more auth methods. + // std::string connection_string; + // std::string sas_token; + + /// \brief Default metadata for OpenOutputStream. + /// + /// This will be ignored if non-empty metadata is passed to OpenOutputStream. + std::shared_ptr default_metadata; + + /// Whether OutputStream writes will be issued in the background, without blocking. + bool background_writes = true; + + private: + enum class CredentialKind { + kDefault, + kAnonymous, + kStorageSharedKey, + kSASToken, + kClientSecret, + kManagedIdentity, + kCLI, + kWorkloadIdentity, + kEnvironment, + } credential_kind_ = CredentialKind::kDefault; + + std::shared_ptr + storage_shared_key_credential_; + std::string sas_token_; + mutable std::shared_ptr token_credential_; + + public: + AzureOptions(); + ~AzureOptions(); + + private: + void ExtractFromUriSchemeAndHierPart(const Uri& uri, std::string* out_path); + Status ExtractFromUriQuery(const Uri& uri); + + public: + /// \brief Construct a new AzureOptions from an URI. + /// + /// Supported formats: + /// + /// 1. abfs[s]://\.blob.core.windows.net[/\[/\]] + /// 2. abfs[s]://\\@\.dfs.core.windows.net[/path] + /// 3. abfs[s]://[\[\<:port\>][/\[/path]] + /// 4. abfs[s]://[\[/path] + /// + /// (1) and (2) are compatible with the Azure Data Lake Storage Gen2 URIs + /// [1], (3) is for Azure Blob Storage compatible service including Azurite, + /// and (4) is a shorter version of (1) and (2). + /// + /// Note that there is no difference between abfs and abfss. HTTPS is + /// used with abfs by default. You can force to use HTTP by specifying + /// "enable_tls=false" query. + /// + /// Supported query parameters: + /// + /// * blob_storage_authority: Set AzureOptions::blob_storage_authority + /// * dfs_storage_authority: Set AzureOptions::dfs_storage_authority + /// * enable_tls: If it's "false" or "0", HTTP not HTTPS is used. + /// * credential_kind: One of "default", "anonymous", "workload_identity", + /// "environment" or "cli". If "default" is specified, it's + /// just ignored. If "anonymous" is specified, + /// AzureOptions::ConfigureAnonymousCredential() is called. If + /// "workload_identity" is specified, + /// AzureOptions::ConfigureWorkloadIdentityCredential() is called. If + /// "environment" is specified, + /// AzureOptions::ConfigureEnvironmentCredential() is called. If "cli" is + /// specified, AzureOptions::ConfigureCLICredential() is called. + /// * tenant_id: You must specify "client_id" and "client_secret" + /// too. AzureOptions::ConfigureClientSecretCredential() is called. + /// * client_id: If you don't specify "tenant_id" and + /// "client_secret", + /// AzureOptions::ConfigureManagedIdentityCredential() is + /// called. If you specify "tenant_id" and "client_secret" too, + /// AzureOptions::ConfigureClientSecretCredential() is called. + /// * client_secret: You must specify "tenant_id" and "client_id" + /// too. AzureOptions::ConfigureClientSecretCredential() is called. + /// * A SAS token is made up of several query parameters. Appending a SAS + /// token to the URI configures SAS token auth by calling + /// AzureOptions::ConfigureSASCredential(). + /// + /// [1]: + /// https://learn.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-introduction-abfs-uri + static Result FromUri(const Uri& uri, std::string* out_path); + static Result FromUri(const std::string& uri, std::string* out_path); + + Status ConfigureDefaultCredential(); + Status ConfigureAnonymousCredential(); + Status ConfigureAccountKeyCredential(const std::string& account_key); + Status ConfigureSASCredential(const std::string& sas_token); + Status ConfigureClientSecretCredential(const std::string& tenant_id, + const std::string& client_id, + const std::string& client_secret); + Status ConfigureManagedIdentityCredential(const std::string& client_id = std::string()); + Status ConfigureCLICredential(); + Status ConfigureWorkloadIdentityCredential(); + Status ConfigureEnvironmentCredential(); + + bool Equals(const AzureOptions& other) const; + + std::string AccountBlobUrl(const std::string& account_name) const; + std::string AccountDfsUrl(const std::string& account_name) const; + + Result> + MakeBlobServiceClient() const; + + Result> + MakeDataLakeServiceClient() const; +}; + +/// \brief FileSystem implementation backed by Azure Blob Storage (ABS) [1] and +/// Azure Data Lake Storage Gen2 (ADLS Gen2) [2]. +/// +/// ADLS Gen2 isn't a dedicated service or account type. It's a set of capabilities that +/// support high throughput analytic workloads, built on Azure Blob Storage. All the data +/// ingested via the ADLS Gen2 APIs is persisted as blobs in the storage account. +/// ADLS Gen2 provides filesystem semantics, file-level security, and Hadoop +/// compatibility. ADLS Gen1 exists as a separate object that will retired on 2024-02-29 +/// and new ADLS accounts use Gen2 instead. +/// +/// ADLS Gen2 and Blob APIs can operate on the same data, but there are +/// some limitations [3]. The ones that are relevant to this +/// implementation are listed here: +/// +/// - You can't use Blob APIs, and ADLS APIs to write to the same instance of a file. If +/// you write to a file by using ADLS APIs then that file's blocks won't be visible +/// to calls to the GetBlockList Blob API. The only exception is when you're +/// overwriting. +/// - When you use the ListBlobs operation without specifying a delimiter, the results +/// include both directories and blobs. If you choose to use a delimiter, use only a +/// forward slash (/) \--- the only supported delimiter. +/// - If you use the DeleteBlob API to delete a directory, that directory is deleted only +/// if it's empty. This means that you can't use the Blob API delete directories +/// recursively. +/// +/// [1]: https://azure.microsoft.com/en-us/products/storage/blobs +/// [2]: https://azure.microsoft.com/en-us/products/storage/data-lake-storage +/// [3]: +/// https://learn.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-known-issues +class ARROW_EXPORT AzureFileSystem : public FileSystem { + private: + class Impl; + std::unique_ptr impl_; + + explicit AzureFileSystem(std::unique_ptr&& impl); + + friend class TestAzureFileSystem; + void ForceCachedHierarchicalNamespaceSupport(int hns_support); + + public: + ~AzureFileSystem() override = default; + + static Result> Make( + const AzureOptions& options, const io::IOContext& = io::default_io_context()); + + std::string type_name() const override { return "abfs"; } + + /// Return the original Azure options when constructing the filesystem + const AzureOptions& options() const; + + bool Equals(const FileSystem& other) const override; + + /// \cond FALSE + using FileSystem::CreateDir; + using FileSystem::DeleteDirContents; + using FileSystem::GetFileInfo; + using FileSystem::OpenAppendStream; + using FileSystem::OpenOutputStream; + /// \endcond + + Result GetFileInfo(const std::string& path) override; + + Result GetFileInfo(const FileSelector& select) override; + + Status CreateDir(const std::string& path, bool recursive) override; + + /// \brief Delete a directory and its contents recursively. + /// + /// Atomicity is guaranteed only on Hierarchical Namespace Storage accounts. + Status DeleteDir(const std::string& path) override; + + /// \brief Non-atomically deletes the contents of a directory. + /// + /// This function can return a bad Status after only partially deleting the + /// contents of the directory. + Status DeleteDirContents(const std::string& path, bool missing_dir_ok) override; + + /// \brief Deletion of all the containers in the storage account (not + /// implemented for safety reasons). + /// + /// \return Status::NotImplemented + Status DeleteRootDirContents() override; + + /// \brief Deletes a file. + /// + /// Supported on both flat namespace and Hierarchical Namespace storage + /// accounts. A check is made to guarantee the parent directory doesn't + /// disappear after the blob is deleted and while this operation is running, + /// no other client can delete the parent directory due to the use of leases. + /// + /// This means applications can safely retry this operation without coordination to + /// guarantee only one client/process is trying to delete the same file. + Status DeleteFile(const std::string& path) override; + + /// \brief Move/rename a file or directory. + /// + /// There are no files immediately at the root directory, so paths like + /// "/segment" always refer to a container of the storage account and are + /// treated as directories. + /// + /// If `dest` exists but the operation fails for some reason, `Move` + /// guarantees `dest` is not lost. + /// + /// Conditions for a successful move: + /// + /// 1. `src` must exist. + /// 2. `dest` can't contain a strict path prefix of `src`. More generally, + /// a directory can't be made a subdirectory of itself. + /// 3. If `dest` already exists and it's a file, `src` must also be a file. + /// `dest` is then replaced by `src`. + /// 4. All components of `dest` must exist, except for the last. + /// 5. If `dest` already exists and it's a directory, `src` must also be a + /// directory and `dest` must be empty. `dest` is then replaced by `src` + /// and its contents. + /// + /// Leases are used to guarantee the pre-condition checks and the rename + /// operation are atomic: other clients can't invalidate the pre-condition in + /// the time between the checks and the actual rename operation. + /// + /// This is possible because Move() is only support on storage accounts with + /// Hierarchical Namespace Support enabled. + /// + /// ## Limitations + /// + /// - Moves are not supported on storage accounts without + /// Hierarchical Namespace support enabled + /// - Moves across different containers are not supported + /// - Moving a path of the form `/container` is not supported as it would + /// require moving all the files in a container to another container. + /// The only exception is a `Move("/container_a", "/container_b")` where + /// both containers are empty or `container_b` doesn't even exist. + /// The atomicity of the emptiness checks followed by the renaming operation + /// is guaranteed by the use of leases. + Status Move(const std::string& src, const std::string& dest) override; + + Status CopyFile(const std::string& src, const std::string& dest) override; + + Result> OpenInputStream( + const std::string& path) override; + + Result> OpenInputStream(const FileInfo& info) override; + + Result> OpenInputFile( + const std::string& path) override; + + Result> OpenInputFile( + const FileInfo& info) override; + + Result> OpenOutputStream( + const std::string& path, + const std::shared_ptr& metadata) override; + + Result> OpenAppendStream( + const std::string& path, + const std::shared_ptr& metadata) override; + + Result PathFromUri(const std::string& uri_string) const override; +}; + +} // namespace arrow::fs diff --git a/shared/package-files/33/33ef6721d000ca7309ec5bc51531d7244519153f2e3936e2cdfe593a7389f939/conftest.py b/shared/package-files/33/33ef6721d000ca7309ec5bc51531d7244519153f2e3936e2cdfe593a7389f939/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..036e4de20ba538bc4dbe6636fc802fb9c8f10e5d --- /dev/null +++ b/shared/package-files/33/33ef6721d000ca7309ec5bc51531d7244519153f2e3936e2cdfe593a7389f939/conftest.py @@ -0,0 +1,132 @@ +import pytest + +from pandas import Series +from pandas.core.strings.accessor import StringMethods + +_any_string_method = [ + ("cat", (), {"sep": ","}), + ("cat", (Series(list("zyx")),), {"sep": ",", "join": "left"}), + ("center", (10,), {}), + ("contains", ("a",), {}), + ("count", ("a",), {}), + ("decode", ("UTF-8",), {}), + ("encode", ("UTF-8",), {}), + ("endswith", ("a",), {}), + ("endswith", ((),), {}), + ("endswith", (("a",),), {}), + ("endswith", (("a", "b"),), {}), + ("endswith", (("a", "MISSING"),), {}), + ("endswith", ("a",), {"na": True}), + ("endswith", ("a",), {"na": False}), + ("extract", ("([a-z]*)",), {"expand": False}), + ("extract", ("([a-z]*)",), {"expand": True}), + ("extractall", ("([a-z]*)",), {}), + ("find", ("a",), {}), + ("findall", ("a",), {}), + ("get", (0,), {}), + # because "index" (and "rindex") fail intentionally + # if the string is not found, search only for empty string + ("index", ("",), {}), + ("join", (",",), {}), + ("ljust", (10,), {}), + ("match", ("a",), {}), + ("fullmatch", ("a",), {}), + ("normalize", ("NFC",), {}), + ("pad", (10,), {}), + ("partition", (" ",), {"expand": False}), + ("partition", (" ",), {"expand": True}), + ("repeat", (3,), {}), + ("replace", ("a", "z"), {}), + ("rfind", ("a",), {}), + ("rindex", ("",), {}), + ("rjust", (10,), {}), + ("rpartition", (" ",), {"expand": False}), + ("rpartition", (" ",), {"expand": True}), + ("slice", (0, 1), {}), + ("slice_replace", (0, 1, "z"), {}), + ("split", (" ",), {"expand": False}), + ("split", (" ",), {"expand": True}), + ("startswith", ("a",), {}), + ("startswith", (("a",),), {}), + ("startswith", (("a", "b"),), {}), + ("startswith", (("a", "MISSING"),), {}), + ("startswith", ((),), {}), + ("startswith", ("a",), {"na": True}), + ("startswith", ("a",), {"na": False}), + ("removeprefix", ("a",), {}), + ("removesuffix", ("a",), {}), + # translating unicode points of "a" to "d" + ("translate", ({97: 100},), {}), + ("wrap", (2,), {}), + ("zfill", (10,), {}), +] + list( + zip( + [ + # methods without positional arguments: zip with empty tuple and empty dict + "capitalize", + "cat", + "get_dummies", + "isalnum", + "isalpha", + "isdecimal", + "isdigit", + "islower", + "isnumeric", + "isspace", + "istitle", + "isupper", + "len", + "lower", + "lstrip", + "partition", + "rpartition", + "rsplit", + "rstrip", + "slice", + "slice_replace", + "split", + "strip", + "swapcase", + "title", + "upper", + "casefold", + ], + [()] * 100, + [{}] * 100, + ) +) +ids, _, _ = zip(*_any_string_method) # use method name as fixture-id +missing_methods = {f for f in dir(StringMethods) if not f.startswith("_")} - set(ids) + +# test that the above list captures all methods of StringMethods +assert not missing_methods + + +@pytest.fixture(params=_any_string_method, ids=ids) +def any_string_method(request): + """ + Fixture for all public methods of `StringMethods` + + This fixture returns a tuple of the method name and sample arguments + necessary to call the method. + + Returns + ------- + method_name : str + The name of the method in `StringMethods` + args : tuple + Sample values for the positional arguments + kwargs : dict + Sample values for the keyword arguments + + Examples + -------- + >>> def test_something(any_string_method): + ... s = Series(['a', 'b', np.nan, 'd']) + ... + ... method_name, args, kwargs = any_string_method + ... method = getattr(s.str, method_name) + ... # will not raise + ... method(*args, **kwargs) + """ + return request.param diff --git a/shared/package-files/33/33f206593c938eb5fdd0da338d551fc2d3ed4ea60d912803c5f05202b3deb30b/provenance.json b/shared/package-files/33/33f206593c938eb5fdd0da338d551fc2d3ed4ea60d912803c5f05202b3deb30b/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..8ad5dd1d75e81258ee47dce3080abf1915eee2bd --- /dev/null +++ b/shared/package-files/33/33f206593c938eb5fdd0da338d551fc2d3ed4ea60d912803c5f05202b3deb30b/provenance.json @@ -0,0 +1,48711 @@ +{ + "parent_package": "/workspace/research/production-affinity-length1/candidate/package", + "parent_provenance": { + "method": "Three-parameter affinity length residual supported by held-out-half recipe evidence", + "parent": "/workspace/research/production-solubility-mean1/candidate/package", + "parent_model_sha256": "ea3bb28deaae8b95f10e8fcfe83ae5f1884eac7c3ecfece4ba5669a31d3e304f", + "parent_provenance": { + "parent_package": "/workspace/research/production-dual-fold-fullpool1/candidate/package", + "parent_sha256": "492ad2b7a8866a3d633616adbc75f29ec4cf093b14957d63171bffa842ea7e07", + "parent_provenance": { + "parent_package": "/workspace/research/production-fold-shared1/candidate/package", + "parent_model_sha256": "93a8fa2aadcb92983cefa53154866e9efc47a21deea0d847042c1f836883b513", + "parent_provenance": { + "parent_package": "/workspace/research/production-allfit-ss1/candidate/package", + "parent_sha256": "7d2e535cf57b776189bd0a6658cf6aca790af0253bb4814ef6a19deffb0f7c39", + "parent_provenance": { + "parent_package": "/workspace/research/production-dual-residue-ss1/candidate/package", + "parent_sha256": "d52293a81c168347002c88a81f2469cb8be72e7a527699946b68b4614b857dfe", + "parent_provenance": { + "parent_package": "/workspace/research/production-shared-fusion8h-ss1/candidate/package", + "parent_sha256": "f7c7dbbdcd9d6f4cc853b2074d1501579c24588405c121430a67b6f0482324d8", + "parent_provenance": { + "parent_package": "/workspace/research/production-dual-summary-subcellular1/candidate/package", + "parent_sha256": "8badfd129686a5d20216b1aba16450f6f471722c8b6ddfc61278dd572283abc0", + "parent_provenance": { + "method": "One primary backbone remains common to all11 tasks. Configured classification heads concatenate two native seven-summary representations. Auxiliary encoder is stored once and was itself jointly trained on all11 tasks.", + "primary_package": "/workspace/research/selected-stability-lengthweight1-replay/candidate/package", + "primary_sha256": "d581e2aad1c8ea712968423348ff2c540352c7d9ad2b36a46e795a1f4d31b73b", + "primary_provenance": { + "parent_package": "/workspace/research/selected-stability-midpoint1/candidate/package", + "parent_sha256": "e01ae99a458b5d8d2aba968e1efc663b3d346220fd16b5498a3f91b5cf29626c", + "parent_provenance": { + "method": "One fixed 50:50 parameter midpoint of parent and fit-only 16-epoch stability head continuation; no ensemble.", + "source_parent": "/workspace/research/shared-summary-residual1/candidate/package", + "source_candidate": "/workspace/research/selected-stability-head64/candidate/package", + "source_model_sha256": { + "/workspace/research/shared-summary-residual1/candidate/package": "f890eebb10bb2dc08b84c28e7e0378960af5df4fb0d646ab2e8b33e130c74202", + "/workspace/research/selected-stability-head64/candidate/package": "8fe80a673a65650bb5769b1cf75a59f10a65961da91cc62a491094f874042c79" + }, + "parent_provenance": { + "method": "One jointly learned nonlinear residual map over frozen shared sequence summaries, with task-specific zero-initialized outputs.", + "fit_tasks": [ + "solubility", + "subcellular_localization", + "binary_localization" + ], + "selected_tasks": [ + "binary_localization" + ], + "selected_global_step": 3000, + "source": "/workspace/research/ss-distillation-continuation1/candidate/package", + "export_base": "/workspace/research/ss-distillation-continuation1/candidate/package", + "export_base_model_sha256": "4fee0a0154af24665de9a95f11a722017f3fa6d92354475bec8e81235a219f00", + "rebased_SS_tensors": [], + "seed": 20270102, + "steps": 6000, + "lr": 0.001, + "weight_decay": 0.01, + "dropout": 0.2, + "data": "Fit only for gradients and existing normalization; Tune chooses oneglobalcheckpoint andresidualexits usingpredeclaredconditionalCIgate.", + "original_parameters_exact": true, + "parameters": 53000306, + "encoder_parameters": 44150303, + "feature_cache_exported": false + }, + "fit_recipe": { + "seed": 20270129, + "epochs": 64, + "evaluate_epochs": [ + 4, + 16, + 32, + 64 + ], + "batch_size": 512, + "lr": 0.0001, + "weight_decay": 0.01, + "loss": "MSE to original fit-standardized stabilitylabels, matching selectedmodeltarget semantics;clip1;originaldropout active inbotharms;fixednormalizationbuffers. No newranktargetchange.", + "optimizer": "FreshCPUAdamW,cosine64epochs to0.1floor; matcheddataorder/dropoutRNG/updatecounts; per-epochatomicresume." + }, + "source_selected_epoch": 16, + "diagnostic": { + "utc": "2026-10-25T13:39:33.197851+00:00", + "status": "CPU_diagnostic_complete_no_export", + "alpha": 0.5, + "points": { + "parent": 0.7226969980994319, + "midpoint": 0.7274924148853711, + "whole": 0.7274598466634085 + }, + "midpoint_delta_vs_parent": 0.004795416785939199, + "conditional95": [ + 0.0017412267324550784, + 0.007940572842815559 + ], + "draws": 1000, + "seed": 20270130, + "parameters": 53000306, + "six_changed_learned_tensors": [ + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.linear.weight", + "heads.stability.3.linear.bias" + ], + "all_other_tensors_and_buffers_exact": true, + "eligible_for_manual_complete_replay": true, + "publication": false, + "GPU_used": false, + "limitations": "Singlepredeclaredparameter midpoint, notpredictionensemble. Conditionalrowbootstrapuncorrectedforpriorcheckpointselectionandfamilydependence. CPUdiagnosticisnotan11taskreplay.", + "source_sha256": { + "/workspace/research/check_selected_stability_midpoint.py": "13615a5b2689a0bd503cbc8a9a8a722014962677f6769cec871e13aa5133ff77", + "/workspace/research/shared-summary-residual1/candidate/package/model.pt": "f890eebb10bb2dc08b84c28e7e0378960af5df4fb0d646ab2e8b33e130c74202", + "/workspace/research/selected-stability-head64/candidate/package/model.pt": "8fe80a673a65650bb5769b1cf75a59f10a65961da91cc62a491094f874042c79" + } + }, + "data": "Fit-only labels and fixed normalization; tune selects epoch and evaluates one predeclared midpoint.", + "parameters": 53000306, + "feature_cache_exported": false + }, + "fit_plan": { + "utc": "2026-10-25T16:08:33.461759+00:00", + "status": "queued", + "CPU_only": true, + "recovery_registered": false, + "source_package": "/workspace/research/selected-stability-midpoint1/candidate/package", + "source_report": "/workspace/research/selected-stability-midpoint1/candidate/report.json", + "features": "/workspace/research/rank-target-functions2/features-stability", + "feature_producer": "/workspace/research/rank-target-fluorescence1/candidate/package", + "arms": [ + "natural", + "balanced" + ], + "expected_fit_lengths": [ + 43, + 50 + ], + "seed": 20270208, + "threads": 6, + "epochs": 16, + "batch_size": 512, + "lr": 0.0001, + "weight_decay": 0.01, + "alpha": 0.5, + "minimum_gain": 0.001, + "bootstrap_seed": 20270209, + "bootstrap_draws": 1000, + "hypothesis": "Natural stability fit data are68%43-residue proteins but all observed Tune chains have50residues. Equal loss mass for the two fit-length groups may reduce interference on the50-residue domain. This is a test prompted by visible Tune distribution, not evidence of benefit.", + "loss": "Original-fit-standardized-label MSE. Identical shuffled full-fit batches in both arms; natural unit weights; balanced weights N/(2*N_group), averaged over minibatch without per-batch renormalization. Both train all six existing head tensors, fixed feature-normalization buffers.", + "schedule": "FreshAdamW,16epochs/1680updates,cosine to0.1floor,clip1; originaldropoutactive with identical RNG and data order. Same current selected initial head.", + "selection": "Only one fixed50:50 parameter midpoint at the final16epoch endpoint per arm is eligible. Raw endpoints are descriptive. Require gain>=.001 and positive conditional95versus selected; balanced additionally requires positive conditional95versus natural control. No intermediate Tune selection, no seed/mixture grid. Manual review then full11 native replay before any publication.", + "all_task_policy": "Only six stabilityheadparameters may change. Shared encoder remains jointly learned for all11. All10otherparameters/config/outputfiles must remain exact on native replay. No automatic export or publication.", + "resume": "CPU per-epoch atomic optimizer/head/NumPy/torchRNG checkpoints; rerun same script after interruption. Planhash verified on resume.", + "recovery_command": [ + "env", + "CUDA_VISIBLE_DEVICES=", + "OMP_NUM_THREADS=6", + "MKL_NUM_THREADS=6", + "OPENBLAS_NUM_THREADS=1", + "python3", + "-u", + "/workspace/research/run_stability_length_weighting.py", + "--run", + "/workspace/research/selected-stability-lengthweight1" + ], + "frozen_sha256": { + "/workspace/research/run_stability_length_weighting.py": "3c5aac6a79a1397e5c50278a7635e32d7c3583438f64996c8a42a372d16a29f6", + "/workspace/research/check_shared_adapters_cpu.py": "db7d8d846b90929decad5865de36dd55fb95139aaa116b6ae2987cd96786c990", + "/workspace/research/crossfit_beta_labels.py": "bd1d29e2ab78cb0273213ef1a00657cef450a91f155ba7d9aa7f3db7721bd632", + "/workspace/research/stability-length-shift-diagnostic.json": "36a890f702bb6709e893c5f9d94c5cf15959f83f4a91d71e58a7b5f681065f6d", + "/workspace/research/selected-stability-midpoint1/candidate/report.json": "feedb171d285a4fa4d3c2a2bdd819873caaad1308ef90fd59df9df1ace166827", + "/workspace/research/selected-stability-midpoint1/candidate/package/model.pt": "e01ae99a458b5d8d2aba968e1efc663b3d346220fd16b5498a3f91b5cf29626c", + "/workspace/research/selected-stability-midpoint1/candidate/package/config.json": "162a2f4985944bba7492854315bd594fd3a38386548ab1c6b0c7a4f0d2bd7625", + "/workspace/research/selected-stability-midpoint1/candidate/package/unified.py": "bb00abef5853bc8badfef6a8d38ef8cb11f0ff6d9fe143eb7deebd582058efa3", + "/workspace/research/selected-stability-midpoint1/candidate/package/esm2.py": "d4d512296047ebbd0f9a26dc1390107f72762cb5de011eefc9fecb18118a9be9", + "/workspace/research/selected-stability-midpoint1/candidate/package/replay.py": "9c5add2d3fb117470241cf63f621e4797a16962cddadbaad6de2cfb481e7fa85", + "/workspace/research/selected-stability-midpoint1/candidate/package/infer.sh": "60f55b73f5b39a35a61df84026abed9a127b1cc035d650c9e1ca62f54fc2b468", + "/workspace/research/rank-target-fluorescence1/candidate/package/model.pt": "a13dad3c4f0cd7a1917d5b6763b27aaf3d38f3b7d775e747b61241ea36b681e0", + "/workspace/research/rank-target-fluorescence1/candidate/package/config.json": "e3da1d0ea2df3e6d6cc8b069016bffca2a37fd05accf1597cc6453f946d8fd89", + "/workspace/research/rank-target-functions2/features-stability/stability-fit.pt": "3fde47645a74370a003dd5f509a73ccecbaaac36ce4e8871938979a003ba3862", + "/workspace/research/rank-target-functions2/features-stability/stability-tune.pt": "92066e0c8abfcfc4ac3b8f2c7edcc4319cb8f8b4b97b53dd6e589147a1c460bf" + } + }, + "fit_outcome": { + "utc": "2026-10-25T16:08:53.918703+00:00", + "status": "cached_analysis_complete", + "arms": { + "natural": { + "arm": "natural", + "endpoint_reward": 0.7291215996959544, + "raw_reward_descriptive_only": 0.72991937369715, + "step": 1680, + "active_seconds": 5.326252081984421, + "final_numpy_rng": { + "bit_generator": "PCG64", + "state": { + "state": 264542032468656517169208881192101401107, + "inc": 100251262600960163324587047460976422035 + }, + "has_uint32": 1, + "uinteger": 637011686 + }, + "final_torch_rng_sha256": "fd56e05488c9ae31e940c2b1d859f13ca90497826206c0e3602aaba9c339ef52", + "optimizer_steps": [ + 1680.0 + ], + "lr": 1.0000078679859099e-05, + "fixed_buffers_exact": true + }, + "balanced": { + "arm": "balanced", + "endpoint_reward": 0.7311607642876724, + "raw_reward_descriptive_only": 0.7330130871638806, + "step": 1680, + "active_seconds": 5.340115340979537, + "final_numpy_rng": { + "bit_generator": "PCG64", + "state": { + "state": 264542032468656517169208881192101401107, + "inc": 100251262600960163324587047460976422035 + }, + "has_uint32": 1, + "uinteger": 637011686 + }, + "final_torch_rng_sha256": "fd56e05488c9ae31e940c2b1d859f13ca90497826206c0e3602aaba9c339ef52", + "optimizer_steps": [ + 1680.0 + ], + "lr": 1.0000078679859099e-05, + "fixed_buffers_exact": true + } + }, + "comparisons": { + "natural_vs_parent": { + "delta": 0.001629184810583273, + "conditional_95": [ + 0.00024683637661263025, + 0.003237432482155497 + ] + }, + "balanced_vs_parent": { + "delta": 0.0036683494023013186, + "conditional_95": [ + 0.0019018632266723152, + 0.0054815225624275 + ] + }, + "balanced_vs_natural": { + "delta": 0.0020391645917180456, + "conditional_95": [ + 0.0012832147204794586, + 0.0028118185483942955 + ] + } + }, + "eligible_arms": [ + "natural", + "balanced" + ], + "published": false, + "GPU_used": false, + "candidate_exported": false, + "matched_order_dropout_optimizer_clocks": true, + "ten_other_tasks": "No state edited; any proposed export must keep their parameters/configuration exact and independently replay all eleven.", + "limitations": "Conditional example bootstrap after repeated tune inspection; family dependence and selection uncertainty omitted. Tune length distribution informed this hypothesis. Raw endpoints are descriptive only. No full-pool or test-time fitting." + }, + "changed_tensors": [ + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.linear.weight", + "heads.stability.3.linear.bias" + ], + "all_other_tensors_and_buffers_exact": true, + "method": "One fixed final balanced-length continuation midpoint; no output averaging or test-time fitting." + }, + "auxiliary_package": "/workspace/research/scale85m-8h-rank3/candidate/package", + "auxiliary_sha256": "e601068c8d9b9a81934404866cea95d69950eb161fe8be0c6dec04bbca36d7db", + "auxiliary_provenance": { + "method": "Fixed rank-target readout transfer within one tensor-identical shared backbone", + "parent": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/candidate/package", + "parent_provenance": { + "method": "Consolidated task readouts with tensor-identical jointly learned shared components; one literal parameter set", + "shared_parameter_digest": "397be7af196fb356e544d391fbcdc9928f0ea6e4cfd66ab6ea4a4e4c656770bc", + "head_sources": { + "fluorescence": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-fluorescence/package", + "stability": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-stability/package", + "beta_lactamase": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-beta_lactamase/package", + "solubility": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-solubility/package", + "subcellular_localization": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-subcellular_localization/package", + "binary_localization": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "fold": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-fold/package", + "secondary_structure": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-secondary_structure/package", + "yeast_ppi": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-yeast_ppi/package", + "human_ppi": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "ppi_affinity": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-ppi_affinity/package" + }, + "parent_provenance": [ + { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "beta_lactamase", + "readout_kind": "residue", + "bins": 320, + "ridge": 1.0, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cuda", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "fluorescence", + "readout_kind": "residue", + "bins": 256, + "ridge": 1.0, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cuda", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "fold", + "readout_kind": "summary", + "bins": null, + "ridge": 0.0001, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.5, + "training_device": "cuda", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "ppi_affinity", + "readout_kind": "pair_symmetric", + "bins": null, + "ridge": 0.01, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random linear local readout on same joint residue states; fit-only fixed normalization and sampled fit residue labels; ridge cross entropy LBFGS", + "seed": 20261103, + "fit_residues_including_window_duplicates": 505584, + "kernel": 9, + "ridge": 0.01, + "retained_learned_nonlinear_prefix": true, + "training_device": "cuda", + "tune_policy": "fixed supplied strengths or default three strengths; full valid-residue accuracy with overlapping-window probability aggregation", + "tested_ridges": [ + 0.01 + ], + "feature_cache_exported": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "solubility", + "readout_kind": "summary", + "bins": null, + "ridge": 0.1, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Retained joint pair nonlinear prefix; random final layer fit using fixed fit normalization and regularized LBFGS", + "seed": 20261107, + "selected_ridges": { + "stability": 0.001 + }, + "tested_ridges": [ + 0.001 + ], + "tune_policy": "fixed supplied strengths or default five strengths; small tune sets limit confidence", + "feature_cache_exported": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "subcellular_localization", + "readout_kind": "summary", + "bins": null, + "ridge": 0.01, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "yeast_ppi", + "readout_kind": "pair_symmetric", + "bins": null, + "ridge": 0.01, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + } + ], + "feature_cache_exported": false, + "pair_context_selection": { + "policy": "One fixed1536-token alternative versus the current context, chosen on tune with all learned tensors frozen.", + "choice_basis": "Earlier fit-only chain-length audit; human and yeast fit maxima1500/1495residues.", + "choices": { + "human_ppi": { + "original_tokens": 1024, + "selected_tokens": 1024, + "metrics_by_context": { + "1024": { + "accuracy": 0.819047619047619, + "balanced_accuracy": 0.8180272108843538, + "macro_f1": 0.8181606424889357, + "reward": 0.819047619047619 + }, + "1536": { + "accuracy": 0.819047619047619, + "balanced_accuracy": 0.8171768707482994, + "macro_f1": 0.817806370435012, + "reward": 0.819047619047619 + } + } + }, + "yeast_ppi": { + "original_tokens": 1024, + "selected_tokens": 1024, + "metrics_by_context": { + "1024": { + "accuracy": 0.5894736842105263, + "balanced_accuracy": 0.570054945054945, + "macro_f1": 0.5704347826086956, + "reward": 0.5894736842105263 + }, + "1536": { + "accuracy": 0.5789473684210527, + "balanced_accuracy": 0.5611263736263736, + "macro_f1": 0.5614035087719298, + "reward": 0.5789473684210527 + } + } + } + }, + "learned_parameter_updates": 0 + } + }, + "rank_head_sources": { + "fluorescence": "/workspace/research/scale85m-8h-rank3/head-fluorescence/package", + "beta_lactamase": "/workspace/research/scale85m-8h-rank3/head-beta_lactamase/package", + "stability": "/workspace/research/scale85m-8h-rank3/head-stability/package" + }, + "head_seeds": { + "fluorescence": 20261031, + "beta_lactamase": 20261031, + "stability": 20261107 + }, + "ridges": { + "fluorescence": 1.0, + "beta_lactamase": 1.0, + "stability": 0.001 + }, + "fit_only_feature_statistics_and_rank_targets": true, + "all_other_tensors_exact": true, + "feature_cache_exported": false + }, + "readout_evidence": { + "subcellular_localization": { + "plan": { + "created_utc": "2026-10-25T16:59:37.548696+00:00", + "status": "queued", + "recovery_registered": true, + "run": "/workspace/research/dual-summary-subcellular1", + "task": "subcellular_localization", + "feature_checks": "/workspace/research/dual-summary-feature-checks.json", + "features": { + "primary": "/workspace/research/conditioned-readout-refit1/features-summary/subcellular_localization", + "auxiliary": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/features-summary/subcellular_localization" + }, + "parent_package": "/workspace/research/selected-stability-lengthweight1-replay/candidate/package", + "auxiliary_package": "/workspace/research/scale85m-8h-rank3/candidate/package", + "parent_predictions": "/workspace/research/selected-stability-lengthweight1-replay/candidate/replay/predictions/subcellular_localization.jsonl", + "frozen_sha256": { + "/workspace/research/dual-summary-feature-checks.json": "c0f3988785747df6360d12eb7d1cfba267f5f80679868fd6f710bde1f803a25f", + "/workspace/research/run_dual_summary_classification_cpu.py": "a8905391b3818364147fc48cc2484aae686a455587ee1d636dae2271abf20474", + "/workspace/research/conditioned-readout-refit1/features-summary/subcellular_localization/fit.pt": "38804fc2d842fa28203cd729e62ebd86ff4acb716cf5ee9e130134a9effdc229", + "/workspace/research/conditioned-readout-refit1/features-summary/subcellular_localization/tune.pt": "8e8a05d1e0553bd24a4915ee88bdc17ee050adc57e989a86874b4de12395a3ec", + "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/features-summary/subcellular_localization/fit.pt": "5da5817b413a8c3ab1aaad18f2e888015c2807f1dcb02336bd249031272df6aa", + "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/features-summary/subcellular_localization/tune.pt": "e7c213d642afefdcd0a7c329f6628bdda9fd34367750d1e2fe015ac4fc317143" + }, + "recovery_command": [ + "env", + "CUDA_VISIBLE_DEVICES=", + "OMP_NUM_THREADS=4", + "MKL_NUM_THREADS=4", + "OPENBLAS_NUM_THREADS=1", + "/opt/conda/bin/python3", + "-u", + "/workspace/research/run_dual_summary_classification_cpu.py", + "--run", + "/workspace/research/dual-summary-subcellular1" + ], + "hypothesis": "Apply the same dual-summary representation comparison to a classification task whose two native encoders make complementary errors. All11 tasks retain one shared primary backbone; any enabled auxiliary routes also share exactly the same auxiliary encoder state. Task-specific readout heads are allowed; no separate task encoder is fitted.", + "recipe": { + "seed": 20270207, + "arms": [ + "primary", + "auxiliary", + "full" + ], + "same_initial_linear_state": true, + "normalization": "fit-only per-feature mean/std floor1e-5; same-width controls zero the inactive normalized block", + "ridge": 0.01, + "class_weights": null, + "optimizer": "FP32CPU LBFGS lr1,strong_wolfe,history30,tolerance_grad1e-6;15 resumable blocks max10iterations/max50evaluations each", + "selection": "Only final15block head; no grid/earlier checkpoint selection" + }, + "eligibility": "Full gains>.005overfit-onlyparent and paired1000drawconditional95lower>0, fullpointbeatsbothmatchedcontrols, primaryfeaturezeroingdrop>=.02. Then standalonearchitecture/all11native/dependence review. Noautoexport/publication.", + "limitations": "One recipe/seed; repeated tune selection, family dependence, CPU/chunkedoptimizer differences and masked-control L2 effects. Ablation is a dependence diagnostic.", + "queued_utc": "2026-10-25T16:59:38.013790+00:00" + }, + "result": { + "utc": "2026-10-25T17:00:11.081483+00:00", + "status": "eligible_for_shared_architecture_native_review", + "task": "subcellular_localization", + "ridge": 0.01, + "results": { + "primary": { + "accuracy": 0.7513340448239061, + "blocks": 15, + "active_seconds": 10.906512092013145, + "LBFGS_iterations": 150, + "closure_evaluations": 174, + "primary_zeroed_accuracy": 0.28779793667733905, + "auxiliary_zeroed_accuracy": 0.7513340448239061 + }, + "auxiliary": { + "accuracy": 0.7776591960156528, + "blocks": 15, + "active_seconds": 7.2808296459843405, + "LBFGS_iterations": 150, + "closure_evaluations": 178, + "primary_zeroed_accuracy": 0.7776591960156528, + "auxiliary_zeroed_accuracy": 0.28779793667733905 + }, + "full": { + "accuracy": 0.7908217716115261, + "blocks": 15, + "active_seconds": 6.470482572942274, + "LBFGS_iterations": 150, + "closure_evaluations": 173, + "primary_zeroed_accuracy": 0.736392742796158, + "auxiliary_zeroed_accuracy": 0.5990750622554251 + } + }, + "comparisons": { + "full_minus_parent": { + "delta": 0.036997509782995375, + "conditional95": [ + 0.024181785841337605, + 0.05052472429740305 + ] + }, + "full_minus_primary": { + "delta": 0.03948772678762007, + "conditional95": [ + 0.026680896478121666, + 0.05407328352899324 + ] + }, + "full_minus_auxiliary": { + "delta": 0.013162575595873355, + "conditional95": [ + 0.002845962290999644, + 0.022767698327997153 + ] + } + }, + "eligible": true, + "GPU_used": false, + "published": false, + "limitations": "One fixed fit-only readout recipe. CPU float32 versus earlier CUDA references may differ. Repeated tune selection; conditional intervals ignore family dependence. Zeroing normalized primary features is a dependence diagnostic, not an in-distribution intervention. Full native architecture and all11 review required." + } + } + }, + "all_nonchanged_primary_tensors_exact": true, + "auxiliary_encoder_copies": 1, + "only_active_auxiliary_pool_rows_included": true, + "external_weights_used": false, + "disposable_check_weights_used": false, + "training_feature_caches_included": false, + "previous_production": { + "utc": "2026-10-25T16:19:32.935143+00:00", + "package": "/workspace/research/production-stability-lengthweight-fullpool1/candidate/package", + "score_kind": "tune_labels_used_for_fold_fluorescence_beta_lactamase_ppi_affinity_and_stability", + "model_sha256": "a6d4bcb459500aa1b7e624c447156560d5343a5e6edbf2d7d1708f4f8d7871c1", + "inference_assets_sha256": { + "model.pt": "a6d4bcb459500aa1b7e624c447156560d5343a5e6edbf2d7d1708f4f8d7871c1", + "config.json": "162a2f4985944bba7492854315bd594fd3a38386548ab1c6b0c7a4f0d2bd7625", + "esm2.py": "d4d512296047ebbd0f9a26dc1390107f72762cb5de011eefc9fecb18118a9be9", + "unified.py": "bb00abef5853bc8badfef6a8d38ef8cb11f0ff6d9fe143eb7deebd582058efa3", + "replay.py": "9c5add2d3fb117470241cf63f621e4797a16962cddadbaad6de2cfb481e7fa85", + "infer.sh": "60f55b73f5b39a35a61df84026abed9a127b1cc035d650c9e1ca62f54fc2b468" + }, + "parameters": 53000306, + "fit_only_development_reference": { + "package": "/workspace/research/selected-stability-lengthweight1-replay/candidate/package", + "report": "/workspace/research/selected-stability-lengthweight1-replay/candidate/report.json", + "reward": 0.7166638090200526, + "model_sha256": "d581e2aad1c8ea712968423348ff2c540352c7d9ad2b36a46e795a1f4d31b73b" + }, + "recipe_selection_evidence": { + "kind": "two_fold_added_label_pilot_not_fullpool_model_replay", + "fold_accuracy": 0.26902173913043476, + "parent_fold_accuracy": 0.24864130434782608, + "matched_fit_only_refit_accuracy": 0.23505434782608695, + "fold_delta": 0.020380434782608696, + "conditional_fold_delta95": [ + 0.001358695652173913, + 0.04076086956521739 + ], + "heldout_half_case_gains": [ + 4, + 11 + ], + "other_ten_tasks": "Unchanged parent weights; full production replay must verify byte-identical predictions.", + "limitations": "Prior tune checkpoint/hyperparameter selection biases thisestimate. Halvesarestratifiedbylabel,notproteinfamily. Crossfitestimatestherecipewithhalftheaddedlabels,notafinalfull-poolmodel. Pairedbootstrapisconditionalanddoesnotcorrectalldependence." + }, + "in_sample_verification_report": "/workspace/research/production-stability-lengthweight-fullpool1/candidate/report.json", + "verification": { + "all_eleven_outputs_valid": true, + "other_ten_predictions_byte_identical_to_previous_production": true, + "tune_rows_used_for_fitting": { + "fold": 736, + "fluorescence": 5362, + "beta_lactamase": 520, + "ppi_affinity": 203, + "stability": 2512 + }, + "in_sample_scores_of_reused_label_tasks_excluded_from_selection": true, + "ss_predictions_exact_accepted_fit_only_development": true, + "stability_native_replay_valid_in_sample": true + }, + "training": "Own-session random-initialized shared all-eleven lineage. Stability now uses the fixed balanced-length whole-head recipe on53614fit+2512Tune labels after positive two-halfcrossfit evidence;1680updates from originalownhead and a fixed50:50parameter midpoint. Six learnedheadtensorschanged, all otherproductionstate/configexact.", + "ss_fit_only_selection_evidence": { + "kind": "fit_only_tune_complete_replay", + "task": "secondary_structure", + "before": 0.7438318211771296, + "after": 0.7441316787896526, + "delta": 0.00029985761252291574, + "conditional_95_percentile_interval": [ + 4.102067509503305e-05, + 0.0005682928659789181 + ], + "examples": 2170, + "valid_residues": 556931, + "correct_residue_gain": 167, + "method": "own-session teacher distillation", + "teacher": "Own85M2hMLM+jointall11+taskconditioning; fit-onlylabels; no teacher exported", + "matched_controls": { + "hard": { + "delta": 0.0006984707261761331, + "conditional95": [ + 0.00020130648256647902, + 0.001201981603808556 + ], + "protein_units": 2170, + "valid_residues": 556931, + "draws": 2000, + "limitations": "Conditional paired protein bootstrap, not corrected for repeated tune selection or protein-family dependence." + }, + "smooth": { + "delta": 0.00027112873946682803, + "conditional95": [ + -0.00019057496656699647, + 0.0007187128477994618 + ], + "protein_units": 2170, + "valid_residues": 556931, + "draws": 2000, + "limitations": "Conditional paired protein bootstrap, not corrected for repeated tune selection or protein-family dependence." + } + }, + "other_ten_development_predictions_byte_identical": true, + "limitations": "Conditional paired protein bootstrap, not corrected for repeated tune selection or protein-family dependence. Teacher-versus-smoothing64 interval crosseszero.", + "selected_distillation_epoch": 64, + "distillation_updates": 9152, + "additional_updates_after16": 6864 + }, + "previous_production_package": "/workspace/research/production-stability-lengthweight1/candidate/package", + "tasks_reusing_tune_labels": [ + "fold", + "fluorescence", + "beta_lactamase", + "ppi_affinity", + "stability" + ], + "fluorescence_recipe_selection_evidence": { + "incumbent_spearman": 0.826705913429907, + "matched_fit_only_refit_spearman": 0.8267059285858314, + "crossfit_spearman": 0.8289887921828193, + "crossfit_delta_vs_incumbent": 0.0022828787529123318, + "crossfit_delta_vs_fit_only_refit": 0.0022828635969879274, + "conditional_paired_95_vs_incumbent": [ + 0.0009792262424118709, + 0.0036331746186231443 + ], + "fold_results": [ + { + "heldout_half": 0, + "heldout_rows": 2681, + "added_tune_rows": 2681, + "training_rows": 24127, + "heldout_spearman": 0.8232686916324296, + "incumbent_same_half_spearman": 0.8211575283985865, + "fit_seconds": 1.7692138720012736, + "closures": 160 + }, + { + "heldout_half": 1, + "heldout_rows": 2681, + "added_tune_rows": 2681, + "training_rows": 24127, + "heldout_spearman": 0.8349378336333676, + "incumbent_same_half_spearman": 0.8324217270853131, + "fit_seconds": 1.6950949229940306, + "closures": 160 + } + ], + "limitations": "Prior tune model selection biases the estimate. Label stratification is not a protein-family split, and unseen test distribution may differ. Combined OOF scores come from two heads with training-only rank normalization, not one full-pool model. Conditional paired bootstrap ignores remaining family dependence and selection." + }, + "beta_lactamase_recipe_selection_evidence": { + "incumbent_spearman": 0.8851158090618965, + "matched_fit_only_refit_spearman": 0.8851173641514167, + "crossfit_spearman": 0.8939613181865891, + "crossfit_delta_vs_incumbent": 0.008845509124692619, + "crossfit_delta_vs_fit_only_refit": 0.008843954035172352, + "conditional_paired_95_vs_incumbent": [ + 0.0030908473904126045, + 0.016275743694867638 + ], + "fold_results": [ + { + "heldout_half": 0, + "heldout_rows": 260, + "added_tune_rows": 260, + "training_rows": 4418, + "heldout_spearman": 0.8954806478975963, + "incumbent_same_half_spearman": 0.8876831699844637, + "fit_seconds": 0.7535757489968091, + "closures": 163 + }, + { + "heldout_half": 1, + "heldout_rows": 260, + "added_tune_rows": 260, + "training_rows": 4418, + "heldout_spearman": 0.8906708928087468, + "incumbent_same_half_spearman": 0.8805064277745905, + "fit_seconds": 0.7396053560078144, + "closures": 161 + } + ], + "limitations": "Prior tune model selection biases the estimate. Label stratification is not a protein-family split, and unseen test distribution may differ. Combined OOF scores come from two heads with training-only rank normalization, not one full-pool model. Conditional paired bootstrap ignores remaining family dependence and selection." + }, + "ppi_affinity_recipe_selection_evidence": { + "status": "research_only_crossfit_complete", + "task": "ppi_affinity", + "incumbent_reward": 0.5341420012716276, + "matched_fit_only_reward": 0.5210555476068024, + "crossfit_reward": 0.5515877648877663, + "crossfit_delta_vs_incumbent": 0.0174457636161387, + "conditional_paired_95_vs_incumbent": [ + 0.002641673708393072, + 0.0303974991382099 + ], + "fold_results": [ + { + "heldout_half": 0, + "heldout_rows": 102, + "added_tune_rows": 101, + "reward": 0.5641044100756688, + "incumbent_reward": 0.5459868174958554, + "closures": 166, + "seconds": 0.1286191190010868 + }, + { + "heldout_half": 1, + "heldout_rows": 101, + "added_tune_rows": 102, + "reward": 0.5396756511271861, + "incumbent_reward": 0.522833934532602, + "closures": 163, + "seconds": 0.12902537698391825 + } + ], + "published": false, + "exported": false, + "limitations": "Tune influenced earlier backbone/head selection. Pair-example resampling does not establish protein or family independence. OOF heads are research evidence only, not a single replayable model.", + "publication": "Research-only out-of-fold evidence; no full-pool head, lookup or package is exported." + }, + "shared_summary_fit_only_evidence": { + "kind": "complete_fit_only_tune_replay", + "selected_global_step": 3000, + "jointly_trained_tasks": [ + "solubility", + "subcellular_localization", + "binary_localization" + ], + "parameters_added": 475906, + "tasks": { + "binary_localization": { + "before": 0.9375361480624639, + "after": 0.9462116830537883, + "delta": 0.008675534991324466, + "case_gain": 15, + "conditional95": [ + 0.002891844997108155, + 0.015037593984962405 + ], + "examples": 1729, + "limitations": "Conditional paired-example bootstrap; not corrected for repeated tune selection or family dependence." + } + }, + "other_ten_development_prediction_files_exact": true, + "limitations": "Conditional paired-example bootstrap does not correct repeated tune selection or family dependence. Only binary localization passes the predeclared exit gate." + }, + "stability_fit_only_selection_evidence": { + "kind": "fit_only_complete_tune_replay", + "task": "stability", + "before": 0.7274923808177973, + "after": 0.7311607642876724, + "delta": 0.0036683834698750806, + "conditional_95_percentile_interval": [ + 0.0017767471141417273, + 0.00544199745819068 + ], + "examples": 2512, + "mean_delta": 0.0003334894063522801, + "conditional_mean95": [ + 0.0001615224649219752, + 0.0004947270416536983 + ], + "matched_natural_mixture_control": { + "delta": 0.0020391645917180456, + "conditional_95": [ + 0.0012832147204794586, + 0.0028118185483942955 + ] + }, + "fixed_endpoint_updates": 1680, + "alpha": 0.5, + "ten_other_prediction_files_exact": true, + "limitations": "Conditional on already-selected models. Does not account for repeated tune selection, shared proteins across tasks, or family dependence within splits; not an independent generalization guarantee. The visible Tune length distribution informed the group-weighting hypothesis." + }, + "stability_extra_label_recipe_selection_evidence": { + "utc": "2026-10-25T16:17:04.539090+00:00", + "status": "research_only_crossfit_complete", + "scores": { + "incumbent": 0.7311607642876724, + "matched_fit_only": 0.7311607642876724, + "crossfit": 0.7337159019671029 + }, + "comparisons": { + "incumbent": { + "delta": 0.002555137679430497, + "conditional_95": [ + 0.0015641029747572976, + 0.0036431410475218527 + ] + }, + "matched_fit_only": { + "delta": 0.002555137679430497, + "conditional_95": [ + 0.0015641029747572976, + 0.0036431410475218527 + ] + } + }, + "fold_results": [ + { + "heldout_half": 0, + "heldout_rows": 1256, + "incumbent_same_half": 0.7325449010474826, + "matched_control_same_half": 0.7325449010474826, + "crossfit_same_half": 0.7351256285381212, + "step": 1680, + "epochs_started": 16, + "active_seconds": 7.389840035961242, + "training_rows": 54870, + "added_tune_rows": 1256, + "fixed_buffers_exact": true, + "group_counts": { + "43": 36446, + "50": 18424 + }, + "final_lr": 1.0000078679859099e-05 + }, + { + "heldout_half": 1, + "heldout_rows": 1256, + "incumbent_same_half": 0.7298113878884595, + "matched_control_same_half": 0.7298113878884595, + "crossfit_same_half": 0.7327158507790285, + "step": 1680, + "epochs_started": 16, + "active_seconds": 7.374784096988151, + "training_rows": 54870, + "added_tune_rows": 1256, + "fixed_buffers_exact": true, + "group_counts": { + "43": 36446, + "50": 18424 + }, + "final_lr": 1.0000078679859099e-05 + } + ], + "passes_predeclared_fullpool_gate": true, + "fit_only_reproduction_all_head_tensors_bit_exact": true, + "updates_per_arm": 1680, + "published": false, + "fullpool_head_fitted": false, + "candidate_exported": false, + "GPU_used": false, + "limitations": "Earlier Tune checkpoint/architecture selection biases estimates. Fixed label-stratified halves do not enforce protein-family or designed-scaffold independence. OOF predicts with two research heads trained on half the extra labels; it is recipe evidence, not a single final model measurement. Conditional bootstrap omits family dependence and prior selection." + } + }, + "production_merge": "All existing production tensors except the subcellular head are preserved bit-for-bit. One own-session auxiliary encoder and its active pool row are shared with the new development architecture. No fitting occurs in assembly.", + "common_feature_state_and_config_exact": true, + "retained_extra_label_heads": [ + "beta_lactamase", + "fluorescence", + "fold", + "ppi_affinity", + "stability" + ], + "native_selection_evidence": { + "kind": "fit_only_complete_native_tune_replay", + "task": "subcellular_localization", + "before": 0.7538242618285308, + "after": 0.7908217716115261, + "delta": 0.03699750978299532, + "conditional95": [ + 0.024181785841337605, + 0.05052472429740305 + ], + "mean_delta": 0.0033634099802724027, + "conditional_mean95": [ + 0.0021983441673943276, + 0.004593156754309368 + ], + "case_gain": 104, + "examples": 2811, + "matched_controls": { + "full_minus_parent": { + "delta": 0.036997509782995375, + "conditional95": [ + 0.024181785841337605, + 0.05052472429740305 + ] + }, + "full_minus_primary": { + "delta": 0.03948772678762007, + "conditional95": [ + 0.026680896478121666, + 0.05407328352899324 + ] + }, + "full_minus_auxiliary": { + "delta": 0.013162575595873355, + "conditional95": [ + 0.002845962290999644, + 0.022767698327997153 + ] + } + }, + "native_dependency": { + "native_accuracy": 0.7908217716115261, + "normal_replay_bit_exact": true, + "primary_ablated": { + "accuracy": 0.736392742796158, + "accuracy_drop": 0.054429028815368194, + "conditional95_drop": [ + 0.04054606901458555, + 0.06794734969761651 + ], + "prediction_changes": 464 + }, + "auxiliary_ablated": { + "accuracy": 0.5990750622554251, + "accuracy_drop": 0.19174670935610102, + "conditional95_drop": [ + 0.17467093561010316, + 0.20988971896122377 + ], + "prediction_changes": 899 + } + }, + "task_deltas": { + "beta_lactamase": 0.0, + "binary_localization": 0.0, + "fluorescence": 0.0, + "fold": 0.0, + "human_ppi": 0.0, + "ppi_affinity": 0.0, + "secondary_structure": 0.0, + "solubility": 0.0, + "stability": 0.0, + "subcellular_localization": 0.03699750978299532, + "yeast_ppi": 0.0 + }, + "ten_other_prediction_files_byte_exact": true, + "limitations": "Conditional paired-example bootstrap after repeated Tune selection; not corrected for protein-family dependence. Feature removal is a dependence diagnostic, not an in-distribution intervention." + } + }, + "fusion_source": "/workspace/research/shared-fusion8h-study1/full/final-ema/package", + "fusion_source_sha256": "8c6f6e7d334d4668a2a6692aa49ab320447b194f6fb4dae66e4859e1171886cb", + "fusion_provenance": { + "method": "One shared residue fusion trained jointly on all11fit tasks; all original tensors frozen.", + "training_provenance": { + "seed": 20270204, + "created_utc": "2026-10-25T17:20:42Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/shared-fusion8h-study1/source/model.pt", + "arguments": { + "run": "/workspace/research/shared-fusion8h-study1/full", + "init": "/workspace/research/shared-fusion8h-study1/source/model.pt", + "resume": null, + "config": "/workspace/research/shared-fusion8h-study1/full/config.json", + "seconds": 1000000000.0, + "max_steps": 4000, + "eval_seconds": 240, + "evaluate_initial": false, + "lr": 0.0001, + "schedule_seconds": 1000000000.0, + "schedule_steps": 4000, + "eval_steps": "4000", + "structure_distillation_cache": null, + "head_lr": 0.0001, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20270204, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 0.0, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "shared_adapter_only": false, + "shared_fusion_only": true, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "e2a420839c9315dbb80570b137568143361ecde29e36921a1539a99a7cda8152", + "transfer": { + "transferred": 521, + "new_tensors": [], + "unexpected": [] + }, + "parent_provenance": null, + "parent_training": {}, + "provenance.json": { + "utc": "2026-10-25T16:36:47.086545+00:00", + "fusion_initialization_seed": 20270204, + "primary_package": "/workspace/research/selected-stability-lengthweight1-replay/candidate/package", + "primary_sha256": "d581e2aad1c8ea712968423348ff2c540352c7d9ad2b36a46e795a1f4d31b73b", + "auxiliary_package": "/workspace/research/scale85m-8h-rank3/candidate/package", + "auxiliary_sha256": "e601068c8d9b9a81934404866cea95d69950eb161fe8be0c6dec04bbca36d7db", + "primary_provenance": { + "parent_package": "/workspace/research/selected-stability-midpoint1/candidate/package", + "parent_sha256": "e01ae99a458b5d8d2aba968e1efc663b3d346220fd16b5498a3f91b5cf29626c", + "parent_provenance": { + "method": "One fixed 50:50 parameter midpoint of parent and fit-only 16-epoch stability head continuation; no ensemble.", + "source_parent": "/workspace/research/shared-summary-residual1/candidate/package", + "source_candidate": "/workspace/research/selected-stability-head64/candidate/package", + "source_model_sha256": { + "/workspace/research/shared-summary-residual1/candidate/package": "f890eebb10bb2dc08b84c28e7e0378960af5df4fb0d646ab2e8b33e130c74202", + "/workspace/research/selected-stability-head64/candidate/package": "8fe80a673a65650bb5769b1cf75a59f10a65961da91cc62a491094f874042c79" + }, + "parent_provenance": { + "method": "One jointly learned nonlinear residual map over frozen shared sequence summaries, with task-specific zero-initialized outputs.", + "fit_tasks": [ + "solubility", + "subcellular_localization", + "binary_localization" + ], + "selected_tasks": [ + "binary_localization" + ], + "selected_global_step": 3000, + "source": "/workspace/research/ss-distillation-continuation1/candidate/package", + "export_base": "/workspace/research/ss-distillation-continuation1/candidate/package", + "export_base_model_sha256": "4fee0a0154af24665de9a95f11a722017f3fa6d92354475bec8e81235a219f00", + "rebased_SS_tensors": [], + "seed": 20270102, + "steps": 6000, + "lr": 0.001, + "weight_decay": 0.01, + "dropout": 0.2, + "data": "Fit only for gradients and existing normalization; Tune chooses oneglobalcheckpoint andresidualexits usingpredeclaredconditionalCIgate.", + "original_parameters_exact": true, + "parameters": 53000306, + "encoder_parameters": 44150303, + "feature_cache_exported": false + }, + "fit_recipe": { + "seed": 20270129, + "epochs": 64, + "evaluate_epochs": [ + 4, + 16, + 32, + 64 + ], + "batch_size": 512, + "lr": 0.0001, + "weight_decay": 0.01, + "loss": "MSE to original fit-standardized stabilitylabels, matching selectedmodeltarget semantics;clip1;originaldropout active inbotharms;fixednormalizationbuffers. No newranktargetchange.", + "optimizer": "FreshCPUAdamW,cosine64epochs to0.1floor; matcheddataorder/dropoutRNG/updatecounts; per-epochatomicresume." + }, + "source_selected_epoch": 16, + "diagnostic": { + "utc": "2026-10-25T13:39:33.197851+00:00", + "status": "CPU_diagnostic_complete_no_export", + "alpha": 0.5, + "points": { + "parent": 0.7226969980994319, + "midpoint": 0.7274924148853711, + "whole": 0.7274598466634085 + }, + "midpoint_delta_vs_parent": 0.004795416785939199, + "conditional95": [ + 0.0017412267324550784, + 0.007940572842815559 + ], + "draws": 1000, + "seed": 20270130, + "parameters": 53000306, + "six_changed_learned_tensors": [ + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.linear.weight", + "heads.stability.3.linear.bias" + ], + "all_other_tensors_and_buffers_exact": true, + "eligible_for_manual_complete_replay": true, + "publication": false, + "GPU_used": false, + "limitations": "Singlepredeclaredparameter midpoint, notpredictionensemble. Conditionalrowbootstrapuncorrectedforpriorcheckpointselectionandfamilydependence. CPUdiagnosticisnotan11taskreplay.", + "source_sha256": { + "/workspace/research/check_selected_stability_midpoint.py": "13615a5b2689a0bd503cbc8a9a8a722014962677f6769cec871e13aa5133ff77", + "/workspace/research/shared-summary-residual1/candidate/package/model.pt": "f890eebb10bb2dc08b84c28e7e0378960af5df4fb0d646ab2e8b33e130c74202", + "/workspace/research/selected-stability-head64/candidate/package/model.pt": "8fe80a673a65650bb5769b1cf75a59f10a65961da91cc62a491094f874042c79" + } + }, + "data": "Fit-only labels and fixed normalization; tune selects epoch and evaluates one predeclared midpoint.", + "parameters": 53000306, + "feature_cache_exported": false + }, + "fit_plan": { + "utc": "2026-10-25T16:08:33.461759+00:00", + "status": "queued", + "CPU_only": true, + "recovery_registered": false, + "source_package": "/workspace/research/selected-stability-midpoint1/candidate/package", + "source_report": "/workspace/research/selected-stability-midpoint1/candidate/report.json", + "features": "/workspace/research/rank-target-functions2/features-stability", + "feature_producer": "/workspace/research/rank-target-fluorescence1/candidate/package", + "arms": [ + "natural", + "balanced" + ], + "expected_fit_lengths": [ + 43, + 50 + ], + "seed": 20270208, + "threads": 6, + "epochs": 16, + "batch_size": 512, + "lr": 0.0001, + "weight_decay": 0.01, + "alpha": 0.5, + "minimum_gain": 0.001, + "bootstrap_seed": 20270209, + "bootstrap_draws": 1000, + "hypothesis": "Natural stability fit data are68%43-residue proteins but all observed Tune chains have50residues. Equal loss mass for the two fit-length groups may reduce interference on the50-residue domain. This is a test prompted by visible Tune distribution, not evidence of benefit.", + "loss": "Original-fit-standardized-label MSE. Identical shuffled full-fit batches in both arms; natural unit weights; balanced weights N/(2*N_group), averaged over minibatch without per-batch renormalization. Both train all six existing head tensors, fixed feature-normalization buffers.", + "schedule": "FreshAdamW,16epochs/1680updates,cosine to0.1floor,clip1; originaldropoutactive with identical RNG and data order. Same current selected initial head.", + "selection": "Only one fixed50:50 parameter midpoint at the final16epoch endpoint per arm is eligible. Raw endpoints are descriptive. Require gain>=.001 and positive conditional95versus selected; balanced additionally requires positive conditional95versus natural control. No intermediate Tune selection, no seed/mixture grid. Manual review then full11 native replay before any publication.", + "all_task_policy": "Only six stabilityheadparameters may change. Shared encoder remains jointly learned for all11. All10otherparameters/config/outputfiles must remain exact on native replay. No automatic export or publication.", + "resume": "CPU per-epoch atomic optimizer/head/NumPy/torchRNG checkpoints; rerun same script after interruption. Planhash verified on resume.", + "recovery_command": [ + "env", + "CUDA_VISIBLE_DEVICES=", + "OMP_NUM_THREADS=6", + "MKL_NUM_THREADS=6", + "OPENBLAS_NUM_THREADS=1", + "python3", + "-u", + "/workspace/research/run_stability_length_weighting.py", + "--run", + "/workspace/research/selected-stability-lengthweight1" + ], + "frozen_sha256": { + "/workspace/research/run_stability_length_weighting.py": "3c5aac6a79a1397e5c50278a7635e32d7c3583438f64996c8a42a372d16a29f6", + "/workspace/research/check_shared_adapters_cpu.py": "db7d8d846b90929decad5865de36dd55fb95139aaa116b6ae2987cd96786c990", + "/workspace/research/crossfit_beta_labels.py": "bd1d29e2ab78cb0273213ef1a00657cef450a91f155ba7d9aa7f3db7721bd632", + "/workspace/research/stability-length-shift-diagnostic.json": "36a890f702bb6709e893c5f9d94c5cf15959f83f4a91d71e58a7b5f681065f6d", + "/workspace/research/selected-stability-midpoint1/candidate/report.json": "feedb171d285a4fa4d3c2a2bdd819873caaad1308ef90fd59df9df1ace166827", + "/workspace/research/selected-stability-midpoint1/candidate/package/model.pt": "e01ae99a458b5d8d2aba968e1efc663b3d346220fd16b5498a3f91b5cf29626c", + "/workspace/research/selected-stability-midpoint1/candidate/package/config.json": "162a2f4985944bba7492854315bd594fd3a38386548ab1c6b0c7a4f0d2bd7625", + "/workspace/research/selected-stability-midpoint1/candidate/package/unified.py": "bb00abef5853bc8badfef6a8d38ef8cb11f0ff6d9fe143eb7deebd582058efa3", + "/workspace/research/selected-stability-midpoint1/candidate/package/esm2.py": "d4d512296047ebbd0f9a26dc1390107f72762cb5de011eefc9fecb18118a9be9", + "/workspace/research/selected-stability-midpoint1/candidate/package/replay.py": "9c5add2d3fb117470241cf63f621e4797a16962cddadbaad6de2cfb481e7fa85", + "/workspace/research/selected-stability-midpoint1/candidate/package/infer.sh": "60f55b73f5b39a35a61df84026abed9a127b1cc035d650c9e1ca62f54fc2b468", + "/workspace/research/rank-target-fluorescence1/candidate/package/model.pt": "a13dad3c4f0cd7a1917d5b6763b27aaf3d38f3b7d775e747b61241ea36b681e0", + "/workspace/research/rank-target-fluorescence1/candidate/package/config.json": "e3da1d0ea2df3e6d6cc8b069016bffca2a37fd05accf1597cc6453f946d8fd89", + "/workspace/research/rank-target-functions2/features-stability/stability-fit.pt": "3fde47645a74370a003dd5f509a73ccecbaaac36ce4e8871938979a003ba3862", + "/workspace/research/rank-target-functions2/features-stability/stability-tune.pt": "92066e0c8abfcfc4ac3b8f2c7edcc4319cb8f8b4b97b53dd6e589147a1c460bf" + } + }, + "fit_outcome": { + "utc": "2026-10-25T16:08:53.918703+00:00", + "status": "cached_analysis_complete", + "arms": { + "natural": { + "arm": "natural", + "endpoint_reward": 0.7291215996959544, + "raw_reward_descriptive_only": 0.72991937369715, + "step": 1680, + "active_seconds": 5.326252081984421, + "final_numpy_rng": { + "bit_generator": "PCG64", + "state": { + "state": 264542032468656517169208881192101401107, + "inc": 100251262600960163324587047460976422035 + }, + "has_uint32": 1, + "uinteger": 637011686 + }, + "final_torch_rng_sha256": "fd56e05488c9ae31e940c2b1d859f13ca90497826206c0e3602aaba9c339ef52", + "optimizer_steps": [ + 1680.0 + ], + "lr": 1.0000078679859099e-05, + "fixed_buffers_exact": true + }, + "balanced": { + "arm": "balanced", + "endpoint_reward": 0.7311607642876724, + "raw_reward_descriptive_only": 0.7330130871638806, + "step": 1680, + "active_seconds": 5.340115340979537, + "final_numpy_rng": { + "bit_generator": "PCG64", + "state": { + "state": 264542032468656517169208881192101401107, + "inc": 100251262600960163324587047460976422035 + }, + "has_uint32": 1, + "uinteger": 637011686 + }, + "final_torch_rng_sha256": "fd56e05488c9ae31e940c2b1d859f13ca90497826206c0e3602aaba9c339ef52", + "optimizer_steps": [ + 1680.0 + ], + "lr": 1.0000078679859099e-05, + "fixed_buffers_exact": true + } + }, + "comparisons": { + "natural_vs_parent": { + "delta": 0.001629184810583273, + "conditional_95": [ + 0.00024683637661263025, + 0.003237432482155497 + ] + }, + "balanced_vs_parent": { + "delta": 0.0036683494023013186, + "conditional_95": [ + 0.0019018632266723152, + 0.0054815225624275 + ] + }, + "balanced_vs_natural": { + "delta": 0.0020391645917180456, + "conditional_95": [ + 0.0012832147204794586, + 0.0028118185483942955 + ] + } + }, + "eligible_arms": [ + "natural", + "balanced" + ], + "published": false, + "GPU_used": false, + "candidate_exported": false, + "matched_order_dropout_optimizer_clocks": true, + "ten_other_tasks": "No state edited; any proposed export must keep their parameters/configuration exact and independently replay all eleven.", + "limitations": "Conditional example bootstrap after repeated tune inspection; family dependence and selection uncertainty omitted. Tune length distribution informed this hypothesis. Raw endpoints are descriptive only. No full-pool or test-time fitting." + }, + "changed_tensors": [ + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.linear.weight", + "heads.stability.3.linear.bias" + ], + "all_other_tensors_and_buffers_exact": true, + "method": "One fixed final balanced-length continuation midpoint; no output averaging or test-time fitting." + }, + "auxiliary_provenance": { + "method": "Fixed rank-target readout transfer within one tensor-identical shared backbone", + "parent": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/candidate/package", + "parent_provenance": { + "method": "Consolidated task readouts with tensor-identical jointly learned shared components; one literal parameter set", + "shared_parameter_digest": "397be7af196fb356e544d391fbcdc9928f0ea6e4cfd66ab6ea4a4e4c656770bc", + "head_sources": { + "fluorescence": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-fluorescence/package", + "stability": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-stability/package", + "beta_lactamase": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-beta_lactamase/package", + "solubility": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-solubility/package", + "subcellular_localization": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-subcellular_localization/package", + "binary_localization": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "fold": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-fold/package", + "secondary_structure": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-secondary_structure/package", + "yeast_ppi": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-yeast_ppi/package", + "human_ppi": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "ppi_affinity": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-ppi_affinity/package" + }, + "parent_provenance": [ + { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "beta_lactamase", + "readout_kind": "residue", + "bins": 320, + "ridge": 1.0, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cuda", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "fluorescence", + "readout_kind": "residue", + "bins": 256, + "ridge": 1.0, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cuda", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "fold", + "readout_kind": "summary", + "bins": null, + "ridge": 0.0001, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.5, + "training_device": "cuda", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "ppi_affinity", + "readout_kind": "pair_symmetric", + "bins": null, + "ridge": 0.01, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random linear local readout on same joint residue states; fit-only fixed normalization and sampled fit residue labels; ridge cross entropy LBFGS", + "seed": 20261103, + "fit_residues_including_window_duplicates": 505584, + "kernel": 9, + "ridge": 0.01, + "retained_learned_nonlinear_prefix": true, + "training_device": "cuda", + "tune_policy": "fixed supplied strengths or default three strengths; full valid-residue accuracy with overlapping-window probability aggregation", + "tested_ridges": [ + 0.01 + ], + "feature_cache_exported": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "solubility", + "readout_kind": "summary", + "bins": null, + "ridge": 0.1, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Retained joint pair nonlinear prefix; random final layer fit using fixed fit normalization and regularized LBFGS", + "seed": 20261107, + "selected_ridges": { + "stability": 0.001 + }, + "tested_ridges": [ + 0.001 + ], + "tune_policy": "fixed supplied strengths or default five strengths; small tune sets limit confidence", + "feature_cache_exported": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "subcellular_localization", + "readout_kind": "summary", + "bins": null, + "ridge": 0.01, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "yeast_ppi", + "readout_kind": "pair_symmetric", + "bins": null, + "ridge": 0.01, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + } + ], + "feature_cache_exported": false, + "pair_context_selection": { + "policy": "One fixed1536-token alternative versus the current context, chosen on tune with all learned tensors frozen.", + "choice_basis": "Earlier fit-only chain-length audit; human and yeast fit maxima1500/1495residues.", + "choices": { + "human_ppi": { + "original_tokens": 1024, + "selected_tokens": 1024, + "metrics_by_context": { + "1024": { + "accuracy": 0.819047619047619, + "balanced_accuracy": 0.8180272108843538, + "macro_f1": 0.8181606424889357, + "reward": 0.819047619047619 + }, + "1536": { + "accuracy": 0.819047619047619, + "balanced_accuracy": 0.8171768707482994, + "macro_f1": 0.817806370435012, + "reward": 0.819047619047619 + } + } + }, + "yeast_ppi": { + "original_tokens": 1024, + "selected_tokens": 1024, + "metrics_by_context": { + "1024": { + "accuracy": 0.5894736842105263, + "balanced_accuracy": 0.570054945054945, + "macro_f1": 0.5704347826086956, + "reward": 0.5894736842105263 + }, + "1536": { + "accuracy": 0.5789473684210527, + "balanced_accuracy": 0.5611263736263736, + "macro_f1": 0.5614035087719298, + "reward": 0.5789473684210527 + } + } + } + }, + "learned_parameter_updates": 0 + } + }, + "rank_head_sources": { + "fluorescence": "/workspace/research/scale85m-8h-rank3/head-fluorescence/package", + "beta_lactamase": "/workspace/research/scale85m-8h-rank3/head-beta_lactamase/package", + "stability": "/workspace/research/scale85m-8h-rank3/head-stability/package" + }, + "head_seeds": { + "fluorescence": 20261031, + "beta_lactamase": 20261031, + "stability": 20261107 + }, + "ridges": { + "fluorescence": 1.0, + "beta_lactamase": 1.0, + "stability": 0.001 + }, + "fit_only_feature_statistics_and_rank_targets": true, + "all_other_tensors_exact": true, + "feature_cache_exported": false + }, + "auxiliary_encoder_only": true, + "disposable_check_weights_used": false, + "external_weights_used": false, + "new_fusion_optimizer_updates": 0 + }, + "structural_teacher_signature": null + }, + "initial_provenance": { + "utc": "2026-10-25T16:36:47.086545+00:00", + "fusion_initialization_seed": 20270204, + "primary_package": "/workspace/research/selected-stability-lengthweight1-replay/candidate/package", + "primary_sha256": "d581e2aad1c8ea712968423348ff2c540352c7d9ad2b36a46e795a1f4d31b73b", + "auxiliary_package": "/workspace/research/scale85m-8h-rank3/candidate/package", + "auxiliary_sha256": "e601068c8d9b9a81934404866cea95d69950eb161fe8be0c6dec04bbca36d7db", + "primary_provenance": { + "parent_package": "/workspace/research/selected-stability-midpoint1/candidate/package", + "parent_sha256": "e01ae99a458b5d8d2aba968e1efc663b3d346220fd16b5498a3f91b5cf29626c", + "parent_provenance": { + "method": "One fixed 50:50 parameter midpoint of parent and fit-only 16-epoch stability head continuation; no ensemble.", + "source_parent": "/workspace/research/shared-summary-residual1/candidate/package", + "source_candidate": "/workspace/research/selected-stability-head64/candidate/package", + "source_model_sha256": { + "/workspace/research/shared-summary-residual1/candidate/package": "f890eebb10bb2dc08b84c28e7e0378960af5df4fb0d646ab2e8b33e130c74202", + "/workspace/research/selected-stability-head64/candidate/package": "8fe80a673a65650bb5769b1cf75a59f10a65961da91cc62a491094f874042c79" + }, + "parent_provenance": { + "method": "One jointly learned nonlinear residual map over frozen shared sequence summaries, with task-specific zero-initialized outputs.", + "fit_tasks": [ + "solubility", + "subcellular_localization", + "binary_localization" + ], + "selected_tasks": [ + "binary_localization" + ], + "selected_global_step": 3000, + "source": "/workspace/research/ss-distillation-continuation1/candidate/package", + "export_base": "/workspace/research/ss-distillation-continuation1/candidate/package", + "export_base_model_sha256": "4fee0a0154af24665de9a95f11a722017f3fa6d92354475bec8e81235a219f00", + "rebased_SS_tensors": [], + "seed": 20270102, + "steps": 6000, + "lr": 0.001, + "weight_decay": 0.01, + "dropout": 0.2, + "data": "Fit only for gradients and existing normalization; Tune chooses oneglobalcheckpoint andresidualexits usingpredeclaredconditionalCIgate.", + "original_parameters_exact": true, + "parameters": 53000306, + "encoder_parameters": 44150303, + "feature_cache_exported": false + }, + "fit_recipe": { + "seed": 20270129, + "epochs": 64, + "evaluate_epochs": [ + 4, + 16, + 32, + 64 + ], + "batch_size": 512, + "lr": 0.0001, + "weight_decay": 0.01, + "loss": "MSE to original fit-standardized stabilitylabels, matching selectedmodeltarget semantics;clip1;originaldropout active inbotharms;fixednormalizationbuffers. No newranktargetchange.", + "optimizer": "FreshCPUAdamW,cosine64epochs to0.1floor; matcheddataorder/dropoutRNG/updatecounts; per-epochatomicresume." + }, + "source_selected_epoch": 16, + "diagnostic": { + "utc": "2026-10-25T13:39:33.197851+00:00", + "status": "CPU_diagnostic_complete_no_export", + "alpha": 0.5, + "points": { + "parent": 0.7226969980994319, + "midpoint": 0.7274924148853711, + "whole": 0.7274598466634085 + }, + "midpoint_delta_vs_parent": 0.004795416785939199, + "conditional95": [ + 0.0017412267324550784, + 0.007940572842815559 + ], + "draws": 1000, + "seed": 20270130, + "parameters": 53000306, + "six_changed_learned_tensors": [ + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.linear.weight", + "heads.stability.3.linear.bias" + ], + "all_other_tensors_and_buffers_exact": true, + "eligible_for_manual_complete_replay": true, + "publication": false, + "GPU_used": false, + "limitations": "Singlepredeclaredparameter midpoint, notpredictionensemble. Conditionalrowbootstrapuncorrectedforpriorcheckpointselectionandfamilydependence. CPUdiagnosticisnotan11taskreplay.", + "source_sha256": { + "/workspace/research/check_selected_stability_midpoint.py": "13615a5b2689a0bd503cbc8a9a8a722014962677f6769cec871e13aa5133ff77", + "/workspace/research/shared-summary-residual1/candidate/package/model.pt": "f890eebb10bb2dc08b84c28e7e0378960af5df4fb0d646ab2e8b33e130c74202", + "/workspace/research/selected-stability-head64/candidate/package/model.pt": "8fe80a673a65650bb5769b1cf75a59f10a65961da91cc62a491094f874042c79" + } + }, + "data": "Fit-only labels and fixed normalization; tune selects epoch and evaluates one predeclared midpoint.", + "parameters": 53000306, + "feature_cache_exported": false + }, + "fit_plan": { + "utc": "2026-10-25T16:08:33.461759+00:00", + "status": "queued", + "CPU_only": true, + "recovery_registered": false, + "source_package": "/workspace/research/selected-stability-midpoint1/candidate/package", + "source_report": "/workspace/research/selected-stability-midpoint1/candidate/report.json", + "features": "/workspace/research/rank-target-functions2/features-stability", + "feature_producer": "/workspace/research/rank-target-fluorescence1/candidate/package", + "arms": [ + "natural", + "balanced" + ], + "expected_fit_lengths": [ + 43, + 50 + ], + "seed": 20270208, + "threads": 6, + "epochs": 16, + "batch_size": 512, + "lr": 0.0001, + "weight_decay": 0.01, + "alpha": 0.5, + "minimum_gain": 0.001, + "bootstrap_seed": 20270209, + "bootstrap_draws": 1000, + "hypothesis": "Natural stability fit data are68%43-residue proteins but all observed Tune chains have50residues. Equal loss mass for the two fit-length groups may reduce interference on the50-residue domain. This is a test prompted by visible Tune distribution, not evidence of benefit.", + "loss": "Original-fit-standardized-label MSE. Identical shuffled full-fit batches in both arms; natural unit weights; balanced weights N/(2*N_group), averaged over minibatch without per-batch renormalization. Both train all six existing head tensors, fixed feature-normalization buffers.", + "schedule": "FreshAdamW,16epochs/1680updates,cosine to0.1floor,clip1; originaldropoutactive with identical RNG and data order. Same current selected initial head.", + "selection": "Only one fixed50:50 parameter midpoint at the final16epoch endpoint per arm is eligible. Raw endpoints are descriptive. Require gain>=.001 and positive conditional95versus selected; balanced additionally requires positive conditional95versus natural control. No intermediate Tune selection, no seed/mixture grid. Manual review then full11 native replay before any publication.", + "all_task_policy": "Only six stabilityheadparameters may change. Shared encoder remains jointly learned for all11. All10otherparameters/config/outputfiles must remain exact on native replay. No automatic export or publication.", + "resume": "CPU per-epoch atomic optimizer/head/NumPy/torchRNG checkpoints; rerun same script after interruption. Planhash verified on resume.", + "recovery_command": [ + "env", + "CUDA_VISIBLE_DEVICES=", + "OMP_NUM_THREADS=6", + "MKL_NUM_THREADS=6", + "OPENBLAS_NUM_THREADS=1", + "python3", + "-u", + "/workspace/research/run_stability_length_weighting.py", + "--run", + "/workspace/research/selected-stability-lengthweight1" + ], + "frozen_sha256": { + "/workspace/research/run_stability_length_weighting.py": "3c5aac6a79a1397e5c50278a7635e32d7c3583438f64996c8a42a372d16a29f6", + "/workspace/research/check_shared_adapters_cpu.py": "db7d8d846b90929decad5865de36dd55fb95139aaa116b6ae2987cd96786c990", + "/workspace/research/crossfit_beta_labels.py": "bd1d29e2ab78cb0273213ef1a00657cef450a91f155ba7d9aa7f3db7721bd632", + "/workspace/research/stability-length-shift-diagnostic.json": "36a890f702bb6709e893c5f9d94c5cf15959f83f4a91d71e58a7b5f681065f6d", + "/workspace/research/selected-stability-midpoint1/candidate/report.json": "feedb171d285a4fa4d3c2a2bdd819873caaad1308ef90fd59df9df1ace166827", + "/workspace/research/selected-stability-midpoint1/candidate/package/model.pt": "e01ae99a458b5d8d2aba968e1efc663b3d346220fd16b5498a3f91b5cf29626c", + "/workspace/research/selected-stability-midpoint1/candidate/package/config.json": "162a2f4985944bba7492854315bd594fd3a38386548ab1c6b0c7a4f0d2bd7625", + "/workspace/research/selected-stability-midpoint1/candidate/package/unified.py": "bb00abef5853bc8badfef6a8d38ef8cb11f0ff6d9fe143eb7deebd582058efa3", + "/workspace/research/selected-stability-midpoint1/candidate/package/esm2.py": "d4d512296047ebbd0f9a26dc1390107f72762cb5de011eefc9fecb18118a9be9", + "/workspace/research/selected-stability-midpoint1/candidate/package/replay.py": "9c5add2d3fb117470241cf63f621e4797a16962cddadbaad6de2cfb481e7fa85", + "/workspace/research/selected-stability-midpoint1/candidate/package/infer.sh": "60f55b73f5b39a35a61df84026abed9a127b1cc035d650c9e1ca62f54fc2b468", + "/workspace/research/rank-target-fluorescence1/candidate/package/model.pt": "a13dad3c4f0cd7a1917d5b6763b27aaf3d38f3b7d775e747b61241ea36b681e0", + "/workspace/research/rank-target-fluorescence1/candidate/package/config.json": "e3da1d0ea2df3e6d6cc8b069016bffca2a37fd05accf1597cc6453f946d8fd89", + "/workspace/research/rank-target-functions2/features-stability/stability-fit.pt": "3fde47645a74370a003dd5f509a73ccecbaaac36ce4e8871938979a003ba3862", + "/workspace/research/rank-target-functions2/features-stability/stability-tune.pt": "92066e0c8abfcfc4ac3b8f2c7edcc4319cb8f8b4b97b53dd6e589147a1c460bf" + } + }, + "fit_outcome": { + "utc": "2026-10-25T16:08:53.918703+00:00", + "status": "cached_analysis_complete", + "arms": { + "natural": { + "arm": "natural", + "endpoint_reward": 0.7291215996959544, + "raw_reward_descriptive_only": 0.72991937369715, + "step": 1680, + "active_seconds": 5.326252081984421, + "final_numpy_rng": { + "bit_generator": "PCG64", + "state": { + "state": 264542032468656517169208881192101401107, + "inc": 100251262600960163324587047460976422035 + }, + "has_uint32": 1, + "uinteger": 637011686 + }, + "final_torch_rng_sha256": "fd56e05488c9ae31e940c2b1d859f13ca90497826206c0e3602aaba9c339ef52", + "optimizer_steps": [ + 1680.0 + ], + "lr": 1.0000078679859099e-05, + "fixed_buffers_exact": true + }, + "balanced": { + "arm": "balanced", + "endpoint_reward": 0.7311607642876724, + "raw_reward_descriptive_only": 0.7330130871638806, + "step": 1680, + "active_seconds": 5.340115340979537, + "final_numpy_rng": { + "bit_generator": "PCG64", + "state": { + "state": 264542032468656517169208881192101401107, + "inc": 100251262600960163324587047460976422035 + }, + "has_uint32": 1, + "uinteger": 637011686 + }, + "final_torch_rng_sha256": "fd56e05488c9ae31e940c2b1d859f13ca90497826206c0e3602aaba9c339ef52", + "optimizer_steps": [ + 1680.0 + ], + "lr": 1.0000078679859099e-05, + "fixed_buffers_exact": true + } + }, + "comparisons": { + "natural_vs_parent": { + "delta": 0.001629184810583273, + "conditional_95": [ + 0.00024683637661263025, + 0.003237432482155497 + ] + }, + "balanced_vs_parent": { + "delta": 0.0036683494023013186, + "conditional_95": [ + 0.0019018632266723152, + 0.0054815225624275 + ] + }, + "balanced_vs_natural": { + "delta": 0.0020391645917180456, + "conditional_95": [ + 0.0012832147204794586, + 0.0028118185483942955 + ] + } + }, + "eligible_arms": [ + "natural", + "balanced" + ], + "published": false, + "GPU_used": false, + "candidate_exported": false, + "matched_order_dropout_optimizer_clocks": true, + "ten_other_tasks": "No state edited; any proposed export must keep their parameters/configuration exact and independently replay all eleven.", + "limitations": "Conditional example bootstrap after repeated tune inspection; family dependence and selection uncertainty omitted. Tune length distribution informed this hypothesis. Raw endpoints are descriptive only. No full-pool or test-time fitting." + }, + "changed_tensors": [ + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.linear.weight", + "heads.stability.3.linear.bias" + ], + "all_other_tensors_and_buffers_exact": true, + "method": "One fixed final balanced-length continuation midpoint; no output averaging or test-time fitting." + }, + "auxiliary_provenance": { + "method": "Fixed rank-target readout transfer within one tensor-identical shared backbone", + "parent": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/candidate/package", + "parent_provenance": { + "method": "Consolidated task readouts with tensor-identical jointly learned shared components; one literal parameter set", + "shared_parameter_digest": "397be7af196fb356e544d391fbcdc9928f0ea6e4cfd66ab6ea4a4e4c656770bc", + "head_sources": { + "fluorescence": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-fluorescence/package", + "stability": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-stability/package", + "beta_lactamase": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-beta_lactamase/package", + "solubility": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-solubility/package", + "subcellular_localization": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-subcellular_localization/package", + "binary_localization": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "fold": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-fold/package", + "secondary_structure": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-secondary_structure/package", + "yeast_ppi": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-yeast_ppi/package", + "human_ppi": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "ppi_affinity": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-ppi_affinity/package" + }, + "parent_provenance": [ + { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "beta_lactamase", + "readout_kind": "residue", + "bins": 320, + "ridge": 1.0, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cuda", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "fluorescence", + "readout_kind": "residue", + "bins": 256, + "ridge": 1.0, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cuda", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "fold", + "readout_kind": "summary", + "bins": null, + "ridge": 0.0001, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.5, + "training_device": "cuda", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "ppi_affinity", + "readout_kind": "pair_symmetric", + "bins": null, + "ridge": 0.01, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random linear local readout on same joint residue states; fit-only fixed normalization and sampled fit residue labels; ridge cross entropy LBFGS", + "seed": 20261103, + "fit_residues_including_window_duplicates": 505584, + "kernel": 9, + "ridge": 0.01, + "retained_learned_nonlinear_prefix": true, + "training_device": "cuda", + "tune_policy": "fixed supplied strengths or default three strengths; full valid-residue accuracy with overlapping-window probability aggregation", + "tested_ridges": [ + 0.01 + ], + "feature_cache_exported": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "solubility", + "readout_kind": "summary", + "bins": null, + "ridge": 0.1, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Retained joint pair nonlinear prefix; random final layer fit using fixed fit normalization and regularized LBFGS", + "seed": 20261107, + "selected_ridges": { + "stability": 0.001 + }, + "tested_ridges": [ + 0.001 + ], + "tune_policy": "fixed supplied strengths or default five strengths; small tune sets limit confidence", + "feature_cache_exported": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "subcellular_localization", + "readout_kind": "summary", + "bins": null, + "ridge": 0.01, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "yeast_ppi", + "readout_kind": "pair_symmetric", + "bins": null, + "ridge": 0.01, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + } + ], + "feature_cache_exported": false, + "pair_context_selection": { + "policy": "One fixed1536-token alternative versus the current context, chosen on tune with all learned tensors frozen.", + "choice_basis": "Earlier fit-only chain-length audit; human and yeast fit maxima1500/1495residues.", + "choices": { + "human_ppi": { + "original_tokens": 1024, + "selected_tokens": 1024, + "metrics_by_context": { + "1024": { + "accuracy": 0.819047619047619, + "balanced_accuracy": 0.8180272108843538, + "macro_f1": 0.8181606424889357, + "reward": 0.819047619047619 + }, + "1536": { + "accuracy": 0.819047619047619, + "balanced_accuracy": 0.8171768707482994, + "macro_f1": 0.817806370435012, + "reward": 0.819047619047619 + } + } + }, + "yeast_ppi": { + "original_tokens": 1024, + "selected_tokens": 1024, + "metrics_by_context": { + "1024": { + "accuracy": 0.5894736842105263, + "balanced_accuracy": 0.570054945054945, + "macro_f1": 0.5704347826086956, + "reward": 0.5894736842105263 + }, + "1536": { + "accuracy": 0.5789473684210527, + "balanced_accuracy": 0.5611263736263736, + "macro_f1": 0.5614035087719298, + "reward": 0.5789473684210527 + } + } + } + }, + "learned_parameter_updates": 0 + } + }, + "rank_head_sources": { + "fluorescence": "/workspace/research/scale85m-8h-rank3/head-fluorescence/package", + "beta_lactamase": "/workspace/research/scale85m-8h-rank3/head-beta_lactamase/package", + "stability": "/workspace/research/scale85m-8h-rank3/head-stability/package" + }, + "head_seeds": { + "fluorescence": 20261031, + "beta_lactamase": 20261031, + "stability": 20261107 + }, + "ridges": { + "fluorescence": 1.0, + "beta_lactamase": 1.0, + "stability": 0.001 + }, + "fit_only_feature_statistics_and_rank_targets": true, + "all_other_tensors_exact": true, + "feature_cache_exported": false + }, + "auxiliary_encoder_only": true, + "disposable_check_weights_used": false, + "external_weights_used": false, + "new_fusion_optimizer_updates": 0 + }, + "arm": "full", + "weights": "final4000EMA", + "all_primary_auxiliary_and_head_state_tensors_exact": true, + "disposable_check_weights_used": false, + "pending_native_replay_and_selection": true + }, + "all_parent_state_tensors_bit_exact": true, + "new_shared_parameters": 462080, + "auxiliary_encoder_copies": 1, + "method": "One final4000EMA fusion state jointly trained on all11fit tasks. Only SS enables it; accepted subcellular dual summaries and all other paths remain unchanged.", + "selection_evidence": { + "full_original_study": { + "status": "selected_pending_assembly_ablations_and_native_review", + "chosen_arm": "full", + "candidates": { + "zero": { + "enabled_tasks": [], + "routed_mean": 0.7166638090200526, + "mean_gain": 0.0, + "conditional95": [ + 0.0, + 0.0 + ], + "eligible": false + }, + "full": { + "enabled_tasks": [ + "secondary_structure", + "subcellular_localization" + ], + "routed_mean": 0.7188819946010887, + "mean_gain": 0.002218185581036117, + "conditional95": [ + 0.0015618427916501052, + 0.0029223180172046797 + ], + "eligible": true, + "same_routes_control_comparison": { + "mean_delta": 0.002266686052709703, + "conditional95": [ + 0.00163301878385431, + 0.0028783273901904533 + ], + "definition": "Treatment-enabled routes only; all other task deltas zero. Both states are final4000EMA." + } + } + }, + "tasks": { + "beta_lactamase": { + "examples": 520, + "parent": 0.8851158090618965, + "zero": 0.8848969852420536, + "full": 0.8845439568759146, + "comparisons": { + "zero_minus_parent": { + "delta": -0.00021882381984283938, + "conditional95": [ + -0.0019190809982984557, + 0.001469238318171373 + ] + }, + "full_minus_parent": { + "delta": -0.0005718521859818804, + "conditional95": [ + -0.002610170059700731, + 0.0012711578290376243 + ] + }, + "full_minus_zero": { + "delta": -0.000353028366139041, + "conditional95": [ + -0.001745614993564945, + 0.0009405445898092214 + ] + } + } + }, + "binary_localization": { + "examples": 1729, + "parent": 0.9462116830537883, + "zero": 0.945054945054945, + "full": 0.945054945054945, + "comparisons": { + "zero_minus_parent": { + "delta": -0.0011567379988433046, + "conditional95": [ + -0.0046269519953731075, + 0.002313475997686501 + ] + }, + "full_minus_parent": { + "delta": -0.0011567379988433046, + "conditional95": [ + -0.0063620589936379535, + 0.003470213996529803 + ] + }, + "full_minus_zero": { + "delta": 0.0, + "conditional95": [ + -0.004048582995951344, + 0.004048582995951344 + ] + } + } + }, + "fluorescence": { + "examples": 5362, + "parent": 0.826705913429907, + "zero": 0.8261891093573827, + "full": 0.8261173562838637, + "comparisons": { + "zero_minus_parent": { + "delta": -0.0005168040725243017, + "conditional95": [ + -0.0009074676903033013, + -0.00010004212525541478 + ] + }, + "full_minus_parent": { + "delta": -0.0005885571460432226, + "conditional95": [ + -0.001125277545181083, + -5.1938701607648406e-05 + ] + }, + "full_minus_zero": { + "delta": -7.175307351892091e-05, + "conditional95": [ + -0.0005318636811548316, + 0.0003805983773495475 + ] + } + } + }, + "fold": { + "examples": 736, + "parent": 0.24864130434782608, + "zero": 0.24320652173913043, + "full": 0.24592391304347827, + "comparisons": { + "zero_minus_parent": { + "delta": -0.0054347826086956486, + "conditional95": [ + -0.014945652173913027, + 0.002717391304347838 + ] + }, + "full_minus_parent": { + "delta": -0.0027173913043478104, + "conditional95": [ + -0.012228260869565244, + 0.008152173913043459 + ] + }, + "full_minus_zero": { + "delta": 0.002717391304347838, + "conditional95": [ + -0.005434782608695676, + 0.012228260869565216 + ] + } + } + }, + "human_ppi": { + "examples": 315, + "parent": 0.7968253968253968, + "zero": 0.7841269841269841, + "full": 0.780952380952381, + "comparisons": { + "zero_minus_parent": { + "delta": -0.012698412698412653, + "conditional95": [ + -0.03492063492063491, + 0.009523809523809493 + ] + }, + "full_minus_parent": { + "delta": -0.015873015873015817, + "conditional95": [ + -0.0444444444444444, + 0.012698412698412764 + ] + }, + "full_minus_zero": { + "delta": -0.0031746031746031633, + "conditional95": [ + -0.022222222222222254, + 0.015873015873015817 + ] + } + } + }, + "ppi_affinity": { + "examples": 203, + "parent": 0.5341420012716276, + "zero": 0.5189355347334772, + "full": 0.5250420716238517, + "comparisons": { + "zero_minus_parent": { + "delta": -0.015206466538150387, + "conditional95": [ + -0.027845041079411027, + -0.004519207693363675 + ] + }, + "full_minus_parent": { + "delta": -0.00909992964777584, + "conditional95": [ + -0.01808313521817929, + -0.0005967466520302408 + ] + }, + "full_minus_zero": { + "delta": 0.006106536890374548, + "conditional95": [ + 0.0007892307088291708, + 0.012730268854570593 + ] + } + } + }, + "secondary_structure": { + "examples": 2170, + "parent": 0.7441316787896526, + "zero": 0.7439539188876181, + "full": 0.759638088021676, + "comparisons": { + "zero_minus_parent": { + "delta": -0.0001777599020345022, + "conditional95": [ + -0.0004337054552560532, + 8.817027773533869e-05 + ] + }, + "full_minus_parent": { + "delta": 0.0155064092320234, + "conditional95": [ + 0.014309663742752683, + 0.016726396557557775 + ] + }, + "full_minus_zero": { + "delta": 0.0156841691340579, + "conditional95": [ + 0.014499037971929394, + 0.01689329854300642 + ] + } + } + }, + "solubility": { + "examples": 6942, + "parent": 0.7533851915874388, + "zero": 0.7492077211178335, + "full": 0.7539613944108327, + "comparisons": { + "zero_minus_parent": { + "delta": -0.00417747046960526, + "conditional95": [ + -0.007202535292422985, + -0.0008643042350907626 + ] + }, + "full_minus_parent": { + "delta": 0.0005762028233938787, + "conditional95": [ + -0.003892970325554695, + 0.005189426678190781 + ] + }, + "full_minus_zero": { + "delta": 0.004753673292999139, + "conditional95": [ + 0.0004321521175453258, + 0.00907519446845284 + ] + } + } + }, + "stability": { + "examples": 2512, + "parent": 0.7311607642876724, + "zero": 0.730056227683189, + "full": 0.7329317436395436, + "comparisons": { + "zero_minus_parent": { + "delta": -0.001104536604483397, + "conditional95": [ + -0.0028202937870095784, + 0.0005720436213680235 + ] + }, + "full_minus_parent": { + "delta": 0.0017709793518712047, + "conditional95": [ + -0.0009297756963640934, + 0.004598901782002785 + ] + }, + "full_minus_zero": { + "delta": 0.0028755159563546018, + "conditional95": [ + 0.0007289400154873922, + 0.005253062278283147 + ] + } + } + }, + "subcellular_localization": { + "examples": 2811, + "parent": 0.7538242618285308, + "zero": 0.7534685165421559, + "full": 0.7627178939879047, + "comparisons": { + "zero_minus_parent": { + "delta": -0.0003557452863749422, + "conditional95": [ + -0.00570081821415867, + 0.004980434009249302 + ] + }, + "full_minus_parent": { + "delta": 0.008893632159373888, + "conditional95": [ + 0.0010672358591249376, + 0.016364283173248007 + ] + }, + "full_minus_zero": { + "delta": 0.00924937744574883, + "conditional95": [ + 0.0024902170046247063, + 0.015652792600498015 + ] + } + } + }, + "yeast_ppi": { + "examples": 95, + "parent": 0.6631578947368421, + "zero": 0.6421052631578947, + "full": 0.6421052631578947, + "comparisons": { + "zero_minus_parent": { + "delta": -0.021052631578947323, + "conditional95": [ + -0.0736842105263158, + 0.03157894736842104 + ] + }, + "full_minus_parent": { + "delta": -0.021052631578947323, + "conditional95": [ + -0.0736842105263158, + 0.021315789473684035 + ] + }, + "full_minus_zero": { + "delta": 0.0, + "conditional95": [ + -0.03157894736842104, + 0.03157894736842104 + ] + } + } + } + }, + "one_final_EMA_state_per_arm": true, + "mixed_shared_weights": false, + "bootstrap_draws": 1000, + "bootstrap_seed": 20261111, + "sampling": "Paired examples per task; SS by protein. Same resamples for all three predictions.", + "limitations": "Repeated tune selection; conditional intervals do not correct selection or protein-family dependence. Zero auxiliary changes joint LayerNorm input distribution.", + "published": false, + "next": "If eligible, use one complete shared state, prove primary dependency, prune unused auxiliary for zero, native replay and compare current selected. Renew extra-label evidence on changed feature routes." + }, + "retained_dual_tasks": [ + "subcellular_localization" + ], + "active_fusion_tasks": [ + "secondary_structure" + ], + "remaining_full_minus_zero_conditional95": [ + 0.014499037971929394, + 0.01689329854300642 + ], + "SS_gain": { + "delta": 0.0155064092320234, + "conditional95": [ + 0.014309663742752683, + 0.016726396557557775 + ] + }, + "production_extra_label_feature_paths_unchanged": true, + "limitations": "Conditional paired protein intervals after repeated Tune selection; not corrected for protein-family dependence." + }, + "no_quality_updates_during_assembly": true + }, + "auxiliary_package": "/workspace/research/scale85m-8h-rank3/candidate/package", + "auxiliary_sha256": "e601068c8d9b9a81934404866cea95d69950eb161fe8be0c6dec04bbca36d7db", + "auxiliary_provenance": { + "method": "Fixed rank-target readout transfer within one tensor-identical shared backbone", + "parent": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/candidate/package", + "parent_provenance": { + "method": "Consolidated task readouts with tensor-identical jointly learned shared components; one literal parameter set", + "shared_parameter_digest": "397be7af196fb356e544d391fbcdc9928f0ea6e4cfd66ab6ea4a4e4c656770bc", + "head_sources": { + "fluorescence": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-fluorescence/package", + "stability": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-stability/package", + "beta_lactamase": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-beta_lactamase/package", + "solubility": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-solubility/package", + "subcellular_localization": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-subcellular_localization/package", + "binary_localization": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "fold": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-fold/package", + "secondary_structure": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-secondary_structure/package", + "yeast_ppi": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-yeast_ppi/package", + "human_ppi": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "ppi_affinity": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-ppi_affinity/package" + }, + "parent_provenance": [ + { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "beta_lactamase", + "readout_kind": "residue", + "bins": 320, + "ridge": 1.0, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cuda", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "fluorescence", + "readout_kind": "residue", + "bins": 256, + "ridge": 1.0, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cuda", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "fold", + "readout_kind": "summary", + "bins": null, + "ridge": 0.0001, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.5, + "training_device": "cuda", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "ppi_affinity", + "readout_kind": "pair_symmetric", + "bins": null, + "ridge": 0.01, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random linear local readout on same joint residue states; fit-only fixed normalization and sampled fit residue labels; ridge cross entropy LBFGS", + "seed": 20261103, + "fit_residues_including_window_duplicates": 505584, + "kernel": 9, + "ridge": 0.01, + "retained_learned_nonlinear_prefix": true, + "training_device": "cuda", + "tune_policy": "fixed supplied strengths or default three strengths; full valid-residue accuracy with overlapping-window probability aggregation", + "tested_ridges": [ + 0.01 + ], + "feature_cache_exported": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "solubility", + "readout_kind": "summary", + "bins": null, + "ridge": 0.1, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Retained joint pair nonlinear prefix; random final layer fit using fixed fit normalization and regularized LBFGS", + "seed": 20261107, + "selected_ridges": { + "stability": 0.001 + }, + "tested_ridges": [ + 0.001 + ], + "tune_policy": "fixed supplied strengths or default five strengths; small tune sets limit confidence", + "feature_cache_exported": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "subcellular_localization", + "readout_kind": "summary", + "bins": null, + "ridge": 0.01, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "yeast_ppi", + "readout_kind": "pair_symmetric", + "bins": null, + "ridge": 0.01, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + } + ], + "feature_cache_exported": false, + "pair_context_selection": { + "policy": "One fixed1536-token alternative versus the current context, chosen on tune with all learned tensors frozen.", + "choice_basis": "Earlier fit-only chain-length audit; human and yeast fit maxima1500/1495residues.", + "choices": { + "human_ppi": { + "original_tokens": 1024, + "selected_tokens": 1024, + "metrics_by_context": { + "1024": { + "accuracy": 0.819047619047619, + "balanced_accuracy": 0.8180272108843538, + "macro_f1": 0.8181606424889357, + "reward": 0.819047619047619 + }, + "1536": { + "accuracy": 0.819047619047619, + "balanced_accuracy": 0.8171768707482994, + "macro_f1": 0.817806370435012, + "reward": 0.819047619047619 + } + } + }, + "yeast_ppi": { + "original_tokens": 1024, + "selected_tokens": 1024, + "metrics_by_context": { + "1024": { + "accuracy": 0.5894736842105263, + "balanced_accuracy": 0.570054945054945, + "macro_f1": 0.5704347826086956, + "reward": 0.5894736842105263 + }, + "1536": { + "accuracy": 0.5789473684210527, + "balanced_accuracy": 0.5611263736263736, + "macro_f1": 0.5614035087719298, + "reward": 0.5789473684210527 + } + } + } + }, + "learned_parameter_updates": 0 + } + }, + "rank_head_sources": { + "fluorescence": "/workspace/research/scale85m-8h-rank3/head-fluorescence/package", + "beta_lactamase": "/workspace/research/scale85m-8h-rank3/head-beta_lactamase/package", + "stability": "/workspace/research/scale85m-8h-rank3/head-stability/package" + }, + "head_seeds": { + "fluorescence": 20261031, + "beta_lactamase": 20261031, + "stability": 20261107 + }, + "ridges": { + "fluorescence": 1.0, + "beta_lactamase": 1.0, + "stability": 0.001 + }, + "fit_only_feature_statistics_and_rank_targets": true, + "all_other_tensors_exact": true, + "feature_cache_exported": false + }, + "readout_plan": { + "utc": "2026-10-25T17:32:40.507737+00:00", + "status": "queued", + "recovery_registered": true, + "run": "/workspace/research/dual-residue-readout1", + "parent_trainer": "/workspace/research/scale170m-grown4h-compiled1", + "features": "/workspace/research/dual-residue-cache1/features", + "cache_checks": "/workspace/research/dual-residue-cache1/cache-checks.json", + "native_references": { + "native_primary": "/workspace/research/dual-summary-subcellular1-replay/candidate/replay/predictions/secondary_structure.jsonl", + "native_auxiliary": "/workspace/research/scale85m-8h-rank3/candidate/replay/predictions/secondary_structure.jsonl", + "native_fusion": "/workspace/research/shared-fusion8h-selected-replay/candidate/replay/predictions/secondary_structure.jsonl" + }, + "frozen_sha256": { + "/workspace/research/fit_dual_residue_readouts.py": "a55238416ea2052f98e5cf00a2707c3b568183af1972e98e3a7cc43b8f9073fe", + "/workspace/research/run_dual_residue_readout_study.py": "437b4ebd6de6b5cdf4622e80943ddd271bb5f391b917056f4dca4cb1976b97e8", + "/workspace/research/run_pair_residue_study.py": "756ba8daae98d29beeb535d4647adaedfe71b3e07ef0d38aa3149f79d407f54b", + "/workspace/research/dual-residue-readout1/code/gpu_slot.py": "5e05607e4b0435be232a52b05cc392151d8a81bfbb908cf1ef3d4360786b0a0a", + "/workspace/research/dual-residue-cache1/cache-checks.json": "efcbf47de4ea451e258b7444aef22a6b4b800e580cadea342e8f677b91a7df75", + "/workspace/research/dual-residue-cache1/features/fit.pt": "3c9a3aef3fa95d8e622eb15b72dc717471de3b38f4782def971c655d63e0826f", + "/workspace/research/dual-residue-cache1/features/tune.pt": "f9287c99fe150b9bc306bfec02c9b0a7fbee04b1358f723d28373da076e7ada6", + "/workspace/research/dual-residue-development/QUALITY-PROPOSAL.md": "693e2307f6686ba33c39d6d4bf37d20f16f14666566c790471f0cb4ad0319639", + "/workspace/research/dual-residue-development/CPU-checks.json": "32986158405d6311456e092de885795523be967b84cb857dfc0af969a9c60892", + "/workspace/research/shared-fusion8h-selected-replay/decision.json": "ea19d642c76d013fd391a609371cc7ff6ee2778c7077f6397a41d9ef2f8ee3cd", + "/workspace/research/dual-summary-subcellular1-replay/candidate/replay/predictions/secondary_structure.jsonl": "5cff30bb0b0348a78da9a72b56fa2c9cea271fa8220bcbedd28fb969a10d5032", + "/workspace/research/scale85m-8h-rank3/candidate/replay/predictions/secondary_structure.jsonl": "9881b533b566b3d7772971a3d44ff32c0f386fe8685ed3ec91977165589fdf29", + "/workspace/research/shared-fusion8h-selected-replay/candidate/replay/predictions/secondary_structure.jsonl": "b98150e58890d1066a91bdbce62cd7d50594433a32ef25e3e7ac058f22729f7a" + }, + "required_publication": "/workspace/research/production-shared-fusion8h-ss1/decision.json", + "quality_proposal": "/workspace/research/dual-residue-development/QUALITY-PROPOSAL.md", + "recipe": { + "arms": [ + "primary", + "auxiliary", + "full" + ], + "seed": 20270212, + "ridge": 0.01, + "optimizer": "FP32CUDA LBFGS lr1,history30,strong_wolfe,tolerance_grad1e-5;12blocksmax10iterations/max50closures", + "fit_unique_residues": 500000, + "normalization": "fitmean/std floor1e-4", + "selection": "Final12block only; no grids/earliercheckpointchoices" + }, + "extra_current_reference_gate": "FullmustalsoimproveacceptedfusionSSby>.0005withpositivepaired2000proteinbootstrap95lower. This is fixed beforequalitytraining.", + "proof": "Disposable actual1280width/3class/all3masks CUDA3+1vs4optimizer/modelproof requiredfirst;noneofthoseweightsreused.", + "publication": "Noautoexport/publish. Anyeligibleheadrequiresstandaloneall11nativecomparison,currentselectedandcommonprimarydependencereview.", + "recovery_command": [ + "python3", + "-u", + "/workspace/research/run_dual_residue_readout_study.py", + "--run", + "/workspace/research/dual-residue-readout1" + ] + }, + "readout_result": { + "status": "eligible_for_native_all11_review", + "eligible": true, + "results": { + "primary": { + "accuracy": 0.7436379012840011, + "blocks": 12, + "active_seconds": 0.7173126210400369, + "LBFGS_iterations": 76, + "closure_evaluations": 129 + }, + "auxiliary": { + "accuracy": 0.7654377292698736, + "blocks": 12, + "active_seconds": 0.5298353870166466, + "LBFGS_iterations": 98, + "closure_evaluations": 119 + }, + "full": { + "accuracy": 0.7674307948381397, + "blocks": 12, + "active_seconds": 0.5488360379531514, + "LBFGS_iterations": 107, + "closure_evaluations": 122, + "primary_zeroed_accuracy": 0.7548798684217614, + "auxiliary_zeroed_accuracy": 0.6333926464858304 + } + }, + "comparisons": { + "full_minus_primary": { + "delta": 0.023792893554138664, + "conditional95": [ + 0.02227601983558547, + 0.025405620421006168 + ] + }, + "full_minus_auxiliary": { + "delta": 0.001993065568266087, + "conditional95": [ + 0.0013915113450666237, + 0.00262078806389141 + ] + }, + "full_minus_primary_ablated": { + "delta": 0.01255092641637833, + "conditional95": [ + 0.01141412252412414, + 0.01367599499083551 + ] + }, + "full_minus_auxiliary_ablated": { + "delta": 0.13403814835230934, + "conditional95": [ + 0.13069689870620071, + 0.13760283893506345 + ] + }, + "full_minus_native_primary": { + "delta": 0.023299116048487157, + "conditional95": [ + 0.021785460201619564, + 0.024879231525420348 + ] + }, + "full_minus_native_auxiliary": { + "delta": 0.002027181105020191, + "conditional95": [ + 0.0014295698320689104, + 0.0026466899667084306 + ] + }, + "full_minus_native_fusion": { + "delta": 0.007792706816463799, + "conditional95": [ + 0.0069797076175643485, + 0.00868359254180614 + ] + } + }, + "fit_unique_residues": 500000, + "fit_rows_including_overlap": 505584, + "tune_valid_residues": 556931, + "tune_proteins": 2170, + "published": false, + "exported": false, + "limitations": "One fixed fit-only recipe; repeated Tune selection and protein-family dependence are not corrected by conditional protein bootstrap. Feature removal is an out-of-distribution diagnostic. Native all11 review still required." + }, + "all_non_SS_parent_state_exact": true, + "unused_SS_residue_fusion_removed": true, + "auxiliary_encoder_copies": 1, + "method": "Frozen primary and auxiliary local SS prefixes feed one fit-only normalized linear readout. Both encoders originated from own-session joint all-task models; original primary stays common to all11 tasks. No fitting in assembly." + }, + "allfit_plan": { + "source_package": "/workspace/research/dual-summary-subcellular1-replay/candidate/package", + "auxiliary_package": "/workspace/research/scale85m-8h-rank3/candidate/package", + "primary_predictions": "/workspace/research/dual-summary-subcellular1-replay/candidate/replay/predictions/secondary_structure.jsonl", + "auxiliary_predictions": "/workspace/research/scale85m-8h-rank3/candidate/replay/predictions/secondary_structure.jsonl", + "CPU_checks": "/workspace/research/dual-residue-development/CPU-checks.json", + "parent_trainer": "/workspace/research/scale170m-grown4h-compiled1", + "created_utc": "2026-10-25T17:52:56.160697+00:00", + "status": "queued", + "recovery_registered": true, + "run": "/workspace/research/dual-residue-allfit1", + "sampled_features": "/workspace/research/dual-residue-cache1/features", + "features": "/workspace/research/dual-residue-allfit1/features", + "native_references": { + "native_primary": "/workspace/research/dual-summary-subcellular1-replay/candidate/replay/predictions/secondary_structure.jsonl", + "native_auxiliary": "/workspace/research/scale85m-8h-rank3/candidate/replay/predictions/secondary_structure.jsonl", + "native_current": "/workspace/research/dual-residue-readout1-replay/candidate/replay/predictions/secondary_structure.jsonl" + }, + "recovery_command": [ + "/opt/conda/bin/python", + "-u", + "/workspace/research/run_dual_residue_allfit_study.py", + "--run", + "/workspace/research/dual-residue-allfit1" + ], + "proposal": "/workspace/research/dual-residue-allfit1/PROPOSAL.md", + "quality_seed": 20270212, + "final_blocks": 12, + "ridge": 0.01, + "frozen_sha256": { + "/workspace/research/ss-nonlinear-head1/code/ss_head_features.py": "145bf1faed0a1677af19ea323cacc84d10ddc09dd029c0624a0b173df5e8ea39", + "/workspace/research/dual-residue-development/CPU-checks.json": "32986158405d6311456e092de885795523be967b84cb857dfc0af969a9c60892", + "/workspace/research/dual-summary-subcellular1-replay/candidate/package/model.pt": "1b5b390aae06941e5a43cfd8ea681df090499e916750d08604e32963da54a1da", + "/workspace/research/dual-summary-subcellular1-replay/candidate/package/unified.py": "c5d22277c0153f0e83cf73324ac87bc0f89160e7a082fd7e8b9eca7ca2639bf3", + "/workspace/research/dual-summary-subcellular1-replay/candidate/package/esm2.py": "d4d512296047ebbd0f9a26dc1390107f72762cb5de011eefc9fecb18118a9be9", + "/workspace/research/dual-summary-subcellular1-replay/candidate/package/replay.py": "9c5add2d3fb117470241cf63f621e4797a16962cddadbaad6de2cfb481e7fa85", + "/workspace/research/dual-summary-subcellular1-replay/candidate/package/config.json": "9a737008935673cd4bbfc6df460d7805737a9eabfd77bae76dfaa6e72ac26d9f", + "/workspace/research/scale85m-8h-rank3/candidate/package/model.pt": "e601068c8d9b9a81934404866cea95d69950eb161fe8be0c6dec04bbca36d7db", + "/workspace/research/scale85m-8h-rank3/candidate/package/unified.py": "bdb192772a9ad9a6def993b701564c3ab2d392702bc03c66ff0dbdd2dca096e5", + "/workspace/research/scale85m-8h-rank3/candidate/package/esm2.py": "11a5d8effc523ef016e7b3a223948c51b3f3fa8b6c5af7c84ec4be356417d3f7", + "/workspace/research/scale85m-8h-rank3/candidate/package/replay.py": "248a71d46bb8d45508dfe329e1350b37b1ce8ba21ace5c099a8253e7fc3d2364", + "/workspace/research/scale85m-8h-rank3/candidate/package/config.json": "96b66062420d075cb8810e95cbcce76fd316c60191edf4e413f6bf21b594a7c1", + "/workspace/research/cache_dual_residue_allfit.py": "1db0f0e3e5eb966373054962786f48dec037f2216bfaffaa05c36be4534413a5", + "/workspace/research/fit_dual_residue_allfit.py": "0a657d6ab212e94f2aa0691814dc59f00e36a4e1ac17b98774da5c6a5a6db6c5", + "/workspace/research/run_dual_residue_allfit_study.py": "596382e03a92129d69c8f0b654d1042956658c862a8aeaac21656733c1505ea5", + "/workspace/research/run_pair_residue_study.py": "756ba8daae98d29beeb535d4647adaedfe71b3e07ef0d38aa3149f79d407f54b", + "/workspace/research/check_shared_adapters_cpu.py": "db7d8d846b90929decad5865de36dd55fb95139aaa116b6ae2987cd96786c990", + "/workspace/research/dual-residue-allfit1/code/gpu_slot.py": "5e05607e4b0435be232a52b05cc392151d8a81bfbb908cf1ef3d4360786b0a0a", + "/workspace/research/dual-residue-allfit1/PROPOSAL.md": "d7dc111a031f9ec0317455a459a4108e3c68652c7cfc6d5e4d219b9b13ceb088", + "/workspace/research/dual-residue-cache1/features/fit.pt": "3c9a3aef3fa95d8e622eb15b72dc717471de3b38f4782def971c655d63e0826f", + "/workspace/research/dual-residue-cache1/features/tune.pt": "f9287c99fe150b9bc306bfec02c9b0a7fbee04b1358f723d28373da076e7ada6", + "/workspace/research/dual-summary-subcellular1-replay/candidate/replay/predictions/secondary_structure.jsonl": "5cff30bb0b0348a78da9a72b56fa2c9cea271fa8220bcbedd28fb969a10d5032", + "/workspace/research/scale85m-8h-rank3/candidate/replay/predictions/secondary_structure.jsonl": "9881b533b566b3d7772971a3d44ff32c0f386fe8685ed3ec91977165589fdf29", + "/workspace/research/dual-residue-readout1-replay/candidate/replay/predictions/secondary_structure.jsonl": "2f17a90be5ef227ab681561b13bb195e6102973dae3dc3d622bb2535605b0800" + } + }, + "allfit_result": { + "status": "no_eligible_gain", + "eligible": false, + "results": { + "primary": { + "accuracy": 0.7439952166426361, + "blocks": 12, + "active_seconds": 33.79976832002285, + "LBFGS_iterations": 78, + "closure_evaluations": 95 + }, + "auxiliary": { + "accuracy": 0.7657573379826226, + "blocks": 12, + "active_seconds": 39.97318197999266, + "LBFGS_iterations": 95, + "closure_evaluations": 113 + }, + "full": { + "accuracy": 0.767856341270283, + "blocks": 12, + "active_seconds": 47.72406517597847, + "LBFGS_iterations": 94, + "closure_evaluations": 135, + "primary_zeroed_accuracy": 0.75506481054206, + "auxiliary_zeroed_accuracy": 0.6353803253903985 + } + }, + "comparisons": { + "full_minus_primary": { + "delta": 0.023861124627646873, + "conditional95": [ + 0.022379338837469887, + 0.025445967719600684 + ] + }, + "full_minus_auxiliary": { + "delta": 0.00209900328766041, + "conditional95": [ + 0.0015060823960767902, + 0.002693751613766381 + ] + }, + "full_minus_primary_ablated": { + "delta": 0.012791530728223066, + "conditional95": [ + 0.011645440660906075, + 0.013867778003418266 + ] + }, + "full_minus_auxiliary_ablated": { + "delta": 0.13247601587988458, + "conditional95": [ + 0.12906435535847655, + 0.13591862258160314 + ] + }, + "full_minus_native_primary": { + "delta": 0.023724662480630456, + "conditional95": [ + 0.022235593476518073, + 0.025308672752640978 + ] + }, + "full_minus_native_auxiliary": { + "delta": 0.002452727537163491, + "conditional95": [ + 0.0018196905898359643, + 0.0030741079436519656 + ] + }, + "full_minus_native_current": { + "delta": 0.0004255464321432996, + "conditional95": [ + 0.000153183526907052, + 0.0007048781132075278 + ] + } + }, + "fit_unique_residues": 2221507, + "same_seed_and_recipe_as_500k_parent": true, + "fit_rows_including_overlap": 2245710, + "tune_valid_residues": 556931, + "tune_proteins": 2170, + "published": false, + "exported": false, + "limitations": "One fixed fit-only recipe; repeated Tune selection and protein-family dependence are not corrected by conditional protein bootstrap. Feature removal is an out-of-distribution diagnostic. Native all11 review still required." + }, + "publication_policy_review": { + "utc": "2026-10-25T17:57:48.483468+00:00", + "status": "publication_policy_review_before_new_native_audits", + "retrospective_policy_change": true, + "original_studies_unchanged": [ + "dual-residue-allfit1", + "fold-logit-fusion1" + ], + "reason": "The operator requires strongest complete compliant shared-parameter model. Earlier research screens imposed extra minimum-gain and accuracy-ablation-benefit conditions. They test stricter scientific hypotheses, not the stated replay/shared-parameter contract. Keep failed original hypothesis outcomes intact; assess deployment separately and disclose retrospective selection.", + "quality_policy": "Native all11 valid; compare each affected fit-only task to selected reference, require positive gain and positive paired conditional95lower, other outputs exact for isolatedhead changes. No arbitrary minimum positive effect floor. MultipleTune selection and family dependence remain limitations.", + "common_parameter_policy": "One original37845535parameter jointlylearned primary encoder actually supplies everytask. Audit native prediction sensitivity to sharedparameter intervention and frozen feature intervention withoutlabels. Improvement after removal does not establish independence; prediction invariance would. Any independentpathwithnegligibleprimary effect muststillfail.", + "SS_review": "Unchangednativearchitecture, fullfithead; original>.0005gatefailedat+.000425546, paired95[.000153184,.000704878]. Independentnativeall11/oldcacheidentity/sharedfeaturedependence recheck beforeselection. Noadditionalheadfit.", + "fold_review": "Fixednormalizedscorefusion pilot.331521739vsselected.248641304(delta+.082880435,95[.055706522,.111413043]); stillbelowaux.34375, originalcontrolgatefailed. Newstandalonearchitectureandlabel-freeprimarysharedparameterdependence tests required. Sources/rulefixed; noadditionalweights, temperatures orgrids.", + "fold_label_free_checks_predeclared_before_measurement": { + "primary_logit_centered_RMS_fraction_minimum": 0.25, + "predicted_class_changes_under_fitmean_primary_features_minimum_fraction": 0.1, + "predicted_class_changes_under_fixed_primary_feature_permutation_minimum_fraction": 0.15, + "predicted_class_changes_under_native_zero_shared_primary_final_normalization_minimum_fraction": 0.1, + "all_ten_other_normal_outputs_byte_exact": true + }, + "production_policy": "Preserveunchangedextra-labelpaths. Ifnewfit-onlyfoldroutepasses, explicitlyreplacepreviousfullpoolfoldroutewithfit-onlyone; remainingfourfullpoolheadsretained. Scoresofretainedfullpoolheadsremainin-sampleandnotselectionevidence.", + "publication": "Noautomaticpublication; completefreshnativeaudits, writehonestREADMEandselectionrecord, atomicmandatorypublisher." + }, + "all_non_SS_readout_state_exact": true, + "method": "Same shared architecture and own-session encoders/local prefixes; only SS readout/fit statistics replaced by final all-fit state. No fitting in assembly." + }, + "fit_only_primary_fold_source": "/workspace/research/dual-residue-readout1-replay/candidate/package", + "fit_only_primary_fold_source_sha256": "bd9bdcc7561bc61d64523b9e99cff98df05ddceebd211a740b07ee8b94abb18e", + "auxiliary_package": "/workspace/research/scale85m-8h-rank3/candidate/package", + "auxiliary_sha256": "e601068c8d9b9a81934404866cea95d69950eb161fe8be0c6dec04bbca36d7db", + "auxiliary_provenance": { + "method": "Fixed rank-target readout transfer within one tensor-identical shared backbone", + "parent": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/candidate/package", + "parent_provenance": { + "method": "Consolidated task readouts with tensor-identical jointly learned shared components; one literal parameter set", + "shared_parameter_digest": "397be7af196fb356e544d391fbcdc9928f0ea6e4cfd66ab6ea4a4e4c656770bc", + "head_sources": { + "fluorescence": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-fluorescence/package", + "stability": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-stability/package", + "beta_lactamase": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-beta_lactamase/package", + "solubility": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-solubility/package", + "subcellular_localization": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-subcellular_localization/package", + "binary_localization": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "fold": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-fold/package", + "secondary_structure": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-secondary_structure/package", + "yeast_ppi": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-yeast_ppi/package", + "human_ppi": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "ppi_affinity": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/head-ppi_affinity/package" + }, + "parent_provenance": [ + { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "beta_lactamase", + "readout_kind": "residue", + "bins": 320, + "ridge": 1.0, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cuda", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "fluorescence", + "readout_kind": "residue", + "bins": 256, + "ridge": 1.0, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cuda", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "fold", + "readout_kind": "summary", + "bins": null, + "ridge": 0.0001, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.5, + "training_device": "cuda", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "ppi_affinity", + "readout_kind": "pair_symmetric", + "bins": null, + "ridge": 0.01, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random linear local readout on same joint residue states; fit-only fixed normalization and sampled fit residue labels; ridge cross entropy LBFGS", + "seed": 20261103, + "fit_residues_including_window_duplicates": 505584, + "kernel": 9, + "ridge": 0.01, + "retained_learned_nonlinear_prefix": true, + "training_device": "cuda", + "tune_policy": "fixed supplied strengths or default three strengths; full valid-residue accuracy with overlapping-window probability aggregation", + "tested_ridges": [ + 0.01 + ], + "feature_cache_exported": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "solubility", + "readout_kind": "summary", + "bins": null, + "ridge": 0.1, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Retained joint pair nonlinear prefix; random final layer fit using fixed fit normalization and regularized LBFGS", + "seed": 20261107, + "selected_ridges": { + "stability": 0.001 + }, + "tested_ridges": [ + 0.001 + ], + "tune_policy": "fixed supplied strengths or default five strengths; small tune sets limit confidence", + "feature_cache_exported": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "subcellular_localization", + "readout_kind": "summary", + "bins": null, + "ridge": 0.01, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + }, + { + "parent": "/run-state/workspace/research/reviews/scale85m-continue4h-compiled1-at14400-joint8486-eval-0008486/raw/package", + "parent_provenance": { + "parent_run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "training_provenance": { + "seed": 20261026, + "created_utc": "2026-10-25T15:44:31Z", + "fit": "/workspace/data/fit", + "tune_policy": "selection only", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486", + "init": "/workspace/research/scale85m-continue4h-compiled1/snapshots/at-0014400s.pt", + "resume": null, + "config": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486/config.json", + "seconds": 3600.0, + "max_steps": 8486, + "eval_seconds": 300.0, + "evaluate_initial": false, + "lr": 3e-05, + "schedule_seconds": 3600.0, + "schedule_steps": 50916, + "head_lr": 0.0003, + "task_alpha": 0.25, + "task_weights": "{\"fold\": 1.5, \"secondary_structure\": 1.3, \"yeast_ppi\": 1.25, \"human_ppi\": 1.25, \"ppi_affinity\": 1.1}", + "token_budget": 16384, + "pair_token_budget": 32768, + "batch_size": 64, + "seed": 20261026, + "ema": 0.999, + "rank_weight": 0.1, + "pair_swap": 0.5, + "pair_label_smoothing": 0.05, + "anchor_decay": 1e-05, + "regression_encoder_scale": 1.0, + "freeze_heads": false, + "condition_only": false, + "condition_row_optimizer": false, + "extension_only": false, + "publish": false + }, + "initial_checkpoint_sha256": "f581d540b6abbb34eef9b424e3cb8d47a876d6e5abdf1ad85402841ea9dc93dc", + "transfer": { + "transferred": 196, + "new_tensors": [ + "pool_query", + "pool_position", + "heads.solubility.0.weight", + "heads.solubility.0.bias", + "heads.solubility.2.weight", + "heads.solubility.2.bias", + "heads.solubility.3.weight", + "heads.solubility.3.bias", + "heads.subcellular_localization.0.weight", + "heads.subcellular_localization.0.bias", + "heads.subcellular_localization.2.weight", + "heads.subcellular_localization.2.bias", + "heads.subcellular_localization.3.weight", + "heads.subcellular_localization.3.bias", + "heads.binary_localization.0.weight", + "heads.binary_localization.0.bias", + "heads.binary_localization.2.weight", + "heads.binary_localization.2.bias", + "heads.binary_localization.3.weight", + "heads.binary_localization.3.bias", + "heads.fold.0.weight", + "heads.fold.0.bias", + "heads.fold.2.weight", + "heads.fold.2.bias", + "heads.fold.3.weight", + "heads.fold.3.bias", + "heads.yeast_ppi.0.weight", + "heads.yeast_ppi.0.bias", + "heads.yeast_ppi.2.weight", + "heads.yeast_ppi.2.bias", + "heads.yeast_ppi.3.weight", + "heads.yeast_ppi.3.bias", + "heads.human_ppi.0.weight", + "heads.human_ppi.0.bias", + "heads.human_ppi.2.weight", + "heads.human_ppi.2.bias", + "heads.human_ppi.3.weight", + "heads.human_ppi.3.bias", + "heads.fluorescence.0.weight", + "heads.fluorescence.0.bias", + "heads.fluorescence.2.weight", + "heads.fluorescence.2.bias", + "heads.fluorescence.3.weight", + "heads.fluorescence.3.bias", + "heads.stability.0.weight", + "heads.stability.0.bias", + "heads.stability.2.weight", + "heads.stability.2.bias", + "heads.stability.3.weight", + "heads.stability.3.bias", + "heads.beta_lactamase.0.weight", + "heads.beta_lactamase.0.bias", + "heads.beta_lactamase.2.weight", + "heads.beta_lactamase.2.bias", + "heads.beta_lactamase.3.weight", + "heads.beta_lactamase.3.bias", + "heads.ppi_affinity.0.weight", + "heads.ppi_affinity.0.bias", + "heads.ppi_affinity.2.weight", + "heads.ppi_affinity.2.bias", + "heads.ppi_affinity.3.weight", + "heads.ppi_affinity.3.bias", + "heads.secondary_structure.0.weight", + "heads.secondary_structure.0.bias", + "heads.secondary_structure.2.weight", + "heads.secondary_structure.2.bias", + "heads.secondary_structure.3.weight", + "heads.secondary_structure.3.bias", + "heads.secondary_structure.context.0.weight", + "heads.secondary_structure.context.0.bias", + "heads.secondary_structure.context.2.weight", + "heads.secondary_structure.context.2.bias", + "pool_fuse.weight", + "pool_fuse.bias", + "pair_fuse.weight", + "pair_fuse.bias" + ], + "unexpected": [] + }, + "parent_provenance": { + "initialization": "Own-session random-initialized lineage; new MLM phase with fresh optimizer", + "parent": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "parent_provenance": { + "initialization": "Fresh random initialization in this session", + "parent": null, + "parent_provenance": null, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": false, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-mlm4h", + "init": null, + "config": "/workspace/research/scale85m-mlm4h/config.json", + "resume": null, + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0004, + "mlm_readout": "linear", + "seed": 20261121, + "snapshot_seconds": "3600,7200,14400", + "stop_after_steps": 0 + } + }, + "sources": { + "generic": { + "source": "/workspace/data/pretrain/uniref50_subset.fasta", + "sequences": 37338993, + "residues": 9903283016, + "seconds": 79.3608110989444, + "byteorder": "little", + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "manifest": { + "decontamination": { + "args": [ + "--min-seq-id", + "0.5", + "--alignment-mode", + "3", + "-c", + "0.8", + "--cov-mode", + "0", + "--max-seqs", + "300", + "-s", + "7" + ], + "query_sequences": 50254, + "removed": 45522, + "tool": "mmseqs easy-search" + }, + "files": { + "uniref50_subset.fasta": "fd68ec1e02ecb6bd1bcba093720a0e03b5e83a13593f241748fa10d98f18c2b6" + }, + "length": { + "max": 1024, + "mean": 265.2263015234503, + "median": 203, + "min": 30 + }, + "pinned_release": "2026_03", + "residues": 9903283016, + "sampling": { + "max_length": 1024, + "method": "all-in-range", + "min_length": 30, + "records_in_range": 37384515, + "records_scanned": 38840027 + }, + "schema": "peer-protein-pretrain/v1", + "sequences": 37338993, + "source": "UniRef50", + "source_release_note": null, + "source_sha256": "95bdf597d2f892295b5aa2925f5da593e1f2e1fcd7a0a4f5e66b9f1c2e83290d", + "source_size": 8780552383 + } + }, + "domain": { + "source": "/workspace/data/fit", + "sequences": 179628, + "residues": 39733941, + "alphabet": "LAGVSERTIDPKQNFYMHWCXBUZO", + "first_residue": 4, + "tokens_sha256": "1f297779c964ed55aa920fe31da99c15aa8797ef049cd2cb484ebd5677aa63fe", + "manifest": { + "inputs": { + "beta_lactamase.jsonl": { + "file_sha256": "6a5305b73b1359f23b3789a0c4198228cc48278ad8a8f91c93e0a04be1d28a91", + "sequence_presentations": 4158 + }, + "binary_localization.jsonl": { + "file_sha256": "6d281ff0a0be446d674358c18a14465658c2c694de7b567a0027237c527354b4", + "sequence_presentations": 5184 + }, + "fluorescence.jsonl": { + "file_sha256": "ff5d18a78ecb0cf584d6d3b96b8d18c8553593007afa356c4e228559b084d9b6", + "sequence_presentations": 21446 + }, + "fold.jsonl": { + "file_sha256": "931f4be0125ef6b38e97a2fc1c8adebb91bf6ae7493ca6f5661573d1d1a19b9a", + "sequence_presentations": 12312 + }, + "human_ppi.jsonl": { + "file_sha256": "ec222f1759d3de2aeacaf77da312df770c64ecaf9fe2c4704109826fb8e8b7f2", + "sequence_presentations": 71338 + }, + "ppi_affinity.jsonl": { + "file_sha256": "b8f571c32248cbb2a9d2b8a3c2393abed4354849b9ca147c46117ffe2174ddce", + "sequence_presentations": 4842 + }, + "secondary_structure.jsonl": { + "file_sha256": "4ef39e08b03fa8c1ed2efce9aa01c003e7ef3b874985e8f800a435eb0fb7be18", + "sequence_presentations": 8678 + }, + "solubility.jsonl": { + "file_sha256": "abe4036e453a79f5428b755721b539899ed81c9be2d2376e9efb0737d8d2ebeb", + "sequence_presentations": 62478 + }, + "stability.jsonl": { + "file_sha256": "48b7663d46efd4d9c9b7128203fac007c5550779923348ffb3262dd71f624d62", + "sequence_presentations": 53614 + }, + "subcellular_localization.jsonl": { + "file_sha256": "72b6be9573ec8eec77268eae099a208f128f409356860c555664d2dad8db2538", + "sequence_presentations": 8420 + }, + "yeast_ppi.jsonl": { + "file_sha256": "43669433617fa600682858d50ce3e23751acf21b85afcd70f16ab4dc37e2b0a9", + "sequence_presentations": 9890 + } + }, + "labels_used": false, + "tune_used": false, + "deduplication": "Exact sequence across all eleven fit tasks; first occurrence in sorted task files" + }, + "purpose": "Training-only label-free domain MLM corpus; never an inference lookup" + } + }, + "labels_used": false, + "tune_used": false, + "mlm_readout": { + "kind": "linear", + "training_only": true, + "inherited": true, + "parameters": 0, + "initialization": "inherited or parameter-free" + }, + "mixing": "Bernoulli by token-budgeted batch; actual tokens reported per corpus", + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": null, + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + }, + "parent_sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "inherited_data_stream": { + "parent_stage_tokens_seen": 4491780664, + "parent_stage_active_seconds": 14400.080329400342, + "parent_stage_source_tokens": { + "generic": 4491780664, + "domain": 0 + }, + "stream_positions": { + "generic": { + "permutation_seed": 38378812455577342, + "cursor": 16809984, + "epoch": 1, + "without_replacement": true + }, + "domain": { + "permutation_seed": null, + "cursor": 0, + "epoch": 0, + "without_replacement": true + } + }, + "pending_batches": { + "generic": 11, + "domain": 0 + }, + "masking_rng": "Fresh stage seed; recovery restores the stage masking RNG exactly", + "optimizer": "Fresh stage optimizer; no optimizer state imported with the data stream", + "sha256": "43f4a552918678df8f1f4acad66ac05a435c5d84905409d84a45ad1591755d8f", + "checkpoint": "/workspace/research/scale85m-mlm4h/pretrain.pt" + }, + "encoder_execution": { + "backend": "torch_inductor", + "dynamic": true, + "fullgraph": true, + "max_rotary_length": 1024, + "persistent_state_keys_unchanged": true, + "inference_requires_compiler": false, + "cache_manager": "same_directory_atomic_replace", + "compile_threads": 4, + "coalesce_tiling_analysis": false, + "max_tiles": 3, + "numerics": "Close but not bit-identical to eager; downstream selection remains required." + }, + "continuations": [ + { + "utc": "2026-10-25T08:58:57Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 0, + "active_seconds": 0.0, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + }, + { + "utc": "2026-10-25T09:06:53Z", + "resume_from": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "step": 1598, + "active_seconds": 300.5015191048733, + "arguments": { + "run": "/workspace/research/scale85m-continue4h-compiled1", + "init": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "config": null, + "resume": "/workspace/research/scale85m-continue4h-compiled1/pretrain.pt", + "init_data_state": "/workspace/research/scale85m-mlm4h/pretrain.pt", + "corpus": "/workspace/research/cache/uniref50", + "domain": "/workspace/research/cache/fit-text", + "domain_fraction": 0.0, + "seconds": 14400.0, + "eval_seconds": 600.0, + "token_budget": 65536, + "lr": 0.0001, + "mlm_readout": "linear", + "compile_encoder": true, + "seed": 20261210, + "snapshot_seconds": "7200,14400", + "stop_after_steps": 0 + } + } + ], + "compiler_warmups": [ + { + "seconds": 73.32705240600626, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + }, + { + "seconds": 41.77339493698673, + "batch_sizes": [ + 4, + 1 + ], + "synthetic_length": 128, + "optimizer_updates": 0, + "parameters_modified": false, + "RNG_restored": true, + "excluded_from_active_training_clock": true, + "reported_as_additional_startup_wall_time": true + } + ] + }, + "parent_training": { + "phase": "pretrain", + "active_seconds": 14400.099049523531, + "step": 90848, + "tokens_seen": 5762728738, + "history": [ + { + "step": 0, + "active_seconds": 0.0, + "tokens": 0, + "source_tokens": { + "generic": 0, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.423511048027335, + "domain": 2.4946916702850217 + } + }, + { + "step": 3492, + "active_seconds": 600.1476070382632, + "tokens": 221623432, + "source_tokens": { + "generic": 221623432, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4253183783676837, + "domain": 2.4948402063720803 + } + }, + { + "step": 7292, + "active_seconds": 1200.1844144255156, + "tokens": 462490612, + "source_tokens": { + "generic": 462490612, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4239450584638504, + "domain": 2.494536972506796 + } + }, + { + "step": 11084, + "active_seconds": 1800.3797199359105, + "tokens": 702974589, + "source_tokens": { + "generic": 702974589, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4218759844501063, + "domain": 2.491229815872936 + } + }, + { + "step": 14881, + "active_seconds": 2400.385638829466, + "tokens": 943804461, + "source_tokens": { + "generic": 943804461, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.419531168362674, + "domain": 2.4875500407982614 + } + }, + { + "step": 18694, + "active_seconds": 3000.49771780608, + "tokens": 1185700038, + "source_tokens": { + "generic": 1185700038, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.417477845550631, + "domain": 2.4883330016508087 + } + }, + { + "step": 22495, + "active_seconds": 3600.5847576800443, + "tokens": 1426832861, + "source_tokens": { + "generic": 1426832861, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4149791911258496, + "domain": 2.4841147177106406 + } + }, + { + "step": 26300, + "active_seconds": 4200.59286573666, + "tokens": 1668114975, + "source_tokens": { + "generic": 1668114975, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4128974753320813, + "domain": 2.482289464189824 + } + }, + { + "step": 30113, + "active_seconds": 4800.7282401409175, + "tokens": 1909816913, + "source_tokens": { + "generic": 1909816913, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4104219554847988, + "domain": 2.480595113831345 + } + }, + { + "step": 33919, + "active_seconds": 5400.8894071894465, + "tokens": 2151378174, + "source_tokens": { + "generic": 2151378174, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4081391597540662, + "domain": 2.4788178428417407 + } + }, + { + "step": 37724, + "active_seconds": 6000.945332366187, + "tokens": 2392498343, + "source_tokens": { + "generic": 2392498343, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.40604953234298, + "domain": 2.4760817078267636 + } + }, + { + "step": 41539, + "active_seconds": 6600.987033036014, + "tokens": 2634479816, + "source_tokens": { + "generic": 2634479816, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4048449735994493, + "domain": 2.4754943315063263 + } + }, + { + "step": 45345, + "active_seconds": 7200.023320763808, + "tokens": 2876046075, + "source_tokens": { + "generic": 2876046075, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.402990461686931, + "domain": 2.471542294896966 + } + }, + { + "step": 49141, + "active_seconds": 7800.068156623776, + "tokens": 3116989552, + "source_tokens": { + "generic": 3116989552, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.4007241614982235, + "domain": 2.470990069713636 + } + }, + { + "step": 52904, + "active_seconds": 8400.131869991426, + "tokens": 3356055558, + "source_tokens": { + "generic": 3356055558, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.399649958355359, + "domain": 2.4703706067141984 + } + }, + { + "step": 56697, + "active_seconds": 9000.173056922475, + "tokens": 3596533259, + "source_tokens": { + "generic": 3596533259, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3977112399422813, + "domain": 2.468582323340381 + } + }, + { + "step": 60495, + "active_seconds": 9600.258449959103, + "tokens": 3837667685, + "source_tokens": { + "generic": 3837667685, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.396356180387372, + "domain": 2.467015188962025 + } + }, + { + "step": 64294, + "active_seconds": 10200.273898192594, + "tokens": 4078536135, + "source_tokens": { + "generic": 4078536135, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3955589558835735, + "domain": 2.4658141508088334 + } + }, + { + "step": 68115, + "active_seconds": 10800.419885064737, + "tokens": 4320950711, + "source_tokens": { + "generic": 4320950711, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3943983132191766, + "domain": 2.4638538644816 + } + }, + { + "step": 71916, + "active_seconds": 11400.505260802456, + "tokens": 4561960446, + "source_tokens": { + "generic": 4561960446, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3931896485983737, + "domain": 2.4637948531786984 + } + }, + { + "step": 75715, + "active_seconds": 12000.620743476233, + "tokens": 4802972926, + "source_tokens": { + "generic": 4802972926, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3925407879288936, + "domain": 2.4616549764964257 + } + }, + { + "step": 79513, + "active_seconds": 12600.718148327753, + "tokens": 5043800640, + "source_tokens": { + "generic": 5043800640, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3921744404289553, + "domain": 2.462337334630697 + } + }, + { + "step": 83309, + "active_seconds": 13200.741079131374, + "tokens": 5284462688, + "source_tokens": { + "generic": 5284462688, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3915259279186594, + "domain": 2.461360936005462 + } + }, + { + "step": 87101, + "active_seconds": 13800.777039410808, + "tokens": 5525156396, + "source_tokens": { + "generic": 5525156396, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3916266299612445, + "domain": 2.4602868844077226 + } + }, + { + "step": 90848, + "active_seconds": 14400.099049523531, + "tokens": 5762728738, + "source_tokens": { + "generic": 5762728738, + "domain": 0 + }, + "mlm_loss": { + "generic": 2.3906130185218766, + "domain": 2.4593765764752398 + } + } + ] + } + }, + "snapshot_step": 8486, + "weights": "raw" + }, + "method": "Random-initialized linear head over expanded shared encoder states; fit-only feature normalization and ridge LBFGS; tune selection", + "task": "yeast_ppi", + "readout_kind": "pair_symmetric", + "bins": null, + "ridge": 0.01, + "seed": 20261031, + "encoder_layers": 12, + "class_weight_power": 0.0, + "training_device": "cpu", + "cpu_threads": 4, + "feature_cache_exported": false, + "fixed_shared_bilinear_residual_included": false, + "uncompressed_chain_summaries": false + } + ], + "feature_cache_exported": false, + "pair_context_selection": { + "policy": "One fixed1536-token alternative versus the current context, chosen on tune with all learned tensors frozen.", + "choice_basis": "Earlier fit-only chain-length audit; human and yeast fit maxima1500/1495residues.", + "choices": { + "human_ppi": { + "original_tokens": 1024, + "selected_tokens": 1024, + "metrics_by_context": { + "1024": { + "accuracy": 0.819047619047619, + "balanced_accuracy": 0.8180272108843538, + "macro_f1": 0.8181606424889357, + "reward": 0.819047619047619 + }, + "1536": { + "accuracy": 0.819047619047619, + "balanced_accuracy": 0.8171768707482994, + "macro_f1": 0.817806370435012, + "reward": 0.819047619047619 + } + } + }, + "yeast_ppi": { + "original_tokens": 1024, + "selected_tokens": 1024, + "metrics_by_context": { + "1024": { + "accuracy": 0.5894736842105263, + "balanced_accuracy": 0.570054945054945, + "macro_f1": 0.5704347826086956, + "reward": 0.5894736842105263 + }, + "1536": { + "accuracy": 0.5789473684210527, + "balanced_accuracy": 0.5611263736263736, + "macro_f1": 0.5614035087719298, + "reward": 0.5789473684210527 + } + } + } + }, + "learned_parameter_updates": 0 + } + }, + "rank_head_sources": { + "fluorescence": "/workspace/research/scale85m-8h-rank3/head-fluorescence/package", + "beta_lactamase": "/workspace/research/scale85m-8h-rank3/head-beta_lactamase/package", + "stability": "/workspace/research/scale85m-8h-rank3/head-stability/package" + }, + "head_seeds": { + "fluorescence": 20261031, + "beta_lactamase": 20261031, + "stability": 20261107 + }, + "ridges": { + "fluorescence": 1.0, + "beta_lactamase": 1.0, + "stability": 0.001 + }, + "fit_only_feature_statistics_and_rank_targets": true, + "all_other_tensors_exact": true, + "feature_cache_exported": false + }, + "fold_study": { + "created_utc": "2026-10-25T17:54:35.605070+00:00", + "status": "queued", + "run": "/workspace/research/fold-logit-fusion1", + "packages": { + "primary": "/workspace/research/dual-residue-readout1-replay/candidate/package", + "auxiliary": "/workspace/research/scale85m-8h-rank3/candidate/package" + }, + "features": { + "primary": "/workspace/research/conditioned-readout-refit1/features-summary/fold/tune.pt", + "auxiliary": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/features-summary/fold/tune.pt" + }, + "predictions": { + "primary": "/workspace/research/dual-residue-readout1-replay/candidate/replay/predictions/fold.jsonl", + "auxiliary": "/workspace/research/scale85m-8h-rank3/candidate/replay/predictions/fold.jsonl" + }, + "frozen_sha256": { + "/workspace/research/run_fold_logit_fusion.py": "3249a75fa71fbcd888e344200b8b0899e76fb6f049d864078f16b938d60cbe75", + "/workspace/research/fit_dual_residue_readouts.py": "a55238416ea2052f98e5cf00a2707c3b568183af1972e98e3a7cc43b8f9073fe", + "/workspace/research/fold-logit-fusion1/PROPOSAL.md": "e0c08009551809807db0941a3ad16e9a7abcc3dd43c3dcd0ea74e15e3d484162", + "/workspace/research/dual-summary-feature-checks.json": "c0f3988785747df6360d12eb7d1cfba267f5f80679868fd6f710bde1f803a25f", + "/workspace/research/conditioned-readout-refit1/features-summary/fold/tune.pt": "7e0bc2c0d63b6673d3dcbbb6f7d15a0251c061742ed6bd949d640ad6fcd82296", + "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/features-summary/fold/tune.pt": "ab948028b9be27d990a0a83b6e6e92384fc19667bc6f87e6777368c9aac2b9da", + "/workspace/research/dual-residue-readout1-replay/candidate/replay/predictions/fold.jsonl": "365d0e8cf6d51bfe90a154cef6dd6ea9d6ca37467193655c131cc2ab1df17a36", + "/workspace/research/scale85m-8h-rank3/candidate/replay/predictions/fold.jsonl": "6c63e2d7c933cb1350be5f3938bee3f73026542122c32a6c572dcbed2c167f73", + "/workspace/research/dual-residue-readout1-replay/candidate/package/model.pt": "bd9bdcc7561bc61d64523b9e99cff98df05ddceebd211a740b07ee8b94abb18e", + "/workspace/research/dual-residue-readout1-replay/candidate/package/config.json": "fa516bd8637412d039d46cc25ceeb318e8da206b892fae9a8fc84540dc68e943", + "/workspace/research/scale85m-8h-rank3/candidate/package/model.pt": "e601068c8d9b9a81934404866cea95d69950eb161fe8be0c6dec04bbca36d7db", + "/workspace/research/scale85m-8h-rank3/candidate/package/config.json": "96b66062420d075cb8810e95cbcce76fd316c60191edf4e413f6bf21b594a7c1" + }, + "recovery_registered": true, + "recovery_command": [ + "/opt/conda/bin/python", + "-u", + "/workspace/research/run_fold_logit_fusion.py", + "--run", + "/workspace/research/fold-logit-fusion1" + ], + "new_training_updates": 0 + }, + "fold_result": { + "status": "no_eligible_gain", + "eligible": false, + "accuracies": { + "primary": 0.24864130434782608, + "auxiliary": 0.34375, + "raw": 0.31657608695652173, + "full": 0.33152173913043476 + }, + "comparisons": { + "full_minus_primary": { + "delta": 0.08288043478260869, + "conditional95": [ + 0.05570652173913043, + 0.11141304347826086 + ] + }, + "full_minus_auxiliary": { + "delta": -0.012228260869565218, + "conditional95": [ + -0.03264266304347826, + 0.009544836956521554 + ] + }, + "full_minus_raw": { + "delta": 0.014945652173913044, + "conditional95": [ + 0.001358695652173913, + 0.028532608695652172 + ] + } + }, + "native_feature_head_checks": { + "primary": { + "native_argmax_exact": true, + "maximum_probability_difference": 3.814697265625e-06 + }, + "auxiliary": { + "native_argmax_exact": true, + "maximum_probability_difference": 2.6226043701171875e-06 + } + }, + "new_training_updates": 0, + "learned_parameter_provenance": "Both source models jointly trained all11 from scratch in this session.", + "exported": false, + "published": false, + "limitations": "Fixedequalweights/rowRMS inference only; conditional intervals do not correct repeated selection or familydependence. Removingprimarylogits yieldsauxiliaryargmax, so dependencegate requirespositive>=.02gain overauxiliary." + }, + "publication_policy_review": { + "utc": "2026-10-25T17:57:48.483468+00:00", + "status": "publication_policy_review_before_new_native_audits", + "retrospective_policy_change": true, + "original_studies_unchanged": [ + "dual-residue-allfit1", + "fold-logit-fusion1" + ], + "reason": "The operator requires strongest complete compliant shared-parameter model. Earlier research screens imposed extra minimum-gain and accuracy-ablation-benefit conditions. They test stricter scientific hypotheses, not the stated replay/shared-parameter contract. Keep failed original hypothesis outcomes intact; assess deployment separately and disclose retrospective selection.", + "quality_policy": "Native all11 valid; compare each affected fit-only task to selected reference, require positive gain and positive paired conditional95lower, other outputs exact for isolatedhead changes. No arbitrary minimum positive effect floor. MultipleTune selection and family dependence remain limitations.", + "common_parameter_policy": "One original37845535parameter jointlylearned primary encoder actually supplies everytask. Audit native prediction sensitivity to sharedparameter intervention and frozen feature intervention withoutlabels. Improvement after removal does not establish independence; prediction invariance would. Any independentpathwithnegligibleprimary effect muststillfail.", + "SS_review": "Unchangednativearchitecture, fullfithead; original>.0005gatefailedat+.000425546, paired95[.000153184,.000704878]. Independentnativeall11/oldcacheidentity/sharedfeaturedependence recheck beforeselection. Noadditionalheadfit.", + "fold_review": "Fixednormalizedscorefusion pilot.331521739vsselected.248641304(delta+.082880435,95[.055706522,.111413043]); stillbelowaux.34375, originalcontrolgatefailed. Newstandalonearchitectureandlabel-freeprimarysharedparameterdependence tests required. Sources/rulefixed; noadditionalweights, temperatures orgrids.", + "fold_label_free_checks_predeclared_before_measurement": { + "primary_logit_centered_RMS_fraction_minimum": 0.25, + "predicted_class_changes_under_fitmean_primary_features_minimum_fraction": 0.1, + "predicted_class_changes_under_fixed_primary_feature_permutation_minimum_fraction": 0.15, + "predicted_class_changes_under_native_zero_shared_primary_final_normalization_minimum_fraction": 0.1, + "all_ten_other_normal_outputs_byte_exact": true + }, + "production_policy": "Preserveunchangedextra-labelpaths. Ifnewfit-onlyfoldroutepasses, explicitlyreplacepreviousfullpoolfoldroutewithfit-onlyone; remainingfourfullpoolheadsretained. Scoresofretainedfullpoolheadsremainin-sampleandnotselectionevidence.", + "publication": "Noautomaticpublication; completefreshnativeaudits, writehonestREADMEandselectionrecord, atomicmandatorypublisher." + }, + "one_auxiliary_encoder": true, + "all_non_fold_parent_paths_exact": true, + "new_training_updates": 0, + "method": "Reuse the two active native fit-only fold readouts; center and divide each class-logit vector by its rowRMS, floor1e-6, and take equalmean. All11 retain the same common jointlytrained primaryencoder. No test-time fitting or lookup." + }, + "fullpool_recipe_plan": { + "created_utc": "2026-10-25T18:10:25.957757+00:00", + "status": "queued", + "recovery_registered": true, + "run": "/workspace/research/production-dual-fold-fullpool1", + "parent_trainer": "/workspace/research/scale170m-grown4h-compiled1", + "pilot_run": "/workspace/research/crossfit-dual-fold-labels1", + "source_fit_only_package": "/workspace/research/fold-shared-publication-review1/candidate/package", + "fit_only_development_reference": { + "reward": 0.7297185914788012, + "tasks": { + "beta_lactamase": { + "invalid_reason": null, + "reward": 0.8851158090618965, + "spearman": 0.8851158090618965 + }, + "binary_localization": { + "accuracy": 0.9462116830537883, + "balanced_accuracy": 0.9419155998103367, + "invalid_reason": null, + "macro_f1": 0.9439947337349208, + "reward": 0.9462116830537883 + }, + "fluorescence": { + "invalid_reason": null, + "reward": 0.826705913429907, + "spearman": 0.826705913429907 + }, + "fold": { + "accuracy": 0.33152173913043476, + "balanced_accuracy": 0.24829334307555725, + "invalid_reason": null, + "macro_f1": 0.06260331921007772, + "reward": 0.33152173913043476 + }, + "human_ppi": { + "accuracy": 0.7968253968253968, + "balanced_accuracy": 0.8005952380952381, + "invalid_reason": null, + "macro_f1": 0.7968233491897122, + "reward": 0.7968253968253968 + }, + "ppi_affinity": { + "invalid_reason": null, + "reward": 0.5341420012716276, + "rmse": 1.9334586965956642, + "spearman": 0.7162121646852028 + }, + "secondary_structure": { + "accuracy": 0.767856341270283, + "invalid_reason": null, + "reward": 0.767856341270283, + "valid_residues": 556931 + }, + "solubility": { + "accuracy": 0.7533851915874388, + "balanced_accuracy": 0.7392508255204544, + "invalid_reason": null, + "macro_f1": 0.742264399722415, + "reward": 0.7533851915874388 + }, + "stability": { + "invalid_reason": null, + "reward": 0.7311607642876724, + "spearman": 0.7311607642876724 + }, + "subcellular_localization": { + "accuracy": 0.7908217716115261, + "balanced_accuracy": 0.6999121500389823, + "invalid_reason": null, + "macro_f1": 0.7198401417205603, + "reward": 0.7908217716115261 + }, + "yeast_ppi": { + "accuracy": 0.6631578947368421, + "balanced_accuracy": 0.6597985347985349, + "invalid_reason": null, + "macro_f1": 0.6567299006323397, + "reward": 0.6631578947368421 + } + }, + "package": "/workspace/research/fold-shared-publication-review1/candidate/package", + "report": "/workspace/research/fold-shared-publication-review1/candidate/report.json", + "model_sha256": "19088470dfe6d5940dcf1589c40a693dcbbf81342320a0551e4bc3612077fb6d", + "inference_assets_sha256": { + "model.pt": "19088470dfe6d5940dcf1589c40a693dcbbf81342320a0551e4bc3612077fb6d", + "config.json": "c0d1e24fea3f93877d6815607918ab67c4f4d79ca213d9f507c4ee31775bd705", + "esm2.py": "d4d512296047ebbd0f9a26dc1390107f72762cb5de011eefc9fecb18118a9be9", + "unified.py": "836d7d3834d8601d2fe2a6f5f3513e9a02153aa39d44f8d38de0a354cf529883", + "replay.py": "9c5add2d3fb117470241cf63f621e4797a16962cddadbaad6de2cfb481e7fa85", + "infer.sh": "60f55b73f5b39a35a61df84026abed9a127b1cc035d650c9e1ca62f54fc2b468" + }, + "parameters": 145755212, + "score_kind": "fit_only_development_tune_selection", + "decision": "/workspace/research/fold-shared-publication-review1/decision.json" + }, + "production_parent": { + "utc": "2026-10-25T18:05:12.882285+00:00", + "package": "/workspace/research/production-fold-shared1/candidate/package", + "score_kind": "tune_labels_used_for_fluorescence_beta_lactamase_ppi_affinity_and_stability", + "model_sha256": "93a8fa2aadcb92983cefa53154866e9efc47a21deea0d847042c1f836883b513", + "inference_assets_sha256": { + "model.pt": "93a8fa2aadcb92983cefa53154866e9efc47a21deea0d847042c1f836883b513", + "config.json": "c0d1e24fea3f93877d6815607918ab67c4f4d79ca213d9f507c4ee31775bd705", + "esm2.py": "d4d512296047ebbd0f9a26dc1390107f72762cb5de011eefc9fecb18118a9be9", + "unified.py": "836d7d3834d8601d2fe2a6f5f3513e9a02153aa39d44f8d38de0a354cf529883", + "replay.py": "9c5add2d3fb117470241cf63f621e4797a16962cddadbaad6de2cfb481e7fa85", + "infer.sh": "60f55b73f5b39a35a61df84026abed9a127b1cc035d650c9e1ca62f54fc2b468" + }, + "parameters": 145755212, + "fit_only_development_reference": { + "package": "/workspace/research/fold-shared-publication-review1/candidate/package", + "report": "/workspace/research/fold-shared-publication-review1/candidate/report.json", + "reward": 0.7297185914788012, + "model_sha256": "19088470dfe6d5940dcf1589c40a693dcbbf81342320a0551e4bc3612077fb6d" + }, + "in_sample_verification_report": "/workspace/research/production-fold-shared1/candidate/report.json", + "verification": { + "all_eleven_outputs_valid": true, + "ten_other_predictions_byte_identical_to_previous_production": true, + "fold_predictions_byte_identical_to_accepted_fit_only_development": true, + "all_non_fold_feature_paths_unchanged": true, + "four_extra_label_heads_and_features_exact": true, + "one_auxiliary_encoder": true, + "tune_rows_used_for_fitting": { + "fluorescence": 5362, + "beta_lactamase": 520, + "ppi_affinity": 203, + "stability": 2512 + }, + "in_sample_scores_of_reused_label_tasks_excluded_from_selection": true, + "native_shared_primary_norm_zero_fold_class_change_fraction": 0.5040760869565217 + }, + "training": "Own-session jointlytrained all11 primary and auxiliary encoders, one copyeach. Fixed equalmean of two centered/RMS-normalized fit-only foldreadouts; primarycommonencoder remainsactiveall11 andnativeparameterzeroingchanges50.4%folddecisions. AllfitSSandother10paths unchanged. Four extra-labelheadsGFP/beta/affinity/stability retained exactly; previousfullpoolfoldheadremoved.", + "ss_fit_only_selection_evidence": { + "kind": "fit_only_tune_complete_replay", + "task": "secondary_structure", + "before": 0.7438318211771296, + "after": 0.7441316787896526, + "delta": 0.00029985761252291574, + "conditional_95_percentile_interval": [ + 4.102067509503305e-05, + 0.0005682928659789181 + ], + "examples": 2170, + "valid_residues": 556931, + "correct_residue_gain": 167, + "method": "own-session teacher distillation", + "teacher": "Own85M2hMLM+jointall11+taskconditioning; fit-onlylabels; no teacher exported", + "matched_controls": { + "hard": { + "delta": 0.0006984707261761331, + "conditional95": [ + 0.00020130648256647902, + 0.001201981603808556 + ], + "protein_units": 2170, + "valid_residues": 556931, + "draws": 2000, + "limitations": "Conditional paired protein bootstrap, not corrected for repeated tune selection or protein-family dependence." + }, + "smooth": { + "delta": 0.00027112873946682803, + "conditional95": [ + -0.00019057496656699647, + 0.0007187128477994618 + ], + "protein_units": 2170, + "valid_residues": 556931, + "draws": 2000, + "limitations": "Conditional paired protein bootstrap, not corrected for repeated tune selection or protein-family dependence." + } + }, + "other_ten_development_predictions_byte_identical": true, + "limitations": "Conditional paired protein bootstrap, not corrected for repeated tune selection or protein-family dependence. Teacher-versus-smoothing64 interval crosseszero.", + "selected_distillation_epoch": 64, + "distillation_updates": 9152, + "additional_updates_after16": 6864 + }, + "previous_production_package": "/workspace/research/production-allfit-ss1/candidate/package", + "tasks_reusing_tune_labels": [ + "fluorescence", + "beta_lactamase", + "ppi_affinity", + "stability" + ], + "fluorescence_recipe_selection_evidence": { + "incumbent_spearman": 0.826705913429907, + "matched_fit_only_refit_spearman": 0.8267059285858314, + "crossfit_spearman": 0.8289887921828193, + "crossfit_delta_vs_incumbent": 0.0022828787529123318, + "crossfit_delta_vs_fit_only_refit": 0.0022828635969879274, + "conditional_paired_95_vs_incumbent": [ + 0.0009792262424118709, + 0.0036331746186231443 + ], + "fold_results": [ + { + "heldout_half": 0, + "heldout_rows": 2681, + "added_tune_rows": 2681, + "training_rows": 24127, + "heldout_spearman": 0.8232686916324296, + "incumbent_same_half_spearman": 0.8211575283985865, + "fit_seconds": 1.7692138720012736, + "closures": 160 + }, + { + "heldout_half": 1, + "heldout_rows": 2681, + "added_tune_rows": 2681, + "training_rows": 24127, + "heldout_spearman": 0.8349378336333676, + "incumbent_same_half_spearman": 0.8324217270853131, + "fit_seconds": 1.6950949229940306, + "closures": 160 + } + ], + "limitations": "Prior tune model selection biases the estimate. Label stratification is not a protein-family split, and unseen test distribution may differ. Combined OOF scores come from two heads with training-only rank normalization, not one full-pool model. Conditional paired bootstrap ignores remaining family dependence and selection." + }, + "beta_lactamase_recipe_selection_evidence": { + "incumbent_spearman": 0.8851158090618965, + "matched_fit_only_refit_spearman": 0.8851173641514167, + "crossfit_spearman": 0.8939613181865891, + "crossfit_delta_vs_incumbent": 0.008845509124692619, + "crossfit_delta_vs_fit_only_refit": 0.008843954035172352, + "conditional_paired_95_vs_incumbent": [ + 0.0030908473904126045, + 0.016275743694867638 + ], + "fold_results": [ + { + "heldout_half": 0, + "heldout_rows": 260, + "added_tune_rows": 260, + "training_rows": 4418, + "heldout_spearman": 0.8954806478975963, + "incumbent_same_half_spearman": 0.8876831699844637, + "fit_seconds": 0.7535757489968091, + "closures": 163 + }, + { + "heldout_half": 1, + "heldout_rows": 260, + "added_tune_rows": 260, + "training_rows": 4418, + "heldout_spearman": 0.8906708928087468, + "incumbent_same_half_spearman": 0.8805064277745905, + "fit_seconds": 0.7396053560078144, + "closures": 161 + } + ], + "limitations": "Prior tune model selection biases the estimate. Label stratification is not a protein-family split, and unseen test distribution may differ. Combined OOF scores come from two heads with training-only rank normalization, not one full-pool model. Conditional paired bootstrap ignores remaining family dependence and selection." + }, + "ppi_affinity_recipe_selection_evidence": { + "status": "research_only_crossfit_complete", + "task": "ppi_affinity", + "incumbent_reward": 0.5341420012716276, + "matched_fit_only_reward": 0.5210555476068024, + "crossfit_reward": 0.5515877648877663, + "crossfit_delta_vs_incumbent": 0.0174457636161387, + "conditional_paired_95_vs_incumbent": [ + 0.002641673708393072, + 0.0303974991382099 + ], + "fold_results": [ + { + "heldout_half": 0, + "heldout_rows": 102, + "added_tune_rows": 101, + "reward": 0.5641044100756688, + "incumbent_reward": 0.5459868174958554, + "closures": 166, + "seconds": 0.1286191190010868 + }, + { + "heldout_half": 1, + "heldout_rows": 101, + "added_tune_rows": 102, + "reward": 0.5396756511271861, + "incumbent_reward": 0.522833934532602, + "closures": 163, + "seconds": 0.12902537698391825 + } + ], + "published": false, + "exported": false, + "limitations": "Tune influenced earlier backbone/head selection. Pair-example resampling does not establish protein or family independence. OOF heads are research evidence only, not a single replayable model.", + "publication": "Research-only out-of-fold evidence; no full-pool head, lookup or package is exported." + }, + "shared_summary_fit_only_evidence": { + "kind": "complete_fit_only_tune_replay", + "selected_global_step": 3000, + "jointly_trained_tasks": [ + "solubility", + "subcellular_localization", + "binary_localization" + ], + "parameters_added": 475906, + "tasks": { + "binary_localization": { + "before": 0.9375361480624639, + "after": 0.9462116830537883, + "delta": 0.008675534991324466, + "case_gain": 15, + "conditional95": [ + 0.002891844997108155, + 0.015037593984962405 + ], + "examples": 1729, + "limitations": "Conditional paired-example bootstrap; not corrected for repeated tune selection or family dependence." + } + }, + "other_ten_development_prediction_files_exact": true, + "limitations": "Conditional paired-example bootstrap does not correct repeated tune selection or family dependence. Only binary localization passes the predeclared exit gate." + }, + "stability_fit_only_selection_evidence": { + "kind": "fit_only_complete_tune_replay", + "task": "stability", + "before": 0.7274923808177973, + "after": 0.7311607642876724, + "delta": 0.0036683834698750806, + "conditional_95_percentile_interval": [ + 0.0017767471141417273, + 0.00544199745819068 + ], + "examples": 2512, + "mean_delta": 0.0003334894063522801, + "conditional_mean95": [ + 0.0001615224649219752, + 0.0004947270416536983 + ], + "matched_natural_mixture_control": { + "delta": 0.0020391645917180456, + "conditional_95": [ + 0.0012832147204794586, + 0.0028118185483942955 + ] + }, + "fixed_endpoint_updates": 1680, + "alpha": 0.5, + "ten_other_prediction_files_exact": true, + "limitations": "Conditional on already-selected models. Does not account for repeated tune selection, shared proteins across tasks, or family dependence within splits; not an independent generalization guarantee. The visible Tune length distribution informed the group-weighting hypothesis." + }, + "stability_extra_label_recipe_selection_evidence": { + "utc": "2026-10-25T16:17:04.539090+00:00", + "status": "research_only_crossfit_complete", + "scores": { + "incumbent": 0.7311607642876724, + "matched_fit_only": 0.7311607642876724, + "crossfit": 0.7337159019671029 + }, + "comparisons": { + "incumbent": { + "delta": 0.002555137679430497, + "conditional_95": [ + 0.0015641029747572976, + 0.0036431410475218527 + ] + }, + "matched_fit_only": { + "delta": 0.002555137679430497, + "conditional_95": [ + 0.0015641029747572976, + 0.0036431410475218527 + ] + } + }, + "fold_results": [ + { + "heldout_half": 0, + "heldout_rows": 1256, + "incumbent_same_half": 0.7325449010474826, + "matched_control_same_half": 0.7325449010474826, + "crossfit_same_half": 0.7351256285381212, + "step": 1680, + "epochs_started": 16, + "active_seconds": 7.389840035961242, + "training_rows": 54870, + "added_tune_rows": 1256, + "fixed_buffers_exact": true, + "group_counts": { + "43": 36446, + "50": 18424 + }, + "final_lr": 1.0000078679859099e-05 + }, + { + "heldout_half": 1, + "heldout_rows": 1256, + "incumbent_same_half": 0.7298113878884595, + "matched_control_same_half": 0.7298113878884595, + "crossfit_same_half": 0.7327158507790285, + "step": 1680, + "epochs_started": 16, + "active_seconds": 7.374784096988151, + "training_rows": 54870, + "added_tune_rows": 1256, + "fixed_buffers_exact": true, + "group_counts": { + "43": 36446, + "50": 18424 + }, + "final_lr": 1.0000078679859099e-05 + } + ], + "passes_predeclared_fullpool_gate": true, + "fit_only_reproduction_all_head_tensors_bit_exact": true, + "updates_per_arm": 1680, + "published": false, + "fullpool_head_fitted": false, + "candidate_exported": false, + "GPU_used": false, + "limitations": "Earlier Tune checkpoint/architecture selection biases estimates. Fixed label-stratified halves do not enforce protein-family or designed-scaffold independence. OOF predicts with two research heads trained on half the extra labels; it is recipe evidence, not a single final model measurement. Conditional bootstrap omits family dependence and prior selection." + }, + "subcellular_fit_only_selection_evidence": { + "kind": "fit_only_complete_native_tune_replay", + "task": "subcellular_localization", + "before": 0.7538242618285308, + "after": 0.7908217716115261, + "delta": 0.03699750978299532, + "conditional95": [ + 0.024181785841337605, + 0.05052472429740305 + ], + "mean_delta": 0.0033634099802724027, + "conditional_mean95": [ + 0.0021983441673943276, + 0.004593156754309368 + ], + "case_gain": 104, + "examples": 2811, + "matched_controls": { + "full_minus_parent": { + "delta": 0.036997509782995375, + "conditional95": [ + 0.024181785841337605, + 0.05052472429740305 + ] + }, + "full_minus_primary": { + "delta": 0.03948772678762007, + "conditional95": [ + 0.026680896478121666, + 0.05407328352899324 + ] + }, + "full_minus_auxiliary": { + "delta": 0.013162575595873355, + "conditional95": [ + 0.002845962290999644, + 0.022767698327997153 + ] + } + }, + "native_dependency": { + "native_accuracy": 0.7908217716115261, + "normal_replay_bit_exact": true, + "primary_ablated": { + "accuracy": 0.736392742796158, + "accuracy_drop": 0.054429028815368194, + "conditional95_drop": [ + 0.04054606901458555, + 0.06794734969761651 + ], + "prediction_changes": 464 + }, + "auxiliary_ablated": { + "accuracy": 0.5990750622554251, + "accuracy_drop": 0.19174670935610102, + "conditional95_drop": [ + 0.17467093561010316, + 0.20988971896122377 + ], + "prediction_changes": 899 + } + }, + "task_deltas": { + "beta_lactamase": 0.0, + "binary_localization": 0.0, + "fluorescence": 0.0, + "fold": 0.0, + "human_ppi": 0.0, + "ppi_affinity": 0.0, + "secondary_structure": 0.0, + "solubility": 0.0, + "stability": 0.0, + "subcellular_localization": 0.03699750978299532, + "yeast_ppi": 0.0 + }, + "ten_other_prediction_files_byte_exact": true, + "limitations": "Conditional paired-example bootstrap after repeated Tune selection; not corrected for protein-family dependence. Feature removal is a dependence diagnostic, not an in-distribution intervention." + }, + "SS_fusion_fit_only_selection_evidence": { + "kind": "fit_only_complete_native_tune_replay", + "task": "secondary_structure", + "before": 0.7441316787896526, + "after": 0.759638088021676, + "delta": 0.0155064092320234, + "conditional95": [ + 0.014309663742752683, + 0.016726396557557775 + ], + "mean_delta": 0.0014096735665475313, + "conditional_mean95": [ + 0.0013008785220684257, + 0.001520581505232525 + ], + "valid_residues": 556931, + "correct_residue_gain": 8636, + "protein_units": 2170, + "native_dependence": { + "native_accuracy": 0.759638088021676, + "normal_replay_bit_exact": true, + "proteins": 2170, + "valid_residues": 556931, + "primary_ablated": { + "accuracy": 0.6834275700221392, + "accuracy_drop": 0.07621051799953675, + "conditional95_drop": [ + 0.07213367476903872, + 0.08041229260742996 + ], + "changed_valid_residue_predictions": 124744 + }, + "auxiliary_ablated": { + "accuracy": 0.7315897301461043, + "accuracy_drop": 0.02804835787557166, + "conditional95_drop": [ + 0.026594330149706396, + 0.029575409027225635 + ], + "changed_valid_residue_predictions": 57661 + } + }, + "matched_zero_control": 0.7439539188876181, + "full_minus_zero": { + "delta": 0.0156841691340579, + "conditional95": [ + 0.014499037971929394, + 0.01689329854300642 + ] + }, + "ten_other_prediction_files_byte_identical": true, + "retained_subcellular_accuracy": 0.7908217716115261, + "limitations": "Repeated tune selection; conditional intervals do not correct selection or protein-family dependence. Zero auxiliary changes joint LayerNorm input distribution." + }, + "SS_dual_residue_fit_only_selection_evidence": { + "kind": "fit_only_complete_native_tune_replay", + "task": "secondary_structure", + "before": 0.759638088021676, + "after": 0.7674307948381397, + "delta": 0.0077927068164637125, + "conditional95": [ + 0.0069797076175643485, + 0.00868359254180614 + ], + "mean_delta": 0.0007084278924057719, + "conditional_mean95": [ + 0.0006345188743240317, + 0.0007894175038005582 + ], + "correct_residue_gain": 4340, + "valid_residues": 556931, + "protein_units": 2170, + "native_dependence_and_control_comparisons": { + "native_accuracy": 0.7674307948381397, + "normal_replay_bit_exact": true, + "proteins": 2170, + "valid_residues": 556931, + "primary_ablated": { + "accuracy": 0.7548798684217614, + "accuracy_drop": 0.01255092641637833, + "conditional95_drop": [ + 0.011389639190540375, + 0.013723655455911954 + ], + "changed_valid_residue_predictions": 47630 + }, + "auxiliary_ablated": { + "accuracy": 0.6333926464858304, + "accuracy_drop": 0.13403814835230934, + "conditional95_drop": [ + 0.13031405384716288, + 0.13710269901418365 + ], + "changed_valid_residue_predictions": 164881 + }, + "cached_vs_native_valid_argmax_changes": 0, + "comparisons": { + "full_minus_primary": { + "delta": 0.023792893554138664, + "conditional95": [ + 0.02227601983558547, + 0.025405620421006168 + ] + }, + "full_minus_auxiliary": { + "delta": 0.001993065568266087, + "conditional95": [ + 0.0013915113450666237, + 0.00262078806389141 + ] + }, + "full_minus_native_primary": { + "delta": 0.023299116048487157, + "conditional95": [ + 0.021785460201619564, + 0.024879231525420348 + ] + }, + "full_minus_native_auxiliary": { + "delta": 0.002027181105020191, + "conditional95": [ + 0.0014295698320689104, + 0.0026466899667084306 + ] + }, + "full_minus_native_fusion": { + "delta": 0.007792706816463799, + "conditional95": [ + 0.0069797076175643485, + 0.00868359254180614 + ] + } + } + }, + "ten_other_prediction_files_byte_identical": true, + "head_fit_unique_residues": 500000, + "fit_blocks": 12, + "ridge": 0.01, + "limitations": "Feature removal is an out-of-distribution diagnostic. Conditional protein bootstrap does not correct repeated selection or family dependence." + }, + "SS_allfit_publication_review": { + "original_minimum_effect_gate_passed": false, + "retrospective_policy": "/workspace/research/publication-selection-review-20261025.json", + "native_evidence": { + "status": "passed_native_all_readout_and_dependence_gates", + "tasks": { + "secondary_structure": { + "native_accuracy": 0.767856341270283, + "normal_replay_bit_exact": true, + "proteins": 2170, + "valid_residues": 556931, + "primary_ablated": { + "accuracy": 0.75506481054206, + "accuracy_drop": 0.012791530728223066, + "conditional95_drop": [ + 0.011657463875457472, + 0.013965807112484933 + ], + "changed_valid_residue_predictions": 47742 + }, + "auxiliary_ablated": { + "accuracy": 0.6353803253903985, + "accuracy_drop": 0.13247601587988458, + "conditional95_drop": [ + 0.12859561434070454, + 0.13576243044433273 + ], + "changed_valid_residue_predictions": 163028 + }, + "cached_vs_native_valid_argmax_changes": 0, + "comparisons": { + "full_minus_primary": { + "delta": 0.023861124627646873, + "conditional95": [ + 0.022379338837469887, + 0.025445967719600684 + ] + }, + "full_minus_auxiliary": { + "delta": 0.00209900328766041, + "conditional95": [ + 0.0015060823960767902, + 0.002693751613766381 + ] + }, + "full_minus_native_primary": { + "delta": 0.023724662480630456, + "conditional95": [ + 0.022235593476518073, + 0.025308672752640978 + ] + }, + "full_minus_native_auxiliary": { + "delta": 0.002452727537163491, + "conditional95": [ + 0.0018196905898359643, + 0.0030741079436519656 + ] + }, + "full_minus_native_current": { + "delta": 0.0004255464321432996, + "conditional95": [ + 0.000153183526907052, + 0.0007048781132075278 + ] + } + } + } + }, + "model_sha256": "a1f79716243444a342df73ad3bfc06ddf5f19bbe8b5b3fe625de12829c5ec9a4", + "weights_modified": false, + "parameter_updates": 0, + "method": "Replace one local-feature block by its fixed fit mean before the normalized linear readout. Both encoders and prefixes execute; no parameter updates. Recompute publication-review gates from native predictions. The original .0005 minimum-effect hypothesis failed and is preserved; this separately recorded retrospective publication review uses positive native improvement with conditional95lower>0.", + "limitations": "Feature removal is an out-of-distribution diagnostic. Conditional protein bootstrap does not correct repeated selection or family dependence.", + "published": false + }, + "gain": { + "delta": 0.0004255464321432996, + "conditional95": [ + 0.000153183526907052, + 0.0007048781132075278 + ] + }, + "fit_unique_residues": 2221507, + "ten_other_production_files_exact": true + }, + "retired_fold_extra_label_recipe_evidence": { + "kind": "two_fold_added_label_pilot_not_fullpool_model_replay", + "fold_accuracy": 0.26902173913043476, + "parent_fold_accuracy": 0.24864130434782608, + "matched_fit_only_refit_accuracy": 0.23505434782608695, + "fold_delta": 0.020380434782608696, + "conditional_fold_delta95": [ + 0.001358695652173913, + 0.04076086956521739 + ], + "heldout_half_case_gains": [ + 4, + 11 + ], + "other_ten_tasks": "Unchanged parent weights; full production replay must verify byte-identical predictions.", + "limitations": "Prior tune checkpoint/hyperparameter selection biases thisestimate. Halvesarestratifiedbylabel,notproteinfamily. Crossfitestimatestherecipewithhalftheaddedlabels,notafinalfull-poolmodel. Pairedbootstrapisconditionalanddoesnotcorrectalldependence." + }, + "retired_production_fold_head": { + "previous_package": "/workspace/research/production-allfit-ss1/candidate/package", + "previous_Tune_label_count": 736, + "replaced_by": "two fit-only native foldreadouts withfixednormalizedequalmean", + "previous_crossfit_accuracy": 0.26902173913043476, + "current_fit_only_accuracy": 0.33152173913043476 + }, + "fold_fit_only_publication_review": { + "original_auxiliary_control_hypothesis_passed": false, + "retrospective_policy": "/workspace/research/publication-selection-review-20261025.json", + "native_shared_parameter_sensitivity": { + "status": "passed_native_label_free_shared_parameter_sensitivity", + "labels_used": false, + "examples": 736, + "normal_replay_bit_exact": true, + "cached_native_class_changes": 0, + "native_interventions": { + "primary_fitmean_features": { + "class_change_fraction": 0.9008152173913043, + "changed_examples": 663, + "mean_probability_L1": 0.8340545014675982 + }, + "zero_shared_primary_final_normalization": { + "class_change_fraction": 0.5040760869565217, + "changed_examples": 371, + "mean_probability_L1": 0.6933331481662077, + "learned_parameter_names": [ + "encoder.norm.weight", + "encoder.norm.bias" + ], + "parameters_restored_exactly": true + } + }, + "cached_feature_interventions": { + "status": "passed_cached_stage", + "primary_mean_replacement_class_change_fraction": 0.9008152173913043, + "primary_fixed_permutation_class_change_fraction": 0.6453804347826086, + "primary_logit_norm_fraction": 0.5, + "permutation_seed": 20270222, + "labels_used": false + }, + "primary_common_encoder_parameters": 37845535, + "primary_encoder_active_in_all_eleven_tasks": true, + "model_sha256": "19088470dfe6d5940dcf1589c40a693dcbbf81342320a0551e4bc3612077fb6d", + "exported_weights_modified": false, + "fitting_updates": 0, + "publication_policy_review_is_retrospective": true, + "original_quality_control_gate_still_failed": true, + "limitations": "Sensitivity establishes prediction dependence, not an accuracy benefit or in-distribution intervention. Previously observed Tune quality supplies separate conditional selection evidence." + }, + "gain_vs_previous_fit_only": { + "delta": 0.08288043478260869, + "conditional95": [ + 0.05570652173913043, + 0.11141304347826086 + ] + }, + "full_accuracy": 0.33152173913043476, + "auxiliary_accuracy": 0.34375, + "raw_mean_accuracy": 0.31657608695652173, + "ten_other_production_files_exact": true, + "primary_encoder_common_parameters": 37845535, + "limitations": "Retrospectivepublicationpolicy; originalfailedhypothesisunchanged. ConditionalTuneintervals ignoreselection/familydependence; sensitivitydoesnotimplyaccuracybenefit." + } + }, + "features": { + "primary": "/workspace/research/conditioned-readout-refit1/features-summary/fold", + "auxiliary": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/features-summary/fold" + }, + "recipe": "Exactpositivelycrossvalidatedwarmstartfunctionpreservingnormalization;inverse-sqrtclassweightedCEridge1e-4/15LBFGSblocksforeachofbothreadouts; nowfitplusall736Tune. Bothencoders/otherheadsunchanged. No furtherselectiononfullpoolTunescore.", + "parameters": 145755212, + "frozen_sha256": { + "/workspace/research/fit_fullpool_dual_fold.py": "de1f81bae675c6d28718067e284e431840ff1a73688a58c3390daf75cbfe7ba6", + "/workspace/research/assemble_fullpool_dual_fold.py": "a5a414685fabb7042eb3b509a7c52adfb1adb48a82141ed0be32a8274604b347", + "/workspace/research/run_fullpool_dual_fold.py": "82719db7cead31889b215b481cca5654be05a0249960cb6cf0f5f2222fd78b36", + "/workspace/research/check_fullpool_fold_shared_native.py": "7c0913f1fb07c9de02b3e5777208aae0e3eea3d20bf666ba0cbff6e782707508", + "/workspace/research/fit_fold_dual_crossfit.py": "10b48b2b4177858d4c84a1c402f4215dcf429dba8fa7dfc608e985c2a6ebeed9", + "/workspace/research/fit_dual_residue_readouts.py": "a55238416ea2052f98e5cf00a2707c3b568183af1972e98e3a7cc43b8f9073fe", + "/workspace/research/run_pair_residue_study.py": "756ba8daae98d29beeb535d4647adaedfe71b3e07ef0d38aa3149f79d407f54b", + "/workspace/research/check_shared_adapters_cpu.py": "db7d8d846b90929decad5865de36dd55fb95139aaa116b6ae2987cd96786c990", + "/workspace/research/publication-selection-review-20261025.json": "1d7d663e9a56121d45c70fcad93d80f2f03a9cbbd07fdf94546be774ba67f170", + "/workspace/research/production-dual-fold-fullpool1/code/gpu_slot.py": "5e05607e4b0435be232a52b05cc392151d8a81bfbb908cf1ef3d4360786b0a0a", + "/workspace/research/crossfit-dual-fold-labels1/plan.json": "8d737ee751a8e7b55c178448378f8ff480b7fed80128f531387f048c146861a5", + "/workspace/research/crossfit-dual-fold-labels1/outcome.json": "7f87de8a629bb70205fc04ec3afac5a9fbfed5c46c063a9d0b75630bde1d6d35", + "/workspace/research/crossfit-dual-fold-labels1/decision.json": "6a6ce8ee723559ad9559275a06d9ddc0ebe1cdb052ce6cb6e57accb11e181cdd", + "/workspace/research/crossfit-dual-fold-labels1/CUDA-checks.json": "0f69e6302fdf5c87d0e3383be5608479073ac76dd1df6291a1c014aa5b9f69c3", + "/workspace/research/fold-shared-publication-review1/candidate/package/model.pt": "19088470dfe6d5940dcf1589c40a693dcbbf81342320a0551e4bc3612077fb6d", + "/workspace/research/production-fold-shared1/candidate/package/model.pt": "93a8fa2aadcb92983cefa53154866e9efc47a21deea0d847042c1f836883b513", + "/workspace/research/production-fold-shared1/candidate/package/config.json": "c0d1e24fea3f93877d6815607918ab67c4f4d79ca213d9f507c4ee31775bd705", + "/workspace/research/conditioned-readout-refit1/features-summary/fold/fit.pt": "c52e3b4ba2460481d23a345128373725fd41dd6d9c3934b9c032ff134fd6d6f4", + "/workspace/research/conditioned-readout-refit1/features-summary/fold/tune.pt": "7e0bc2c0d63b6673d3dcbbb6f7d15a0251c061742ed6bd949d640ad6fcd82296", + "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/features-summary/fold/fit.pt": "bfc7f3dfc5de857965d83c2dabdc2496a17f1937299fdc1c6384dff74bdfc9ac", + "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/features-summary/fold/tune.pt": "ab948028b9be27d990a0a83b6e6e92384fc19667bc6f87e6777368c9aac2b9da" + }, + "recovery_command": [ + "/opt/conda/bin/python", + "-u", + "/workspace/research/run_fullpool_dual_fold.py", + "--run", + "/workspace/research/production-dual-fold-fullpool1" + ], + "publication": "Aftercompleteall11native+tenunchangedfiles+label-freeprimaryparameterdependence; manualrecordedreviewthenatomicmandatorypublisher. Fit-onlyreferenceunchanged." + }, + "fullpool_readout_training": { + "status": "completed_fixed_fullpool_readouts", + "fit_rows": 12312, + "added_Tune_rows": 736, + "branches": { + "primary": { + "blocks": 15, + "active_seconds": 1.5581168120261282, + "training_rows": 13048, + "LBFGS_iterations": 150, + "closures": 177, + "initial_function_max_logit_error": 7.2479248046875e-05 + }, + "auxiliary": { + "blocks": 15, + "active_seconds": 1.9283095080172643, + "training_rows": 13048, + "LBFGS_iterations": 150, + "closures": 171, + "initial_function_max_logit_error": 0.0001163482666015625 + } + }, + "label_free_sensitivity": { + "primary_mean_replacement_class_change_fraction": 0.6589673913043478, + "primary_fixed_permutation_class_change_fraction": 0.36684782608695654, + "primary_logit_norm_fraction": 0.5, + "permutation_seed": 20270227, + "labels_used": false, + "status": "passed_cached_stage" + }, + "parameters_fitted_only_in_fold_readouts": true, + "in_sample_Tune_fold_score_excluded_from_selection": true, + "quality_evidence": "/workspace/research/crossfit-dual-fold-labels1/decision.json", + "all_other_model_tensors_unmodified": true, + "exported": false, + "published": false + }, + "crossfit_quality_evidence": { + "status": "eligible_for_manual_fullpool_recipe_review", + "eligible": true, + "OOF_accuracy": 0.3736413043478261, + "incumbent_accuracy": 0.33152173913043476, + "matched_control_accuracy": 0.33152173913043476, + "comparisons": { + "OOF_minus_incumbent": { + "delta": 0.042119565217391304, + "conditional95": [ + 0.02309782608695652, + 0.06117527173913025 + ] + }, + "OOF_minus_matched_control": { + "delta": 0.042119565217391304, + "conditional95": [ + 0.024456521739130436, + 0.06114130434782609 + ] + } + }, + "arms": [ + { + "arm": "fit-only-control", + "heldout_rows": 736, + "added_tune_rows": 0, + "accuracy": 0.33152173913043476, + "incumbent_accuracy": 0.33152173913043476, + "branches": { + "primary": { + "blocks": 15, + "active_seconds": 1.493866186006926, + "training_rows": 12312, + "LBFGS_iterations": 150, + "closures": 173, + "initial_function_max_logit_error": 0.0001049041748046875 + }, + "auxiliary": { + "blocks": 15, + "active_seconds": 1.9239742969803046, + "training_rows": 12312, + "LBFGS_iterations": 150, + "closures": 174, + "initial_function_max_logit_error": 0.0 + } + }, + "sensitivity": { + "primary_fitmean_class_change_fraction": 0.7703804347826086, + "primary_permutation_class_change_fraction": 0.7133152173913043, + "labels_used": false + } + }, + { + "arm": "heldout-0", + "heldout_rows": 371, + "added_tune_rows": 365, + "accuracy": 0.40161725067385445, + "incumbent_accuracy": 0.33692722371967654, + "branches": { + "primary": { + "blocks": 15, + "active_seconds": 1.4214324810891412, + "training_rows": 12677, + "LBFGS_iterations": 150, + "closures": 177, + "initial_function_max_logit_error": 8.392333984375e-05 + }, + "auxiliary": { + "blocks": 15, + "active_seconds": 1.928408305044286, + "training_rows": 12677, + "LBFGS_iterations": 150, + "closures": 174, + "initial_function_max_logit_error": 0.0001125335693359375 + } + }, + "sensitivity": { + "primary_fitmean_class_change_fraction": 0.77088948787062, + "primary_permutation_class_change_fraction": 0.660377358490566, + "labels_used": false + } + }, + { + "arm": "heldout-1", + "heldout_rows": 365, + "added_tune_rows": 371, + "accuracy": 0.3452054794520548, + "incumbent_accuracy": 0.32602739726027397, + "branches": { + "primary": { + "blocks": 15, + "active_seconds": 1.4144776619796176, + "training_rows": 12683, + "LBFGS_iterations": 150, + "closures": 177, + "initial_function_max_logit_error": 7.2479248046875e-05 + }, + "auxiliary": { + "blocks": 15, + "active_seconds": 1.9321627549652476, + "training_rows": 12683, + "LBFGS_iterations": 150, + "closures": 174, + "initial_function_max_logit_error": 9.918212890625e-05 + } + }, + "sensitivity": { + "primary_fitmean_class_change_fraction": 0.7917808219178082, + "primary_permutation_class_change_fraction": 0.6794520547945205, + "labels_used": false + } + } + ], + "fullpool_head_fitted": false, + "exported": false, + "published": false, + "limitations": "OOF estimates adding half the Tune labels, not fullpool replay. Existing representations and previous selection used Tune. Conditional paired-example intervals ignore family dependence. Mean/permutation sensitivity is out of distribution." + }, + "all_non_fold_tensors_exact": true, + "head_training": "Only primary and auxiliary fold readouts continued from own-session fit-only states; same fixed inverse-sqrtweightedCE/ridge1e-4/15LBFGSblocks with function-preserving normalization transfer. Both encoders and all other heads frozen." + }, + "auxiliary_fit_only_readout_source": "/workspace/research/scale85m-8h-rank3/candidate/package", + "auxiliary_sha256": "e601068c8d9b9a81934404866cea95d69950eb161fe8be0c6dec04bbca36d7db", + "solubility_mean_plan": { + "created_utc": "2026-10-25T18:17:08.060403+00:00", + "status": "queued", + "recovery_registered": true, + "run": "/workspace/research/solubility-fixed-mean1", + "packages": { + "primary": "/workspace/research/fold-shared-publication-review1/candidate/package", + "auxiliary": "/workspace/research/scale85m-8h-rank3/candidate/package" + }, + "features": { + "primary": "/workspace/research/conditioned-readout-refit1/features-summary/solubility/tune.pt", + "auxiliary": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/features-summary/solubility/tune.pt" + }, + "predictions": { + "primary": "/workspace/research/fold-shared-publication-review1/candidate/replay/predictions/solubility.jsonl", + "auxiliary": "/workspace/research/scale85m-8h-rank3/candidate/replay/predictions/solubility.jsonl" + }, + "frozen_sha256": { + "/workspace/research/solubility-fixed-mean1/PROPOSAL.md": "400a1aa94d8899c8e4dfa735eced1a63ae9eb47ce626a647d6db30f67d979048", + "/workspace/research/review_solubility_mean.py": "61f9c3d4f0f7059adc582b4967c91a182a026c74215b49a74b6c4cf4ecb0b58e", + "/workspace/research/fit_dual_residue_readouts.py": "a55238416ea2052f98e5cf00a2707c3b568183af1972e98e3a7cc43b8f9073fe", + "/workspace/research/dual-summary-feature-checks.json": "c0f3988785747df6360d12eb7d1cfba267f5f80679868fd6f710bde1f803a25f", + "/workspace/research/conditioned-readout-refit1/features-summary/solubility/tune.pt": "0a253bbe46f86be5e220bda28ba3489b548b2f76a7f082fe8df79be0f5fdd353", + "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/features-summary/solubility/tune.pt": "e7e4271fc8a028b83b43a5fbc73463ddf7a7c089013c092b4323c1f294b0772d", + "/workspace/research/fold-shared-publication-review1/candidate/replay/predictions/solubility.jsonl": "000113a9e356601d942cfa093b9dfebeb3d962e6cce34c9e379bb15e3105cba9", + "/workspace/research/scale85m-8h-rank3/candidate/replay/predictions/solubility.jsonl": "2a4dbf782bd2195240fcffa6bf47f850564f573bb2314a4cf44618b2f1620a27", + "/workspace/research/fold-shared-publication-review1/candidate/package/model.pt": "19088470dfe6d5940dcf1589c40a693dcbbf81342320a0551e4bc3612077fb6d", + "/workspace/research/fold-shared-publication-review1/candidate/package/config.json": "c0d1e24fea3f93877d6815607918ab67c4f4d79ca213d9f507c4ee31775bd705", + "/workspace/research/scale85m-8h-rank3/candidate/package/model.pt": "e601068c8d9b9a81934404866cea95d69950eb161fe8be0c6dec04bbca36d7db", + "/workspace/research/scale85m-8h-rank3/candidate/package/config.json": "96b66062420d075cb8810e95cbcce76fd316c60191edf4e413f6bf21b594a7c1" + }, + "recovery_command": [ + "env", + "CUDA_VISIBLE_DEVICES=", + "OMP_NUM_THREADS=4", + "MKL_NUM_THREADS=4", + "OPENBLAS_NUM_THREADS=1", + "/opt/conda/bin/python", + "-u", + "/workspace/research/review_solubility_mean.py", + "--run", + "/workspace/research/solubility-fixed-mean1" + ] + }, + "solubility_mean_result": { + "status": "eligible_for_native_architecture_review", + "eligible": true, + "accuracies": { + "primary": 0.7533851915874388, + "auxiliary": 0.7503601267646212, + "full": 0.7620282339383463 + }, + "comparisons": { + "full_minus_primary": { + "delta": 0.00864304235090752, + "conditional95": [ + 0.0023048112935753384, + 0.0149812734082397 + ] + }, + "full_minus_auxiliary": { + "delta": 0.011668107173725151, + "conditional95": [ + 0.004897723998847595, + 0.017862287525208874 + ] + } + }, + "label_free_sensitivity": { + "primary_fitmean_mean_probability_L1": 0.2038029432296753, + "primary_fitmean_class_change_fraction": 0.1571593200806684, + "primary_permutation_class_change_fraction": 0.24603860558916738, + "primary_centered_logit_norm_fraction": 0.502633273601532, + "labels_used": false, + "permutation_seed": 20270304 + }, + "source_cached_native_checks": { + "primary": { + "native_argmax_exact": true, + "maximum_probability_difference": 2.980232238769531e-07 + }, + "auxiliary": { + "native_argmax_exact": true, + "maximum_probability_difference": 5.364418029785156e-07 + } + }, + "new_training_updates": 0, + "exported": false, + "published": false, + "limitations": "One fixed equalrawlogitmean; no weightsearch. Conditional paired-example intervals ignore repeatedTune selection andfamilydependence. Mean/permutationinterventionsoutofdistribution. Nativeall11 andunlabeledcommonparameterprobabilitysensitivityrequired beforepublication." + }, + "all_non_solubility_paths_exact": true, + "one_auxiliary_encoder": true, + "new_training_updates": 0, + "method": "Concatenate source normalization buffers, concatenate half of each native solubility weight matrix, average biases; one normalized linear readout realizes exactly equal native logit mean. Only one auxiliary pool row is added; inference code unchanged." + }, + "source_of_new_weights": "Fresh random seed20270329 and FP64 LBFGS on permitted fit+allTune affinity residuals; convex optimum independently checked.", + "rows_used": { + "fit": 2421, + "tune": 203 + }, + "normalization": "Length feature moments use fit+allTune; affinity regression scale retains original fit mean/std.", + "old_model_parameters_unchanged": true, + "new_parameters": 3, + "OOF_evidence": "/workspace/research/crossfit-affinity-length1/outcome.json", + "lookup_or_feature_caches_exported": false, + "in_sample_scores_excluded_from_selection": true + }, + "method": "One bounded scalar learned from FIT-only two-half readout crossvalidation; existing fold heads and all other parameters retained exactly.", + "pilot_plan": { + "utc": "2026-10-26T02:35:55.270604+00:00", + "status": "queued_CPU", + "parent_package": "/workspace/research/affinity-length-residual1/candidate/package", + "parent_model_sha256": "0f0dc93a68cc0b047867d6689d4f974f7dfa65f9d8809ffa1dbbf438e5cc9008", + "old_fold_pilot": "/workspace/research/crossfit-dual-fold-labels1", + "features": { + "primary": "/workspace/research/conditioned-readout-refit1/features-summary/fold", + "auxiliary": "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/features-summary/fold" + }, + "split_seed": 20270417, + "head_seed": 20270418, + "head_recipe": "Two classbalanced FIT halves. Fresh readout perbranch/half, training-half moments floor1e-5, inverse-rootCE/ridge1e-4/15blocks max10LBFGS/strongWolfe/history30/gradtol1e-6. No nativehead warmstart. AllFITrows receive OOF logits, including singletonclasses missing in their head-training half.", + "calibration_recipe": "Normalize each branch logits by existing centeredRMS; one global primaryalpha in[1/3,2/3] minimizes unweighted FIT-OOF CE+.01*(alpha-.5)^2/2, FP64 bounded convex solve, exportFP32. Encoders alreadytrained onFIT; this is conditional readoutcrossvalidation only. NoTune labels enteralpha.", + "quality_gate": "Single learnedalpha versus fixed.5, no grid. Independentfit-onlyTune requires positivepaired95foldgain andsharedprimaryconformance beforedevelopmentexport. Production separatelyrequires positivepaired95 vsoldOOF275/736, bothhalfpointgains, sharedprimaryconformance; sameFIT-onlyalpha, noextra fitting onTune. Nativeall11/tenotherbyteexact beforepublication.", + "limits": "Frozenencoders saw allFITlabels; calibrationcrossvalidation onlyholds labelsout from temporaryreadouts. DifferentFIT-half training size and many rareclasses maymiscalibratefull-data heads. RepeatedTunechoices/familydependence remain. ResearchOOFheads neverexported.", + "frozen_sha256": { + "/run-state/workspace/research/fold_blend_calibration.py": "31abf968835efcb376d2309aa39d3cc72d201dbf8f5d3ef2d8a584764d5731c0", + "/workspace/research/fit_fold_dual_crossfit.py": "10b48b2b4177858d4c84a1c402f4215dcf429dba8fa7dfc608e985c2a6ebeed9", + "/workspace/research/fit_dual_residue_readouts.py": "a55238416ea2052f98e5cf00a2707c3b568183af1972e98e3a7cc43b8f9073fe", + "/workspace/research/auxiliary_refresh_production_common.py": "41f368fb0a3255578920254f6ab66c23b39cc1105fd18628f3886bdd1812bce5", + "/workspace/research/fold-blend-calibration1/CPU-checks.json": "5341c9c353bc1ceb08bc793987b857b0513188c3e809b4e3c3b02c22dc497fef", + "/workspace/research/crossfit-dual-fold-labels1/research-predictions.pt": "9547fcbf6b1d41876df7ce7479ef523060faa33e46bcaffe352ac8f8d37189c3", + "/workspace/research/affinity-length-residual1/candidate/package/model.pt": "0f0dc93a68cc0b047867d6689d4f974f7dfa65f9d8809ffa1dbbf438e5cc9008", + "/workspace/research/affinity-length-residual1/candidate/package/config.json": "94c311134ce12d8268e5ad0117baee82596fd8a01b9bdb9c9bff4747dc5418d9", + "/workspace/research/affinity-length-residual1/candidate/replay/predictions/fold.jsonl": "d466ab551a58003a32a0ea2aa5caa6e2a355af96d23d0f4657d3dbd5dec8ee4e", + "/workspace/research/conditioned-readout-refit1/features-summary/fold/fit.pt": "c52e3b4ba2460481d23a345128373725fd41dd6d9c3934b9c032ff134fd6d6f4", + "/workspace/research/conditioned-readout-refit1/features-summary/fold/tune.pt": "7e0bc2c0d63b6673d3dcbbb6f7d15a0251c061742ed6bd949d640ad6fcd82296", + "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/features-summary/fold/fit.pt": "bfc7f3dfc5de857965d83c2dabdc2496a17f1937299fdc1c6384dff74bdfc9ac", + "/workspace/research/scale85m-continue4h-compiled1-at14400-joint8486-readout-review/features-summary/fold/tune.pt": "ab948028b9be27d990a0a83b6e6e92384fc19667bc6f87e6777368c9aac2b9da", + "/workspace/research/crossfit-dual-fold-labels1/heldout-0-primary/head.pt": "049652eab4f2d721d5f664857439e133602ddbf5f1c7ab51aa0aba78951e2c8f", + "/workspace/research/crossfit-dual-fold-labels1/heldout-0-auxiliary/head.pt": "a39f5525bbe5e4241f85dcc83498d232ded65cd6b012423c9135bd2b89d79396", + "/workspace/research/crossfit-dual-fold-labels1/heldout-1-primary/head.pt": "5576a41b512edf374407ba1c9f78cd5f722eb9981ad21b95d1148c2e2cf41862", + "/workspace/research/crossfit-dual-fold-labels1/heldout-1-auxiliary/head.pt": "0e51c9138d60edb1bac98fcbc524dd84589a5ed1ae95134c4a27d2dd79655adf" + }, + "GPU_used": false, + "quality_updates": 0, + "automatic_publication": false, + "queue_decision": { + "utc": "2026-10-26T02:36:09.967927+00:00", + "reason": "Analytic scalarobjective/gradient/Hessian and actualwidth3plus1vs4 readoutresume passed; fixed recipe and both development/productionOOF gates frozen. CPU-only, mainMLM uninterrupted.", + "CPU_threads": 4, + "GPU": false + } + }, + "pilot_results": { + "status": "complete_calibration_quality_review_pending", + "calibration": { + "primary_alpha_FP64": 0.3333333333333333, + "export_alpha_FP32": 0.3333333432674408, + "objective_at_equal": [ + 1.6003692461763912, + 0.7014380237944748, + 1.5587358448608297 + ], + "objective_at_optimum": [ + 1.504147971867554, + 0.45872725047152185, + 1.360423020545405 + ], + "FIT_rows": 12312, + "Tune_labels_used_for_fitting": false + }, + "development": { + "before": 0.33152173913043476, + "after": 0.34375, + "delta": 0.012228260869565218, + "conditional95": [ + 0.0, + 0.024456521739130436 + ] + }, + "production_OOF": { + "before": 0.3736413043478261, + "after": 0.389945652173913, + "delta": 0.016304347826086956, + "conditional95": [ + 0.002717391304347826, + 0.029891304347826088 + ] + }, + "production_halves": [ + { + "before": 0.40161725067385445, + "after": 0.40970350404312667, + "delta": 0.008086253369272238, + "conditional95": [ + -0.01078167115902965, + 0.029649595687331536 + ] + }, + { + "before": 0.3452054794520548, + "after": 0.3698630136986301, + "delta": 0.024657534246575342, + "conditional95": [ + 0.005479452054794521, + 0.043835616438356165 + ] + } + ], + "development_statistical_gate": false, + "production_statistical_gate": true, + "shared_primary_conformance_and_native_replay_pending_if_positive": true, + "limits": "Frozenencoders saw allFITlabels; calibrationcrossvalidation onlyholds labelsout from temporaryreadouts. DifferentFIT-half training size and many rareclasses maymiscalibratefull-data heads. RepeatedTunechoices/familydependence remain. ResearchOOFheads neverexported.", + "exported": false, + "published": false + }, + "primary_alpha_FP32": 0.3333333432674408, + "old_parameter_tensors_retained_exact": 532, + "new_learned_parameters": 1, + "temporary_crossfit_heads_not_exported": true, + "additional_Tune_fitting_for_scalar": false, + "failed_training_input_conformance_and_separate_unlabeled_followup": { + "utc": "2026-10-26T02:46:41.154845+00:00", + "status": "separate_unlabeled_conformance_followup_before_new_predictions", + "prior_failure": "/workspace/research/production-fold-blend1-assembly-v1-failed/failure.json", + "prior_failure_remains_failed": true, + "weights_and_learned_alpha_unchanged": true, + "quality_selection_evidence_unchanged": "FIT-only learnedalpha; productionOOF275to287,positivepaired95andbothhalvespositive;developmentgatefailedunchanged.", + "reason": "Fullpoolheads useallTune labels and theirtraining-class agreement is saturated. OOFfeaturedependence passed, but finalfullpoolinput-class checks failed. Test actual frozenfullpoolmodel on previously fixed unlabeled sample to assess commonparameterdependence on inputsnotusedas supervisedlabels. This adds a new conformance distribution after a failed check; doesnot retroactively pass originalcriterion.", + "unlabeled_inputs": "/workspace/research/production-dual-fold-fullpool1/unlabeled-audit-inputs.jsonl", + "unlabeled_inputs_sha256": "d16c4bbe8d7feb87070a2aedacffc6cb30b719cb13bac13989f42c8ad2e7febe", + "rows": 1024, + "fixed_thresholds": { + "native_primary_training_mean_class_change_min": 0.1, + "native_primary_permutation_class_change_min": 0.15, + "native_shared_norm_zero_class_change_min": 0.1, + "native_shared_norm_zero_probability_L1_min": 0.1, + "primary_weighted_logit_RMS_fraction_min": 0.25 + }, + "permutation_seed": 20270227, + "sample_or_coefficient_search": false, + "limits": "Unlabeledsampleisnotfoldtestdistribution. Outofdistributioninterventionsestablishdependence,notaccuracybenefit. Priortraining-inputfailure andretrospectivefollowupchoice mustbedisclosed." + }, + "independent_native_verification": { + "all11_valid": true, + "ten_other_files_exact": [ + "beta_lactamase", + "binary_localization", + "fluorescence", + "human_ppi", + "ppi_affinity", + "secondary_structure", + "solubility", + "stability", + "subcellular_localization", + "yeast_ppi" + ], + "common_primary_native_checks": { + "status": "passed_native_common_primary_dependence", + "native_Tune_predictions_bit_exact": true, + "native_cached_fold_classes_exact": true, + "native_training_mean_intervention": { + "class_change_fraction": 0.08016304347826086, + "mean_probability_L1": 0.7129052172857414 + }, + "fixed1024_unlabeled_shared_norm_zero": { + "class_change_fraction": 0.4931640625, + "mean_probability_L1": 0.4397785993781522 + }, + "fixed1024_unlabeled_training_mean": { + "class_change_fraction": 0.623046875, + "mean_probability_L1": 0.3721115595105666 + }, + "fixed1024_unlabeled_primary_permutation": { + "class_change_fraction": 0.5595703125, + "mean_probability_L1": 0.38590037528734855 + }, + "unlabeled_primary_weighted_logit_RMS_fraction": 0.3333333730697632, + "cached_primary_dependence": { + "OOF-half0": { + "primary_training_mean_class_change": 0.4716981132075472, + "primary_permutation_class_change": 0.41778975741239893, + "primary_weighted_logit_RMS_fraction": 0.3333333730697632, + "labels_used": false, + "passed": true + }, + "OOF-half1": { + "primary_training_mean_class_change": 0.5095890410958904, + "primary_permutation_class_change": 0.39452054794520547, + "primary_weighted_logit_RMS_fraction": 0.3333333432674408, + "labels_used": false, + "passed": true + }, + "fullpool": { + "primary_training_mean_class_change": 0.08016304347826086, + "primary_permutation_class_change": 0.019021739130434784, + "primary_weighted_logit_RMS_fraction": 0.33333340287208557, + "labels_used": false, + "passed": false + } + }, + "common_primary_parameters": 37845535, + "original_fullpool_training_input_conformance_failed_and_preserved": true, + "separate_unlabeled_followup_policy": { + "utc": "2026-10-26T02:46:41.154845+00:00", + "status": "separate_unlabeled_conformance_followup_before_new_predictions", + "prior_failure": "/workspace/research/production-fold-blend1-assembly-v1-failed/failure.json", + "prior_failure_remains_failed": true, + "weights_and_learned_alpha_unchanged": true, + "quality_selection_evidence_unchanged": "FIT-only learnedalpha; productionOOF275to287,positivepaired95andbothhalvespositive;developmentgatefailedunchanged.", + "reason": "Fullpoolheads useallTune labels and theirtraining-class agreement is saturated. OOFfeaturedependence passed, but finalfullpoolinput-class checks failed. Test actual frozenfullpoolmodel on previously fixed unlabeled sample to assess commonparameterdependence on inputsnotusedas supervisedlabels. This adds a new conformance distribution after a failed check; doesnot retroactively pass originalcriterion.", + "unlabeled_inputs": "/workspace/research/production-dual-fold-fullpool1/unlabeled-audit-inputs.jsonl", + "unlabeled_inputs_sha256": "d16c4bbe8d7feb87070a2aedacffc6cb30b719cb13bac13989f42c8ad2e7febe", + "rows": 1024, + "fixed_thresholds": { + "native_primary_training_mean_class_change_min": 0.1, + "native_primary_permutation_class_change_min": 0.15, + "native_shared_norm_zero_class_change_min": 0.1, + "native_shared_norm_zero_probability_L1_min": 0.1, + "primary_weighted_logit_RMS_fraction_min": 0.25 + }, + "permutation_seed": 20270227, + "sample_or_coefficient_search": false, + "limits": "Unlabeledsampleisnotfoldtestdistribution. Outofdistributioninterventionsestablishdependence,notaccuracybenefit. Priortraining-inputfailure andretrospectivefollowupchoice mustbedisclosed." + }, + "old_parameters_restored_exactly": true, + "saved_weights_unchanged": true, + "optimizer_updates": 0, + "labels_used": false, + "thresholds": { + "primary_training_mean_class_change_min": 0.1, + "primary_permutation_min": 0.15, + "primary_weighted_logit_RMS_fraction_min": 0.25, + "unlabeled_shared_norm_class_change_min": 0.1, + "unlabeled_shared_norm_probability_L1_min": 0.1 + }, + "limits": "Out-of-distribution sensitivity establishes common-parameter use, not an accuracy benefit. The fixed unlabeled sample was already used for the parent publication; no resampling." + } + } +} diff --git a/shared/package-files/33/33f2185d264f69b410265dd2c179990b08eee2f7b320795c353f4ea910ce438c/test_openpy.py b/shared/package-files/33/33f2185d264f69b410265dd2c179990b08eee2f7b320795c353f4ea910ce438c/test_openpy.py new file mode 100644 index 0000000000000000000000000000000000000000..e205f06ace3893dd7a0a15cf4e0e77f9ec118e63 --- /dev/null +++ b/shared/package-files/33/33f2185d264f69b410265dd2c179990b08eee2f7b320795c353f4ea910ce438c/test_openpy.py @@ -0,0 +1,38 @@ +import io +import os.path + +from IPython.utils import openpy + +mydir = os.path.dirname(__file__) +nonascii_path = os.path.join(mydir, "../../core/tests/nonascii.py") + + +def test_detect_encoding(): + with open(nonascii_path, "rb") as f: + enc, lines = openpy.detect_encoding(f.readline) + assert enc == "iso-8859-5" + + +def test_read_file(): + with io.open(nonascii_path, encoding="iso-8859-5") as f: + read_specified_enc = f.read() + read_detected_enc = openpy.read_py_file(nonascii_path, skip_encoding_cookie=False) + assert read_detected_enc == read_specified_enc + assert "coding: iso-8859-5" in read_detected_enc + + read_strip_enc_cookie = openpy.read_py_file( + nonascii_path, skip_encoding_cookie=True + ) + assert "coding: iso-8859-5" not in read_strip_enc_cookie + + +def test_source_to_unicode(): + with io.open(nonascii_path, "rb") as f: + source_bytes = f.read() + assert ( + openpy.source_to_unicode(source_bytes, skip_encoding_cookie=False).splitlines() + == source_bytes.decode("iso-8859-5").splitlines() + ) + + source_no_cookie = openpy.source_to_unicode(source_bytes, skip_encoding_cookie=True) + assert "coding: iso-8859-5" not in source_no_cookie diff --git a/shared/package-files/33/33f2c0b6e16357e083c3a98877e7317abe1578a44c288e5979c9d96fb5aa6727/fix_set_literal.py b/shared/package-files/33/33f2c0b6e16357e083c3a98877e7317abe1578a44c288e5979c9d96fb5aa6727/fix_set_literal.py new file mode 100644 index 0000000000000000000000000000000000000000..762550cf73dc0b627612465e63f0368d06847ae1 --- /dev/null +++ b/shared/package-files/33/33f2c0b6e16357e083c3a98877e7317abe1578a44c288e5979c9d96fb5aa6727/fix_set_literal.py @@ -0,0 +1,53 @@ +""" +Optional fixer to transform set() calls to set literals. +""" + +# Author: Benjamin Peterson + +from lib2to3 import fixer_base, pytree +from lib2to3.fixer_util import token, syms + + + +class FixSetLiteral(fixer_base.BaseFix): + + BM_compatible = True + explicit = True + + PATTERN = """power< 'set' trailer< '(' + (atom=atom< '[' (items=listmaker< any ((',' any)* [',']) > + | + single=any) ']' > + | + atom< '(' items=testlist_gexp< any ((',' any)* [',']) > ')' > + ) + ')' > > + """ + + def transform(self, node, results): + single = results.get("single") + if single: + # Make a fake listmaker + fake = pytree.Node(syms.listmaker, [single.clone()]) + single.replace(fake) + items = fake + else: + items = results["items"] + + # Build the contents of the literal + literal = [pytree.Leaf(token.LBRACE, "{")] + literal.extend(n.clone() for n in items.children) + literal.append(pytree.Leaf(token.RBRACE, "}")) + # Set the prefix of the right brace to that of the ')' or ']' + literal[-1].prefix = items.next_sibling.prefix + maker = pytree.Node(syms.dictsetmaker, literal) + maker.prefix = node.prefix + + # If the original was a one tuple, we need to remove the extra comma. + if len(maker.children) == 4: + n = maker.children[2] + n.remove() + maker.children[-1].prefix = n.prefix + + # Finally, replace the set call with our shiny new literal. + return maker diff --git a/shared/package-files/33/33f4c177ed378fedd873d2b0846128053c1227158ed653c11bb9ddb2dd7a3c6a/Sakhalin b/shared/package-files/33/33f4c177ed378fedd873d2b0846128053c1227158ed653c11bb9ddb2dd7a3c6a/Sakhalin new file mode 100644 index 0000000000000000000000000000000000000000..69f0faad1e7247882721bb81a7242ddd4b1d269f Binary files /dev/null and b/shared/package-files/33/33f4c177ed378fedd873d2b0846128053c1227158ed653c11bb9ddb2dd7a3c6a/Sakhalin differ diff --git a/shared/package-files/33/33f541d42514a67b8cda24709d798b2756eaf1efe884b11edac1d9d5f0dcdcec/test_constructors.py b/shared/package-files/33/33f541d42514a67b8cda24709d798b2756eaf1efe884b11edac1d9d5f0dcdcec/test_constructors.py new file mode 100644 index 0000000000000000000000000000000000000000..66c9b456f18adc6824333e46f8dbc3e3f806221e --- /dev/null +++ b/shared/package-files/33/33f541d42514a67b8cda24709d798b2756eaf1efe884b11edac1d9d5f0dcdcec/test_constructors.py @@ -0,0 +1,382 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + DataFrame, + DatetimeIndex, + Index, + Period, + PeriodIndex, + Series, + Timedelta, + TimedeltaIndex, + Timestamp, +) +import pandas._testing as tm +from pandas.tests.copy_view.util import get_array + +# ----------------------------------------------------------------------------- +# Copy/view behaviour for Series / DataFrame constructors + + +@pytest.mark.parametrize("dtype", [None, "int64"]) +def test_series_from_series(dtype, using_copy_on_write, warn_copy_on_write): + # Case: constructing a Series from another Series object follows CoW rules: + # a new object is returned and thus mutations are not propagated + ser = Series([1, 2, 3], name="name") + + # default is copy=False -> new Series is a shallow copy / view of original + result = Series(ser, dtype=dtype) + + # the shallow copy still shares memory + assert np.shares_memory(get_array(ser), get_array(result)) + + if using_copy_on_write: + assert result._mgr.blocks[0].refs.has_reference() + + if using_copy_on_write: + # mutating new series copy doesn't mutate original + result.iloc[0] = 0 + assert ser.iloc[0] == 1 + # mutating triggered a copy-on-write -> no longer shares memory + assert not np.shares_memory(get_array(ser), get_array(result)) + else: + # mutating shallow copy does mutate original + with tm.assert_cow_warning(warn_copy_on_write): + result.iloc[0] = 0 + assert ser.iloc[0] == 0 + # and still shares memory + assert np.shares_memory(get_array(ser), get_array(result)) + + # the same when modifying the parent + result = Series(ser, dtype=dtype) + + if using_copy_on_write: + # mutating original doesn't mutate new series + ser.iloc[0] = 0 + assert result.iloc[0] == 1 + else: + # mutating original does mutate shallow copy + with tm.assert_cow_warning(warn_copy_on_write): + ser.iloc[0] = 0 + assert result.iloc[0] == 0 + + +def test_series_from_series_with_reindex(using_copy_on_write, warn_copy_on_write): + # Case: constructing a Series from another Series with specifying an index + # that potentially requires a reindex of the values + ser = Series([1, 2, 3], name="name") + + # passing an index that doesn't actually require a reindex of the values + # -> without CoW we get an actual mutating view + for index in [ + ser.index, + ser.index.copy(), + list(ser.index), + ser.index.rename("idx"), + ]: + result = Series(ser, index=index) + assert np.shares_memory(ser.values, result.values) + with tm.assert_cow_warning(warn_copy_on_write): + result.iloc[0] = 0 + if using_copy_on_write: + assert ser.iloc[0] == 1 + else: + assert ser.iloc[0] == 0 + + # ensure that if an actual reindex is needed, we don't have any refs + # (mutating the result wouldn't trigger CoW) + result = Series(ser, index=[0, 1, 2, 3]) + assert not np.shares_memory(ser.values, result.values) + if using_copy_on_write: + assert not result._mgr.blocks[0].refs.has_reference() + + +@pytest.mark.parametrize("fastpath", [False, True]) +@pytest.mark.parametrize("dtype", [None, "int64"]) +@pytest.mark.parametrize("idx", [None, pd.RangeIndex(start=0, stop=3, step=1)]) +@pytest.mark.parametrize( + "arr", [np.array([1, 2, 3], dtype="int64"), pd.array([1, 2, 3], dtype="Int64")] +) +def test_series_from_array(using_copy_on_write, idx, dtype, fastpath, arr): + if idx is None or dtype is not None: + fastpath = False + msg = "The 'fastpath' keyword in pd.Series is deprecated" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + ser = Series(arr, dtype=dtype, index=idx, fastpath=fastpath) + ser_orig = ser.copy() + data = getattr(arr, "_data", arr) + if using_copy_on_write: + assert not np.shares_memory(get_array(ser), data) + else: + assert np.shares_memory(get_array(ser), data) + + arr[0] = 100 + if using_copy_on_write: + tm.assert_series_equal(ser, ser_orig) + else: + expected = Series([100, 2, 3], dtype=dtype if dtype is not None else arr.dtype) + tm.assert_series_equal(ser, expected) + + +@pytest.mark.parametrize("copy", [True, False, None]) +def test_series_from_array_different_dtype(using_copy_on_write, copy): + arr = np.array([1, 2, 3], dtype="int64") + ser = Series(arr, dtype="int32", copy=copy) + assert not np.shares_memory(get_array(ser), arr) + + +@pytest.mark.parametrize( + "idx", + [ + Index([1, 2]), + DatetimeIndex([Timestamp("2019-12-31"), Timestamp("2020-12-31")]), + PeriodIndex([Period("2019-12-31"), Period("2020-12-31")]), + TimedeltaIndex([Timedelta("1 days"), Timedelta("2 days")]), + ], +) +def test_series_from_index(using_copy_on_write, idx): + ser = Series(idx) + expected = idx.copy(deep=True) + if using_copy_on_write: + assert np.shares_memory(get_array(ser), get_array(idx)) + assert not ser._mgr._has_no_reference(0) + else: + assert not np.shares_memory(get_array(ser), get_array(idx)) + ser.iloc[0] = ser.iloc[1] + tm.assert_index_equal(idx, expected) + + +def test_series_from_index_different_dtypes(using_copy_on_write): + idx = Index([1, 2, 3], dtype="int64") + ser = Series(idx, dtype="int32") + assert not np.shares_memory(get_array(ser), get_array(idx)) + if using_copy_on_write: + assert ser._mgr._has_no_reference(0) + + +@pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning") +@pytest.mark.parametrize("fastpath", [False, True]) +@pytest.mark.parametrize("dtype", [None, "int64"]) +@pytest.mark.parametrize("idx", [None, pd.RangeIndex(start=0, stop=3, step=1)]) +def test_series_from_block_manager(using_copy_on_write, idx, dtype, fastpath): + ser = Series([1, 2, 3], dtype="int64") + ser_orig = ser.copy() + msg = "The 'fastpath' keyword in pd.Series is deprecated" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + ser2 = Series(ser._mgr, dtype=dtype, fastpath=fastpath, index=idx) + assert np.shares_memory(get_array(ser), get_array(ser2)) + if using_copy_on_write: + assert not ser2._mgr._has_no_reference(0) + + ser2.iloc[0] = 100 + if using_copy_on_write: + tm.assert_series_equal(ser, ser_orig) + else: + expected = Series([100, 2, 3]) + tm.assert_series_equal(ser, expected) + + +def test_series_from_block_manager_different_dtype(using_copy_on_write): + ser = Series([1, 2, 3], dtype="int64") + msg = "Passing a SingleBlockManager to Series" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + ser2 = Series(ser._mgr, dtype="int32") + assert not np.shares_memory(get_array(ser), get_array(ser2)) + if using_copy_on_write: + assert ser2._mgr._has_no_reference(0) + + +@pytest.mark.parametrize("use_mgr", [True, False]) +@pytest.mark.parametrize("columns", [None, ["a"]]) +def test_dataframe_constructor_mgr_or_df( + using_copy_on_write, warn_copy_on_write, columns, use_mgr +): + df = DataFrame({"a": [1, 2, 3]}) + df_orig = df.copy() + + if use_mgr: + data = df._mgr + warn = DeprecationWarning + else: + data = df + warn = None + msg = "Passing a BlockManager to DataFrame" + with tm.assert_produces_warning(warn, match=msg, check_stacklevel=False): + new_df = DataFrame(data) + + assert np.shares_memory(get_array(df, "a"), get_array(new_df, "a")) + with tm.assert_cow_warning(warn_copy_on_write and not use_mgr): + new_df.iloc[0] = 100 + + if using_copy_on_write: + assert not np.shares_memory(get_array(df, "a"), get_array(new_df, "a")) + tm.assert_frame_equal(df, df_orig) + else: + assert np.shares_memory(get_array(df, "a"), get_array(new_df, "a")) + tm.assert_frame_equal(df, new_df) + + +@pytest.mark.parametrize("dtype", [None, "int64", "Int64"]) +@pytest.mark.parametrize("index", [None, [0, 1, 2]]) +@pytest.mark.parametrize("columns", [None, ["a", "b"], ["a", "b", "c"]]) +def test_dataframe_from_dict_of_series( + request, using_copy_on_write, warn_copy_on_write, columns, index, dtype +): + # Case: constructing a DataFrame from Series objects with copy=False + # has to do a lazy following CoW rules + # (the default for DataFrame(dict) is still to copy to ensure consolidation) + s1 = Series([1, 2, 3]) + s2 = Series([4, 5, 6]) + s1_orig = s1.copy() + expected = DataFrame( + {"a": [1, 2, 3], "b": [4, 5, 6]}, index=index, columns=columns, dtype=dtype + ) + + result = DataFrame( + {"a": s1, "b": s2}, index=index, columns=columns, dtype=dtype, copy=False + ) + + # the shallow copy still shares memory + assert np.shares_memory(get_array(result, "a"), get_array(s1)) + + # mutating the new dataframe doesn't mutate original + with tm.assert_cow_warning(warn_copy_on_write): + result.iloc[0, 0] = 10 + if using_copy_on_write: + assert not np.shares_memory(get_array(result, "a"), get_array(s1)) + tm.assert_series_equal(s1, s1_orig) + else: + assert s1.iloc[0] == 10 + + # the same when modifying the parent series + s1 = Series([1, 2, 3]) + s2 = Series([4, 5, 6]) + result = DataFrame( + {"a": s1, "b": s2}, index=index, columns=columns, dtype=dtype, copy=False + ) + with tm.assert_cow_warning(warn_copy_on_write): + s1.iloc[0] = 10 + if using_copy_on_write: + assert not np.shares_memory(get_array(result, "a"), get_array(s1)) + tm.assert_frame_equal(result, expected) + else: + assert result.iloc[0, 0] == 10 + + +@pytest.mark.parametrize("dtype", [None, "int64"]) +def test_dataframe_from_dict_of_series_with_reindex(dtype): + # Case: constructing a DataFrame from Series objects with copy=False + # and passing an index that requires an actual (no-view) reindex -> need + # to ensure the result doesn't have refs set up to unnecessarily trigger + # a copy on write + s1 = Series([1, 2, 3]) + s2 = Series([4, 5, 6]) + df = DataFrame({"a": s1, "b": s2}, index=[1, 2, 3], dtype=dtype, copy=False) + + # df should own its memory, so mutating shouldn't trigger a copy + arr_before = get_array(df, "a") + assert not np.shares_memory(arr_before, get_array(s1)) + df.iloc[0, 0] = 100 + arr_after = get_array(df, "a") + assert np.shares_memory(arr_before, arr_after) + + +@pytest.mark.parametrize("cons", [Series, Index]) +@pytest.mark.parametrize( + "data, dtype", [([1, 2], None), ([1, 2], "int64"), (["a", "b"], object)] +) +def test_dataframe_from_series_or_index( + using_copy_on_write, warn_copy_on_write, data, dtype, cons +): + obj = cons(data, dtype=dtype) + obj_orig = obj.copy() + df = DataFrame(obj, dtype=dtype) + assert np.shares_memory(get_array(obj), get_array(df, 0)) + if using_copy_on_write: + assert not df._mgr._has_no_reference(0) + + with tm.assert_cow_warning(warn_copy_on_write): + df.iloc[0, 0] = data[-1] + if using_copy_on_write: + tm.assert_equal(obj, obj_orig) + + +@pytest.mark.parametrize("cons", [Series, Index]) +def test_dataframe_from_series_or_index_different_dtype(using_copy_on_write, cons): + obj = cons([1, 2], dtype="int64") + df = DataFrame(obj, dtype="int32") + assert not np.shares_memory(get_array(obj), get_array(df, 0)) + if using_copy_on_write: + assert df._mgr._has_no_reference(0) + + +def test_dataframe_from_series_infer_datetime(using_copy_on_write): + ser = Series([Timestamp("2019-12-31"), Timestamp("2020-12-31")], dtype=object) + with tm.assert_produces_warning(FutureWarning, match="Dtype inference"): + df = DataFrame(ser) + assert not np.shares_memory(get_array(ser), get_array(df, 0)) + if using_copy_on_write: + assert df._mgr._has_no_reference(0) + + +@pytest.mark.parametrize("index", [None, [0, 1, 2]]) +def test_dataframe_from_dict_of_series_with_dtype(index): + # Variant of above, but now passing a dtype that causes a copy + # -> need to ensure the result doesn't have refs set up to unnecessarily + # trigger a copy on write + s1 = Series([1.0, 2.0, 3.0]) + s2 = Series([4, 5, 6]) + df = DataFrame({"a": s1, "b": s2}, index=index, dtype="int64", copy=False) + + # df should own its memory, so mutating shouldn't trigger a copy + arr_before = get_array(df, "a") + assert not np.shares_memory(arr_before, get_array(s1)) + df.iloc[0, 0] = 100 + arr_after = get_array(df, "a") + assert np.shares_memory(arr_before, arr_after) + + +@pytest.mark.parametrize("copy", [False, None, True]) +def test_frame_from_numpy_array(using_copy_on_write, copy, using_array_manager): + arr = np.array([[1, 2], [3, 4]]) + df = DataFrame(arr, copy=copy) + + if ( + using_copy_on_write + and copy is not False + or copy is True + or (using_array_manager and copy is None) + ): + assert not np.shares_memory(get_array(df, 0), arr) + else: + assert np.shares_memory(get_array(df, 0), arr) + + +def test_dataframe_from_records_with_dataframe(using_copy_on_write, warn_copy_on_write): + df = DataFrame({"a": [1, 2, 3]}) + df_orig = df.copy() + with tm.assert_produces_warning(FutureWarning): + df2 = DataFrame.from_records(df) + if using_copy_on_write: + assert not df._mgr._has_no_reference(0) + assert np.shares_memory(get_array(df, "a"), get_array(df2, "a")) + with tm.assert_cow_warning(warn_copy_on_write): + df2.iloc[0, 0] = 100 + if using_copy_on_write: + tm.assert_frame_equal(df, df_orig) + else: + tm.assert_frame_equal(df, df2) + + +def test_frame_from_dict_of_index(using_copy_on_write): + idx = Index([1, 2, 3]) + expected = idx.copy(deep=True) + df = DataFrame({"a": idx}, copy=False) + assert np.shares_memory(get_array(df, "a"), idx._values) + if using_copy_on_write: + assert not df._mgr._has_no_reference(0) + + df.iloc[0, 0] = 100 + tm.assert_index_equal(idx, expected) diff --git a/shared/package-files/33/33f6f39c2078b9e22df61925315bb89825ec9082a465ed405412f96e2692bd36/least_squares.py b/shared/package-files/33/33f6f39c2078b9e22df61925315bb89825ec9082a465ed405412f96e2692bd36/least_squares.py new file mode 100644 index 0000000000000000000000000000000000000000..1595e40d16a01b8355510c4721ca0fb6b5b23b4a --- /dev/null +++ b/shared/package-files/33/33f6f39c2078b9e22df61925315bb89825ec9082a465ed405412f96e2692bd36/least_squares.py @@ -0,0 +1,972 @@ +"""Generic interface for least-squares minimization.""" +from warnings import warn + +import numpy as np +from numpy.linalg import norm + +from scipy.sparse import issparse +from scipy.sparse.linalg import LinearOperator +from scipy.optimize import _minpack, OptimizeResult +from scipy.optimize._numdiff import approx_derivative, group_columns +from scipy.optimize._minimize import Bounds + +from .trf import trf +from .dogbox import dogbox +from .common import EPS, in_bounds, make_strictly_feasible + + +TERMINATION_MESSAGES = { + -1: "Improper input parameters status returned from `leastsq`", + 0: "The maximum number of function evaluations is exceeded.", + 1: "`gtol` termination condition is satisfied.", + 2: "`ftol` termination condition is satisfied.", + 3: "`xtol` termination condition is satisfied.", + 4: "Both `ftol` and `xtol` termination conditions are satisfied." +} + + +FROM_MINPACK_TO_COMMON = { + 0: -1, # Improper input parameters from MINPACK. + 1: 2, + 2: 3, + 3: 4, + 4: 1, + 5: 0 + # There are 6, 7, 8 for too small tolerance parameters, + # but we guard against it by checking ftol, xtol, gtol beforehand. +} + + +def call_minpack(fun, x0, jac, ftol, xtol, gtol, max_nfev, x_scale, diff_step): + n = x0.size + + if diff_step is None: + epsfcn = EPS + else: + epsfcn = diff_step**2 + + # Compute MINPACK's `diag`, which is inverse of our `x_scale` and + # ``x_scale='jac'`` corresponds to ``diag=None``. + if isinstance(x_scale, str) and x_scale == 'jac': + diag = None + else: + diag = 1 / x_scale + + full_output = True + col_deriv = False + factor = 100.0 + + if jac is None: + if max_nfev is None: + # n squared to account for Jacobian evaluations. + max_nfev = 100 * n * (n + 1) + x, info, status = _minpack._lmdif( + fun, x0, (), full_output, ftol, xtol, gtol, + max_nfev, epsfcn, factor, diag) + else: + if max_nfev is None: + max_nfev = 100 * n + x, info, status = _minpack._lmder( + fun, jac, x0, (), full_output, col_deriv, + ftol, xtol, gtol, max_nfev, factor, diag) + + f = info['fvec'] + + if callable(jac): + J = jac(x) + else: + J = np.atleast_2d(approx_derivative(fun, x)) + + cost = 0.5 * np.dot(f, f) + g = J.T.dot(f) + g_norm = norm(g, ord=np.inf) + + nfev = info['nfev'] + njev = info.get('njev', None) + + status = FROM_MINPACK_TO_COMMON[status] + active_mask = np.zeros_like(x0, dtype=int) + + return OptimizeResult( + x=x, cost=cost, fun=f, jac=J, grad=g, optimality=g_norm, + active_mask=active_mask, nfev=nfev, njev=njev, status=status) + + +def prepare_bounds(bounds, n): + lb, ub = (np.asarray(b, dtype=float) for b in bounds) + if lb.ndim == 0: + lb = np.resize(lb, n) + + if ub.ndim == 0: + ub = np.resize(ub, n) + + return lb, ub + + +def check_tolerance(ftol, xtol, gtol, method): + def check(tol, name): + if tol is None: + tol = 0 + elif tol < EPS: + warn(f"Setting `{name}` below the machine epsilon ({EPS:.2e}) effectively " + f"disables the corresponding termination condition.", + stacklevel=3) + return tol + + ftol = check(ftol, "ftol") + xtol = check(xtol, "xtol") + gtol = check(gtol, "gtol") + + if method == "lm" and (ftol < EPS or xtol < EPS or gtol < EPS): + raise ValueError("All tolerances must be higher than machine epsilon " + f"({EPS:.2e}) for method 'lm'.") + elif ftol < EPS and xtol < EPS and gtol < EPS: + raise ValueError("At least one of the tolerances must be higher than " + f"machine epsilon ({EPS:.2e}).") + + return ftol, xtol, gtol + + +def check_x_scale(x_scale, x0): + if isinstance(x_scale, str) and x_scale == 'jac': + return x_scale + + try: + x_scale = np.asarray(x_scale, dtype=float) + valid = np.all(np.isfinite(x_scale)) and np.all(x_scale > 0) + except (ValueError, TypeError): + valid = False + + if not valid: + raise ValueError("`x_scale` must be 'jac' or array_like with " + "positive numbers.") + + if x_scale.ndim == 0: + x_scale = np.resize(x_scale, x0.shape) + + if x_scale.shape != x0.shape: + raise ValueError("Inconsistent shapes between `x_scale` and `x0`.") + + return x_scale + + +def check_jac_sparsity(jac_sparsity, m, n): + if jac_sparsity is None: + return None + + if not issparse(jac_sparsity): + jac_sparsity = np.atleast_2d(jac_sparsity) + + if jac_sparsity.shape != (m, n): + raise ValueError("`jac_sparsity` has wrong shape.") + + return jac_sparsity, group_columns(jac_sparsity) + + +# Loss functions. + + +def huber(z, rho, cost_only): + mask = z <= 1 + rho[0, mask] = z[mask] + rho[0, ~mask] = 2 * z[~mask]**0.5 - 1 + if cost_only: + return + rho[1, mask] = 1 + rho[1, ~mask] = z[~mask]**-0.5 + rho[2, mask] = 0 + rho[2, ~mask] = -0.5 * z[~mask]**-1.5 + + +def soft_l1(z, rho, cost_only): + t = 1 + z + rho[0] = 2 * (t**0.5 - 1) + if cost_only: + return + rho[1] = t**-0.5 + rho[2] = -0.5 * t**-1.5 + + +def cauchy(z, rho, cost_only): + rho[0] = np.log1p(z) + if cost_only: + return + t = 1 + z + rho[1] = 1 / t + rho[2] = -1 / t**2 + + +def arctan(z, rho, cost_only): + rho[0] = np.arctan(z) + if cost_only: + return + t = 1 + z**2 + rho[1] = 1 / t + rho[2] = -2 * z / t**2 + + +IMPLEMENTED_LOSSES = dict(linear=None, huber=huber, soft_l1=soft_l1, + cauchy=cauchy, arctan=arctan) + + +def construct_loss_function(m, loss, f_scale): + if loss == 'linear': + return None + + if not callable(loss): + loss = IMPLEMENTED_LOSSES[loss] + rho = np.empty((3, m)) + + def loss_function(f, cost_only=False): + z = (f / f_scale) ** 2 + loss(z, rho, cost_only=cost_only) + if cost_only: + return 0.5 * f_scale ** 2 * np.sum(rho[0]) + rho[0] *= f_scale ** 2 + rho[2] /= f_scale ** 2 + return rho + else: + def loss_function(f, cost_only=False): + z = (f / f_scale) ** 2 + rho = loss(z) + if cost_only: + return 0.5 * f_scale ** 2 * np.sum(rho[0]) + rho[0] *= f_scale ** 2 + rho[2] /= f_scale ** 2 + return rho + + return loss_function + + +def least_squares( + fun, x0, jac='2-point', bounds=(-np.inf, np.inf), method='trf', + ftol=1e-8, xtol=1e-8, gtol=1e-8, x_scale=1.0, loss='linear', + f_scale=1.0, diff_step=None, tr_solver=None, tr_options=None, + jac_sparsity=None, max_nfev=None, verbose=0, args=(), kwargs=None): + """Solve a nonlinear least-squares problem with bounds on the variables. + + Given the residuals f(x) (an m-D real function of n real + variables) and the loss function rho(s) (a scalar function), `least_squares` + finds a local minimum of the cost function F(x):: + + minimize F(x) = 0.5 * sum(rho(f_i(x)**2), i = 0, ..., m - 1) + subject to lb <= x <= ub + + The purpose of the loss function rho(s) is to reduce the influence of + outliers on the solution. + + Parameters + ---------- + fun : callable + Function which computes the vector of residuals, with the signature + ``fun(x, *args, **kwargs)``, i.e., the minimization proceeds with + respect to its first argument. The argument ``x`` passed to this + function is an ndarray of shape (n,) (never a scalar, even for n=1). + It must allocate and return a 1-D array_like of shape (m,) or a scalar. + If the argument ``x`` is complex or the function ``fun`` returns + complex residuals, it must be wrapped in a real function of real + arguments, as shown at the end of the Examples section. + x0 : array_like with shape (n,) or float + Initial guess on independent variables. If float, it will be treated + as a 1-D array with one element. When `method` is 'trf', the initial + guess might be slightly adjusted to lie sufficiently within the given + `bounds`. + jac : {'2-point', '3-point', 'cs', callable}, optional + Method of computing the Jacobian matrix (an m-by-n matrix, where + element (i, j) is the partial derivative of f[i] with respect to + x[j]). The keywords select a finite difference scheme for numerical + estimation. The scheme '3-point' is more accurate, but requires + twice as many operations as '2-point' (default). The scheme 'cs' + uses complex steps, and while potentially the most accurate, it is + applicable only when `fun` correctly handles complex inputs and + can be analytically continued to the complex plane. Method 'lm' + always uses the '2-point' scheme. If callable, it is used as + ``jac(x, *args, **kwargs)`` and should return a good approximation + (or the exact value) for the Jacobian as an array_like (np.atleast_2d + is applied), a sparse matrix (csr_matrix preferred for performance) or + a `scipy.sparse.linalg.LinearOperator`. + bounds : 2-tuple of array_like or `Bounds`, optional + There are two ways to specify bounds: + + 1. Instance of `Bounds` class + 2. Lower and upper bounds on independent variables. Defaults to no + bounds. Each array must match the size of `x0` or be a scalar, + in the latter case a bound will be the same for all variables. + Use ``np.inf`` with an appropriate sign to disable bounds on all + or some variables. + + method : {'trf', 'dogbox', 'lm'}, optional + Algorithm to perform minimization. + + * 'trf' : Trust Region Reflective algorithm, particularly suitable + for large sparse problems with bounds. Generally robust method. + * 'dogbox' : dogleg algorithm with rectangular trust regions, + typical use case is small problems with bounds. Not recommended + for problems with rank-deficient Jacobian. + * 'lm' : Levenberg-Marquardt algorithm as implemented in MINPACK. + Doesn't handle bounds and sparse Jacobians. Usually the most + efficient method for small unconstrained problems. + + Default is 'trf'. See Notes for more information. + ftol : float or None, optional + Tolerance for termination by the change of the cost function. Default + is 1e-8. The optimization process is stopped when ``dF < ftol * F``, + and there was an adequate agreement between a local quadratic model and + the true model in the last step. + + If None and 'method' is not 'lm', the termination by this condition is + disabled. If 'method' is 'lm', this tolerance must be higher than + machine epsilon. + xtol : float or None, optional + Tolerance for termination by the change of the independent variables. + Default is 1e-8. The exact condition depends on the `method` used: + + * For 'trf' and 'dogbox' : ``norm(dx) < xtol * (xtol + norm(x))``. + * For 'lm' : ``Delta < xtol * norm(xs)``, where ``Delta`` is + a trust-region radius and ``xs`` is the value of ``x`` + scaled according to `x_scale` parameter (see below). + + If None and 'method' is not 'lm', the termination by this condition is + disabled. If 'method' is 'lm', this tolerance must be higher than + machine epsilon. + gtol : float or None, optional + Tolerance for termination by the norm of the gradient. Default is 1e-8. + The exact condition depends on a `method` used: + + * For 'trf' : ``norm(g_scaled, ord=np.inf) < gtol``, where + ``g_scaled`` is the value of the gradient scaled to account for + the presence of the bounds [STIR]_. + * For 'dogbox' : ``norm(g_free, ord=np.inf) < gtol``, where + ``g_free`` is the gradient with respect to the variables which + are not in the optimal state on the boundary. + * For 'lm' : the maximum absolute value of the cosine of angles + between columns of the Jacobian and the residual vector is less + than `gtol`, or the residual vector is zero. + + If None and 'method' is not 'lm', the termination by this condition is + disabled. If 'method' is 'lm', this tolerance must be higher than + machine epsilon. + x_scale : array_like or 'jac', optional + Characteristic scale of each variable. Setting `x_scale` is equivalent + to reformulating the problem in scaled variables ``xs = x / x_scale``. + An alternative view is that the size of a trust region along jth + dimension is proportional to ``x_scale[j]``. Improved convergence may + be achieved by setting `x_scale` such that a step of a given size + along any of the scaled variables has a similar effect on the cost + function. If set to 'jac', the scale is iteratively updated using the + inverse norms of the columns of the Jacobian matrix (as described in + [JJMore]_). + loss : str or callable, optional + Determines the loss function. The following keyword values are allowed: + + * 'linear' (default) : ``rho(z) = z``. Gives a standard + least-squares problem. + * 'soft_l1' : ``rho(z) = 2 * ((1 + z)**0.5 - 1)``. The smooth + approximation of l1 (absolute value) loss. Usually a good + choice for robust least squares. + * 'huber' : ``rho(z) = z if z <= 1 else 2*z**0.5 - 1``. Works + similarly to 'soft_l1'. + * 'cauchy' : ``rho(z) = ln(1 + z)``. Severely weakens outliers + influence, but may cause difficulties in optimization process. + * 'arctan' : ``rho(z) = arctan(z)``. Limits a maximum loss on + a single residual, has properties similar to 'cauchy'. + + If callable, it must take a 1-D ndarray ``z=f**2`` and return an + array_like with shape (3, m) where row 0 contains function values, + row 1 contains first derivatives and row 2 contains second + derivatives. Method 'lm' supports only 'linear' loss. + f_scale : float, optional + Value of soft margin between inlier and outlier residuals, default + is 1.0. The loss function is evaluated as follows + ``rho_(f**2) = C**2 * rho(f**2 / C**2)``, where ``C`` is `f_scale`, + and ``rho`` is determined by `loss` parameter. This parameter has + no effect with ``loss='linear'``, but for other `loss` values it is + of crucial importance. + max_nfev : None or int, optional + Maximum number of function evaluations before the termination. + If None (default), the value is chosen automatically: + + * For 'trf' and 'dogbox' : 100 * n. + * For 'lm' : 100 * n if `jac` is callable and 100 * n * (n + 1) + otherwise (because 'lm' counts function calls in Jacobian + estimation). + + diff_step : None or array_like, optional + Determines the relative step size for the finite difference + approximation of the Jacobian. The actual step is computed as + ``x * diff_step``. If None (default), then `diff_step` is taken to be + a conventional "optimal" power of machine epsilon for the finite + difference scheme used [NR]_. + tr_solver : {None, 'exact', 'lsmr'}, optional + Method for solving trust-region subproblems, relevant only for 'trf' + and 'dogbox' methods. + + * 'exact' is suitable for not very large problems with dense + Jacobian matrices. The computational complexity per iteration is + comparable to a singular value decomposition of the Jacobian + matrix. + * 'lsmr' is suitable for problems with sparse and large Jacobian + matrices. It uses the iterative procedure + `scipy.sparse.linalg.lsmr` for finding a solution of a linear + least-squares problem and only requires matrix-vector product + evaluations. + + If None (default), the solver is chosen based on the type of Jacobian + returned on the first iteration. + tr_options : dict, optional + Keyword options passed to trust-region solver. + + * ``tr_solver='exact'``: `tr_options` are ignored. + * ``tr_solver='lsmr'``: options for `scipy.sparse.linalg.lsmr`. + Additionally, ``method='trf'`` supports 'regularize' option + (bool, default is True), which adds a regularization term to the + normal equation, which improves convergence if the Jacobian is + rank-deficient [Byrd]_ (eq. 3.4). + + jac_sparsity : {None, array_like, sparse matrix}, optional + Defines the sparsity structure of the Jacobian matrix for finite + difference estimation, its shape must be (m, n). If the Jacobian has + only few non-zero elements in *each* row, providing the sparsity + structure will greatly speed up the computations [Curtis]_. A zero + entry means that a corresponding element in the Jacobian is identically + zero. If provided, forces the use of 'lsmr' trust-region solver. + If None (default), then dense differencing will be used. Has no effect + for 'lm' method. + verbose : {0, 1, 2}, optional + Level of algorithm's verbosity: + + * 0 (default) : work silently. + * 1 : display a termination report. + * 2 : display progress during iterations (not supported by 'lm' + method). + + args, kwargs : tuple and dict, optional + Additional arguments passed to `fun` and `jac`. Both empty by default. + The calling signature is ``fun(x, *args, **kwargs)`` and the same for + `jac`. + + Returns + ------- + result : OptimizeResult + `OptimizeResult` with the following fields defined: + + x : ndarray, shape (n,) + Solution found. + cost : float + Value of the cost function at the solution. + fun : ndarray, shape (m,) + Vector of residuals at the solution. + jac : ndarray, sparse matrix or LinearOperator, shape (m, n) + Modified Jacobian matrix at the solution, in the sense that J^T J + is a Gauss-Newton approximation of the Hessian of the cost function. + The type is the same as the one used by the algorithm. + grad : ndarray, shape (m,) + Gradient of the cost function at the solution. + optimality : float + First-order optimality measure. In unconstrained problems, it is + always the uniform norm of the gradient. In constrained problems, + it is the quantity which was compared with `gtol` during iterations. + active_mask : ndarray of int, shape (n,) + Each component shows whether a corresponding constraint is active + (that is, whether a variable is at the bound): + + * 0 : a constraint is not active. + * -1 : a lower bound is active. + * 1 : an upper bound is active. + + Might be somewhat arbitrary for 'trf' method as it generates a + sequence of strictly feasible iterates and `active_mask` is + determined within a tolerance threshold. + nfev : int + Number of function evaluations done. Methods 'trf' and 'dogbox' do + not count function calls for numerical Jacobian approximation, as + opposed to 'lm' method. + njev : int or None + Number of Jacobian evaluations done. If numerical Jacobian + approximation is used in 'lm' method, it is set to None. + status : int + The reason for algorithm termination: + + * -1 : improper input parameters status returned from MINPACK. + * 0 : the maximum number of function evaluations is exceeded. + * 1 : `gtol` termination condition is satisfied. + * 2 : `ftol` termination condition is satisfied. + * 3 : `xtol` termination condition is satisfied. + * 4 : Both `ftol` and `xtol` termination conditions are satisfied. + + message : str + Verbal description of the termination reason. + success : bool + True if one of the convergence criteria is satisfied (`status` > 0). + + See Also + -------- + leastsq : A legacy wrapper for the MINPACK implementation of the + Levenberg-Marquadt algorithm. + curve_fit : Least-squares minimization applied to a curve-fitting problem. + + Notes + ----- + Method 'lm' (Levenberg-Marquardt) calls a wrapper over least-squares + algorithms implemented in MINPACK (lmder, lmdif). It runs the + Levenberg-Marquardt algorithm formulated as a trust-region type algorithm. + The implementation is based on paper [JJMore]_, it is very robust and + efficient with a lot of smart tricks. It should be your first choice + for unconstrained problems. Note that it doesn't support bounds. Also, + it doesn't work when m < n. + + Method 'trf' (Trust Region Reflective) is motivated by the process of + solving a system of equations, which constitute the first-order optimality + condition for a bound-constrained minimization problem as formulated in + [STIR]_. The algorithm iteratively solves trust-region subproblems + augmented by a special diagonal quadratic term and with trust-region shape + determined by the distance from the bounds and the direction of the + gradient. This enhancements help to avoid making steps directly into bounds + and efficiently explore the whole space of variables. To further improve + convergence, the algorithm considers search directions reflected from the + bounds. To obey theoretical requirements, the algorithm keeps iterates + strictly feasible. With dense Jacobians trust-region subproblems are + solved by an exact method very similar to the one described in [JJMore]_ + (and implemented in MINPACK). The difference from the MINPACK + implementation is that a singular value decomposition of a Jacobian + matrix is done once per iteration, instead of a QR decomposition and series + of Givens rotation eliminations. For large sparse Jacobians a 2-D subspace + approach of solving trust-region subproblems is used [STIR]_, [Byrd]_. + The subspace is spanned by a scaled gradient and an approximate + Gauss-Newton solution delivered by `scipy.sparse.linalg.lsmr`. When no + constraints are imposed the algorithm is very similar to MINPACK and has + generally comparable performance. The algorithm works quite robust in + unbounded and bounded problems, thus it is chosen as a default algorithm. + + Method 'dogbox' operates in a trust-region framework, but considers + rectangular trust regions as opposed to conventional ellipsoids [Voglis]_. + The intersection of a current trust region and initial bounds is again + rectangular, so on each iteration a quadratic minimization problem subject + to bound constraints is solved approximately by Powell's dogleg method + [NumOpt]_. The required Gauss-Newton step can be computed exactly for + dense Jacobians or approximately by `scipy.sparse.linalg.lsmr` for large + sparse Jacobians. The algorithm is likely to exhibit slow convergence when + the rank of Jacobian is less than the number of variables. The algorithm + often outperforms 'trf' in bounded problems with a small number of + variables. + + Robust loss functions are implemented as described in [BA]_. The idea + is to modify a residual vector and a Jacobian matrix on each iteration + such that computed gradient and Gauss-Newton Hessian approximation match + the true gradient and Hessian approximation of the cost function. Then + the algorithm proceeds in a normal way, i.e., robust loss functions are + implemented as a simple wrapper over standard least-squares algorithms. + + .. versionadded:: 0.17.0 + + References + ---------- + .. [STIR] M. A. Branch, T. F. Coleman, and Y. Li, "A Subspace, Interior, + and Conjugate Gradient Method for Large-Scale Bound-Constrained + Minimization Problems," SIAM Journal on Scientific Computing, + Vol. 21, Number 1, pp 1-23, 1999. + .. [NR] William H. Press et. al., "Numerical Recipes. The Art of Scientific + Computing. 3rd edition", Sec. 5.7. + .. [Byrd] R. H. Byrd, R. B. Schnabel and G. A. Shultz, "Approximate + solution of the trust region problem by minimization over + two-dimensional subspaces", Math. Programming, 40, pp. 247-263, + 1988. + .. [Curtis] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of + sparse Jacobian matrices", Journal of the Institute of + Mathematics and its Applications, 13, pp. 117-120, 1974. + .. [JJMore] J. J. More, "The Levenberg-Marquardt Algorithm: Implementation + and Theory," Numerical Analysis, ed. G. A. Watson, Lecture + Notes in Mathematics 630, Springer Verlag, pp. 105-116, 1977. + .. [Voglis] C. Voglis and I. E. Lagaris, "A Rectangular Trust Region + Dogleg Approach for Unconstrained and Bound Constrained + Nonlinear Optimization", WSEAS International Conference on + Applied Mathematics, Corfu, Greece, 2004. + .. [NumOpt] J. Nocedal and S. J. Wright, "Numerical optimization, + 2nd edition", Chapter 4. + .. [BA] B. Triggs et. al., "Bundle Adjustment - A Modern Synthesis", + Proceedings of the International Workshop on Vision Algorithms: + Theory and Practice, pp. 298-372, 1999. + + Examples + -------- + In this example we find a minimum of the Rosenbrock function without bounds + on independent variables. + + >>> import numpy as np + >>> def fun_rosenbrock(x): + ... return np.array([10 * (x[1] - x[0]**2), (1 - x[0])]) + + Notice that we only provide the vector of the residuals. The algorithm + constructs the cost function as a sum of squares of the residuals, which + gives the Rosenbrock function. The exact minimum is at ``x = [1.0, 1.0]``. + + >>> from scipy.optimize import least_squares + >>> x0_rosenbrock = np.array([2, 2]) + >>> res_1 = least_squares(fun_rosenbrock, x0_rosenbrock) + >>> res_1.x + array([ 1., 1.]) + >>> res_1.cost + 9.8669242910846867e-30 + >>> res_1.optimality + 8.8928864934219529e-14 + + We now constrain the variables, in such a way that the previous solution + becomes infeasible. Specifically, we require that ``x[1] >= 1.5``, and + ``x[0]`` left unconstrained. To this end, we specify the `bounds` parameter + to `least_squares` in the form ``bounds=([-np.inf, 1.5], np.inf)``. + + We also provide the analytic Jacobian: + + >>> def jac_rosenbrock(x): + ... return np.array([ + ... [-20 * x[0], 10], + ... [-1, 0]]) + + Putting this all together, we see that the new solution lies on the bound: + + >>> res_2 = least_squares(fun_rosenbrock, x0_rosenbrock, jac_rosenbrock, + ... bounds=([-np.inf, 1.5], np.inf)) + >>> res_2.x + array([ 1.22437075, 1.5 ]) + >>> res_2.cost + 0.025213093946805685 + >>> res_2.optimality + 1.5885401433157753e-07 + + Now we solve a system of equations (i.e., the cost function should be zero + at a minimum) for a Broyden tridiagonal vector-valued function of 100000 + variables: + + >>> def fun_broyden(x): + ... f = (3 - x) * x + 1 + ... f[1:] -= x[:-1] + ... f[:-1] -= 2 * x[1:] + ... return f + + The corresponding Jacobian matrix is sparse. We tell the algorithm to + estimate it by finite differences and provide the sparsity structure of + Jacobian to significantly speed up this process. + + >>> from scipy.sparse import lil_matrix + >>> def sparsity_broyden(n): + ... sparsity = lil_matrix((n, n), dtype=int) + ... i = np.arange(n) + ... sparsity[i, i] = 1 + ... i = np.arange(1, n) + ... sparsity[i, i - 1] = 1 + ... i = np.arange(n - 1) + ... sparsity[i, i + 1] = 1 + ... return sparsity + ... + >>> n = 100000 + >>> x0_broyden = -np.ones(n) + ... + >>> res_3 = least_squares(fun_broyden, x0_broyden, + ... jac_sparsity=sparsity_broyden(n)) + >>> res_3.cost + 4.5687069299604613e-23 + >>> res_3.optimality + 1.1650454296851518e-11 + + Let's also solve a curve fitting problem using robust loss function to + take care of outliers in the data. Define the model function as + ``y = a + b * exp(c * t)``, where t is a predictor variable, y is an + observation and a, b, c are parameters to estimate. + + First, define the function which generates the data with noise and + outliers, define the model parameters, and generate data: + + >>> from numpy.random import default_rng + >>> rng = default_rng() + >>> def gen_data(t, a, b, c, noise=0., n_outliers=0, seed=None): + ... rng = default_rng(seed) + ... + ... y = a + b * np.exp(t * c) + ... + ... error = noise * rng.standard_normal(t.size) + ... outliers = rng.integers(0, t.size, n_outliers) + ... error[outliers] *= 10 + ... + ... return y + error + ... + >>> a = 0.5 + >>> b = 2.0 + >>> c = -1 + >>> t_min = 0 + >>> t_max = 10 + >>> n_points = 15 + ... + >>> t_train = np.linspace(t_min, t_max, n_points) + >>> y_train = gen_data(t_train, a, b, c, noise=0.1, n_outliers=3) + + Define function for computing residuals and initial estimate of + parameters. + + >>> def fun(x, t, y): + ... return x[0] + x[1] * np.exp(x[2] * t) - y + ... + >>> x0 = np.array([1.0, 1.0, 0.0]) + + Compute a standard least-squares solution: + + >>> res_lsq = least_squares(fun, x0, args=(t_train, y_train)) + + Now compute two solutions with two different robust loss functions. The + parameter `f_scale` is set to 0.1, meaning that inlier residuals should + not significantly exceed 0.1 (the noise level used). + + >>> res_soft_l1 = least_squares(fun, x0, loss='soft_l1', f_scale=0.1, + ... args=(t_train, y_train)) + >>> res_log = least_squares(fun, x0, loss='cauchy', f_scale=0.1, + ... args=(t_train, y_train)) + + And, finally, plot all the curves. We see that by selecting an appropriate + `loss` we can get estimates close to optimal even in the presence of + strong outliers. But keep in mind that generally it is recommended to try + 'soft_l1' or 'huber' losses first (if at all necessary) as the other two + options may cause difficulties in optimization process. + + >>> t_test = np.linspace(t_min, t_max, n_points * 10) + >>> y_true = gen_data(t_test, a, b, c) + >>> y_lsq = gen_data(t_test, *res_lsq.x) + >>> y_soft_l1 = gen_data(t_test, *res_soft_l1.x) + >>> y_log = gen_data(t_test, *res_log.x) + ... + >>> import matplotlib.pyplot as plt + >>> plt.plot(t_train, y_train, 'o') + >>> plt.plot(t_test, y_true, 'k', linewidth=2, label='true') + >>> plt.plot(t_test, y_lsq, label='linear loss') + >>> plt.plot(t_test, y_soft_l1, label='soft_l1 loss') + >>> plt.plot(t_test, y_log, label='cauchy loss') + >>> plt.xlabel("t") + >>> plt.ylabel("y") + >>> plt.legend() + >>> plt.show() + + In the next example, we show how complex-valued residual functions of + complex variables can be optimized with ``least_squares()``. Consider the + following function: + + >>> def f(z): + ... return z - (0.5 + 0.5j) + + We wrap it into a function of real variables that returns real residuals + by simply handling the real and imaginary parts as independent variables: + + >>> def f_wrap(x): + ... fx = f(x[0] + 1j*x[1]) + ... return np.array([fx.real, fx.imag]) + + Thus, instead of the original m-D complex function of n complex + variables we optimize a 2m-D real function of 2n real variables: + + >>> from scipy.optimize import least_squares + >>> res_wrapped = least_squares(f_wrap, (0.1, 0.1), bounds=([0, 0], [1, 1])) + >>> z = res_wrapped.x[0] + res_wrapped.x[1]*1j + >>> z + (0.49999999999925893+0.49999999999925893j) + + """ + if method not in ['trf', 'dogbox', 'lm']: + raise ValueError("`method` must be 'trf', 'dogbox' or 'lm'.") + + if jac not in ['2-point', '3-point', 'cs'] and not callable(jac): + raise ValueError("`jac` must be '2-point', '3-point', 'cs' or " + "callable.") + + if tr_solver not in [None, 'exact', 'lsmr']: + raise ValueError("`tr_solver` must be None, 'exact' or 'lsmr'.") + + if loss not in IMPLEMENTED_LOSSES and not callable(loss): + raise ValueError(f"`loss` must be one of {IMPLEMENTED_LOSSES.keys()}" + " or a callable.") + + if method == 'lm' and loss != 'linear': + raise ValueError("method='lm' supports only 'linear' loss function.") + + if verbose not in [0, 1, 2]: + raise ValueError("`verbose` must be in [0, 1, 2].") + + if max_nfev is not None and max_nfev <= 0: + raise ValueError("`max_nfev` must be None or positive integer.") + + if np.iscomplexobj(x0): + raise ValueError("`x0` must be real.") + + x0 = np.atleast_1d(x0).astype(float) + + if x0.ndim > 1: + raise ValueError("`x0` must have at most 1 dimension.") + + if isinstance(bounds, Bounds): + lb, ub = bounds.lb, bounds.ub + bounds = (lb, ub) + else: + if len(bounds) == 2: + lb, ub = prepare_bounds(bounds, x0.shape[0]) + else: + raise ValueError("`bounds` must contain 2 elements.") + + if method == 'lm' and not np.all((lb == -np.inf) & (ub == np.inf)): + raise ValueError("Method 'lm' doesn't support bounds.") + + if lb.shape != x0.shape or ub.shape != x0.shape: + raise ValueError("Inconsistent shapes between bounds and `x0`.") + + if np.any(lb >= ub): + raise ValueError("Each lower bound must be strictly less than each " + "upper bound.") + + if not in_bounds(x0, lb, ub): + raise ValueError("Initial guess is outside of provided bounds") + + x_scale = check_x_scale(x_scale, x0) + + ftol, xtol, gtol = check_tolerance(ftol, xtol, gtol, method) + + if method == 'trf': + x0 = make_strictly_feasible(x0, lb, ub) + + if kwargs is None: + kwargs = {} + if tr_options is None: + tr_options = {} + + def fun_wrapped(x): + return np.atleast_1d(fun(x, *args, **kwargs)) + + f0 = fun_wrapped(x0) + + if f0.ndim != 1: + raise ValueError("`fun` must return at most 1-d array_like. " + f"f0.shape: {f0.shape}") + + if not np.all(np.isfinite(f0)): + raise ValueError("Residuals are not finite in the initial point.") + + n = x0.size + m = f0.size + + if method == 'lm' and m < n: + raise ValueError("Method 'lm' doesn't work when the number of " + "residuals is less than the number of variables.") + + loss_function = construct_loss_function(m, loss, f_scale) + if callable(loss): + rho = loss_function(f0) + if rho.shape != (3, m): + raise ValueError("The return value of `loss` callable has wrong " + "shape.") + initial_cost = 0.5 * np.sum(rho[0]) + elif loss_function is not None: + initial_cost = loss_function(f0, cost_only=True) + else: + initial_cost = 0.5 * np.dot(f0, f0) + + if callable(jac): + J0 = jac(x0, *args, **kwargs) + + if issparse(J0): + J0 = J0.tocsr() + + def jac_wrapped(x, _=None): + return jac(x, *args, **kwargs).tocsr() + + elif isinstance(J0, LinearOperator): + def jac_wrapped(x, _=None): + return jac(x, *args, **kwargs) + + else: + J0 = np.atleast_2d(J0) + + def jac_wrapped(x, _=None): + return np.atleast_2d(jac(x, *args, **kwargs)) + + else: # Estimate Jacobian by finite differences. + if method == 'lm': + if jac_sparsity is not None: + raise ValueError("method='lm' does not support " + "`jac_sparsity`.") + + if jac != '2-point': + warn(f"jac='{jac}' works equivalently to '2-point' for method='lm'.", + stacklevel=2) + + J0 = jac_wrapped = None + else: + if jac_sparsity is not None and tr_solver == 'exact': + raise ValueError("tr_solver='exact' is incompatible " + "with `jac_sparsity`.") + + jac_sparsity = check_jac_sparsity(jac_sparsity, m, n) + + def jac_wrapped(x, f): + J = approx_derivative(fun, x, rel_step=diff_step, method=jac, + f0=f, bounds=bounds, args=args, + kwargs=kwargs, sparsity=jac_sparsity) + if J.ndim != 2: # J is guaranteed not sparse. + J = np.atleast_2d(J) + + return J + + J0 = jac_wrapped(x0, f0) + + if J0 is not None: + if J0.shape != (m, n): + raise ValueError( + f"The return value of `jac` has wrong shape: expected {(m, n)}, " + f"actual {J0.shape}." + ) + + if not isinstance(J0, np.ndarray): + if method == 'lm': + raise ValueError("method='lm' works only with dense " + "Jacobian matrices.") + + if tr_solver == 'exact': + raise ValueError( + "tr_solver='exact' works only with dense " + "Jacobian matrices.") + + jac_scale = isinstance(x_scale, str) and x_scale == 'jac' + if isinstance(J0, LinearOperator) and jac_scale: + raise ValueError("x_scale='jac' can't be used when `jac` " + "returns LinearOperator.") + + if tr_solver is None: + if isinstance(J0, np.ndarray): + tr_solver = 'exact' + else: + tr_solver = 'lsmr' + + if method == 'lm': + result = call_minpack(fun_wrapped, x0, jac_wrapped, ftol, xtol, gtol, + max_nfev, x_scale, diff_step) + + elif method == 'trf': + result = trf(fun_wrapped, jac_wrapped, x0, f0, J0, lb, ub, ftol, xtol, + gtol, max_nfev, x_scale, loss_function, tr_solver, + tr_options.copy(), verbose) + + elif method == 'dogbox': + if tr_solver == 'lsmr' and 'regularize' in tr_options: + warn("The keyword 'regularize' in `tr_options` is not relevant " + "for 'dogbox' method.", + stacklevel=2) + tr_options = tr_options.copy() + del tr_options['regularize'] + + result = dogbox(fun_wrapped, jac_wrapped, x0, f0, J0, lb, ub, ftol, + xtol, gtol, max_nfev, x_scale, loss_function, + tr_solver, tr_options, verbose) + + result.message = TERMINATION_MESSAGES[result.status] + result.success = result.status > 0 + + if verbose >= 1: + print(result.message) + print(f"Function evaluations {result.nfev}, initial cost {initial_cost:.4e}, " + f"final cost {result.cost:.4e}, " + f"first-order optimality {result.optimality:.2e}.") + + return result diff --git a/shared/package-files/33/33f8936bd3e7f05ee343593a44df4abdb8449f4d20ed46096793d5e7b8a47193/char.pyi b/shared/package-files/33/33f8936bd3e7f05ee343593a44df4abdb8449f4d20ed46096793d5e7b8a47193/char.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e15ed0801a0d9b70c0abdb0723df6793fae12046 --- /dev/null +++ b/shared/package-files/33/33f8936bd3e7f05ee343593a44df4abdb8449f4d20ed46096793d5e7b8a47193/char.pyi @@ -0,0 +1,154 @@ +import sys +from typing import Any + +import numpy as np +import numpy.typing as npt + +if sys.version_info >= (3, 11): + from typing import assert_type +else: + from typing_extensions import assert_type + +AR_U: npt.NDArray[np.str_] +AR_S: npt.NDArray[np.bytes_] + +assert_type(np.char.equal(AR_U, AR_U), npt.NDArray[np.bool_]) +assert_type(np.char.equal(AR_S, AR_S), npt.NDArray[np.bool_]) + +assert_type(np.char.not_equal(AR_U, AR_U), npt.NDArray[np.bool_]) +assert_type(np.char.not_equal(AR_S, AR_S), npt.NDArray[np.bool_]) + +assert_type(np.char.greater_equal(AR_U, AR_U), npt.NDArray[np.bool_]) +assert_type(np.char.greater_equal(AR_S, AR_S), npt.NDArray[np.bool_]) + +assert_type(np.char.less_equal(AR_U, AR_U), npt.NDArray[np.bool_]) +assert_type(np.char.less_equal(AR_S, AR_S), npt.NDArray[np.bool_]) + +assert_type(np.char.greater(AR_U, AR_U), npt.NDArray[np.bool_]) +assert_type(np.char.greater(AR_S, AR_S), npt.NDArray[np.bool_]) + +assert_type(np.char.less(AR_U, AR_U), npt.NDArray[np.bool_]) +assert_type(np.char.less(AR_S, AR_S), npt.NDArray[np.bool_]) + +assert_type(np.char.multiply(AR_U, 5), npt.NDArray[np.str_]) +assert_type(np.char.multiply(AR_S, [5, 4, 3]), npt.NDArray[np.bytes_]) + +assert_type(np.char.mod(AR_U, "test"), npt.NDArray[np.str_]) +assert_type(np.char.mod(AR_S, "test"), npt.NDArray[np.bytes_]) + +assert_type(np.char.capitalize(AR_U), npt.NDArray[np.str_]) +assert_type(np.char.capitalize(AR_S), npt.NDArray[np.bytes_]) + +assert_type(np.char.center(AR_U, 5), npt.NDArray[np.str_]) +assert_type(np.char.center(AR_S, [2, 3, 4], b"a"), npt.NDArray[np.bytes_]) + +assert_type(np.char.encode(AR_U), npt.NDArray[np.bytes_]) +assert_type(np.char.decode(AR_S), npt.NDArray[np.str_]) + +assert_type(np.char.expandtabs(AR_U), npt.NDArray[np.str_]) +assert_type(np.char.expandtabs(AR_S, tabsize=4), npt.NDArray[np.bytes_]) + +assert_type(np.char.join(AR_U, "_"), npt.NDArray[np.str_]) +assert_type(np.char.join(AR_S, [b"_", b""]), npt.NDArray[np.bytes_]) + +assert_type(np.char.ljust(AR_U, 5), npt.NDArray[np.str_]) +assert_type(np.char.ljust(AR_S, [4, 3, 1], fillchar=[b"a", b"b", b"c"]), npt.NDArray[np.bytes_]) +assert_type(np.char.rjust(AR_U, 5), npt.NDArray[np.str_]) +assert_type(np.char.rjust(AR_S, [4, 3, 1], fillchar=[b"a", b"b", b"c"]), npt.NDArray[np.bytes_]) + +assert_type(np.char.lstrip(AR_U), npt.NDArray[np.str_]) +assert_type(np.char.lstrip(AR_S, chars=b"_"), npt.NDArray[np.bytes_]) +assert_type(np.char.rstrip(AR_U), npt.NDArray[np.str_]) +assert_type(np.char.rstrip(AR_S, chars=b"_"), npt.NDArray[np.bytes_]) +assert_type(np.char.strip(AR_U), npt.NDArray[np.str_]) +assert_type(np.char.strip(AR_S, chars=b"_"), npt.NDArray[np.bytes_]) + +assert_type(np.char.partition(AR_U, "\n"), npt.NDArray[np.str_]) +assert_type(np.char.partition(AR_S, [b"a", b"b", b"c"]), npt.NDArray[np.bytes_]) +assert_type(np.char.rpartition(AR_U, "\n"), npt.NDArray[np.str_]) +assert_type(np.char.rpartition(AR_S, [b"a", b"b", b"c"]), npt.NDArray[np.bytes_]) + +assert_type(np.char.replace(AR_U, "_", "-"), npt.NDArray[np.str_]) +assert_type(np.char.replace(AR_S, [b"_", b""], [b"a", b"b"]), npt.NDArray[np.bytes_]) + +assert_type(np.char.split(AR_U, "_"), npt.NDArray[np.object_]) +assert_type(np.char.split(AR_S, maxsplit=[1, 2, 3]), npt.NDArray[np.object_]) +assert_type(np.char.rsplit(AR_U, "_"), npt.NDArray[np.object_]) +assert_type(np.char.rsplit(AR_S, maxsplit=[1, 2, 3]), npt.NDArray[np.object_]) + +assert_type(np.char.splitlines(AR_U), npt.NDArray[np.object_]) +assert_type(np.char.splitlines(AR_S, keepends=[True, True, False]), npt.NDArray[np.object_]) + +assert_type(np.char.swapcase(AR_U), npt.NDArray[np.str_]) +assert_type(np.char.swapcase(AR_S), npt.NDArray[np.bytes_]) + +assert_type(np.char.title(AR_U), npt.NDArray[np.str_]) +assert_type(np.char.title(AR_S), npt.NDArray[np.bytes_]) + +assert_type(np.char.upper(AR_U), npt.NDArray[np.str_]) +assert_type(np.char.upper(AR_S), npt.NDArray[np.bytes_]) + +assert_type(np.char.zfill(AR_U, 5), npt.NDArray[np.str_]) +assert_type(np.char.zfill(AR_S, [2, 3, 4]), npt.NDArray[np.bytes_]) + +assert_type(np.char.count(AR_U, "a", start=[1, 2, 3]), npt.NDArray[np.int_]) +assert_type(np.char.count(AR_S, [b"a", b"b", b"c"], end=9), npt.NDArray[np.int_]) + +assert_type(np.char.endswith(AR_U, "a", start=[1, 2, 3]), npt.NDArray[np.bool_]) +assert_type(np.char.endswith(AR_S, [b"a", b"b", b"c"], end=9), npt.NDArray[np.bool_]) +assert_type(np.char.startswith(AR_U, "a", start=[1, 2, 3]), npt.NDArray[np.bool_]) +assert_type(np.char.startswith(AR_S, [b"a", b"b", b"c"], end=9), npt.NDArray[np.bool_]) + +assert_type(np.char.find(AR_U, "a", start=[1, 2, 3]), npt.NDArray[np.int_]) +assert_type(np.char.find(AR_S, [b"a", b"b", b"c"], end=9), npt.NDArray[np.int_]) +assert_type(np.char.rfind(AR_U, "a", start=[1, 2, 3]), npt.NDArray[np.int_]) +assert_type(np.char.rfind(AR_S, [b"a", b"b", b"c"], end=9), npt.NDArray[np.int_]) + +assert_type(np.char.index(AR_U, "a", start=[1, 2, 3]), npt.NDArray[np.int_]) +assert_type(np.char.index(AR_S, [b"a", b"b", b"c"], end=9), npt.NDArray[np.int_]) +assert_type(np.char.rindex(AR_U, "a", start=[1, 2, 3]), npt.NDArray[np.int_]) +assert_type(np.char.rindex(AR_S, [b"a", b"b", b"c"], end=9), npt.NDArray[np.int_]) + +assert_type(np.char.isalpha(AR_U), npt.NDArray[np.bool_]) +assert_type(np.char.isalpha(AR_S), npt.NDArray[np.bool_]) + +assert_type(np.char.isalnum(AR_U), npt.NDArray[np.bool_]) +assert_type(np.char.isalnum(AR_S), npt.NDArray[np.bool_]) + +assert_type(np.char.isdecimal(AR_U), npt.NDArray[np.bool_]) +assert_type(np.char.isdecimal(AR_S), npt.NDArray[np.bool_]) + +assert_type(np.char.isdigit(AR_U), npt.NDArray[np.bool_]) +assert_type(np.char.isdigit(AR_S), npt.NDArray[np.bool_]) + +assert_type(np.char.islower(AR_U), npt.NDArray[np.bool_]) +assert_type(np.char.islower(AR_S), npt.NDArray[np.bool_]) + +assert_type(np.char.isnumeric(AR_U), npt.NDArray[np.bool_]) +assert_type(np.char.isnumeric(AR_S), npt.NDArray[np.bool_]) + +assert_type(np.char.isspace(AR_U), npt.NDArray[np.bool_]) +assert_type(np.char.isspace(AR_S), npt.NDArray[np.bool_]) + +assert_type(np.char.istitle(AR_U), npt.NDArray[np.bool_]) +assert_type(np.char.istitle(AR_S), npt.NDArray[np.bool_]) + +assert_type(np.char.isupper(AR_U), npt.NDArray[np.bool_]) +assert_type(np.char.isupper(AR_S), npt.NDArray[np.bool_]) + +assert_type(np.char.str_len(AR_U), npt.NDArray[np.int_]) +assert_type(np.char.str_len(AR_S), npt.NDArray[np.int_]) + +assert_type(np.char.array(AR_U), np.chararray[Any, np.dtype[np.str_]]) +assert_type(np.char.array(AR_S, order="K"), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(np.char.array("bob", copy=True), np.chararray[Any, np.dtype[np.str_]]) +assert_type(np.char.array(b"bob", itemsize=5), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(np.char.array(1, unicode=False), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(np.char.array(1, unicode=True), np.chararray[Any, np.dtype[np.str_]]) + +assert_type(np.char.asarray(AR_U), np.chararray[Any, np.dtype[np.str_]]) +assert_type(np.char.asarray(AR_S, order="K"), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(np.char.asarray("bob"), np.chararray[Any, np.dtype[np.str_]]) +assert_type(np.char.asarray(b"bob", itemsize=5), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(np.char.asarray(1, unicode=False), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(np.char.asarray(1, unicode=True), np.chararray[Any, np.dtype[np.str_]]) diff --git a/shared/package-files/33/33fc889cbff57bb78c913bb6c24c5d52bd02f3cba0f4b1cb2913340294a6ec1a/errors.py b/shared/package-files/33/33fc889cbff57bb78c913bb6c24c5d52bd02f3cba0f4b1cb2913340294a6ec1a/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..3ad00565549968629376276f2a304dbce070076a --- /dev/null +++ b/shared/package-files/33/33fc889cbff57bb78c913bb6c24c5d52bd02f3cba0f4b1cb2913340294a6ec1a/errors.py @@ -0,0 +1,113 @@ +# Copyright (C) 2001-2006 Python Software Foundation +# Author: Barry Warsaw +# Contact: email-sig@python.org + +"""email package exception classes.""" + + +class MessageError(Exception): + """Base class for errors in the email package.""" + + +class MessageParseError(MessageError): + """Base class for message parsing errors.""" + + +class HeaderParseError(MessageParseError): + """Error while parsing headers.""" + + +class BoundaryError(MessageParseError): + """Couldn't find terminating boundary.""" + + +class MultipartConversionError(MessageError, TypeError): + """Conversion to a multipart is prohibited.""" + + +class CharsetError(MessageError): + """An illegal charset was given.""" + + +# These are parsing defects which the parser was able to work around. +class MessageDefect(ValueError): + """Base class for a message defect.""" + + def __init__(self, line=None): + if line is not None: + super().__init__(line) + self.line = line + +class NoBoundaryInMultipartDefect(MessageDefect): + """A message claimed to be a multipart but had no boundary parameter.""" + +class StartBoundaryNotFoundDefect(MessageDefect): + """The claimed start boundary was never found.""" + +class CloseBoundaryNotFoundDefect(MessageDefect): + """A start boundary was found, but not the corresponding close boundary.""" + +class FirstHeaderLineIsContinuationDefect(MessageDefect): + """A message had a continuation line as its first header line.""" + +class MisplacedEnvelopeHeaderDefect(MessageDefect): + """A 'Unix-from' header was found in the middle of a header block.""" + +class MissingHeaderBodySeparatorDefect(MessageDefect): + """Found line with no leading whitespace and no colon before blank line.""" +# XXX: backward compatibility, just in case (it was never emitted). +MalformedHeaderDefect = MissingHeaderBodySeparatorDefect + +class MultipartInvariantViolationDefect(MessageDefect): + """A message claimed to be a multipart but no subparts were found.""" + +class InvalidMultipartContentTransferEncodingDefect(MessageDefect): + """An invalid content transfer encoding was set on the multipart itself.""" + +class UndecodableBytesDefect(MessageDefect): + """Header contained bytes that could not be decoded""" + +class InvalidBase64PaddingDefect(MessageDefect): + """base64 encoded sequence had an incorrect length""" + +class InvalidBase64CharactersDefect(MessageDefect): + """base64 encoded sequence had characters not in base64 alphabet""" + +class InvalidBase64LengthDefect(MessageDefect): + """base64 encoded sequence had invalid length (1 mod 4)""" + +# These errors are specific to header parsing. + +class HeaderDefect(MessageDefect): + """Base class for a header defect.""" + + def __init__(self, *args, **kw): + super().__init__(*args, **kw) + +class InvalidHeaderDefect(HeaderDefect): + """Header is not valid, message gives details.""" + +class HeaderMissingRequiredValue(HeaderDefect): + """A header that must have a value had none""" + +class NonPrintableDefect(HeaderDefect): + """ASCII characters outside the ascii-printable range found""" + + def __init__(self, non_printables): + super().__init__(non_printables) + self.non_printables = non_printables + + def __str__(self): + return ("the following ASCII non-printables found in header: " + "{}".format(self.non_printables)) + +class ObsoleteHeaderDefect(HeaderDefect): + """Header uses syntax declared obsolete by RFC 5322""" + +class NonASCIILocalPartDefect(HeaderDefect): + """local_part contains non-ASCII characters""" + # This defect only occurs during unicode parsing, not when + # parsing messages decoded from binary. + +class InvalidDateDefect(HeaderDefect): + """Header has unparsable or invalid date""" diff --git a/shared/package-files/33/33ffa2f718e123fd1c4e536bb4a471978515787ee9fbf7806a92073a787a733a/idle.py b/shared/package-files/33/33ffa2f718e123fd1c4e536bb4a471978515787ee9fbf7806a92073a787a733a/idle.py new file mode 100644 index 0000000000000000000000000000000000000000..485d5a75a29c1ad8f39f4558ce4759797951baa1 --- /dev/null +++ b/shared/package-files/33/33ffa2f718e123fd1c4e536bb4a471978515787ee9fbf7806a92073a787a733a/idle.py @@ -0,0 +1,14 @@ +import os.path +import sys + + +# Enable running IDLE with idlelib in a non-standard location. +# This was once used to run development versions of IDLE. +# Because PEP 434 declared idle.py a public interface, +# removal should require deprecation. +idlelib_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +if idlelib_dir not in sys.path: + sys.path.insert(0, idlelib_dir) + +from idlelib.pyshell import main # This is subject to change +main() diff --git a/shared/package-files/35/35022b6817d7751ddaec52b7a803d9ba957aa70719ed7b7d0bdb695b9562f713/addr_native.h b/shared/package-files/35/35022b6817d7751ddaec52b7a803d9ba957aa70719ed7b7d0bdb695b9562f713/addr_native.h new file mode 100644 index 0000000000000000000000000000000000000000..7740fc800c3e5a9f3eacd32a4647ffee461cf5f1 --- /dev/null +++ b/shared/package-files/35/35022b6817d7751ddaec52b7a803d9ba957aa70719ed7b7d0bdb695b9562f713/addr_native.h @@ -0,0 +1,25 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor math_addr(const at::Tensor & self, const at::Tensor & vec1, const at::Tensor & vec2, const at::Scalar & beta=1, const at::Scalar & alpha=1); +TORCH_API at::Tensor & math_addr_out(const at::Tensor & self, const at::Tensor & vec1, const at::Tensor & vec2, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out); +TORCH_API at::Tensor & addr_(at::Tensor & self, const at::Tensor & vec1, const at::Tensor & vec2, const at::Scalar & beta=1, const at::Scalar & alpha=1); +TORCH_API at::Tensor addr(const at::Tensor & self, const at::Tensor & vec1, const at::Tensor & vec2, const at::Scalar & beta=1, const at::Scalar & alpha=1); +TORCH_API at::Tensor & addr_out(const at::Tensor & self, const at::Tensor & vec1, const at::Tensor & vec2, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/35/350d06c4db40e24eb83c7e49931c3158d0ea39f4801349f315b993fd6345c024/upsample_bilinear2d_ops.h b/shared/package-files/35/350d06c4db40e24eb83c7e49931c3158d0ea39f4801349f315b993fd6345c024/upsample_bilinear2d_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..ee6c0d108ea19bee8b688d0180d25f3f117e233e --- /dev/null +++ b/shared/package-files/35/350d06c4db40e24eb83c7e49931c3158d0ea39f4801349f315b993fd6345c024/upsample_bilinear2d_ops.h @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API upsample_bilinear2d_vec { + using schema = at::Tensor (const at::Tensor &, at::OptionalSymIntArrayRef, bool, c10::optional>); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::upsample_bilinear2d") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "vec") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "upsample_bilinear2d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor") + static at::Tensor call(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, bool align_corners, c10::optional> scale_factors); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, at::OptionalSymIntArrayRef output_size, bool align_corners, c10::optional> scale_factors); +}; + +struct TORCH_API upsample_bilinear2d_out { + using schema = at::Tensor & (const at::Tensor &, c10::SymIntArrayRef, bool, c10::optional, c10::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::upsample_bilinear2d") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "upsample_bilinear2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & out); +}; + +struct TORCH_API upsample_bilinear2d { + using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef, bool, c10::optional, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::upsample_bilinear2d") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "upsample_bilinear2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/35/350e106029a10bdf20056d85bf62d6d31cc535923ef6023a0234d6fd4a9e3896/upload.pyi b/shared/package-files/35/350e106029a10bdf20056d85bf62d6d31cc535923ef6023a0234d6fd4a9e3896/upload.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a30fabb188beb512771ee918317c5134cfdf4b1a --- /dev/null +++ b/shared/package-files/35/350e106029a10bdf20056d85bf62d6d31cc535923ef6023a0234d6fd4a9e3896/upload.pyi @@ -0,0 +1,8 @@ +from distutils.config import PyPIRCCommand +from typing import ClassVar, List + +class upload(PyPIRCCommand): + description: ClassVar[str] + boolean_options: ClassVar[List[str]] + def run(self) -> None: ... + def upload_file(self, command, pyversion, filename) -> None: ... diff --git a/shared/package-files/35/350fe1c03c1124114c7e1b324876892976ea478b1c8e0889440c64f76e054169/scatter_add_cuda_dispatch.h b/shared/package-files/35/350fe1c03c1124114c7e1b324876892976ea478b1c8e0889440c64f76e054169/scatter_add_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..59328cbc756e7ecc5072c49732afe74680451ed6 --- /dev/null +++ b/shared/package-files/35/350fe1c03c1124114c7e1b324876892976ea478b1c8e0889440c64f76e054169/scatter_add_cuda_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor scatter_add(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src); +TORCH_API at::Tensor & scatter_add_out(at::Tensor & out, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src); +TORCH_API at::Tensor & scatter_add_outf(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, at::Tensor & out); +TORCH_API at::Tensor & scatter_add_(at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/35/351140073760af4a3cf82b9a4c11646524f3e9e54f8b1fa149f5d1a31575582f/_int_mm_ops.h b/shared/package-files/35/351140073760af4a3cf82b9a4c11646524f3e9e54f8b1fa149f5d1a31575582f/_int_mm_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..6b4e90ef4752b129aaddc0264ca592c930c5efaa --- /dev/null +++ b/shared/package-files/35/351140073760af4a3cf82b9a4c11646524f3e9e54f8b1fa149f5d1a31575582f/_int_mm_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _int_mm { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_int_mm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_int_mm(Tensor self, Tensor mat2) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & mat2); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mat2); +}; + +struct TORCH_API _int_mm_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_int_mm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_int_mm.out(Tensor self, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & mat2, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mat2, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/35/35141f490a393aded279b7e3849b6a2eb7a0252db6da3afe48563d999d409aae/Functions.cpp b/shared/package-files/35/35141f490a393aded279b7e3849b6a2eb7a0252db6da3afe48563d999d409aae/Functions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05962bc2482914a32f04ce2b45bfda9579550bdd --- /dev/null +++ b/shared/package-files/35/35141f490a393aded279b7e3849b6a2eb7a0252db6da3afe48563d999d409aae/Functions.cpp @@ -0,0 +1,103 @@ +#include + +#include +#include +#include + +namespace at { + +Tensor TensorMaker::make_tensor() { + AutoDispatchBelowADInplaceOrView guard{}; // TODO: Remove. + tracer::impl::NoTracerDispatchMode tracer_guard{}; + + check_size_nonnegative(sizes_); + + TORCH_CHECK_VALUE( + !deleter_ || !ctx_, + "The deleter and context arguments are mutually exclusive."); + + if (device_ == nullopt) { + device_ = globalContext().getDeviceFromPtr(data_, opts_.device().type()); + } + + if (opts_.device().has_index()) { + // clang-format off + TORCH_CHECK_VALUE( + opts_.device() == *device_, + "Specified device ", opts_.device(), " does not match device of data ", *device_); + // clang-format on + } + + std::size_t size_bytes = computeStorageSize(); + + DataPtr data_ptr{}; + if (deleter_) { + data_ptr = makeDataPtrFromDeleter(); + } else { + data_ptr = makeDataPtrFromContext(); + } + + TORCH_CHECK(!resizeable_ || allocator_ != nullptr, "Must specify an allocator with allocator() if you want to use resizeable_storage()"); + Storage storage{Storage::use_byte_size_t{}, size_bytes, std::move(data_ptr), /*allocator=*/allocator_, /*resizeable=*/resizeable_}; + + Tensor tensor = detail::make_tensor( + std::move(storage), opts_.computeDispatchKey(), opts_.dtype()); + + TensorImpl* tensor_impl = tensor.unsafeGetTensorImpl(); + if (strides_) { + tensor_impl->set_sizes_and_strides(sizes_, *strides_); + } else { + tensor_impl->set_sizes_contiguous(sizes_); + } + if (storage_offset_) { + tensor_impl->set_storage_offset(*storage_offset_); + } + + return tensor; + } + + std::size_t TensorMaker::computeStorageSize() const noexcept { + std::size_t itemsize = opts_.dtype().itemsize(); + + if (strides_) { + auto storage_size = detail::computeStorageNbytes(sizes_, *strides_, itemsize); + if (storage_offset_) { + storage_size += storage_offset_.value(); + } + return storage_size; + } + + std::size_t size = 1; + for (std::int64_t s : sizes_) { + size *= static_cast(s); + } + auto storage_size = size * itemsize; + if (storage_offset_) { + storage_size += storage_offset_.value(); + } + return storage_size; + } + + inline DataPtr TensorMaker::makeDataPtrFromDeleter() noexcept { + return InefficientStdFunctionContext::makeDataPtr(data_, std::move(deleter_), *device_); + } + + inline DataPtr TensorMaker::makeDataPtrFromContext() noexcept { + return DataPtr{data_, ctx_.release(), ctx_.get_deleter(), *device_}; + } + + IntArrayRef TensorMaker::makeTempSizes() const noexcept { + static std::int64_t zeros[5] = {0, 0, 0, 0, 0}; + if (opts_.has_memory_format()) { + MemoryFormat format = *opts_.memory_format_opt(); + if (format == MemoryFormat::ChannelsLast) { + return IntArrayRef(zeros, 4); + } + if (format == MemoryFormat::ChannelsLast3d) { + return IntArrayRef(zeros, 5); + } + } + return IntArrayRef(zeros, 1); + } + +} // namespace at diff --git a/shared/package-files/35/35184dd28b8c4306a09fa9f0897ac53060991636d4da66478311fc00d32c66a1/traitlets.py b/shared/package-files/35/35184dd28b8c4306a09fa9f0897ac53060991636d4da66478311fc00d32c66a1/traitlets.py new file mode 100644 index 0000000000000000000000000000000000000000..6f03c257accb8981757475200f5d875838ad5b5d --- /dev/null +++ b/shared/package-files/35/35184dd28b8c4306a09fa9f0897ac53060991636d4da66478311fc00d32c66a1/traitlets.py @@ -0,0 +1,3624 @@ +""" +A lightweight Traits like module. + +This is designed to provide a lightweight, simple, pure Python version of +many of the capabilities of enthought.traits. This includes: + +* Validation +* Type specification with defaults +* Static and dynamic notification +* Basic predefined types +* An API that is similar to enthought.traits + +We don't support: + +* Delegation +* Automatic GUI generation +* A full set of trait types. Most importantly, we don't provide container + traits (list, dict, tuple) that can trigger notifications if their + contents change. +* API compatibility with enthought.traits + +There are also some important difference in our design: + +* enthought.traits does not validate default values. We do. + +We choose to create this module because we need these capabilities, but +we need them to be pure Python so they work in all Python implementations, +including Jython and IronPython. + +Inheritance diagram: + +.. inheritance-diagram:: traitlets.traitlets + :parts: 3 +""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. +# +# Adapted from enthought.traits, Copyright (c) Enthought, Inc., +# also under the terms of the Modified BSD License. + +import contextlib +import enum +import inspect +import os +import re +import sys +import types +import typing as t +from ast import literal_eval +from warnings import warn, warn_explicit + +from .utils.bunch import Bunch +from .utils.descriptions import add_article, class_of, describe, repr_type +from .utils.getargspec import getargspec +from .utils.importstring import import_item +from .utils.sentinel import Sentinel + +SequenceTypes = (list, tuple, set, frozenset) + +# backward compatibility, use to differ between Python 2 and 3. +ClassTypes = (type,) + +# exports: + +__all__ = [ + "All", + "Any", + "BaseDescriptor", + "Bool", + "Bytes", + "CBool", + "CBytes", + "CComplex", + "CFloat", + "CInt", + "CLong", + "CRegExp", + "CUnicode", + "Callable", + "CaselessStrEnum", + "ClassBasedTraitType", + "Complex", + "Container", + "DefaultHandler", + "Dict", + "DottedObjectName", + "Enum", + "EventHandler", + "Float", + "ForwardDeclaredInstance", + "ForwardDeclaredMixin", + "ForwardDeclaredType", + "FuzzyEnum", + "HasDescriptors", + "HasTraits", + "Instance", + "Int", + "Integer", + "List", + "Long", + "MetaHasDescriptors", + "MetaHasTraits", + "ObjectName", + "ObserveHandler", + "Set", + "TCPAddress", + "This", + "TraitError", + "TraitType", + "Tuple", + "Type", + "Unicode", + "Undefined", + "Union", + "UseEnum", + "ValidateHandler", + "default", + "directional_link", + "dlink", + "link", + "observe", + "observe_compat", + "parse_notifier_name", + "validate", +] + +# any TraitType subclass (that doesn't start with _) will be added automatically + +# ----------------------------------------------------------------------------- +# Basic classes +# ----------------------------------------------------------------------------- + + +Undefined = Sentinel( + "Undefined", + "traitlets", + """ +Used in Traitlets to specify that no defaults are set in kwargs +""", +) + +All = Sentinel( + "All", + "traitlets", + """ +Used in Traitlets to listen to all types of notification or to notifications +from all trait attributes. +""", +) + +# Deprecated alias +NoDefaultSpecified = Undefined + + +class TraitError(Exception): + pass + + +# ----------------------------------------------------------------------------- +# Utilities +# ----------------------------------------------------------------------------- + +_name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$") + + +def isidentifier(s): + return s.isidentifier() + + +_deprecations_shown = set() + + +def _should_warn(key): + """Add our own checks for too many deprecation warnings. + + Limit to once per package. + """ + env_flag = os.environ.get("TRAITLETS_ALL_DEPRECATIONS") + if env_flag and env_flag != "0": + return True + + if key not in _deprecations_shown: + _deprecations_shown.add(key) + return True + else: + return False + + +def _deprecated_method(method, cls, method_name, msg): + """Show deprecation warning about a magic method definition. + + Uses warn_explicit to bind warning to method definition instead of triggering code, + which isn't relevant. + """ + warn_msg = "{classname}.{method_name} is deprecated in traitlets 4.1: {msg}".format( + classname=cls.__name__, method_name=method_name, msg=msg + ) + + for parent in inspect.getmro(cls): + if method_name in parent.__dict__: + cls = parent + break + # limit deprecation messages to once per package + package_name = cls.__module__.split(".", 1)[0] + key = (package_name, msg) + if not _should_warn(key): + return + try: + fname = inspect.getsourcefile(method) or "" + lineno = inspect.getsourcelines(method)[1] or 0 + except (OSError, TypeError) as e: + # Failed to inspect for some reason + warn(warn_msg + ("\n(inspection failed) %s" % e), DeprecationWarning) + else: + warn_explicit(warn_msg, DeprecationWarning, fname, lineno) + + +def _safe_literal_eval(s): + """Safely evaluate an expression + + Returns original string if eval fails. + + Use only where types are ambiguous. + """ + try: + return literal_eval(s) + except (NameError, SyntaxError, ValueError): + return s + + +def is_trait(t): + """Returns whether the given value is an instance or subclass of TraitType.""" + return isinstance(t, TraitType) or (isinstance(t, type) and issubclass(t, TraitType)) + + +def parse_notifier_name(names): + """Convert the name argument to a list of names. + + Examples + -------- + >>> parse_notifier_name([]) + [traitlets.All] + >>> parse_notifier_name("a") + ['a'] + >>> parse_notifier_name(["a", "b"]) + ['a', 'b'] + >>> parse_notifier_name(All) + [traitlets.All] + """ + if names is All or isinstance(names, str): + return [names] + else: + if not names or All in names: + return [All] + for n in names: + if not isinstance(n, str): + raise TypeError("names must be strings, not %r" % n) + return names + + +class _SimpleTest: + def __init__(self, value): + self.value = value + + def __call__(self, test): + return test == self.value + + def __repr__(self): + return ">> class X(HasTraits): + ... value = Int() + + >>> src = X(value=1) + >>> tgt = X(value=42) + >>> c = link((src, "value"), (tgt, "value")) + + Setting source updates target objects: + >>> src.value = 5 + >>> tgt.value + 5 + """ + + updating = False + + def __init__(self, source, target, transform=None): + _validate_link(source, target) + self.source, self.target = source, target + self._transform, self._transform_inv = transform if transform else (lambda x: x,) * 2 + + self.link() + + def link(self): + try: + setattr( + self.target[0], + self.target[1], + self._transform(getattr(self.source[0], self.source[1])), + ) + + finally: + self.source[0].observe(self._update_target, names=self.source[1]) + self.target[0].observe(self._update_source, names=self.target[1]) + + @contextlib.contextmanager + def _busy_updating(self): + self.updating = True + try: + yield + finally: + self.updating = False + + def _update_target(self, change): + if self.updating: + return + with self._busy_updating(): + setattr(self.target[0], self.target[1], self._transform(change.new)) + if getattr(self.source[0], self.source[1]) != change.new: + raise TraitError( + "Broken link {}: the source value changed while updating " + "the target.".format(self) + ) + + def _update_source(self, change): + if self.updating: + return + with self._busy_updating(): + setattr(self.source[0], self.source[1], self._transform_inv(change.new)) + if getattr(self.target[0], self.target[1]) != change.new: + raise TraitError( + "Broken link {}: the target value changed while updating " + "the source.".format(self) + ) + + def unlink(self): + self.source[0].unobserve(self._update_target, names=self.source[1]) + self.target[0].unobserve(self._update_source, names=self.target[1]) + + +class directional_link: + """Link the trait of a source object with traits of target objects. + + Parameters + ---------- + source : (object, attribute name) pair + target : (object, attribute name) pair + transform: callable (optional) + Data transformation between source and target. + + Examples + -------- + >>> class X(HasTraits): + ... value = Int() + + >>> src = X(value=1) + >>> tgt = X(value=42) + >>> c = directional_link((src, "value"), (tgt, "value")) + + Setting source updates target objects: + >>> src.value = 5 + >>> tgt.value + 5 + + Setting target does not update source object: + >>> tgt.value = 6 + >>> src.value + 5 + + """ + + updating = False + + def __init__(self, source, target, transform=None): + self._transform = transform if transform else lambda x: x + _validate_link(source, target) + self.source, self.target = source, target + self.link() + + def link(self): + try: + setattr( + self.target[0], + self.target[1], + self._transform(getattr(self.source[0], self.source[1])), + ) + finally: + self.source[0].observe(self._update, names=self.source[1]) + + @contextlib.contextmanager + def _busy_updating(self): + self.updating = True + try: + yield + finally: + self.updating = False + + def _update(self, change): + if self.updating: + return + with self._busy_updating(): + setattr(self.target[0], self.target[1], self._transform(change.new)) + + def unlink(self): + self.source[0].unobserve(self._update, names=self.source[1]) + + +dlink = directional_link + + +# ----------------------------------------------------------------------------- +# Base Descriptor Class +# ----------------------------------------------------------------------------- + + +class BaseDescriptor: + """Base descriptor class + + Notes + ----- + This implements Python's descriptor protocol. + + This class is the base class for all such descriptors. The + only magic we use is a custom metaclass for the main :class:`HasTraits` + class that does the following: + + 1. Sets the :attr:`name` attribute of every :class:`BaseDescriptor` + instance in the class dict to the name of the attribute. + 2. Sets the :attr:`this_class` attribute of every :class:`BaseDescriptor` + instance in the class dict to the *class* that declared the trait. + This is used by the :class:`This` trait to allow subclasses to + accept superclasses for :class:`This` values. + """ + + name: t.Optional[str] = None + this_class: t.Optional[t.Type[t.Any]] = None + + def class_init(self, cls, name): + """Part of the initialization which may depend on the underlying + HasDescriptors class. + + It is typically overloaded for specific types. + + This method is called by :meth:`MetaHasDescriptors.__init__` + passing the class (`cls`) and `name` under which the descriptor + has been assigned. + """ + self.this_class = cls + self.name = name + + def subclass_init(self, cls): + # Instead of HasDescriptors.setup_instance calling + # every instance_init, we opt in by default. + # This gives descriptors a change to opt out for + # performance reasons. + # Because most traits do not need instance_init, + # and it will otherwise be called for every HasTrait instance + # beging created, this otherwise gives a significant performance + # pentalty. Most TypeTraits in traitlets opt out. + cls._instance_inits.append(self.instance_init) + + def instance_init(self, obj): + """Part of the initialization which may depend on the underlying + HasDescriptors instance. + + It is typically overloaded for specific types. + + This method is called by :meth:`HasTraits.__new__` and in the + :meth:`BaseDescriptor.instance_init` method of descriptors holding + other descriptors. + """ + pass + + +class TraitType(BaseDescriptor): + """A base class for all trait types.""" + + metadata: t.Dict[str, t.Any] = {} + allow_none = False + read_only = False + info_text = "any value" + default_value: t.Optional[t.Any] = Undefined + + def __init__( + self, + default_value=Undefined, + allow_none=False, + read_only=None, + help=None, + config=None, + **kwargs, + ): + """Declare a traitlet. + + If *allow_none* is True, None is a valid value in addition to any + values that are normally valid. The default is up to the subclass. + For most trait types, the default value for ``allow_none`` is False. + + If *read_only* is True, attempts to directly modify a trait attribute raises a TraitError. + + Extra metadata can be associated with the traitlet using the .tag() convenience method + or by using the traitlet instance's .metadata dictionary. + """ + if default_value is not Undefined: + self.default_value = default_value + if allow_none: + self.allow_none = allow_none + if read_only is not None: + self.read_only = read_only + self.help = help if help is not None else "" + + if len(kwargs) > 0: + stacklevel = 1 + f = inspect.currentframe() + # count supers to determine stacklevel for warning + assert f is not None + while f.f_code.co_name == "__init__": + stacklevel += 1 + f = f.f_back + assert f is not None + mod = f.f_globals.get("__name__") or "" + pkg = mod.split(".", 1)[0] + key = tuple(["metadata-tag", pkg] + sorted(kwargs)) + if _should_warn(key): + warn( + "metadata %s was set from the constructor. " + "With traitlets 4.1, metadata should be set using the .tag() method, " + "e.g., Int().tag(key1='value1', key2='value2')" % (kwargs,), + DeprecationWarning, + stacklevel=stacklevel, + ) + if len(self.metadata) > 0: + self.metadata = self.metadata.copy() + self.metadata.update(kwargs) + else: + self.metadata = kwargs + else: + self.metadata = self.metadata.copy() + if config is not None: + self.metadata["config"] = config + + # We add help to the metadata during a deprecation period so that + # code that looks for the help string there can find it. + if help is not None: + self.metadata["help"] = help + + def from_string(self, s): + """Get a value from a config string + + such as an environment variable or CLI arguments. + + Traits can override this method to define their own + parsing of config strings. + + .. seealso:: item_from_string + + .. versionadded:: 5.0 + """ + if self.allow_none and s == "None": + return None + return s + + def default(self, obj=None): + """The default generator for this trait + + Notes + ----- + This method is registered to HasTraits classes during ``class_init`` + in the same way that dynamic defaults defined by ``@default`` are. + """ + if self.default_value is not Undefined: + return self.default_value + elif hasattr(self, "make_dynamic_default"): + return self.make_dynamic_default() + else: + # Undefined will raise in TraitType.get + return self.default_value + + def get_default_value(self): + """DEPRECATED: Retrieve the static default value for this trait. + Use self.default_value instead + """ + warn( + "get_default_value is deprecated in traitlets 4.0: use the .default_value attribute", + DeprecationWarning, + stacklevel=2, + ) + return self.default_value + + def init_default_value(self, obj): + """DEPRECATED: Set the static default value for the trait type.""" + warn( + "init_default_value is deprecated in traitlets 4.0, and may be removed in the future", + DeprecationWarning, + stacklevel=2, + ) + value = self._validate(obj, self.default_value) + obj._trait_values[self.name] = value + return value + + def get(self, obj, cls=None): + try: + value = obj._trait_values[self.name] + except KeyError: + # Check for a dynamic initializer. + default = obj.trait_defaults(self.name) + if default is Undefined: + warn( + "Explicit using of Undefined as the default value " + "is deprecated in traitlets 5.0, and may cause " + "exceptions in the future.", + DeprecationWarning, + stacklevel=2, + ) + # Using a context manager has a large runtime overhead, so we + # write out the obj.cross_validation_lock call here. + _cross_validation_lock = obj._cross_validation_lock + try: + obj._cross_validation_lock = True + value = self._validate(obj, default) + finally: + obj._cross_validation_lock = _cross_validation_lock + obj._trait_values[self.name] = value + obj._notify_observers( + Bunch( + name=self.name, + value=value, + owner=obj, + type="default", + ) + ) + return value + except Exception as e: + # This should never be reached. + raise TraitError("Unexpected error in TraitType: default value not set properly") from e + else: + return value + + def __get__(self, obj, cls=None): + """Get the value of the trait by self.name for the instance. + + Default values are instantiated when :meth:`HasTraits.__new__` + is called. Thus by the time this method gets called either the + default value or a user defined value (they called :meth:`__set__`) + is in the :class:`HasTraits` instance. + """ + if obj is None: + return self + else: + return self.get(obj, cls) + + def set(self, obj, value): + new_value = self._validate(obj, value) + try: + old_value = obj._trait_values[self.name] + except KeyError: + old_value = self.default_value + + obj._trait_values[self.name] = new_value + try: + silent = bool(old_value == new_value) + except Exception: + # if there is an error in comparing, default to notify + silent = False + if silent is not True: + # we explicitly compare silent to True just in case the equality + # comparison above returns something other than True/False + obj._notify_trait(self.name, old_value, new_value) + + def __set__(self, obj, value): + """Set the value of the trait by self.name for the instance. + + Values pass through a validation stage where errors are raised when + impropper types, or types that cannot be coerced, are encountered. + """ + if self.read_only: + raise TraitError('The "%s" trait is read-only.' % self.name) + else: + self.set(obj, value) + + def _validate(self, obj, value): + if value is None and self.allow_none: + return value + if hasattr(self, "validate"): + value = self.validate(obj, value) + if obj._cross_validation_lock is False: + value = self._cross_validate(obj, value) + return value + + def _cross_validate(self, obj, value): + if self.name in obj._trait_validators: + proposal = Bunch({"trait": self, "value": value, "owner": obj}) + value = obj._trait_validators[self.name](obj, proposal) + elif hasattr(obj, "_%s_validate" % self.name): + meth_name = "_%s_validate" % self.name + cross_validate = getattr(obj, meth_name) + _deprecated_method( + cross_validate, + obj.__class__, + meth_name, + "use @validate decorator instead.", + ) + value = cross_validate(value, self) + return value + + def __or__(self, other): + if isinstance(other, Union): + return Union([self] + other.trait_types) + else: + return Union([self, other]) + + def info(self): + return self.info_text + + def error(self, obj, value, error=None, info=None): + """Raise a TraitError + + Parameters + ---------- + obj : HasTraits or None + The instance which owns the trait. If not + object is given, then an object agnostic + error will be raised. + value : any + The value that caused the error. + error : Exception (default: None) + An error that was raised by a child trait. + The arguments of this exception should be + of the form ``(value, info, *traits)``. + Where the ``value`` and ``info`` are the + problem value, and string describing the + expected value. The ``traits`` are a series + of :class:`TraitType` instances that are + "children" of this one (the first being + the deepest). + info : str (default: None) + A description of the expected value. By + default this is infered from this trait's + ``info`` method. + """ + if error is not None: + # handle nested error + error.args += (self,) + if self.name is not None: + # this is the root trait that must format the final message + chain = " of ".join(describe("a", t) for t in error.args[2:]) + if obj is not None: + error.args = ( + "The '%s' trait of %s instance contains %s which " + "expected %s, not %s." + % ( + self.name, + describe("an", obj), + chain, + error.args[1], + describe("the", error.args[0]), + ), + ) + else: + error.args = ( + "The '%s' trait contains %s which " + "expected %s, not %s." + % ( + self.name, + chain, + error.args[1], + describe("the", error.args[0]), + ), + ) + raise error + else: + # this trait caused an error + if self.name is None: + # this is not the root trait + raise TraitError(value, info or self.info(), self) + else: + # this is the root trait + if obj is not None: + e = "The '{}' trait of {} instance expected {}, not {}.".format( + self.name, + class_of(obj), + self.info(), + describe("the", value), + ) + else: + e = "The '{}' trait expected {}, not {}.".format( + self.name, + self.info(), + describe("the", value), + ) + raise TraitError(e) + + def get_metadata(self, key, default=None): + """DEPRECATED: Get a metadata value. + + Use .metadata[key] or .metadata.get(key, default) instead. + """ + if key == "help": + msg = "use the instance .help string directly, like x.help" + else: + msg = "use the instance .metadata dictionary directly, like x.metadata[key] or x.metadata.get(key, default)" + warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2) + return self.metadata.get(key, default) + + def set_metadata(self, key, value): + """DEPRECATED: Set a metadata key/value. + + Use .metadata[key] = value instead. + """ + if key == "help": + msg = "use the instance .help string directly, like x.help = value" + else: + msg = "use the instance .metadata dictionary directly, like x.metadata[key] = value" + warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2) + self.metadata[key] = value + + def tag(self, **metadata): + """Sets metadata and returns self. + + This allows convenient metadata tagging when initializing the trait, such as: + + Examples + -------- + >>> Int(0).tag(config=True, sync=True) + + + """ + maybe_constructor_keywords = set(metadata.keys()).intersection( + {"help", "allow_none", "read_only", "default_value"} + ) + if maybe_constructor_keywords: + warn( + "The following attributes are set in using `tag`, but seem to be constructor keywords arguments: %s " + % maybe_constructor_keywords, + UserWarning, + stacklevel=2, + ) + + self.metadata.update(metadata) + return self + + def default_value_repr(self): + return repr(self.default_value) + + +# ----------------------------------------------------------------------------- +# The HasTraits implementation +# ----------------------------------------------------------------------------- + + +class _CallbackWrapper: + """An object adapting a on_trait_change callback into an observe callback. + + The comparison operator __eq__ is implemented to enable removal of wrapped + callbacks. + """ + + def __init__(self, cb): + self.cb = cb + # Bound methods have an additional 'self' argument. + offset = -1 if isinstance(self.cb, types.MethodType) else 0 + self.nargs = len(getargspec(cb)[0]) + offset + if self.nargs > 4: + raise TraitError("a trait changed callback must have 0-4 arguments.") + + def __eq__(self, other): + # The wrapper is equal to the wrapped element + if isinstance(other, _CallbackWrapper): + return self.cb == other.cb + else: + return self.cb == other + + def __call__(self, change): + # The wrapper is callable + if self.nargs == 0: + self.cb() + elif self.nargs == 1: + self.cb(change.name) + elif self.nargs == 2: + self.cb(change.name, change.new) + elif self.nargs == 3: + self.cb(change.name, change.old, change.new) + elif self.nargs == 4: + self.cb(change.name, change.old, change.new, change.owner) + + +def _callback_wrapper(cb): + if isinstance(cb, _CallbackWrapper): + return cb + else: + return _CallbackWrapper(cb) + + +class MetaHasDescriptors(type): + """A metaclass for HasDescriptors. + + This metaclass makes sure that any TraitType class attributes are + instantiated and sets their name attribute. + """ + + def __new__(mcls, name, bases, classdict): # noqa + """Create the HasDescriptors class.""" + for k, v in classdict.items(): + # ---------------------------------------------------------------- + # Support of deprecated behavior allowing for TraitType types + # to be used instead of TraitType instances. + if inspect.isclass(v) and issubclass(v, TraitType): + warn( + "Traits should be given as instances, not types (for example, `Int()`, not `Int`)." + " Passing types is deprecated in traitlets 4.1.", + DeprecationWarning, + stacklevel=2, + ) + classdict[k] = v() + # ---------------------------------------------------------------- + + return super().__new__(mcls, name, bases, classdict) + + def __init__(cls, name, bases, classdict): + """Finish initializing the HasDescriptors class.""" + super().__init__(name, bases, classdict) + cls.setup_class(classdict) + + def setup_class(cls, classdict): + """Setup descriptor instance on the class + + This sets the :attr:`this_class` and :attr:`name` attributes of each + BaseDescriptor in the class dict of the newly created ``cls`` before + calling their :attr:`class_init` method. + """ + cls._descriptors = [] + cls._instance_inits = [] + for k, v in classdict.items(): + if isinstance(v, BaseDescriptor): + v.class_init(cls, k) + + for _, v in getmembers(cls): + if isinstance(v, BaseDescriptor): + v.subclass_init(cls) + cls._descriptors.append(v) + + +class MetaHasTraits(MetaHasDescriptors): + """A metaclass for HasTraits.""" + + def setup_class(cls, classdict): # noqa + # for only the current class + cls._trait_default_generators = {} + # also looking at base classes + cls._all_trait_default_generators = {} + cls._traits = {} + cls._static_immutable_initial_values = {} + + super().setup_class(classdict) + + mro = cls.mro() + + for name in dir(cls): + # Some descriptors raise AttributeError like zope.interface's + # __provides__ attributes even though they exist. This causes + # AttributeErrors even though they are listed in dir(cls). + try: + value = getattr(cls, name) + except AttributeError: + continue + if isinstance(value, TraitType): + cls._traits[name] = value + trait = value + default_method_name = "_%s_default" % name + try: + mro_trait = mro[: mro.index(trait.this_class) + 1] # type:ignore[arg-type] + except ValueError: + # this_class not in mro + pass + for c in mro_trait: + if default_method_name in c.__dict__: + cls._all_trait_default_generators[name] = c.__dict__[default_method_name] + break + if name in c.__dict__.get("_trait_default_generators", {}): + cls._all_trait_default_generators[name] = c._trait_default_generators[name] # type: ignore[attr-defined] + break + else: + # We don't have a dynamic default generator using @default etc. + # Now if the default value is not dynamic and immutable (string, number) + # and does not require any validation, we keep them in a dict + # of initial values to speed up instance creation. + # This is a very specific optimization, but a very common scenario in + # for instance ipywidgets. + none_ok = trait.default_value is None and trait.allow_none + if ( + type(trait) in [CInt, Int] + and trait.min is None # type: ignore[attr-defined] + and trait.max is None # type: ignore[attr-defined] + and (isinstance(trait.default_value, int) or none_ok) + ): + cls._static_immutable_initial_values[name] = trait.default_value + elif ( + type(trait) in [CFloat, Float] + and trait.min is None # type: ignore[attr-defined] + and trait.max is None # type: ignore[attr-defined] + and (isinstance(trait.default_value, float) or none_ok) + ): + cls._static_immutable_initial_values[name] = trait.default_value + elif type(trait) in [CBool, Bool] and ( + isinstance(trait.default_value, bool) or none_ok + ): + cls._static_immutable_initial_values[name] = trait.default_value + elif type(trait) in [CUnicode, Unicode] and ( + isinstance(trait.default_value, str) or none_ok + ): + cls._static_immutable_initial_values[name] = trait.default_value + elif type(trait) == Any and ( + isinstance(trait.default_value, (str, int, float, bool)) or none_ok + ): + cls._static_immutable_initial_values[name] = trait.default_value + elif type(trait) == Union and trait.default_value is None: + cls._static_immutable_initial_values[name] = None + elif ( + isinstance(trait, Instance) + and trait.default_args is None + and trait.default_kwargs is None + and trait.allow_none + ): + cls._static_immutable_initial_values[name] = None + + # we always add it, because a class may change when we call add_trait + # and then the instance may not have all the _static_immutable_initial_values + cls._all_trait_default_generators[name] = trait.default + + +def observe(*names: t.Union[Sentinel, str], type: str = "change") -> "ObserveHandler": + """A decorator which can be used to observe Traits on a class. + + The handler passed to the decorator will be called with one ``change`` + dict argument. The change dictionary at least holds a 'type' key and a + 'name' key, corresponding respectively to the type of notification and the + name of the attribute that triggered the notification. + + Other keys may be passed depending on the value of 'type'. In the case + where type is 'change', we also have the following keys: + * ``owner`` : the HasTraits instance + * ``old`` : the old value of the modified trait attribute + * ``new`` : the new value of the modified trait attribute + * ``name`` : the name of the modified trait attribute. + + Parameters + ---------- + *names + The str names of the Traits to observe on the object. + type : str, kwarg-only + The type of event to observe (e.g. 'change') + """ + if not names: + raise TypeError("Please specify at least one trait name to observe.") + for name in names: + if name is not All and not isinstance(name, str): + raise TypeError("trait names to observe must be strings or All, not %r" % name) + return ObserveHandler(names, type=type) + + +def observe_compat(func): + """Backward-compatibility shim decorator for observers + + Use with: + + @observe('name') + @observe_compat + def _foo_changed(self, change): + ... + + With this, `super()._foo_changed(self, name, old, new)` in subclasses will still work. + Allows adoption of new observer API without breaking subclasses that override and super. + """ + + def compatible_observer(self, change_or_name, old=Undefined, new=Undefined): + if isinstance(change_or_name, dict): + change = change_or_name + else: + clsname = self.__class__.__name__ + warn( + "A parent of %s._%s_changed has adopted the new (traitlets 4.1) @observe(change) API" + % (clsname, change_or_name), + DeprecationWarning, + ) + change = Bunch( + type="change", + old=old, + new=new, + name=change_or_name, + owner=self, + ) + return func(self, change) + + return compatible_observer + + +def validate(*names: t.Union[Sentinel, str]) -> "ValidateHandler": + """A decorator to register cross validator of HasTraits object's state + when a Trait is set. + + The handler passed to the decorator must have one ``proposal`` dict argument. + The proposal dictionary must hold the following keys: + + * ``owner`` : the HasTraits instance + * ``value`` : the proposed value for the modified trait attribute + * ``trait`` : the TraitType instance associated with the attribute + + Parameters + ---------- + *names + The str names of the Traits to validate. + + Notes + ----- + Since the owner has access to the ``HasTraits`` instance via the 'owner' key, + the registered cross validator could potentially make changes to attributes + of the ``HasTraits`` instance. However, we recommend not to do so. The reason + is that the cross-validation of attributes may run in arbitrary order when + exiting the ``hold_trait_notifications`` context, and such changes may not + commute. + """ + if not names: + raise TypeError("Please specify at least one trait name to validate.") + for name in names: + if name is not All and not isinstance(name, str): + raise TypeError("trait names to validate must be strings or All, not %r" % name) + return ValidateHandler(names) + + +def default(name: str) -> "DefaultHandler": + """A decorator which assigns a dynamic default for a Trait on a HasTraits object. + + Parameters + ---------- + name + The str name of the Trait on the object whose default should be generated. + + Notes + ----- + Unlike observers and validators which are properties of the HasTraits + instance, default value generators are class-level properties. + + Besides, default generators are only invoked if they are registered in + subclasses of `this_type`. + + :: + + class A(HasTraits): + bar = Int() + + @default('bar') + def get_bar_default(self): + return 11 + + class B(A): + bar = Float() # This trait ignores the default generator defined in + # the base class A + + class C(B): + + @default('bar') + def some_other_default(self): # This default generator should not be + return 3.0 # ignored since it is defined in a + # class derived from B.a.this_class. + """ + if not isinstance(name, str): + raise TypeError("Trait name must be a string or All, not %r" % name) + return DefaultHandler(name) + + +class EventHandler(BaseDescriptor): + def _init_call(self, func): + self.func = func + return self + + def __call__(self, *args, **kwargs): + """Pass `*args` and `**kwargs` to the handler's function if it exists.""" + if hasattr(self, "func"): + return self.func(*args, **kwargs) + else: + return self._init_call(*args, **kwargs) + + def __get__(self, inst, cls=None): + if inst is None: + return self + return types.MethodType(self.func, inst) + + +class ObserveHandler(EventHandler): + def __init__(self, names, type): + self.trait_names = names + self.type = type + + def instance_init(self, inst): + inst.observe(self, self.trait_names, type=self.type) + + +class ValidateHandler(EventHandler): + def __init__(self, names): + self.trait_names = names + + def instance_init(self, inst): + inst._register_validator(self, self.trait_names) + + +class DefaultHandler(EventHandler): + def __init__(self, name): + self.trait_name = name + + def class_init(self, cls, name): + super().class_init(cls, name) + cls._trait_default_generators[self.trait_name] = self + + +class HasDescriptors(metaclass=MetaHasDescriptors): + """The base class for all classes that have descriptors.""" + + def __new__(*args: t.Any, **kwargs: t.Any) -> t.Any: + # Pass cls as args[0] to allow "cls" as keyword argument + cls = args[0] + args = args[1:] + + # This is needed because object.__new__ only accepts + # the cls argument. + new_meth = super(HasDescriptors, cls).__new__ + if new_meth is object.__new__: + inst = new_meth(cls) + else: + inst = new_meth(cls, *args, **kwargs) + inst.setup_instance(*args, **kwargs) + return inst + + def setup_instance(*args, **kwargs): + """ + This is called **before** self.__init__ is called. + """ + # Pass self as args[0] to allow "self" as keyword argument + self = args[0] + args = args[1:] + + self._cross_validation_lock = False # type:ignore[attr-defined] + cls = self.__class__ + # Let descriptors performance initialization when a HasDescriptor + # instance is created. This allows registration of observers and + # default creations or other bookkeepings. + # Note that descriptors can opt-out of this behavior by overriding + # subclass_init. + for init in cls._instance_inits: + init(self) + + +class HasTraits(HasDescriptors, metaclass=MetaHasTraits): + _trait_values: t.Dict[str, t.Any] + _static_immutable_initial_values: t.Dict[str, t.Any] + _trait_notifiers: t.Dict[str, t.Any] + _trait_validators: t.Dict[str, t.Any] + _cross_validation_lock: bool + _traits: t.Dict[str, t.Any] + _all_trait_default_generators: t.Dict[str, t.Any] + + def setup_instance(*args, **kwargs): + # Pass self as args[0] to allow "self" as keyword argument + self = args[0] + args = args[1:] + + # although we'd prefer to set only the initial values not present + # in kwargs, we will overwrite them in `__init__`, and simply making + # a copy of a dict is faster than checking for each key. + self._trait_values = self._static_immutable_initial_values.copy() + self._trait_notifiers = {} + self._trait_validators = {} + self._cross_validation_lock = False + super(HasTraits, self).setup_instance(*args, **kwargs) + + def __init__(self, *args, **kwargs): + # Allow trait values to be set using keyword arguments. + # We need to use setattr for this to trigger validation and + # notifications. + super_args = args + super_kwargs = {} + + if kwargs: + # this is a simplified (and faster) version of + # the hold_trait_notifications(self) context manager + def ignore(*_ignore_args): + pass + + self.notify_change = ignore # type:ignore[assignment] + self._cross_validation_lock = True + changes = {} + for key, value in kwargs.items(): + if self.has_trait(key): + setattr(self, key, value) + changes[key] = Bunch( + name=key, + old=None, + new=value, + owner=self, + type="change", + ) + else: + # passthrough args that don't set traits to super + super_kwargs[key] = value + # notify and cross validate all trait changes that were set in kwargs + changed = set(kwargs) & set(self._traits) + for key in changed: + value = self._traits[key]._cross_validate(self, getattr(self, key)) + self.set_trait(key, value) + changes[key]['new'] = value + self._cross_validation_lock = False + # Restore method retrieval from class + del self.notify_change + for key in changed: + self.notify_change(changes[key]) + + try: + super().__init__(*super_args, **super_kwargs) + except TypeError as e: + arg_s_list = [repr(arg) for arg in super_args] + for k, v in super_kwargs.items(): + arg_s_list.append(f"{k}={v!r}") + arg_s = ", ".join(arg_s_list) + warn( + "Passing unrecognized arguments to super({classname}).__init__({arg_s}).\n" + "{error}\n" + "This is deprecated in traitlets 4.2." + "This error will be raised in a future release of traitlets.".format( + arg_s=arg_s, + classname=self.__class__.__name__, + error=e, + ), + DeprecationWarning, + stacklevel=2, + ) + + def __getstate__(self): + d = self.__dict__.copy() + # event handlers stored on an instance are + # expected to be reinstantiated during a + # recall of instance_init during __setstate__ + d["_trait_notifiers"] = {} + d["_trait_validators"] = {} + d["_trait_values"] = self._trait_values.copy() + d["_cross_validation_lock"] = False # FIXME: raise if cloning locked! + + return d + + def __setstate__(self, state): + self.__dict__ = state.copy() + + # event handlers are reassigned to self + cls = self.__class__ + for key in dir(cls): + # Some descriptors raise AttributeError like zope.interface's + # __provides__ attributes even though they exist. This causes + # AttributeErrors even though they are listed in dir(cls). + try: + value = getattr(cls, key) + except AttributeError: + pass + else: + if isinstance(value, EventHandler): + value.instance_init(self) + + @property + @contextlib.contextmanager + def cross_validation_lock(self): + """ + A contextmanager for running a block with our cross validation lock set + to True. + + At the end of the block, the lock's value is restored to its value + prior to entering the block. + """ + if self._cross_validation_lock: + yield + return + else: + try: + self._cross_validation_lock = True + yield + finally: + self._cross_validation_lock = False + + @contextlib.contextmanager + def hold_trait_notifications(self): + """Context manager for bundling trait change notifications and cross + validation. + + Use this when doing multiple trait assignments (init, config), to avoid + race conditions in trait notifiers requesting other trait values. + All trait notifications will fire after all values have been assigned. + """ + if self._cross_validation_lock: + yield + return + else: + cache: t.Dict[str, t.Any] = {} + + def compress(past_changes, change): + """Merges the provided change with the last if possible.""" + if past_changes is None: + return [change] + else: + if past_changes[-1]["type"] == "change" and change.type == "change": + past_changes[-1]["new"] = change.new + else: + # In case of changes other than 'change', append the notification. + past_changes.append(change) + return past_changes + + def hold(change): + name = change.name + cache[name] = compress(cache.get(name), change) + + try: + # Replace notify_change with `hold`, caching and compressing + # notifications, disable cross validation and yield. + self.notify_change = hold # type:ignore[assignment] + self._cross_validation_lock = True + yield + # Cross validate final values when context is released. + for name in list(cache.keys()): + trait = getattr(self.__class__, name) + value = trait._cross_validate(self, getattr(self, name)) + self.set_trait(name, value) + except TraitError as e: + # Roll back in case of TraitError during final cross validation. + self.notify_change = lambda x: None # type:ignore[assignment] + for name, changes in cache.items(): + for change in changes[::-1]: + # TODO: Separate in a rollback function per notification type. + if change.type == "change": + if change.old is not Undefined: + self.set_trait(name, change.old) + else: + self._trait_values.pop(name) + cache = {} + raise e + finally: + self._cross_validation_lock = False + # Restore method retrieval from class + del self.notify_change + + # trigger delayed notifications + for changes in cache.values(): + for change in changes: + self.notify_change(change) + + def _notify_trait(self, name, old_value, new_value): + self.notify_change( + Bunch( + name=name, + old=old_value, + new=new_value, + owner=self, + type="change", + ) + ) + + def notify_change(self, change): + """Notify observers of a change event""" + return self._notify_observers(change) + + def _notify_observers(self, event): + """Notify observers of any event""" + if not isinstance(event, Bunch): + # cast to bunch if given a dict + event = Bunch(event) + name, type = event['name'], event['type'] + + callables = [] + if name in self._trait_notifiers: + callables.extend(self._trait_notifiers.get(name, {}).get(type, [])) + callables.extend(self._trait_notifiers.get(name, {}).get(All, [])) + if All in self._trait_notifiers: # type:ignore[comparison-overlap] + callables.extend( + self._trait_notifiers.get(All, {}).get(type, []) # type:ignore[call-overload] + ) + callables.extend( + self._trait_notifiers.get(All, {}).get(All, []) # type:ignore[call-overload] + ) + + # Now static ones + magic_name = "_%s_changed" % name + if event['type'] == "change" and hasattr(self, magic_name): + class_value = getattr(self.__class__, magic_name) + if not isinstance(class_value, ObserveHandler): + _deprecated_method( + class_value, + self.__class__, + magic_name, + "use @observe and @unobserve instead.", + ) + cb = getattr(self, magic_name) + # Only append the magic method if it was not manually registered + if cb not in callables: + callables.append(_callback_wrapper(cb)) + + # Call them all now + # Traits catches and logs errors here. I allow them to raise + for c in callables: + # Bound methods have an additional 'self' argument. + + if isinstance(c, _CallbackWrapper): + c = c.__call__ + elif isinstance(c, EventHandler) and c.name is not None: + c = getattr(self, c.name) + + c(event) + + def _add_notifiers(self, handler, name, type): + if name not in self._trait_notifiers: + nlist: t.List[t.Any] = [] + self._trait_notifiers[name] = {type: nlist} + else: + if type not in self._trait_notifiers[name]: + nlist = [] + self._trait_notifiers[name][type] = nlist + else: + nlist = self._trait_notifiers[name][type] + if handler not in nlist: + nlist.append(handler) + + def _remove_notifiers(self, handler, name, type): + try: + if handler is None: + del self._trait_notifiers[name][type] + else: + self._trait_notifiers[name][type].remove(handler) + except KeyError: + pass + + def on_trait_change(self, handler=None, name=None, remove=False): + """DEPRECATED: Setup a handler to be called when a trait changes. + + This is used to setup dynamic notifications of trait changes. + + Static handlers can be created by creating methods on a HasTraits + subclass with the naming convention '_[traitname]_changed'. Thus, + to create static handler for the trait 'a', create the method + _a_changed(self, name, old, new) (fewer arguments can be used, see + below). + + If `remove` is True and `handler` is not specified, all change + handlers for the specified name are uninstalled. + + Parameters + ---------- + handler : callable, None + A callable that is called when a trait changes. Its + signature can be handler(), handler(name), handler(name, new), + handler(name, old, new), or handler(name, old, new, self). + name : list, str, None + If None, the handler will apply to all traits. If a list + of str, handler will apply to all names in the list. If a + str, the handler will apply just to that name. + remove : bool + If False (the default), then install the handler. If True + then unintall it. + """ + warn( + "on_trait_change is deprecated in traitlets 4.1: use observe instead", + DeprecationWarning, + stacklevel=2, + ) + if name is None: + name = All + if remove: + self.unobserve(_callback_wrapper(handler), names=name) + else: + self.observe(_callback_wrapper(handler), names=name) + + def observe(self, handler, names=All, type="change"): + """Setup a handler to be called when a trait changes. + + This is used to setup dynamic notifications of trait changes. + + Parameters + ---------- + handler : callable + A callable that is called when a trait changes. Its + signature should be ``handler(change)``, where ``change`` is a + dictionary. The change dictionary at least holds a 'type' key. + * ``type``: the type of notification. + Other keys may be passed depending on the value of 'type'. In the + case where type is 'change', we also have the following keys: + * ``owner`` : the HasTraits instance + * ``old`` : the old value of the modified trait attribute + * ``new`` : the new value of the modified trait attribute + * ``name`` : the name of the modified trait attribute. + names : list, str, All + If names is All, the handler will apply to all traits. If a list + of str, handler will apply to all names in the list. If a + str, the handler will apply just to that name. + type : str, All (default: 'change') + The type of notification to filter by. If equal to All, then all + notifications are passed to the observe handler. + """ + names = parse_notifier_name(names) + for n in names: + self._add_notifiers(handler, n, type) + + def unobserve(self, handler, names=All, type="change"): + """Remove a trait change handler. + + This is used to unregister handlers to trait change notifications. + + Parameters + ---------- + handler : callable + The callable called when a trait attribute changes. + names : list, str, All (default: All) + The names of the traits for which the specified handler should be + uninstalled. If names is All, the specified handler is uninstalled + from the list of notifiers corresponding to all changes. + type : str or All (default: 'change') + The type of notification to filter by. If All, the specified handler + is uninstalled from the list of notifiers corresponding to all types. + """ + names = parse_notifier_name(names) + for n in names: + self._remove_notifiers(handler, n, type) + + def unobserve_all(self, name=All): + """Remove trait change handlers of any type for the specified name. + If name is not specified, removes all trait notifiers.""" + if name is All: + self._trait_notifiers: t.Dict[str, t.Any] = {} + else: + try: + del self._trait_notifiers[name] + except KeyError: + pass + + def _register_validator(self, handler, names): + """Setup a handler to be called when a trait should be cross validated. + + This is used to setup dynamic notifications for cross-validation. + + If a validator is already registered for any of the provided names, a + TraitError is raised and no new validator is registered. + + Parameters + ---------- + handler : callable + A callable that is called when the given trait is cross-validated. + Its signature is handler(proposal), where proposal is a Bunch (dictionary with attribute access) + with the following attributes/keys: + * ``owner`` : the HasTraits instance + * ``value`` : the proposed value for the modified trait attribute + * ``trait`` : the TraitType instance associated with the attribute + names : List of strings + The names of the traits that should be cross-validated + """ + for name in names: + magic_name = "_%s_validate" % name + if hasattr(self, magic_name): + class_value = getattr(self.__class__, magic_name) + if not isinstance(class_value, ValidateHandler): + _deprecated_method( + class_value, + self.__class__, + magic_name, + "use @validate decorator instead.", + ) + for name in names: + self._trait_validators[name] = handler + + def add_traits(self, **traits): + """Dynamically add trait attributes to the HasTraits instance.""" + cls = self.__class__ + attrs = {"__module__": cls.__module__} + if hasattr(cls, "__qualname__"): + # __qualname__ introduced in Python 3.3 (see PEP 3155) + attrs["__qualname__"] = cls.__qualname__ + attrs.update(traits) + self.__class__ = type(cls.__name__, (cls,), attrs) + for trait in traits.values(): + trait.instance_init(self) + + def set_trait(self, name, value): + """Forcibly sets trait attribute, including read-only attributes.""" + cls = self.__class__ + if not self.has_trait(name): + raise TraitError(f"Class {cls.__name__} does not have a trait named {name}") + else: + getattr(cls, name).set(self, value) + + @classmethod + def class_trait_names(cls, **metadata): + """Get a list of all the names of this class' traits. + + This method is just like the :meth:`trait_names` method, + but is unbound. + """ + return list(cls.class_traits(**metadata)) + + @classmethod + def class_traits(cls, **metadata): + """Get a ``dict`` of all the traits of this class. The dictionary + is keyed on the name and the values are the TraitType objects. + + This method is just like the :meth:`traits` method, but is unbound. + + The TraitTypes returned don't know anything about the values + that the various HasTrait's instances are holding. + + The metadata kwargs allow functions to be passed in which + filter traits based on metadata values. The functions should + take a single value as an argument and return a boolean. If + any function returns False, then the trait is not included in + the output. If a metadata key doesn't exist, None will be passed + to the function. + """ + traits = cls._traits.copy() + + if len(metadata) == 0: + return traits + + result = {} + for name, trait in traits.items(): + for meta_name, meta_eval in metadata.items(): + if not callable(meta_eval): + meta_eval = _SimpleTest(meta_eval) + if not meta_eval(trait.metadata.get(meta_name, None)): + break + else: + result[name] = trait + + return result + + @classmethod + def class_own_traits(cls, **metadata): + """Get a dict of all the traitlets defined on this class, not a parent. + + Works like `class_traits`, except for excluding traits from parents. + """ + sup = super(cls, cls) + return { + n: t + for (n, t) in cls.class_traits(**metadata).items() + if getattr(sup, n, None) is not t + } + + def has_trait(self, name): + """Returns True if the object has a trait with the specified name.""" + return name in self._traits + + def trait_has_value(self, name): + """Returns True if the specified trait has a value. + + This will return false even if ``getattr`` would return a + dynamically generated default value. These default values + will be recognized as existing only after they have been + generated. + + Example + + .. code-block:: python + + class MyClass(HasTraits): + i = Int() + + mc = MyClass() + assert not mc.trait_has_value("i") + mc.i # generates a default value + assert mc.trait_has_value("i") + """ + return name in self._trait_values + + def trait_values(self, **metadata): + """A ``dict`` of trait names and their values. + + The metadata kwargs allow functions to be passed in which + filter traits based on metadata values. The functions should + take a single value as an argument and return a boolean. If + any function returns False, then the trait is not included in + the output. If a metadata key doesn't exist, None will be passed + to the function. + + Returns + ------- + A ``dict`` of trait names and their values. + + Notes + ----- + Trait values are retrieved via ``getattr``, any exceptions raised + by traits or the operations they may trigger will result in the + absence of a trait value in the result ``dict``. + """ + return {name: getattr(self, name) for name in self.trait_names(**metadata)} + + def _get_trait_default_generator(self, name): + """Return default generator for a given trait + + Walk the MRO to resolve the correct default generator according to inheritance. + """ + method_name = "_%s_default" % name + if method_name in self.__dict__: + return getattr(self, method_name) + if method_name in self.__class__.__dict__: + return getattr(self.__class__, method_name) + return self._all_trait_default_generators[name] + + def trait_defaults(self, *names, **metadata): + """Return a trait's default value or a dictionary of them + + Notes + ----- + Dynamically generated default values may + depend on the current state of the object.""" + for n in names: + if not self.has_trait(n): + raise TraitError(f"'{n}' is not a trait of '{type(self).__name__}' instances") + + if len(names) == 1 and len(metadata) == 0: + return self._get_trait_default_generator(names[0])(self) + + trait_names = self.trait_names(**metadata) + trait_names.extend(names) + + defaults = {} + for n in trait_names: + defaults[n] = self._get_trait_default_generator(n)(self) + return defaults + + def trait_names(self, **metadata): + """Get a list of all the names of this class' traits.""" + return list(self.traits(**metadata)) + + def traits(self, **metadata): + """Get a ``dict`` of all the traits of this class. The dictionary + is keyed on the name and the values are the TraitType objects. + + The TraitTypes returned don't know anything about the values + that the various HasTrait's instances are holding. + + The metadata kwargs allow functions to be passed in which + filter traits based on metadata values. The functions should + take a single value as an argument and return a boolean. If + any function returns False, then the trait is not included in + the output. If a metadata key doesn't exist, None will be passed + to the function. + """ + traits = self._traits.copy() + + if len(metadata) == 0: + return traits + + result = {} + for name, trait in traits.items(): + for meta_name, meta_eval in metadata.items(): + if not callable(meta_eval): + meta_eval = _SimpleTest(meta_eval) + if not meta_eval(trait.metadata.get(meta_name, None)): + break + else: + result[name] = trait + + return result + + def trait_metadata(self, traitname, key, default=None): + """Get metadata values for trait by key.""" + try: + trait = getattr(self.__class__, traitname) + except AttributeError as e: + raise TraitError( + f"Class {self.__class__.__name__} does not have a trait named {traitname}" + ) from e + metadata_name = "_" + traitname + "_metadata" + if hasattr(self, metadata_name) and key in getattr(self, metadata_name): + return getattr(self, metadata_name).get(key, default) + else: + return trait.metadata.get(key, default) + + @classmethod + def class_own_trait_events(cls, name): + """Get a dict of all event handlers defined on this class, not a parent. + + Works like ``event_handlers``, except for excluding traits from parents. + """ + sup = super(cls, cls) + return { + n: e + for (n, e) in cls.events(name).items() # type:ignore[attr-defined] + if getattr(sup, n, None) is not e + } + + @classmethod + def trait_events(cls, name=None): + """Get a ``dict`` of all the event handlers of this class. + + Parameters + ---------- + name : str (default: None) + The name of a trait of this class. If name is ``None`` then all + the event handlers of this class will be returned instead. + + Returns + ------- + The event handlers associated with a trait name, or all event handlers. + """ + events = {} + for k, v in getmembers(cls): + if isinstance(v, EventHandler): + if name is None: + events[k] = v + elif name in v.trait_names: # type:ignore[attr-defined] + events[k] = v + elif hasattr(v, "tags"): + if cls.trait_names(**v.tags): + events[k] = v + return events + + +# ----------------------------------------------------------------------------- +# Actual TraitTypes implementations/subclasses +# ----------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------- +# TraitTypes subclasses for handling classes and instances of classes +# ----------------------------------------------------------------------------- + + +class ClassBasedTraitType(TraitType): + """ + A trait with error reporting and string -> type resolution for Type, + Instance and This. + """ + + def _resolve_string(self, string): + """ + Resolve a string supplied for a type into an actual object. + """ + return import_item(string) + + +class Type(ClassBasedTraitType): + """A trait whose value must be a subclass of a specified class.""" + + def __init__(self, default_value=Undefined, klass=None, **kwargs): + """Construct a Type trait + + A Type trait specifies that its values must be subclasses of + a particular class. + + If only ``default_value`` is given, it is used for the ``klass`` as + well. If neither are given, both default to ``object``. + + Parameters + ---------- + default_value : class, str or None + The default value must be a subclass of klass. If an str, + the str must be a fully specified class name, like 'foo.bar.Bah'. + The string is resolved into real class, when the parent + :class:`HasTraits` class is instantiated. + klass : class, str [ default object ] + Values of this trait must be a subclass of klass. The klass + may be specified in a string like: 'foo.bar.MyClass'. + The string is resolved into real class, when the parent + :class:`HasTraits` class is instantiated. + allow_none : bool [ default False ] + Indicates whether None is allowed as an assignable value. + **kwargs + extra kwargs passed to `ClassBasedTraitType` + """ + if default_value is Undefined: + new_default_value = object if (klass is None) else klass + else: + new_default_value = default_value + + if klass is None: + if (default_value is None) or (default_value is Undefined): + klass = object + else: + klass = default_value + + if not (inspect.isclass(klass) or isinstance(klass, str)): + raise TraitError("A Type trait must specify a class.") + + self.klass = klass + + super().__init__(new_default_value, **kwargs) + + def validate(self, obj, value): + """Validates that the value is a valid object instance.""" + if isinstance(value, str): + try: + value = self._resolve_string(value) + except ImportError as e: + raise TraitError( + "The '%s' trait of %s instance must be a type, but " + "%r could not be imported" % (self.name, obj, value) + ) from e + try: + if issubclass(value, self.klass): # type:ignore[arg-type] + return value + except Exception: + pass + + self.error(obj, value) + + def info(self): + """Returns a description of the trait.""" + if isinstance(self.klass, str): + klass = self.klass + else: + klass = self.klass.__module__ + "." + self.klass.__name__ + result = "a subclass of '%s'" % klass + if self.allow_none: + return result + " or None" + return result + + def instance_init(self, obj): + # we can't do this in subclass_init because that + # might be called before all imports are done. + self._resolve_classes() + + def _resolve_classes(self): + if isinstance(self.klass, str): + self.klass = self._resolve_string(self.klass) + if isinstance(self.default_value, str): + self.default_value = self._resolve_string(self.default_value) + + def default_value_repr(self): + value = self.default_value + assert value is not None + if isinstance(value, str): + return repr(value) + else: + return repr(f"{value.__module__}.{value.__name__}") + + +class Instance(ClassBasedTraitType): + """A trait whose value must be an instance of a specified class. + + The value can also be an instance of a subclass of the specified class. + + Subclasses can declare default classes by overriding the klass attribute + """ + + klass = None + + def __init__(self, klass=None, args=None, kw=None, **kwargs): + """Construct an Instance trait. + + This trait allows values that are instances of a particular + class or its subclasses. Our implementation is quite different + from that of enthough.traits as we don't allow instances to be used + for klass and we handle the ``args`` and ``kw`` arguments differently. + + Parameters + ---------- + klass : class, str + The class that forms the basis for the trait. Class names + can also be specified as strings, like 'foo.bar.Bar'. + args : tuple + Positional arguments for generating the default value. + kw : dict + Keyword arguments for generating the default value. + allow_none : bool [ default False ] + Indicates whether None is allowed as a value. + **kwargs + Extra kwargs passed to `ClassBasedTraitType` + + Notes + ----- + If both ``args`` and ``kw`` are None, then the default value is None. + If ``args`` is a tuple and ``kw`` is a dict, then the default is + created as ``klass(*args, **kw)``. If exactly one of ``args`` or ``kw`` is + None, the None is replaced by ``()`` or ``{}``, respectively. + """ + if klass is None: + klass = self.klass + + if (klass is not None) and (inspect.isclass(klass) or isinstance(klass, str)): + self.klass = klass + else: + raise TraitError("The klass attribute must be a class not: %r" % klass) + + if (kw is not None) and not isinstance(kw, dict): + raise TraitError("The 'kw' argument must be a dict or None.") + if (args is not None) and not isinstance(args, tuple): + raise TraitError("The 'args' argument must be a tuple or None.") + + self.default_args = args + self.default_kwargs = kw + + super().__init__(**kwargs) + + def validate(self, obj, value): + assert self.klass is not None + if isinstance(value, self.klass): # type:ignore[arg-type] + return value + else: + self.error(obj, value) + + def info(self): + if isinstance(self.klass, str): + result = add_article(self.klass) + else: + result = describe("a", self.klass) + if self.allow_none: + result += " or None" + return result + + def instance_init(self, obj): + # we can't do this in subclass_init because that + # might be called before all imports are done. + self._resolve_classes() + + def _resolve_classes(self): + if isinstance(self.klass, str): + self.klass = self._resolve_string(self.klass) + + def make_dynamic_default(self): + if (self.default_args is None) and (self.default_kwargs is None): + return None + assert self.klass is not None + return self.klass( + *(self.default_args or ()), **(self.default_kwargs or {}) + ) # type:ignore[operator] + + def default_value_repr(self): + return repr(self.make_dynamic_default()) + + def from_string(self, s): + return _safe_literal_eval(s) + + +class ForwardDeclaredMixin: + """ + Mixin for forward-declared versions of Instance and Type. + """ + + def _resolve_string(self, string): + """ + Find the specified class name by looking for it in the module in which + our this_class attribute was defined. + """ + modname = self.this_class.__module__ # type:ignore[attr-defined] + return import_item(".".join([modname, string])) + + +class ForwardDeclaredType(ForwardDeclaredMixin, Type): + """ + Forward-declared version of Type. + """ + + pass + + +class ForwardDeclaredInstance(ForwardDeclaredMixin, Instance): + """ + Forward-declared version of Instance. + """ + + pass + + +class This(ClassBasedTraitType): + """A trait for instances of the class containing this trait. + + Because how how and when class bodies are executed, the ``This`` + trait can only have a default value of None. This, and because we + always validate default values, ``allow_none`` is *always* true. + """ + + info_text = "an instance of the same type as the receiver or None" + + def __init__(self, **kwargs): + super().__init__(None, **kwargs) + + def validate(self, obj, value): + # What if value is a superclass of obj.__class__? This is + # complicated if it was the superclass that defined the This + # trait. + assert self.this_class is not None + if isinstance(value, self.this_class) or (value is None): + return value + else: + self.error(obj, value) + + +class Union(TraitType): + """A trait type representing a Union type.""" + + def __init__(self, trait_types, **kwargs): + """Construct a Union trait. + + This trait allows values that are allowed by at least one of the + specified trait types. A Union traitlet cannot have metadata on + its own, besides the metadata of the listed types. + + Parameters + ---------- + trait_types : sequence + The list of trait types of length at least 1. + **kwargs + Extra kwargs passed to `TraitType` + + Notes + ----- + Union([Float(), Bool(), Int()]) attempts to validate the provided values + with the validation function of Float, then Bool, and finally Int. + + Parsing from string is ambiguous for container types which accept other + collection-like literals (e.g. List accepting both `[]` and `()` + precludes Union from ever parsing ``Union([List(), Tuple()])`` as a tuple; + you can modify behaviour of too permissive container traits by overriding + ``_literal_from_string_pairs`` in subclasses. + Similarly, parsing unions of numeric types is only unambiguous if + types are provided in order of increasing permissiveness, e.g. + ``Union([Int(), Float()])`` (since floats accept integer-looking values). + """ + self.trait_types = list(trait_types) + self.info_text = " or ".join([tt.info() for tt in self.trait_types]) + super().__init__(**kwargs) + + def default(self, obj=None): + default = super().default(obj) + for trait in self.trait_types: + if default is Undefined: + default = trait.default(obj) + else: + break + return default + + def class_init(self, cls, name): + for trait_type in reversed(self.trait_types): + trait_type.class_init(cls, None) + super().class_init(cls, name) + + def subclass_init(self, cls): + for trait_type in reversed(self.trait_types): + trait_type.subclass_init(cls) + # explicitly not calling super().subclass_init(cls) + # to opt out of instance_init + + def validate(self, obj, value): + with obj.cross_validation_lock: + for trait_type in self.trait_types: + try: + v = trait_type._validate(obj, value) + # In the case of an element trait, the name is None + if self.name is not None: + setattr(obj, "_" + self.name + "_metadata", trait_type.metadata) + return v + except TraitError: + continue + self.error(obj, value) + + def __or__(self, other): + if isinstance(other, Union): + return Union(self.trait_types + other.trait_types) + else: + return Union(self.trait_types + [other]) + + def from_string(self, s): + for trait_type in self.trait_types: + try: + v = trait_type.from_string(s) + return trait_type.validate(None, v) + except (TraitError, ValueError): + continue + return super().from_string(s) + + +# ----------------------------------------------------------------------------- +# Basic TraitTypes implementations/subclasses +# ----------------------------------------------------------------------------- + + +class Any(TraitType): + """A trait which allows any value.""" + + default_value: t.Optional[t.Any] = None + allow_none = True + info_text = "any value" + + def subclass_init(self, cls): + pass # fully opt out of instance_init + + +def _validate_bounds(trait, obj, value): + """ + Validate that a number to be applied to a trait is between bounds. + + If value is not between min_bound and max_bound, this raises a + TraitError with an error message appropriate for this trait. + """ + if trait.min is not None and value < trait.min: + raise TraitError( + "The value of the '{name}' trait of {klass} instance should " + "not be less than {min_bound}, but a value of {value} was " + "specified".format( + name=trait.name, klass=class_of(obj), value=value, min_bound=trait.min + ) + ) + if trait.max is not None and value > trait.max: + raise TraitError( + "The value of the '{name}' trait of {klass} instance should " + "not be greater than {max_bound}, but a value of {value} was " + "specified".format( + name=trait.name, klass=class_of(obj), value=value, max_bound=trait.max + ) + ) + return value + + +class Int(TraitType): + """An int trait.""" + + default_value = 0 + info_text = "an int" + + def __init__(self, default_value=Undefined, allow_none=False, **kwargs): + self.min = kwargs.pop("min", None) + self.max = kwargs.pop("max", None) + super().__init__(default_value=default_value, allow_none=allow_none, **kwargs) + + def validate(self, obj, value): + if not isinstance(value, int): + self.error(obj, value) + return _validate_bounds(self, obj, value) + + def from_string(self, s): + if self.allow_none and s == "None": + return None + return int(s) + + def subclass_init(self, cls): + pass # fully opt out of instance_init + + +class CInt(Int): + """A casting version of the int trait.""" + + def validate(self, obj, value): + try: + value = int(value) + except Exception: + self.error(obj, value) + return _validate_bounds(self, obj, value) + + +Long, CLong = Int, CInt +Integer = Int + + +class Float(TraitType): + """A float trait.""" + + default_value = 0.0 + info_text = "a float" + + def __init__(self, default_value=Undefined, allow_none=False, **kwargs): + self.min = kwargs.pop("min", -float("inf")) + self.max = kwargs.pop("max", float("inf")) + super().__init__(default_value=default_value, allow_none=allow_none, **kwargs) + + def validate(self, obj, value): + if isinstance(value, int): + value = float(value) + if not isinstance(value, float): + self.error(obj, value) + return _validate_bounds(self, obj, value) + + def from_string(self, s): + if self.allow_none and s == "None": + return None + return float(s) + + def subclass_init(self, cls): + pass # fully opt out of instance_init + + +class CFloat(Float): + """A casting version of the float trait.""" + + def validate(self, obj, value): + try: + value = float(value) + except Exception: + self.error(obj, value) + return _validate_bounds(self, obj, value) + + +class Complex(TraitType): + """A trait for complex numbers.""" + + default_value = 0.0 + 0.0j + info_text = "a complex number" + + def validate(self, obj, value): + if isinstance(value, complex): + return value + if isinstance(value, (float, int)): + return complex(value) + self.error(obj, value) + + def from_string(self, s): + if self.allow_none and s == "None": + return None + return complex(s) + + def subclass_init(self, cls): + pass # fully opt out of instance_init + + +class CComplex(Complex): + """A casting version of the complex number trait.""" + + def validate(self, obj, value): + try: + return complex(value) + except Exception: + self.error(obj, value) + + +# We should always be explicit about whether we're using bytes or unicode, both +# for Python 3 conversion and for reliable unicode behaviour on Python 2. So +# we don't have a Str type. +class Bytes(TraitType): + """A trait for byte strings.""" + + default_value = b"" + info_text = "a bytes object" + + def validate(self, obj, value): + if isinstance(value, bytes): + return value + self.error(obj, value) + + def from_string(self, s): + if self.allow_none and s == "None": + return None + if len(s) >= 3: + # handle deprecated b"string" + for quote in ('"', "'"): + if s[:2] == f"b{quote}" and s[-1] == quote: + old_s = s + s = s[2:-1] + warn( + "Supporting extra quotes around Bytes is deprecated in traitlets 5.0. " + "Use %r instead of %r." % (s, old_s), + FutureWarning, + ) + break + return s.encode("utf8") + + def subclass_init(self, cls): + pass # fully opt out of instance_init + + +class CBytes(Bytes): + """A casting version of the byte string trait.""" + + def validate(self, obj, value): + try: + return bytes(value) + except Exception: + self.error(obj, value) + + +class Unicode(TraitType): + """A trait for unicode strings.""" + + default_value = "" + info_text = "a unicode string" + + def validate(self, obj, value): + if isinstance(value, str): + return value + if isinstance(value, bytes): + try: + return value.decode("ascii", "strict") + except UnicodeDecodeError as e: + msg = "Could not decode {!r} for unicode trait '{}' of {} instance." + raise TraitError(msg.format(value, self.name, class_of(obj))) from e + self.error(obj, value) + + def from_string(self, s): + if self.allow_none and s == "None": + return None + s = os.path.expanduser(s) + if len(s) >= 2: + # handle deprecated "1" + for c in ('"', "'"): + if s[0] == s[-1] == c: + old_s = s + s = s[1:-1] + warn( + "Supporting extra quotes around strings is deprecated in traitlets 5.0. " + "You can use %r instead of %r if you require traitlets >=5." % (s, old_s), + FutureWarning, + ) + return s + + def subclass_init(self, cls): + pass # fully opt out of instance_init + + +class CUnicode(Unicode): + """A casting version of the unicode trait.""" + + def validate(self, obj, value): + try: + return str(value) + except Exception: + self.error(obj, value) + + +class ObjectName(TraitType): + """A string holding a valid object name in this version of Python. + + This does not check that the name exists in any scope.""" + + info_text = "a valid object identifier in Python" + + coerce_str = staticmethod(lambda _, s: s) # type:ignore[no-any-return] + + def validate(self, obj, value): + value = self.coerce_str(obj, value) + + if isinstance(value, str) and isidentifier(value): + return value + self.error(obj, value) + + def from_string(self, s): + if self.allow_none and s == "None": + return None + return s + + +class DottedObjectName(ObjectName): + """A string holding a valid dotted object name in Python, such as A.b3._c""" + + def validate(self, obj, value): + value = self.coerce_str(obj, value) + + if isinstance(value, str) and all(isidentifier(a) for a in value.split(".")): + return value + self.error(obj, value) + + +class Bool(TraitType): + """A boolean (True, False) trait.""" + + default_value = False + info_text = "a boolean" + + def validate(self, obj, value): + if isinstance(value, bool): + return value + elif isinstance(value, int): + if value == 1: + return True + elif value == 0: + return False + self.error(obj, value) + + def from_string(self, s): + if self.allow_none and s == "None": + return None + s = s.lower() + if s in {"true", "1"}: + return True + elif s in {"false", "0"}: + return False + else: + raise ValueError("%r is not 1, 0, true, or false") + + def subclass_init(self, cls): + pass # fully opt out of instance_init + + +class CBool(Bool): + """A casting version of the boolean trait.""" + + def validate(self, obj, value): + try: + return bool(value) + except Exception: + self.error(obj, value) + + +class Enum(TraitType): + """An enum whose value must be in a given sequence.""" + + def __init__(self, values, default_value=Undefined, **kwargs): + self.values = values + if kwargs.get("allow_none", False) and default_value is Undefined: + default_value = None + super().__init__(default_value, **kwargs) + + def validate(self, obj, value): + if value in self.values: + return value + self.error(obj, value) + + def _choices_str(self, as_rst=False): + """Returns a description of the trait choices (not none).""" + choices = self.values + if as_rst: + choices = "|".join("``%r``" % x for x in choices) + else: + choices = repr(list(choices)) + return choices + + def _info(self, as_rst=False): + """Returns a description of the trait.""" + none = " or %s" % ("`None`" if as_rst else "None") if self.allow_none else "" + return f"any of {self._choices_str(as_rst)}{none}" + + def info(self): + return self._info(as_rst=False) + + def info_rst(self): + return self._info(as_rst=True) + + def from_string(self, s): + try: + return self.validate(None, s) + except TraitError: + return _safe_literal_eval(s) + + def subclass_init(self, cls): + pass # fully opt out of instance_init + + +class CaselessStrEnum(Enum): + """An enum of strings where the case should be ignored.""" + + def __init__(self, values, default_value=Undefined, **kwargs): + super().__init__(values, default_value=default_value, **kwargs) + + def validate(self, obj, value): + if not isinstance(value, str): + self.error(obj, value) + + for v in self.values: + if v.lower() == value.lower(): + return v + self.error(obj, value) + + def _info(self, as_rst=False): + """Returns a description of the trait.""" + none = " or %s" % ("`None`" if as_rst else "None") if self.allow_none else "" + return f"any of {self._choices_str(as_rst)} (case-insensitive){none}" + + def info(self): + return self._info(as_rst=False) + + def info_rst(self): + return self._info(as_rst=True) + + +class FuzzyEnum(Enum): + """An case-ignoring enum matching choices by unique prefixes/substrings.""" + + case_sensitive = False + #: If True, choices match anywhere in the string, otherwise match prefixes. + substring_matching = False + + def __init__( + self, + values, + default_value=Undefined, + case_sensitive=False, + substring_matching=False, + **kwargs, + ): + self.case_sensitive = case_sensitive + self.substring_matching = substring_matching + super().__init__(values, default_value=default_value, **kwargs) + + def validate(self, obj, value): + if not isinstance(value, str): + self.error(obj, value) + + conv_func = (lambda c: c) if self.case_sensitive else lambda c: c.lower() + substring_matching = self.substring_matching + match_func = ( + (lambda v, c: v in c) + if substring_matching + else (lambda v, c: c.startswith(v)) # type:ignore[no-any-return] + ) + value = conv_func(value) + choices = self.values + matches = [match_func(value, conv_func(c)) for c in choices] + if sum(matches) == 1: + for v, m in zip(choices, matches): + if m: + return v + + self.error(obj, value) + + def _info(self, as_rst=False): + """Returns a description of the trait.""" + none = " or %s" % ("`None`" if as_rst else "None") if self.allow_none else "" + case = "sensitive" if self.case_sensitive else "insensitive" + substr = "substring" if self.substring_matching else "prefix" + return f"any case-{case} {substr} of {self._choices_str(as_rst)}{none}" + + def info(self): + return self._info(as_rst=False) + + def info_rst(self): + return self._info(as_rst=True) + + +class Container(Instance): + """An instance of a container (list, set, etc.) + + To be subclassed by overriding klass. + """ + + klass: t.Optional[t.Union[str, t.Type[t.Any]]] = None + _cast_types: t.Any = () + _valid_defaults = SequenceTypes + _trait = None + _literal_from_string_pairs: t.Any = ("[]", "()") + + def __init__(self, trait=None, default_value=Undefined, **kwargs): + """Create a container trait type from a list, set, or tuple. + + The default value is created by doing ``List(default_value)``, + which creates a copy of the ``default_value``. + + ``trait`` can be specified, which restricts the type of elements + in the container to that TraitType. + + If only one arg is given and it is not a Trait, it is taken as + ``default_value``: + + ``c = List([1, 2, 3])`` + + Parameters + ---------- + trait : TraitType [ optional ] + the type for restricting the contents of the Container. If unspecified, + types are not checked. + default_value : SequenceType [ optional ] + The default value for the Trait. Must be list/tuple/set, and + will be cast to the container type. + allow_none : bool [ default False ] + Whether to allow the value to be None + **kwargs : any + further keys for extensions to the Trait (e.g. config) + + """ + + # allow List([values]): + if trait is not None and default_value is Undefined and not is_trait(trait): + default_value = trait + trait = None + + if default_value is None and not kwargs.get("allow_none", False): + # improve backward-compatibility for possible subclasses + # specifying default_value=None as default, + # keeping 'unspecified' behavior (i.e. empty container) + warn( + f"Specifying {self.__class__.__name__}(default_value=None)" + " for no default is deprecated in traitlets 5.0.5." + " Use default_value=Undefined", + DeprecationWarning, + stacklevel=2, + ) + default_value = Undefined + + if default_value is Undefined: + args: t.Any = () + elif default_value is None: + # default_value back on kwargs for super() to handle + args = () + kwargs["default_value"] = None + elif isinstance(default_value, self._valid_defaults): + args = (default_value,) + else: + raise TypeError(f"default value of {self.__class__.__name__} was {default_value}") + + if is_trait(trait): + if isinstance(trait, type): + warn( + "Traits should be given as instances, not types (for example, `Int()`, not `Int`)." + " Passing types is deprecated in traitlets 4.1.", + DeprecationWarning, + stacklevel=3, + ) + self._trait = trait() if isinstance(trait, type) else trait + elif trait is not None: + raise TypeError("`trait` must be a Trait or None, got %s" % repr_type(trait)) + + super().__init__(klass=self.klass, args=args, **kwargs) + + def validate(self, obj, value): + if isinstance(value, self._cast_types): + assert self.klass is not None + value = self.klass(value) # type:ignore[operator] + value = super().validate(obj, value) + if value is None: + return value + + value = self.validate_elements(obj, value) + + return value + + def validate_elements(self, obj, value): + validated = [] + if self._trait is None or isinstance(self._trait, Any): + return value + for v in value: + try: + v = self._trait._validate(obj, v) + except TraitError as error: + self.error(obj, v, error) + else: + validated.append(v) + assert self.klass is not None + return self.klass(validated) # type:ignore[operator] + + def class_init(self, cls, name): + if isinstance(self._trait, TraitType): + self._trait.class_init(cls, None) + super().class_init(cls, name) + + def subclass_init(self, cls): + if isinstance(self._trait, TraitType): + self._trait.subclass_init(cls) + # explicitly not calling super().subclass_init(cls) + # to opt out of instance_init + + def from_string(self, s): + """Load value from a single string""" + if not isinstance(s, str): + raise TraitError(f"Expected string, got {s!r}") + try: + test = literal_eval(s) + except Exception: + test = None + return self.validate(None, test) + + def from_string_list(self, s_list): + """Return the value from a list of config strings + + This is where we parse CLI configuration + """ + assert self.klass is not None + if len(s_list) == 1: + # check for deprecated --Class.trait="['a', 'b', 'c']" + r = s_list[0] + if r == "None" and self.allow_none: + return None + if len(r) >= 2 and any( + r.startswith(start) and r.endswith(end) + for start, end in self._literal_from_string_pairs + ): + if self.this_class: + clsname = self.this_class.__name__ + "." + else: + clsname = "" + assert self.name is not None + warn( + "--{0}={1} for containers is deprecated in traitlets 5.0. " + "You can pass `--{0} item` ... multiple times to add items to a list.".format( + clsname + self.name, r + ), + FutureWarning, + ) + return self.klass(literal_eval(r)) # type:ignore[operator] + sig = inspect.signature(self.item_from_string) + if "index" in sig.parameters: + item_from_string = self.item_from_string + else: + # backward-compat: allow item_from_string to ignore index arg + item_from_string = lambda s, index=None: self.item_from_string(s) # noqa[E371] + + return self.klass( + [item_from_string(s, index=idx) for idx, s in enumerate(s_list)] + ) # type:ignore[operator] + + def item_from_string(self, s, index=None): + """Cast a single item from a string + + Evaluated when parsing CLI configuration from a string + """ + if self._trait: + return self._trait.from_string(s) + else: + return s + + +class List(Container): + """An instance of a Python list.""" + + klass = list + _cast_types: t.Any = (tuple,) + + def __init__( + self, + trait=None, + default_value=Undefined, + minlen=0, + maxlen=sys.maxsize, + **kwargs, + ): + """Create a List trait type from a list, set, or tuple. + + The default value is created by doing ``list(default_value)``, + which creates a copy of the ``default_value``. + + ``trait`` can be specified, which restricts the type of elements + in the container to that TraitType. + + If only one arg is given and it is not a Trait, it is taken as + ``default_value``: + + ``c = List([1, 2, 3])`` + + Parameters + ---------- + trait : TraitType [ optional ] + the type for restricting the contents of the Container. + If unspecified, types are not checked. + default_value : SequenceType [ optional ] + The default value for the Trait. Must be list/tuple/set, and + will be cast to the container type. + minlen : Int [ default 0 ] + The minimum length of the input list + maxlen : Int [ default sys.maxsize ] + The maximum length of the input list + """ + self._minlen = minlen + self._maxlen = maxlen + super().__init__(trait=trait, default_value=default_value, **kwargs) + + def length_error(self, obj, value): + e = ( + "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." + % (self.name, class_of(obj), self._minlen, self._maxlen, value) + ) + raise TraitError(e) + + def validate_elements(self, obj, value): + length = len(value) + if length < self._minlen or length > self._maxlen: + self.length_error(obj, value) + + return super().validate_elements(obj, value) + + def set(self, obj, value): + if isinstance(value, str): + return super().set(obj, [value]) + else: + return super().set(obj, value) + + +class Set(List): + """An instance of a Python set.""" + + klass = set # type:ignore[assignment] + _cast_types = (tuple, list) + + _literal_from_string_pairs = ("[]", "()", "{}") + + # Redefine __init__ just to make the docstring more accurate. + def __init__( + self, + trait=None, + default_value=Undefined, + minlen=0, + maxlen=sys.maxsize, + **kwargs, + ): + """Create a Set trait type from a list, set, or tuple. + + The default value is created by doing ``set(default_value)``, + which creates a copy of the ``default_value``. + + ``trait`` can be specified, which restricts the type of elements + in the container to that TraitType. + + If only one arg is given and it is not a Trait, it is taken as + ``default_value``: + + ``c = Set({1, 2, 3})`` + + Parameters + ---------- + trait : TraitType [ optional ] + the type for restricting the contents of the Container. + If unspecified, types are not checked. + default_value : SequenceType [ optional ] + The default value for the Trait. Must be list/tuple/set, and + will be cast to the container type. + minlen : Int [ default 0 ] + The minimum length of the input list + maxlen : Int [ default sys.maxsize ] + The maximum length of the input list + """ + super().__init__(trait, default_value, minlen, maxlen, **kwargs) + + def default_value_repr(self): + # Ensure default value is sorted for a reproducible build + list_repr = repr(sorted(self.make_dynamic_default())) + if list_repr == "[]": + return "set()" + return "{" + list_repr[1:-1] + "}" + + +class Tuple(Container): + """An instance of a Python tuple.""" + + klass = tuple + _cast_types = (list,) + + def __init__(self, *traits, **kwargs): + """Create a tuple from a list, set, or tuple. + + Create a fixed-type tuple with Traits: + + ``t = Tuple(Int(), Str(), CStr())`` + + would be length 3, with Int,Str,CStr for each element. + + If only one arg is given and it is not a Trait, it is taken as + default_value: + + ``t = Tuple((1, 2, 3))`` + + Otherwise, ``default_value`` *must* be specified by keyword. + + Parameters + ---------- + *traits : TraitTypes [ optional ] + the types for restricting the contents of the Tuple. If unspecified, + types are not checked. If specified, then each positional argument + corresponds to an element of the tuple. Tuples defined with traits + are of fixed length. + default_value : SequenceType [ optional ] + The default value for the Tuple. Must be list/tuple/set, and + will be cast to a tuple. If ``traits`` are specified, + ``default_value`` must conform to the shape and type they specify. + **kwargs + Other kwargs passed to `Container` + """ + default_value = kwargs.pop("default_value", Undefined) + # allow Tuple((values,)): + if len(traits) == 1 and default_value is Undefined and not is_trait(traits[0]): + default_value = traits[0] + traits = () + + if default_value is None and not kwargs.get("allow_none", False): + # improve backward-compatibility for possible subclasses + # specifying default_value=None as default, + # keeping 'unspecified' behavior (i.e. empty container) + warn( + f"Specifying {self.__class__.__name__}(default_value=None)" + " for no default is deprecated in traitlets 5.0.5." + " Use default_value=Undefined", + DeprecationWarning, + stacklevel=2, + ) + default_value = Undefined + + if default_value is Undefined: + args: t.Any = () + elif default_value is None: + # default_value back on kwargs for super() to handle + args = () + kwargs["default_value"] = None + elif isinstance(default_value, self._valid_defaults): + args = (default_value,) + else: + raise TypeError(f"default value of {self.__class__.__name__} was {default_value}") + + self._traits = [] + for trait in traits: + if isinstance(trait, type): + warn( + "Traits should be given as instances, not types (for example, `Int()`, not `Int`)" + " Passing types is deprecated in traitlets 4.1.", + DeprecationWarning, + stacklevel=2, + ) + trait = trait() + self._traits.append(trait) + + if self._traits and (default_value is None or default_value is Undefined): + # don't allow default to be an empty container if length is specified + args = None + super(Container, self).__init__(klass=self.klass, args=args, **kwargs) + + def item_from_string(self, s, index): + """Cast a single item from a string + + Evaluated when parsing CLI configuration from a string + """ + if not self._traits or index >= len(self._traits): + # return s instead of raising index error + # length errors will be raised later on validation + return s + return self._traits[index].from_string(s) + + def validate_elements(self, obj, value): + if not self._traits: + # nothing to validate + return value + if len(value) != len(self._traits): + e = ( + "The '%s' trait of %s instance requires %i elements, but a value of %s was specified." + % (self.name, class_of(obj), len(self._traits), repr_type(value)) + ) + raise TraitError(e) + + validated = [] + for trait, v in zip(self._traits, value): + try: + v = trait._validate(obj, v) + except TraitError as error: + self.error(obj, v, error) + else: + validated.append(v) + return tuple(validated) + + def class_init(self, cls, name): + for trait in self._traits: + if isinstance(trait, TraitType): + trait.class_init(cls, None) + super(Container, self).class_init(cls, name) + + def subclass_init(self, cls): + for trait in self._traits: + if isinstance(trait, TraitType): + trait.subclass_init(cls) + # explicitly not calling super().subclass_init(cls) + # to opt out of instance_init + + +class Dict(Instance): + """An instance of a Python dict. + + One or more traits can be passed to the constructor + to validate the keys and/or values of the dict. + If you need more detailed validation, + you may use a custom validator method. + + .. versionchanged:: 5.0 + Added key_trait for validating dict keys. + + .. versionchanged:: 5.0 + Deprecated ambiguous ``trait``, ``traits`` args in favor of ``value_trait``, ``per_key_traits``. + """ + + _value_trait = None + _key_trait = None + + def __init__( + self, + value_trait=None, + per_key_traits=None, + key_trait=None, + default_value=Undefined, + **kwargs, + ): + """Create a dict trait type from a Python dict. + + The default value is created by doing ``dict(default_value)``, + which creates a copy of the ``default_value``. + + Parameters + ---------- + value_trait : TraitType [ optional ] + The specified trait type to check and use to restrict the values of + the dict. If unspecified, values are not checked. + per_key_traits : Dictionary of {keys:trait types} [ optional, keyword-only ] + A Python dictionary containing the types that are valid for + restricting the values of the dict on a per-key basis. + Each value in this dict should be a Trait for validating + key_trait : TraitType [ optional, keyword-only ] + The type for restricting the keys of the dict. If + unspecified, the types of the keys are not checked. + default_value : SequenceType [ optional, keyword-only ] + The default value for the Dict. Must be dict, tuple, or None, and + will be cast to a dict if not None. If any key or value traits are specified, + the `default_value` must conform to the constraints. + + Examples + -------- + a dict whose values must be text + >>> d = Dict(Unicode()) + + d2['n'] must be an integer + d2['s'] must be text + >>> d2 = Dict(per_key_traits={"n": Integer(), "s": Unicode()}) + + d3's keys must be text + d3's values must be integers + >>> d3 = Dict(value_trait=Integer(), key_trait=Unicode()) + + """ + + # handle deprecated keywords + trait = kwargs.pop("trait", None) + if trait is not None: + if value_trait is not None: + raise TypeError( + "Found a value for both `value_trait` and its deprecated alias `trait`." + ) + value_trait = trait + warn( + "Keyword `trait` is deprecated in traitlets 5.0, use `value_trait` instead", + DeprecationWarning, + stacklevel=2, + ) + traits = kwargs.pop("traits", None) + if traits is not None: + if per_key_traits is not None: + raise TypeError( + "Found a value for both `per_key_traits` and its deprecated alias `traits`." + ) + per_key_traits = traits + warn( + "Keyword `traits` is deprecated in traitlets 5.0, use `per_key_traits` instead", + DeprecationWarning, + stacklevel=2, + ) + + # Handling positional arguments + if default_value is Undefined and value_trait is not None: + if not is_trait(value_trait): + default_value = value_trait + value_trait = None + + if key_trait is None and per_key_traits is not None: + if is_trait(per_key_traits): + key_trait = per_key_traits + per_key_traits = None + + # Handling default value + if default_value is Undefined: + default_value = {} + if default_value is None: + args: t.Any = None + elif isinstance(default_value, dict): + args = (default_value,) + elif isinstance(default_value, SequenceTypes): + args = (default_value,) + else: + raise TypeError("default value of Dict was %s" % default_value) + + # Case where a type of TraitType is provided rather than an instance + if is_trait(value_trait): + if isinstance(value_trait, type): + warn( + "Traits should be given as instances, not types (for example, `Int()`, not `Int`)" + " Passing types is deprecated in traitlets 4.1.", + DeprecationWarning, + stacklevel=2, + ) + value_trait = value_trait() + self._value_trait = value_trait + elif value_trait is not None: + raise TypeError( + "`value_trait` must be a Trait or None, got %s" % repr_type(value_trait) + ) + + if is_trait(key_trait): + if isinstance(key_trait, type): + warn( + "Traits should be given as instances, not types (for example, `Int()`, not `Int`)" + " Passing types is deprecated in traitlets 4.1.", + DeprecationWarning, + stacklevel=2, + ) + key_trait = key_trait() + self._key_trait = key_trait + elif key_trait is not None: + raise TypeError("`key_trait` must be a Trait or None, got %s" % repr_type(key_trait)) + + self._per_key_traits = per_key_traits + + super().__init__(klass=dict, args=args, **kwargs) + + def element_error(self, obj, element, validator, side="Values"): + e = ( + side + + " of the '%s' trait of %s instance must be %s, but a value of %s was specified." + % (self.name, class_of(obj), validator.info(), repr_type(element)) + ) + raise TraitError(e) + + def validate(self, obj, value): + value = super().validate(obj, value) + if value is None: + return value + value = self.validate_elements(obj, value) + return value + + def validate_elements(self, obj, value): + per_key_override = self._per_key_traits or {} + key_trait = self._key_trait + value_trait = self._value_trait + if not (key_trait or value_trait or per_key_override): + return value + + validated = {} + for key in value: + v = value[key] + if key_trait: + try: + key = key_trait._validate(obj, key) + except TraitError: + self.element_error(obj, key, key_trait, "Keys") + active_value_trait = per_key_override.get(key, value_trait) + if active_value_trait: + try: + v = active_value_trait._validate(obj, v) + except TraitError: + self.element_error(obj, v, active_value_trait, "Values") + validated[key] = v + + return self.klass(validated) # type:ignore + + def class_init(self, cls, name): + if isinstance(self._value_trait, TraitType): + self._value_trait.class_init(cls, None) + if isinstance(self._key_trait, TraitType): + self._key_trait.class_init(cls, None) + if self._per_key_traits is not None: + for trait in self._per_key_traits.values(): + trait.class_init(cls, None) + super().class_init(cls, name) + + def subclass_init(self, cls): + if isinstance(self._value_trait, TraitType): + self._value_trait.subclass_init(cls) + if isinstance(self._key_trait, TraitType): + self._key_trait.subclass_init(cls) + if self._per_key_traits is not None: + for trait in self._per_key_traits.values(): + trait.subclass_init(cls) + # explicitly not calling super().subclass_init(cls) + # to opt out of instance_init + + def from_string(self, s): + """Load value from a single string""" + if not isinstance(s, str): + raise TypeError(f"from_string expects a string, got {repr(s)} of type {type(s)}") + try: + return self.from_string_list([s]) + except Exception: + test = _safe_literal_eval(s) + if isinstance(test, dict): + return test + raise + + def from_string_list(self, s_list): + """Return a dict from a list of config strings. + + This is where we parse CLI configuration. + + Each item should have the form ``"key=value"``. + + item parsing is done in :meth:`.item_from_string`. + """ + if len(s_list) == 1 and s_list[0] == "None" and self.allow_none: + return None + if len(s_list) == 1 and s_list[0].startswith("{") and s_list[0].endswith("}"): + warn( + "--{0}={1} for dict-traits is deprecated in traitlets 5.0. " + "You can pass --{0} ... multiple times to add items to a dict.".format( + self.name, + s_list[0], + ), + FutureWarning, + ) + + return literal_eval(s_list[0]) + + combined = {} + for d in [self.item_from_string(s) for s in s_list]: + combined.update(d) + return combined + + def item_from_string(self, s): + """Cast a single-key dict from a string. + + Evaluated when parsing CLI configuration from a string. + + Dicts expect strings of the form key=value. + + Returns a one-key dictionary, + which will be merged in :meth:`.from_string_list`. + """ + + if "=" not in s: + raise TraitError( + "'%s' options must have the form 'key=value', got %s" + % ( + self.__class__.__name__, + repr(s), + ) + ) + key, value = s.split("=", 1) + + # cast key with key trait, if defined + if self._key_trait: + key = self._key_trait.from_string(key) + + # cast value with value trait, if defined (per-key or global) + value_trait = (self._per_key_traits or {}).get(key, self._value_trait) + if value_trait: + value = value_trait.from_string(value) + return {key: value} + + +class TCPAddress(TraitType): + """A trait for an (ip, port) tuple. + + This allows for both IPv4 IP addresses as well as hostnames. + """ + + default_value = ("127.0.0.1", 0) + info_text = "an (ip, port) tuple" + + def validate(self, obj, value): + if isinstance(value, tuple): + if len(value) == 2: + if isinstance(value[0], str) and isinstance(value[1], int): + port = value[1] + if port >= 0 and port <= 65535: + return value + self.error(obj, value) + + def from_string(self, s): + if self.allow_none and s == "None": + return None + if ":" not in s: + raise ValueError("Require `ip:port`, got %r" % s) + ip, port = s.split(":", 1) + port = int(port) + return (ip, port) + + +class CRegExp(TraitType): + """A casting compiled regular expression trait. + + Accepts both strings and compiled regular expressions. The resulting + attribute will be a compiled regular expression.""" + + info_text = "a regular expression" + + def validate(self, obj, value): + try: + return re.compile(value) + except Exception: + self.error(obj, value) + + +class UseEnum(TraitType): + """Use a Enum class as model for the data type description. + Note that if no default-value is provided, the first enum-value is used + as default-value. + + .. sourcecode:: python + + # -- SINCE: Python 3.4 (or install backport: pip install enum34) + import enum + from traitlets import HasTraits, UseEnum + + class Color(enum.Enum): + red = 1 # -- IMPLICIT: default_value + blue = 2 + green = 3 + + class MyEntity(HasTraits): + color = UseEnum(Color, default_value=Color.blue) + + entity = MyEntity(color=Color.red) + entity.color = Color.green # USE: Enum-value (preferred) + entity.color = "green" # USE: name (as string) + entity.color = "Color.green" # USE: scoped-name (as string) + entity.color = 3 # USE: number (as int) + assert entity.color is Color.green + """ + + default_value: t.Optional[enum.Enum] = None + info_text = "Trait type adapter to a Enum class" + + def __init__(self, enum_class, default_value=None, **kwargs): + assert issubclass(enum_class, enum.Enum), "REQUIRE: enum.Enum, but was: %r" % enum_class + allow_none = kwargs.get("allow_none", False) + if default_value is None and not allow_none: + default_value = list(enum_class.__members__.values())[0] + super().__init__(default_value=default_value, **kwargs) + self.enum_class = enum_class + self.name_prefix = enum_class.__name__ + "." + + def select_by_number(self, value, default=Undefined): + """Selects enum-value by using its number-constant.""" + assert isinstance(value, int) + enum_members = self.enum_class.__members__ + for enum_item in enum_members.values(): + if enum_item.value == value: + return enum_item + # -- NOT FOUND: + return default + + def select_by_name(self, value, default=Undefined): + """Selects enum-value by using its name or scoped-name.""" + assert isinstance(value, str) + if value.startswith(self.name_prefix): + # -- SUPPORT SCOPED-NAMES, like: "Color.red" => "red" + value = value.replace(self.name_prefix, "", 1) + return self.enum_class.__members__.get(value, default) + + def validate(self, obj, value): + if isinstance(value, self.enum_class): + return value + elif isinstance(value, int): + # -- CONVERT: number => enum_value (item) + value2 = self.select_by_number(value) + if value2 is not Undefined: + return value2 + elif isinstance(value, str): + # -- CONVERT: name or scoped_name (as string) => enum_value (item) + value2 = self.select_by_name(value) + if value2 is not Undefined: + return value2 + elif value is None: + if self.allow_none: + return None + else: + return self.default_value + self.error(obj, value) + + def _choices_str(self, as_rst=False): + """Returns a description of the trait choices (not none).""" + choices = self.enum_class.__members__.keys() + if as_rst: + return "|".join("``%r``" % x for x in choices) + else: + return repr(list(choices)) # Listify because py3.4- prints odict-class + + def _info(self, as_rst=False): + """Returns a description of the trait.""" + none = " or %s" % ("`None`" if as_rst else "None") if self.allow_none else "" + return f"any of {self._choices_str(as_rst)}{none}" + + def info(self): + return self._info(as_rst=False) + + def info_rst(self): + return self._info(as_rst=True) + + +class Callable(TraitType): + """A trait which is callable. + + Notes + ----- + Classes are callable, as are instances + with a __call__() method.""" + + info_text = "a callable" + + def validate(self, obj, value): + if callable(value): + return value + else: + self.error(obj, value) diff --git a/shared/package-files/35/351a16c0ead9cda9b83059cde27bc744f25addafe62e7ad487f949ba40ad1f1f/_foreach_acos_cuda_dispatch.h b/shared/package-files/35/351a16c0ead9cda9b83059cde27bc744f25addafe62e7ad487f949ba40ad1f1f/_foreach_acos_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..3df8eb38caae007b55c38fa214fe8fb426ac5c7f --- /dev/null +++ b/shared/package-files/35/351a16c0ead9cda9b83059cde27bc744f25addafe62e7ad487f949ba40ad1f1f/_foreach_acos_cuda_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::vector _foreach_acos(at::TensorList self); +TORCH_API void _foreach_acos_(at::TensorList self); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/35/351c0ec08838491e97b83d75937871073efbba8069cde8d7abbbf1b6ad97cacf/Khartoum b/shared/package-files/35/351c0ec08838491e97b83d75937871073efbba8069cde8d7abbbf1b6ad97cacf/Khartoum new file mode 100644 index 0000000000000000000000000000000000000000..3f8e44b8a6e171a0fde96736ed9d4fcde1bcd4a8 Binary files /dev/null and b/shared/package-files/35/351c0ec08838491e97b83d75937871073efbba8069cde8d7abbbf1b6ad97cacf/Khartoum differ diff --git a/shared/package-files/35/351e675ef076cab797195161c7621cc902434ca22a816152726203420dcd760f/rnn.h b/shared/package-files/35/351e675ef076cab797195161c7621cc902434ca22a816152726203420dcd760f/rnn.h new file mode 100644 index 0000000000000000000000000000000000000000..eea517a2b60f371f21aaa48e06d5496938804c14 --- /dev/null +++ b/shared/package-files/35/351e675ef076cab797195161c7621cc902434ca22a816152726203420dcd760f/rnn.h @@ -0,0 +1,351 @@ +#pragma once + +#include +#include + +#include + +namespace torch { +namespace nn { +namespace utils { +namespace rnn { + +inline Tensor invert_permutation(const Tensor& permutation) { + if (!permutation.defined()) { + return torch::Tensor(); + } + Tensor output = + torch::empty_like(permutation, torch::MemoryFormat::Contiguous); + output.scatter_( + 0, + permutation, + torch::arange(0, permutation.numel(), permutation.device())); + return output; +} + +/// Holds the data and list of `batch_sizes` of a packed sequence. +/// +/// All RNN modules accept packed sequences as inputs. +/// +/// Note: +/// Instances of this class should never be created manually. They are meant +/// to be instantiated by functions like `pack_padded_sequence`. +/// +/// Batch sizes represent the number elements at each sequence step in +/// the batch, not the varying sequence lengths passed to +/// `pack_padded_sequence`. For instance, given data ``abc`` and ``x`` +/// the :class:`PackedSequence` would contain data ``axbc`` with +/// ``batch_sizes=[2,1,1]``. +/// +/// Attributes: +/// data (Tensor): Tensor containing packed sequence +/// batch_sizes (Tensor): Tensor of integers holding +/// information about the batch size at each sequence step +/// sorted_indices (Tensor, optional): Tensor of integers holding how this +/// :class:`PackedSequence` is constructed from sequences. +/// unsorted_indices (Tensor, optional): Tensor of integers holding how this +/// to recover the original sequences with correct order. +/// +/// .. note:: +/// `data` can be on arbitrary device and of arbitrary dtype. +/// `sorted_indices` and `unsorted_indices` must be ``torch::kInt64`` +/// tensors on the same device as `data`. +/// +/// However, `batch_sizes` should always be a CPU ``torch::kInt64`` tensor. +/// +/// This invariant is maintained throughout `PackedSequence` class, +/// and all functions that construct a `PackedSequence` in libtorch +/// (i.e., they only pass in tensors conforming to this constraint). +class PackedSequence { + public: + explicit PackedSequence( + Tensor data, + Tensor batch_sizes, + Tensor sorted_indices = {}, + Tensor unsorted_indices = {}) { + // NB: if unsorted_indices is provided, it should be the inverse permutation + // to sorted_indices. Don't assert it here because the PackedSequence ctor + // should only be used internally. + if (!unsorted_indices.defined()) { + unsorted_indices = invert_permutation(sorted_indices); + } + TORCH_CHECK( + batch_sizes.device().type() == kCPU, + "batch_sizes should always be on CPU. " + "Instances of PackedSequence should never be created manually. " + "They should be instantiated by functions like pack_sequence " + "and pack_padded_sequences in nn::utils::rnn. " + "https://pytorch.org/docs/stable/nn.html#torch.nn.utils.rnn.pack_sequence"); + data_ = std::move(data); + batch_sizes_ = std::move(batch_sizes); + sorted_indices_ = std::move(sorted_indices); + unsorted_indices_ = std::move(unsorted_indices); + } + + const Tensor& data() const { + return data_; + } + + const Tensor& batch_sizes() const { + return batch_sizes_; + } + + const Tensor& sorted_indices() const { + return sorted_indices_; + } + + const Tensor& unsorted_indices() const { + return unsorted_indices_; + } + + PackedSequence pin_memory() const { + // Why not convert `batch_sizes`? + // See NOTE [ device and dtype of a PackedSequence ] + return PackedSequence( + data_.pin_memory(), + batch_sizes_, + sorted_indices_.defined() ? sorted_indices_.pin_memory() : Tensor(), + unsorted_indices_.defined() ? unsorted_indices_.pin_memory() + : Tensor()); + } + + PackedSequence to(TensorOptions options) const { + // Performs dtype and/or device conversion on `data_`. + // + // If the ``data_`` Tensor already has the correct `torch::Dtype` + // and `torch::Device`, then ``self`` is returned. + // Otherwise, returns a copy with the desired configuration. + + // Why not convert `batch_sizes`? + // See NOTE [ device and dtype of a PackedSequence ] + Tensor data = data_.to(options); + if (data.is_same(data_)) { + return *this; + } else { + // Does not forward device or dtype args, device is set from data.device() + Tensor sorted_indices = sorted_indices_.defined() + ? sorted_indices_.to( + options.device(data.device()).dtype(sorted_indices_.dtype())) + : Tensor(); + Tensor unsorted_indices = unsorted_indices_.defined() + ? unsorted_indices_.to( + options.device(data.device()).dtype(unsorted_indices_.dtype())) + : Tensor(); + return PackedSequence( + std::move(data), + batch_sizes_, + std::move(sorted_indices), + std::move(unsorted_indices)); + } + } + + PackedSequence cuda() const { + return to(kCUDA); + } + + PackedSequence cpu() const { + return to(kCPU); + } + + /// Returns true if `data_` stored on a gpu + bool is_cuda() const { + return data_.is_cuda(); + } + + /// Returns true if `data_` stored on in pinned memory + bool is_pinned() const { + return data_.is_pinned(); + } + + private: + Tensor data_; + Tensor batch_sizes_; + Tensor sorted_indices_; + Tensor unsorted_indices_; +}; + +/// Packs a Tensor containing padded sequences of variable length. +/// +/// `input` can be of size ``T x B x *`` where `T` is the length of the +/// longest sequence (equal to ``lengths[0]``), ``B`` is the batch size, and +/// ``*`` is any number of dimensions (including 0). If ``batch_first`` is +/// ``true``, ``B x T x *`` `input` is expected. +/// +/// For unsorted sequences, use `enforce_sorted = false`. If `enforce_sorted` is +/// ``true``, the sequences should be sorted by length in a decreasing order, +/// i.e. +/// ``input[:,0]`` should be the longest sequence, and ``input[:,B-1]`` the +/// shortest one. +/// +/// Note: +/// This function accepts any input that has at least two dimensions. You +/// can apply it to pack the labels, and use the output of the RNN with +/// them to compute the loss directly. A Tensor can be retrieved from +/// a `PackedSequence` object by calling its ``.data()`` function. +/// +/// Arguments: +/// input (Tensor): padded batch of variable length sequences. +/// lengths (Tensor): list of sequences lengths of each batch element. +/// batch_first (bool, optional): if ``true``, the input is expected in ``B +/// x T x *`` +/// format. Default: ``false``. +/// enforce_sorted (bool, optional): if ``true``, the input is expected to +/// contain sequences sorted by length in a decreasing order. If +/// ``false``, this condition is not checked. Default: ``true``. +/// +/// Returns: +/// a `PackedSequence` object +inline PackedSequence pack_padded_sequence( + Tensor input, + Tensor lengths, + bool batch_first = false, + bool enforce_sorted = true) { + lengths = lengths.to(kInt64); + Tensor sorted_indices; + if (enforce_sorted) { + sorted_indices = Tensor(); + } else { + std::tie(lengths, sorted_indices) = + torch::sort(lengths, /*dim=*/-1, /*descending=*/true); + sorted_indices = sorted_indices.to(input.device()); + int64_t batch_dim = batch_first ? 0 : 1; + input = input.index_select(batch_dim, sorted_indices); + } + + auto [data, batch_sizes] = + torch::_pack_padded_sequence(input, lengths, batch_first); + return PackedSequence( + std::move(data), std::move(batch_sizes), std::move(sorted_indices), {}); +} + +/// Pads a packed batch of variable length sequences. +/// +/// It is an inverse operation to `pack_padded_sequence`. +/// +/// The returned Tensor's data will be of size ``T x B x *``, where `T` is the +/// length of the longest sequence and `B` is the batch size. If ``batch_first`` +/// is true, the data will be transposed into ``B x T x *`` format. +/// +/// Batch elements will be ordered decreasingly by their length. +/// +/// Arguments: +/// sequence (PackedSequence): batch to pad +/// batch_first (bool, optional): if ``true``, the output will be in ``B x T +/// x *`` +/// format. +/// padding_value (double, optional): values for padded elements. +/// total_length (int64_t, optional): if specified, the output will be +/// padded to +/// have length `total_length`. This method will throw error +/// if `total_length` is less than the max sequence length in +/// `sequence`. +/// +/// Returns: +/// Tuple of Tensor containing the padded sequence, and a Tensor +/// containing the list of lengths of each sequence in the batch. +inline std::tuple pad_packed_sequence( + PackedSequence sequence, + bool batch_first = false, + double padding_value = 0.0, + c10::optional total_length = torch::nullopt) { + int64_t max_seq_length = sequence.batch_sizes().size(0); + if (total_length.has_value()) { + int64_t total_length_val = total_length.value(); + TORCH_CHECK( + total_length_val >= max_seq_length, + "Expected total_length to be at least the length " + "of the longest sequence in input, but got " + "total_length=", + total_length_val, + " and max sequence length being ", + max_seq_length); + max_seq_length = total_length_val; + } + auto [padded_output, lengths] = torch::_pad_packed_sequence( + sequence.data(), + sequence.batch_sizes(), + batch_first, + padding_value, + max_seq_length); + const Tensor& unsorted_indices = sequence.unsorted_indices(); + if (unsorted_indices.defined()) { + int64_t batch_dim = batch_first ? 0 : 1; + return std::make_tuple( + padded_output.index_select(batch_dim, unsorted_indices), + lengths.index({unsorted_indices.cpu()})); + } + return std::make_tuple(padded_output, lengths); +} + +/// Pad a list of variable length Tensors with ``padding_value`` +/// +/// ``pad_sequence`` stacks a list of Tensors along a new dimension, +/// and pads them to equal length. For example, if the input is list of +/// sequences with size ``L x *`` and if batch_first is false, and ``T x B x *`` +/// otherwise. +/// +/// `B` is batch size. It is equal to the number of elements in ``sequences``. +/// `T` is length of the longest sequence. +/// `L` is length of the sequence. +/// `*` is any number of trailing dimensions, including none. +/// +/// Note: +/// This function returns a Tensor of size ``T x B x *`` or ``B x T x *`` +/// where `T` is the length of the longest sequence. This function assumes +/// trailing dimensions and type of all the Tensors in sequences are same. +/// +/// Arguments: +/// sequences (torch::ArrayRef): list of variable length sequences. +/// batch_first (bool, optional): output will be in ``B x T x *`` if true, +/// or in +/// ``T x B x *`` otherwise +/// padding_value (double, optional): value for padded elements. Default: 0. +/// +/// Returns: +/// Tensor of size ``T x B x *`` if `batch_first` is ``false``. +/// Tensor of size ``B x T x *`` otherwise +inline Tensor pad_sequence( + ArrayRef sequences, + bool batch_first = false, + double padding_value = 0) { + return at::pad_sequence(sequences, batch_first, padding_value); +} + +/// Packs a list of variable length Tensors +/// +/// ``sequences`` should be a list of Tensors of size ``L x *``, where `L` is +/// the length of a sequence and `*` is any number of trailing dimensions, +/// including zero. +/// +/// For unsorted sequences, use `enforce_sorted = false`. If ``enforce_sorted`` +/// is ``true``, the sequences should be sorted in the order of decreasing +/// length. +/// +/// +/// Arguments: +/// sequences (torch::ArrayRef): A list of sequences of decreasing +/// length. enforce_sorted (bool, optional): if ``true``, checks that the +/// input +/// contains sequences sorted by length in a decreasing order. If +/// ``false``, this condition is not checked. Default: ``true``. +/// +/// Returns: +/// a `PackedSequence` object +inline PackedSequence pack_sequence( + ArrayRef sequences, + bool enforce_sorted = true) { + Tensor lengths = torch::empty({(int64_t)sequences.size()}, kInt64); + for (const auto i : c10::irange(sequences.size())) { + lengths[i] = sequences[i].size(0); + } + return pack_padded_sequence( + at::pad_sequence(sequences), + std::move(lengths), + /*batch_first=*/false, + /*enforce_sorted=*/enforce_sorted); +} + +} // namespace rnn +} // namespace utils +} // namespace nn +} // namespace torch diff --git a/shared/package-files/35/351fb7d014ba4e09f95dde6a8ff1cc88dd72bddeb14f40f6d4760b99290e3bc4/tasks.pyi b/shared/package-files/35/351fb7d014ba4e09f95dde6a8ff1cc88dd72bddeb14f40f6d4760b99290e3bc4/tasks.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ed5db581578293f9c391eda94f4bd1d1471451d2 --- /dev/null +++ b/shared/package-files/35/351fb7d014ba4e09f95dde6a8ff1cc88dd72bddeb14f40f6d4760b99290e3bc4/tasks.pyi @@ -0,0 +1,204 @@ +import concurrent.futures +import sys +from types import FrameType +from typing import ( + Any, + Awaitable, + Generator, + Generic, + Iterable, + Iterator, + List, + Optional, + Set, + TextIO, + Tuple, + TypeVar, + Union, + overload, +) +from typing_extensions import Literal + +from .events import AbstractEventLoop +from .futures import Future + +if sys.version_info >= (3, 9): + from types import GenericAlias + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_T4 = TypeVar("_T4") +_T5 = TypeVar("_T5") +_FutureT = Union[Future[_T], Generator[Any, None, _T], Awaitable[_T]] + +FIRST_EXCEPTION: str +FIRST_COMPLETED: str +ALL_COMPLETED: str + +def as_completed( + fs: Iterable[_FutureT[_T]], *, loop: Optional[AbstractEventLoop] = ..., timeout: Optional[float] = ... +) -> Iterator[Future[_T]]: ... +def ensure_future(coro_or_future: _FutureT[_T], *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... + +# Prior to Python 3.7 'async' was an alias for 'ensure_future'. +# It became a keyword in 3.7. + +# `gather()` actually returns a list with length equal to the number +# of tasks passed; however, Tuple is used similar to the annotation for +# zip() because typing does not support variadic type variables. See +# typing PR #1550 for discussion. +@overload +def gather( + coro_or_future1: _FutureT[_T1], *, loop: Optional[AbstractEventLoop] = ..., return_exceptions: Literal[False] = ... +) -> Future[Tuple[_T1]]: ... +@overload +def gather( + coro_or_future1: _FutureT[_T1], + coro_or_future2: _FutureT[_T2], + *, + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: Literal[False] = ..., +) -> Future[Tuple[_T1, _T2]]: ... +@overload +def gather( + coro_or_future1: _FutureT[_T1], + coro_or_future2: _FutureT[_T2], + coro_or_future3: _FutureT[_T3], + *, + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: Literal[False] = ..., +) -> Future[Tuple[_T1, _T2, _T3]]: ... +@overload +def gather( + coro_or_future1: _FutureT[_T1], + coro_or_future2: _FutureT[_T2], + coro_or_future3: _FutureT[_T3], + coro_or_future4: _FutureT[_T4], + *, + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: Literal[False] = ..., +) -> Future[Tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def gather( + coro_or_future1: _FutureT[_T1], + coro_or_future2: _FutureT[_T2], + coro_or_future3: _FutureT[_T3], + coro_or_future4: _FutureT[_T4], + coro_or_future5: _FutureT[_T5], + *, + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: Literal[False] = ..., +) -> Future[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def gather( + coro_or_future1: _FutureT[Any], + coro_or_future2: _FutureT[Any], + coro_or_future3: _FutureT[Any], + coro_or_future4: _FutureT[Any], + coro_or_future5: _FutureT[Any], + coro_or_future6: _FutureT[Any], + *coros_or_futures: _FutureT[Any], + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: bool = ..., +) -> Future[List[Any]]: ... +@overload +def gather( + coro_or_future1: _FutureT[_T1], *, loop: Optional[AbstractEventLoop] = ..., return_exceptions: bool = ... +) -> Future[Tuple[Union[_T1, BaseException]]]: ... +@overload +def gather( + coro_or_future1: _FutureT[_T1], + coro_or_future2: _FutureT[_T2], + *, + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: bool = ..., +) -> Future[Tuple[Union[_T1, BaseException], Union[_T2, BaseException]]]: ... +@overload +def gather( + coro_or_future1: _FutureT[_T1], + coro_or_future2: _FutureT[_T2], + coro_or_future3: _FutureT[_T3], + *, + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: bool = ..., +) -> Future[Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException]]]: ... +@overload +def gather( + coro_or_future1: _FutureT[_T1], + coro_or_future2: _FutureT[_T2], + coro_or_future3: _FutureT[_T3], + coro_or_future4: _FutureT[_T4], + *, + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: bool = ..., +) -> Future[ + Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] +]: ... +@overload +def gather( + coro_or_future1: _FutureT[_T1], + coro_or_future2: _FutureT[_T2], + coro_or_future3: _FutureT[_T3], + coro_or_future4: _FutureT[_T4], + coro_or_future5: _FutureT[_T5], + *, + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: bool = ..., +) -> Future[ + Tuple[ + Union[_T1, BaseException], + Union[_T2, BaseException], + Union[_T3, BaseException], + Union[_T4, BaseException], + Union[_T5, BaseException], + ] +]: ... +def run_coroutine_threadsafe(coro: _FutureT[_T], loop: AbstractEventLoop) -> concurrent.futures.Future[_T]: ... +def shield(arg: _FutureT[_T], *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... +def sleep(delay: float, result: _T = ..., *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... +def wait( + fs: Iterable[_FutureT[_T]], *, loop: Optional[AbstractEventLoop] = ..., timeout: Optional[float] = ..., return_when: str = ... +) -> Future[Tuple[Set[Future[_T]], Set[Future[_T]]]]: ... +def wait_for(fut: _FutureT[_T], timeout: Optional[float], *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... + +class Task(Future[_T], Generic[_T]): + if sys.version_info >= (3, 8): + def __init__( + self, + coro: Union[Generator[Any, None, _T], Awaitable[_T]], + *, + loop: AbstractEventLoop = ..., + name: Optional[str] = ..., + ) -> None: ... + else: + def __init__(self, coro: Union[Generator[Any, None, _T], Awaitable[_T]], *, loop: AbstractEventLoop = ...) -> None: ... + def __repr__(self) -> str: ... + if sys.version_info >= (3, 8): + def get_coro(self) -> Any: ... + def get_name(self) -> str: ... + def set_name(self, __value: object) -> None: ... + def get_stack(self, *, limit: int = ...) -> List[FrameType]: ... + def print_stack(self, *, limit: int = ..., file: TextIO = ...) -> None: ... + if sys.version_info >= (3, 9): + def cancel(self, msg: Optional[str] = ...) -> bool: ... + else: + def cancel(self) -> bool: ... + if sys.version_info < (3, 9): + @classmethod + def current_task(cls, loop: Optional[AbstractEventLoop] = ...) -> Optional[Task[Any]]: ... + @classmethod + def all_tasks(cls, loop: Optional[AbstractEventLoop] = ...) -> Set[Task[Any]]: ... + if sys.version_info < (3, 7): + def _wakeup(self, fut: Future[Any]) -> None: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +if sys.version_info >= (3, 7): + def all_tasks(loop: Optional[AbstractEventLoop] = ...) -> Set[Task[Any]]: ... + if sys.version_info >= (3, 8): + def create_task(coro: Union[Generator[Any, None, _T], Awaitable[_T]], *, name: Optional[str] = ...) -> Task[_T]: ... + else: + def create_task(coro: Union[Generator[Any, None, _T], Awaitable[_T]]) -> Task[_T]: ... + def current_task(loop: Optional[AbstractEventLoop] = ...) -> Optional[Task[Any]]: ... diff --git a/shared/package-files/35/3524016c164c330eeab64bbe486ab738a78066dafc1bc59e36e2c137a8406eb9/special_i0e_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/35/3524016c164c330eeab64bbe486ab738a78066dafc1bc59e36e2c137a8406eb9/special_i0e_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b75fbfddd0d71e537bb4a5f39ee883daa9522cd6 --- /dev/null +++ b/shared/package-files/35/3524016c164c330eeab64bbe486ab738a78066dafc1bc59e36e2c137a8406eb9/special_i0e_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor special_i0e(const at::Tensor & self); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/35/3524e9d37d6ad24abe5702d8e5f717982316618c1b2784c2813b0dc99050acda/fft_hfftn_compositeimplicitautograd_dispatch.h b/shared/package-files/35/3524e9d37d6ad24abe5702d8e5f717982316618c1b2784c2813b0dc99050acda/fft_hfftn_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..12a032606638f624e3bbd4328c0e61ed3122bccf --- /dev/null +++ b/shared/package-files/35/3524e9d37d6ad24abe5702d8e5f717982316618c1b2784c2813b0dc99050acda/fft_hfftn_compositeimplicitautograd_dispatch.h @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor fft_hfftn(const at::Tensor & self, at::OptionalIntArrayRef s=c10::nullopt, at::OptionalIntArrayRef dim=c10::nullopt, c10::optional norm=c10::nullopt); +TORCH_API at::Tensor fft_hfftn_symint(const at::Tensor & self, at::OptionalSymIntArrayRef s=c10::nullopt, at::OptionalIntArrayRef dim=c10::nullopt, c10::optional norm=c10::nullopt); +TORCH_API const at::Tensor & fft_hfftn_out(const at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef s=c10::nullopt, at::OptionalIntArrayRef dim=c10::nullopt, c10::optional norm=c10::nullopt); +TORCH_API const at::Tensor & fft_hfftn_outf(const at::Tensor & self, at::OptionalIntArrayRef s, at::OptionalIntArrayRef dim, c10::optional norm, const at::Tensor & out); +TORCH_API const at::Tensor & fft_hfftn_symint_out(const at::Tensor & out, const at::Tensor & self, at::OptionalSymIntArrayRef s=c10::nullopt, at::OptionalIntArrayRef dim=c10::nullopt, c10::optional norm=c10::nullopt); +TORCH_API const at::Tensor & fft_hfftn_symint_outf(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::OptionalIntArrayRef dim, c10::optional norm, const at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/35/352a97d63979656b2c566d1298d147a783dc909632f18089c652f4d8c29ae147/lib.h b/shared/package-files/35/352a97d63979656b2c566d1298d147a783dc909632f18089c652f4d8c29ae147/lib.h new file mode 100644 index 0000000000000000000000000000000000000000..5be7e85c997412117304362770b85fffed80e055 --- /dev/null +++ b/shared/package-files/35/352a97d63979656b2c566d1298d147a783dc909632f18089c652f4d8c29ae147/lib.h @@ -0,0 +1,79 @@ +/* Generated by Cython 3.2.4 */ + +#ifndef __PYX_HAVE__pyarrow__lib +#define __PYX_HAVE__pyarrow__lib + +#include "Python.h" + +#ifndef __PYX_HAVE_API__pyarrow__lib + +#ifdef CYTHON_EXTERN_C + #undef __PYX_EXTERN_C + #define __PYX_EXTERN_C CYTHON_EXTERN_C +#elif defined(__PYX_EXTERN_C) + #ifdef _MSC_VER + #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.") + #else + #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead. + #endif +#else + #define __PYX_EXTERN_C extern "C++" +#endif + +#ifndef DL_IMPORT + #define DL_IMPORT(_T) _T +#endif + +__PYX_EXTERN_C PyObject *pyarrow_wrap_buffer(std::shared_ptr< arrow::Buffer> const &); +__PYX_EXTERN_C PyObject *pyarrow_wrap_resizable_buffer(std::shared_ptr< arrow::ResizableBuffer> const &); +__PYX_EXTERN_C PyObject *pyarrow_wrap_data_type(std::shared_ptr< arrow::DataType> const &); +__PYX_EXTERN_C PyObject *pyarrow_wrap_field(std::shared_ptr< arrow::Field> const &); +__PYX_EXTERN_C PyObject *pyarrow_wrap_schema(std::shared_ptr< arrow::Schema> const &); +__PYX_EXTERN_C PyObject *pyarrow_wrap_scalar(std::shared_ptr< arrow::Scalar> const &); +__PYX_EXTERN_C PyObject *pyarrow_wrap_array(std::shared_ptr< arrow::Array> const &); +__PYX_EXTERN_C PyObject *pyarrow_wrap_chunked_array(std::shared_ptr< arrow::ChunkedArray> const &); +__PYX_EXTERN_C PyObject *pyarrow_wrap_sparse_coo_tensor(std::shared_ptr< arrow::SparseCOOTensor> const &); +__PYX_EXTERN_C PyObject *pyarrow_wrap_sparse_csc_matrix(std::shared_ptr< arrow::SparseCSCMatrix> const &); +__PYX_EXTERN_C PyObject *pyarrow_wrap_sparse_csf_tensor(std::shared_ptr< arrow::SparseCSFTensor> const &); +__PYX_EXTERN_C PyObject *pyarrow_wrap_sparse_csr_matrix(std::shared_ptr< arrow::SparseCSRMatrix> const &); +__PYX_EXTERN_C PyObject *pyarrow_wrap_tensor(std::shared_ptr< arrow::Tensor> const &); +__PYX_EXTERN_C PyObject *pyarrow_wrap_batch(std::shared_ptr< arrow::RecordBatch> const &); +__PYX_EXTERN_C PyObject *pyarrow_wrap_table(std::shared_ptr< arrow::Table> const &); +__PYX_EXTERN_C std::shared_ptr< arrow::Buffer> pyarrow_unwrap_buffer(PyObject *); +__PYX_EXTERN_C std::shared_ptr< arrow::DataType> pyarrow_unwrap_data_type(PyObject *); +__PYX_EXTERN_C std::shared_ptr< arrow::Field> pyarrow_unwrap_field(PyObject *); +__PYX_EXTERN_C std::shared_ptr< arrow::Schema> pyarrow_unwrap_schema(PyObject *); +__PYX_EXTERN_C std::shared_ptr< arrow::Scalar> pyarrow_unwrap_scalar(PyObject *); +__PYX_EXTERN_C std::shared_ptr< arrow::Array> pyarrow_unwrap_array(PyObject *); +__PYX_EXTERN_C std::shared_ptr< arrow::ChunkedArray> pyarrow_unwrap_chunked_array(PyObject *); +__PYX_EXTERN_C std::shared_ptr< arrow::SparseCOOTensor> pyarrow_unwrap_sparse_coo_tensor(PyObject *); +__PYX_EXTERN_C std::shared_ptr< arrow::SparseCSCMatrix> pyarrow_unwrap_sparse_csc_matrix(PyObject *); +__PYX_EXTERN_C std::shared_ptr< arrow::SparseCSFTensor> pyarrow_unwrap_sparse_csf_tensor(PyObject *); +__PYX_EXTERN_C std::shared_ptr< arrow::SparseCSRMatrix> pyarrow_unwrap_sparse_csr_matrix(PyObject *); +__PYX_EXTERN_C std::shared_ptr< arrow::Tensor> pyarrow_unwrap_tensor(PyObject *); +__PYX_EXTERN_C std::shared_ptr< arrow::RecordBatch> pyarrow_unwrap_batch(PyObject *); +__PYX_EXTERN_C std::shared_ptr< arrow::Table> pyarrow_unwrap_table(PyObject *); + +#endif /* !__PYX_HAVE_API__pyarrow__lib */ + +/* WARNING: the interface of the module init function changed in CPython 3.5. */ +/* It now returns a PyModuleDef instance instead of a PyModule instance. */ + +/* WARNING: Use PyImport_AppendInittab("lib", PyInit_lib) instead of calling PyInit_lib directly from Python 3.5 */ +PyMODINIT_FUNC PyInit_lib(void); + +#if PY_VERSION_HEX >= 0x03050000 && (defined(__GNUC__) || defined(__clang__) || defined(_MSC_VER) || (defined(__cplusplus) && __cplusplus >= 201402L)) +#if defined(__cplusplus) && __cplusplus >= 201402L +[[deprecated("Use PyImport_AppendInittab(\"lib\", PyInit_lib) instead of calling PyInit_lib directly.")]] inline +#elif defined(__GNUC__) || defined(__clang__) +__attribute__ ((__deprecated__("Use PyImport_AppendInittab(\"lib\", PyInit_lib) instead of calling PyInit_lib directly."), __unused__)) __inline__ +#elif defined(_MSC_VER) +__declspec(deprecated("Use PyImport_AppendInittab(\"lib\", PyInit_lib) instead of calling PyInit_lib directly.")) __inline +#endif +static PyObject* __PYX_WARN_IF_PyInit_lib_INIT_CALLED(PyObject* res) { + return res; +} +#define PyInit_lib() __PYX_WARN_IF_PyInit_lib_INIT_CALLED(PyInit_lib()) +#endif + +#endif /* !__PYX_HAVE__pyarrow__lib */ diff --git a/shared/package-files/35/352f80bc5d8077cfbcffb6ec84a067a676b497779aafa21f87575557ef78c3a8/nonzero_cuda_dispatch.h b/shared/package-files/35/352f80bc5d8077cfbcffb6ec84a067a676b497779aafa21f87575557ef78c3a8/nonzero_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..24d7d2dfa70d45871f7d1c57c40aac607783bb6d --- /dev/null +++ b/shared/package-files/35/352f80bc5d8077cfbcffb6ec84a067a676b497779aafa21f87575557ef78c3a8/nonzero_cuda_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor nonzero(const at::Tensor & self); +TORCH_API at::Tensor & nonzero_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & nonzero_outf(const at::Tensor & self, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/35/353070330b040ab7479b179717bb1ebac1cbceb87a2dd9f503daa14b9703b9fd/__init__.py b/shared/package-files/35/353070330b040ab7479b179717bb1ebac1cbceb87a2dd9f503daa14b9703b9fd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..af5d4288d3c7f7c00d131e3341716755bb95351f --- /dev/null +++ b/shared/package-files/35/353070330b040ab7479b179717bb1ebac1cbceb87a2dd9f503daa14b9703b9fd/__init__.py @@ -0,0 +1,37 @@ +"""Jinja is a template engine written in pure Python. It provides a +non-XML syntax that supports inline expressions and an optional +sandboxed environment. +""" +from .bccache import BytecodeCache as BytecodeCache +from .bccache import FileSystemBytecodeCache as FileSystemBytecodeCache +from .bccache import MemcachedBytecodeCache as MemcachedBytecodeCache +from .environment import Environment as Environment +from .environment import Template as Template +from .exceptions import TemplateAssertionError as TemplateAssertionError +from .exceptions import TemplateError as TemplateError +from .exceptions import TemplateNotFound as TemplateNotFound +from .exceptions import TemplateRuntimeError as TemplateRuntimeError +from .exceptions import TemplatesNotFound as TemplatesNotFound +from .exceptions import TemplateSyntaxError as TemplateSyntaxError +from .exceptions import UndefinedError as UndefinedError +from .loaders import BaseLoader as BaseLoader +from .loaders import ChoiceLoader as ChoiceLoader +from .loaders import DictLoader as DictLoader +from .loaders import FileSystemLoader as FileSystemLoader +from .loaders import FunctionLoader as FunctionLoader +from .loaders import ModuleLoader as ModuleLoader +from .loaders import PackageLoader as PackageLoader +from .loaders import PrefixLoader as PrefixLoader +from .runtime import ChainableUndefined as ChainableUndefined +from .runtime import DebugUndefined as DebugUndefined +from .runtime import make_logging_undefined as make_logging_undefined +from .runtime import StrictUndefined as StrictUndefined +from .runtime import Undefined as Undefined +from .utils import clear_caches as clear_caches +from .utils import is_undefined as is_undefined +from .utils import pass_context as pass_context +from .utils import pass_environment as pass_environment +from .utils import pass_eval_context as pass_eval_context +from .utils import select_autoescape as select_autoescape + +__version__ = "3.1.3" diff --git a/shared/package-files/35/3532f8f690e3616ef85e772e78cfdc01c3790f866e4b3157229437d17dcff7ba/E_B_S_C_.py b/shared/package-files/35/3532f8f690e3616ef85e772e78cfdc01c3790f866e4b3157229437d17dcff7ba/E_B_S_C_.py new file mode 100644 index 0000000000000000000000000000000000000000..74ff8b575010d56e22d07d8d68a933fcbec3f96c --- /dev/null +++ b/shared/package-files/35/3532f8f690e3616ef85e772e78cfdc01c3790f866e4b3157229437d17dcff7ba/E_B_S_C_.py @@ -0,0 +1,153 @@ +from __future__ import annotations + +from typing import Any + +from fontTools.misc import sstruct +from fontTools.misc.textTools import bytesjoin, safeEval +from fontTools.misc.xmlWriter import XMLWriter +from fontTools.ttLib import TTFont, TTLibError +from fontTools.ttLib.tables import DefaultTable +from fontTools.ttLib.tables.DefaultTable import XMLAttrs, XMLContent +from fontTools.ttLib.tables.E_B_L_C_ import sbitLineMetricsFormat, SbitLineMetrics + +ebscHeaderFormat = """ + > # big endian + version: 16.16F + numSizes: I +""" + +bitmapScaleTableFormatPart2 = """ + > # big endian + ppemX: B + ppemY: B + substitutePpemX: B + substitutePpemY: B +""" + + +class table_E_B_S_C_(DefaultTable.DefaultTable): + """ + Embedded Bitmap Scaling Table + + The ``EBSC`` table provides a mechanism for describing embedded bitmaps which are created by + scaling other embedded bitmaps. While this is the sort of thing that outline font technologies + were invented to avoid, there are cases (small sizes of Kanji, for example) where scaling a bitmap + produces more legible glyphs than scan-converting an outline. For this reason, the EBSC table + allows a font to define a bitmap strike as a scaled version of another strike. + + The ``EBSC`` table is used together with the ``EBDT`` table, which provides embedded monochrome or + grayscale bitmap data, and the ``EBLC`` table, which provides embedded bitmap locators. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/ebsc + """ + + dependencies = ["EBDT", "EBLC"] + + version: float + numSizes: int + bitmapScaleTables: list[BitmapScaleTable] + + def decompile(self, data: bytes, ttFont: TTFont): + _, data = sstruct.unpack2(ebscHeaderFormat, data, self) + self.bitmapScaleTables = [] + for _ in range(self.numSizes): + bitmapScaleTable = BitmapScaleTable() + data = bitmapScaleTable.decompile(data) + self.bitmapScaleTables.append(bitmapScaleTable) + + def compile(self, ttFont: TTFont) -> bytes: + self.numSizes = len(self.bitmapScaleTables) + dataList = [sstruct.pack(ebscHeaderFormat, self)] + for bitmapScaleTable in self.bitmapScaleTables: + dataList.append(bitmapScaleTable.compile()) + return bytesjoin(dataList) + + def toXML(self, writer: XMLWriter, ttFont: TTFont, **kwargs: Any): + writer.simpletag( + "header", + [("version", self.version), ("numSizes", len(self.bitmapScaleTables))], + ) + writer.newline() + for index, bitmapScaleTable in enumerate(self.bitmapScaleTables): + bitmapScaleTable.toXML(index, writer, ttFont) + + def fromXML( + self, name: str, attrs: dict[str, str], content: XMLContent, ttFont: TTFont + ): + if not hasattr(self, "bitmapScaleTables"): + self.bitmapScaleTables = [] + if name == "header": + self.version = safeEval(attrs["version"]) + self.numSizes = safeEval(attrs["numSizes"]) + elif name == "bitmapScaleTable": + bitmapScaleTable = BitmapScaleTable() + bitmapScaleTable.fromXML(content, ttFont) + self.bitmapScaleTables.append(bitmapScaleTable) + + +class BitmapScaleTable: + hori: SbitLineMetrics + vert: SbitLineMetrics + ppemX: int + ppemY: int + substitutePpemX: int + substitutePpemY: int + + def __init__( + self, + hori: SbitLineMetrics | None = None, + vert: SbitLineMetrics | None = None, + ppemX: int = 0, + ppemY: int = 0, + substitutePpemX: int = 0, + substitutePpemY: int = 0, + ): + self.hori = hori if hori is not None else SbitLineMetrics() + self.vert = vert if vert is not None else SbitLineMetrics() + self.ppemX = ppemX + self.ppemY = ppemY + self.substitutePpemX = substitutePpemX + self.substitutePpemY = substitutePpemY + + def decompile(self, data: bytes) -> bytes: + dummy, data = sstruct.unpack2(sbitLineMetricsFormat, data, self.hori) + dummy, data = sstruct.unpack2(sbitLineMetricsFormat, data, self.vert) + dummy, data = sstruct.unpack2(bitmapScaleTableFormatPart2, data, self) + return data + + def compile(self) -> bytes: + dataList = [ + sstruct.pack(sbitLineMetricsFormat, self.hori), + sstruct.pack(sbitLineMetricsFormat, self.vert), + sstruct.pack(bitmapScaleTableFormatPart2, self), + ] + return bytesjoin(dataList) + + def toXML(self, index: int, writer: XMLWriter, ttFont: TTFont): + writer.begintag("bitmapScaleTable", [("index", index)]) + writer.newline() + self.hori.toXML("hori", writer, ttFont) + self.vert.toXML("vert", writer, ttFont) + for name in sstruct.getformat(bitmapScaleTableFormatPart2)[1]: + writer.simpletag(name, value=getattr(self, name)) + writer.newline() + writer.endtag("bitmapScaleTable") + writer.newline() + + def fromXML(self, content: XMLContent, ttFont: TTFont): + dataNames = set(sstruct.getformat(bitmapScaleTableFormatPart2)[1]) + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name == "sbitLineMetrics": + direction = attrs["direction"] + if direction not in ("hori", "vert"): + raise TTLibError( + f"invalid sbitLineMetrics direction: {direction!r}" + ) + metricObj = SbitLineMetrics() + metricObj.fromXML(name, attrs, content, ttFont) + setattr(self, direction, metricObj) + elif name in dataNames: + setattr(self, name, safeEval(attrs["value"])) diff --git a/shared/package-files/35/3534a5022f756e0c5b18a55f07160bfb3f40a54dba76e47de9ae570daea87bdb/maunaloa_c.dat b/shared/package-files/35/3534a5022f756e0c5b18a55f07160bfb3f40a54dba76e47de9ae570daea87bdb/maunaloa_c.dat new file mode 100644 index 0000000000000000000000000000000000000000..a7da9cf2b288245217000ecc8cef0bbbbd469012 --- /dev/null +++ b/shared/package-files/35/3534a5022f756e0c5b18a55f07160bfb3f40a54dba76e47de9ae570daea87bdb/maunaloa_c.dat @@ -0,0 +1,2252 @@ +******************************************************************* +*** Weekly averages derived from continuous air samples *** +*** for the Mauna Loa Observatory, Hawaii, U.S.A. *** +*** *** +*** *** +*** September 2004 *** +*** *** +*** Source: Carbon Dioxide Research Group *** +*** Scripps Institution of Oceanography *** +*** University of California, San Diego *** +*** La Jolla, California, USA 92023-0444 *** +******************************************************************* + +These weekly averages are ultimately based on measurements of 4 air +samples per hour taken atop intake lines on several towers during +steady periods of CO2 concentration of not less than 6 hours per day; +if no such periods are available on a given day, then no data are +used for that day. The "Weight" column gives the number of days used +in each weekly average. Flag codes are explained in the NDP writeup, available +electronically from the home page of this data set. CO2 concentrations +are in terms of the 1999 calibration scale (Keeling et al., 2002) +available electronically from the references in the NDP writeup which +can be accessed from the home page of this data set. + +Station Sample Weight Flag CO2 concentration + code date code (ppmv) + +MLO 580329 4 0 316.10 +MLO 580405 6 0 317.30 +MLO 580412 4 0 317.60 +MLO 580419 6 0 317.50 +MLO 580426 2 0 316.40 +MLO 580503 6 0 316.90 +MLO 580517 1 0 317.50 +MLO 580524 5 0 317.90 +MLO 580705 2 0 315.80 +MLO 580712 4 0 315.80 +MLO 580719 4 0 315.40 +MLO 580726 7 0 315.50 +MLO 580802 3 0 315.60 +MLO 580809 4 0 315.10 +MLO 580816 3 0 315.00 +MLO 580830 5 0 314.10 +MLO 580906 1 0 313.50 +MLO 581108 4 0 313.00 +MLO 581115 7 0 313.20 +MLO 581122 5 0 313.50 +MLO 581129 7 0 314.00 +MLO 581206 6 0 314.50 +MLO 581213 7 0 314.40 +MLO 581220 4 0 314.70 +MLO 581227 2 0 315.20 +MLO 590103 3 0 315.20 +MLO 590110 7 0 315.50 +MLO 590117 7 0 315.60 +MLO 590124 5 0 315.80 +MLO 590131 2 0 315.40 +MLO 590214 1 0 316.90 +MLO 590221 7 0 316.60 +MLO 590228 3 0 316.60 +MLO 590307 7 0 316.80 +MLO 590321 4 0 316.70 +MLO 590328 6 0 316.70 +MLO 590404 7 0 317.70 +MLO 590411 7 0 317.10 +MLO 590418 6 0 317.60 +MLO 590425 5 0 318.30 +MLO 590502 3 0 318.20 +MLO 590509 1 0 318.70 +MLO 590516 7 0 318.00 +MLO 590523 5 0 318.40 +MLO 590606 7 0 318.50 +MLO 590613 5 0 318.10 +MLO 590620 5 0 317.80 +MLO 590627 2 0 317.70 +MLO 590704 7 0 316.80 +MLO 590711 7 0 316.80 +MLO 590718 5 0 316.40 +MLO 590725 4 0 316.10 +MLO 590801 7 0 315.60 +MLO 590808 3 0 314.90 +MLO 590822 1 0 315.00 +MLO 590829 4 0 314.10 +MLO 590905 5 0 314.40 +MLO 590912 3 0 313.90 +MLO 590919 5 0 313.50 +MLO 590926 4 0 313.50 +MLO 591003 6 0 313.00 +MLO 591010 3 0 313.10 +MLO 591017 7 0 313.40 +MLO 591024 7 0 313.40 +MLO 591031 7 0 314.10 +MLO 591107 2 0 314.40 +MLO 591114 5 0 314.80 +MLO 591121 6 0 315.20 +MLO 591128 5 0 315.10 +MLO 591205 4 0 315.00 +MLO 591212 5 0 315.60 +MLO 591219 6 0 315.80 +MLO 591226 6 0 315.70 +MLO 600102 4 0 315.70 +MLO 600109 5 0 316.40 +MLO 600116 6 0 316.70 +MLO 600123 5 0 316.50 +MLO 600130 6 0 316.60 +MLO 600206 2 0 316.60 +MLO 600213 6 0 316.90 +MLO 600220 4 0 317.40 +MLO 600227 5 0 317.00 +MLO 600305 7 0 316.90 +MLO 600312 7 0 317.70 +MLO 600319 4 0 318.00 +MLO 600326 6 0 317.70 +MLO 600402 5 0 318.60 +MLO 600409 3 0 319.30 +MLO 600416 7 0 319.00 +MLO 600423 7 0 319.00 +MLO 600430 1 0 319.70 +MLO 600507 6 0 319.90 +MLO 600514 5 0 319.80 +MLO 600521 6 0 320.00 +MLO 600528 7 0 320.00 +MLO 600604 3 0 319.40 +MLO 600611 5 0 320.00 +MLO 600618 3 0 319.40 +MLO 600625 2 0 319.00 +MLO 600702 5 0 318.10 +MLO 600709 4 0 318.60 +MLO 600716 5 0 318.40 +MLO 600723 6 0 317.90 +MLO 600730 5 0 317.30 +MLO 600806 3 0 316.60 +MLO 600813 6 0 316.70 +MLO 600820 5 0 315.10 +MLO 600827 5 0 314.70 +MLO 600903 7 0 314.70 +MLO 600910 7 0 314.50 +MLO 600917 6 0 314.20 +MLO 600924 5 0 313.30 +MLO 601001 2 0 313.60 +MLO 601008 4 0 313.30 +MLO 601015 5 0 313.90 +MLO 601022 6 0 314.20 +MLO 601029 3 0 314.20 +MLO 601105 7 0 314.50 +MLO 601112 6 0 315.10 +MLO 601119 7 0 315.10 +MLO 601126 7 0 315.40 +MLO 601203 5 0 315.80 +MLO 601210 7 0 316.00 +MLO 601217 7 0 316.20 +MLO 601224 5 0 316.40 +MLO 601231 7 0 316.60 +MLO 610107 6 0 316.70 +MLO 610114 7 0 317.00 +MLO 610121 7 0 317.00 +MLO 610128 7 0 317.00 +MLO 610204 6 0 317.00 +MLO 610211 6 0 317.70 +MLO 610218 7 0 317.90 +MLO 610225 7 0 318.00 +MLO 610304 5 0 318.00 +MLO 610311 4 0 318.50 +MLO 610318 6 0 318.90 +MLO 610325 7 0 318.70 +MLO 610401 7 0 319.40 +MLO 610408 6 0 319.50 +MLO 610415 7 0 318.90 +MLO 610422 6 0 319.70 +MLO 610429 6 0 319.60 +MLO 610506 7 0 320.60 +MLO 610513 3 0 320.40 +MLO 610520 6 0 320.60 +MLO 610527 7 0 320.30 +MLO 610603 6 0 320.00 +MLO 610610 5 0 320.00 +MLO 610617 7 0 319.60 +MLO 610624 6 0 319.40 +MLO 610701 5 0 319.20 +MLO 610708 6 0 319.00 +MLO 610715 5 0 318.40 +MLO 610722 1 0 317.10 +MLO 610729 3 0 317.90 +MLO 610805 7 0 317.90 +MLO 610812 2 0 317.30 +MLO 610819 5 0 316.70 +MLO 610826 6 0 315.20 +MLO 610902 5 0 315.20 +MLO 610909 5 0 314.90 +MLO 610916 5 0 314.50 +MLO 610923 4 0 315.00 +MLO 610930 4 0 315.60 +MLO 611007 5 0 314.90 +MLO 611014 7 0 315.40 +MLO 611021 7 0 315.40 +MLO 611028 6 0 315.70 +MLO 611104 6 0 315.80 +MLO 611111 5 0 315.70 +MLO 611118 7 0 316.20 +MLO 611125 6 0 316.50 +MLO 611202 5 0 316.50 +MLO 611209 5 0 317.00 +MLO 611216 6 0 316.90 +MLO 611223 3 0 317.10 +MLO 611230 7 0 317.40 +MLO 620106 5 0 317.90 +MLO 620113 7 0 318.10 +MLO 620120 5 0 318.00 +MLO 620127 7 0 317.70 +MLO 620203 7 0 318.00 +MLO 620210 4 0 318.30 +MLO 620217 4 0 318.90 +MLO 620224 1 0 319.30 +MLO 620303 6 0 319.20 +MLO 620310 6 0 319.40 +MLO 620317 7 0 319.90 +MLO 620324 4 0 319.70 +MLO 620331 5 0 320.20 +MLO 620407 3 0 320.20 +MLO 620414 6 0 321.00 +MLO 620421 2 0 320.70 +MLO 620428 5 0 320.30 +MLO 620505 4 0 320.80 +MLO 620512 5 0 320.70 +MLO 620519 5 0 321.00 +MLO 620526 5 0 321.10 +MLO 620602 6 0 320.90 +MLO 620609 5 0 320.80 +MLO 620616 6 0 320.50 +MLO 620623 6 0 320.10 +MLO 620630 7 0 320.20 +MLO 620707 6 0 320.10 +MLO 620714 3 0 319.90 +MLO 620721 2 0 319.00 +MLO 620728 7 0 318.70 +MLO 620804 3 0 318.60 +MLO 620811 6 0 317.20 +MLO 620818 3 0 317.40 +MLO 620915 5 0 316.60 +MLO 620922 4 0 315.70 +MLO 620929 7 0 315.90 +MLO 621006 5 0 315.10 +MLO 621013 4 0 315.40 +MLO 621020 5 0 315.70 +MLO 621027 5 0 315.70 +MLO 621103 5 0 315.90 +MLO 621110 6 0 316.40 +MLO 621117 7 0 316.90 +MLO 621124 7 0 317.00 +MLO 621201 7 0 317.10 +MLO 621208 5 0 317.30 +MLO 621215 7 0 317.60 +MLO 621222 4 0 318.10 +MLO 630105 5 0 318.50 +MLO 630112 7 0 318.70 +MLO 630119 7 0 318.90 +MLO 630126 7 0 318.80 +MLO 630202 7 0 318.70 +MLO 630209 7 0 318.90 +MLO 630223 2 0 319.30 +MLO 630302 5 0 319.30 +MLO 630309 6 0 319.70 +MLO 630316 5 0 319.80 +MLO 630323 7 0 320.30 +MLO 630330 5 0 320.20 +MLO 630406 3 0 320.30 +MLO 630413 6 0 320.90 +MLO 630420 6 0 322.00 +MLO 630427 6 0 321.90 +MLO 630511 3 0 321.90 +MLO 630518 5 0 322.20 +MLO 630525 6 0 322.20 +MLO 630601 3 0 322.30 +MLO 630608 2 0 322.00 +MLO 630615 6 0 321.80 +MLO 630622 4 0 320.80 +MLO 630629 7 0 320.40 +MLO 630706 7 0 320.10 +MLO 630713 5 0 319.80 +MLO 630720 7 0 319.50 +MLO 630727 6 0 319.00 +MLO 630803 3 0 318.60 +MLO 630810 7 0 318.20 +MLO 630817 3 0 317.70 +MLO 630824 7 0 317.10 +MLO 630831 3 0 316.40 +MLO 630907 7 0 316.80 +MLO 630914 7 0 315.90 +MLO 630921 5 0 316.00 +MLO 630928 4 0 315.90 +MLO 631005 3 0 316.20 +MLO 631012 7 0 315.60 +MLO 631019 6 0 316.10 +MLO 631026 7 0 316.30 +MLO 631102 4 0 316.60 +MLO 631109 6 0 316.80 +MLO 631116 1 0 317.10 +MLO 631130 5 0 317.50 +MLO 631207 6 0 318.00 +MLO 631214 4 0 318.20 +MLO 631221 7 0 318.50 +MLO 631228 7 0 318.70 +MLO 640104 6 0 319.00 +MLO 640111 6 0 319.40 +MLO 640118 6 0 319.80 +MLO 640530 2 0 322.00 +MLO 640606 4 0 322.00 +MLO 640627 3 0 321.50 +MLO 640704 4 0 321.10 +MLO 640711 2 0 319.90 +MLO 640718 7 0 320.20 +MLO 640725 5 0 320.00 +MLO 640801 2 0 319.10 +MLO 640815 4 0 318.60 +MLO 640822 6 0 318.20 +MLO 640829 5 0 318.10 +MLO 640905 5 0 317.40 +MLO 640912 4 0 316.50 +MLO 640919 2 0 315.50 +MLO 640926 2 0 317.00 +MLO 641003 4 0 316.90 +MLO 641010 7 0 316.50 +MLO 641017 7 0 316.80 +MLO 641024 2 0 317.00 +MLO 641031 6 0 317.60 +MLO 641107 7 0 317.70 +MLO 641114 7 0 317.60 +MLO 641121 6 0 317.50 +MLO 641128 6 0 318.10 +MLO 641205 6 0 318.40 +MLO 641212 7 0 318.50 +MLO 641219 7 0 318.90 +MLO 641226 6 0 318.90 +MLO 650102 5 0 319.00 +MLO 650109 7 0 319.10 +MLO 650116 7 0 319.10 +MLO 650123 4 0 319.70 +MLO 650130 7 0 320.10 +MLO 650206 7 0 320.20 +MLO 650213 7 0 320.10 +MLO 650220 7 0 320.70 +MLO 650227 6 0 320.80 +MLO 650306 5 0 321.00 +MLO 650313 7 0 320.90 +MLO 650320 7 0 320.40 +MLO 650327 7 0 321.40 +MLO 650403 7 0 321.90 +MLO 650410 4 0 322.20 +MLO 650417 7 0 322.10 +MLO 650424 5 0 321.80 +MLO 650501 7 0 322.40 +MLO 650508 6 0 322.20 +MLO 650515 7 0 321.90 +MLO 650522 7 0 321.60 +MLO 650529 5 0 322.20 +MLO 650605 7 0 321.80 +MLO 650612 7 0 321.70 +MLO 650619 7 0 321.70 +MLO 650626 6 0 321.90 +MLO 650703 7 0 321.90 +MLO 650710 6 0 321.80 +MLO 650717 3 0 321.70 +MLO 650724 6 0 320.40 +MLO 650731 5 0 319.40 +MLO 650807 7 0 319.40 +MLO 650814 5 0 318.00 +MLO 650821 6 0 318.80 +MLO 650828 3 0 318.70 +MLO 650904 7 0 318.30 +MLO 650911 4 0 318.00 +MLO 650918 6 0 318.20 +MLO 650925 6 0 316.80 +MLO 651002 6 0 316.60 +MLO 651009 7 0 317.20 +MLO 651016 7 0 317.80 +MLO 651023 7 0 317.50 +MLO 651030 7 0 317.60 +MLO 651106 7 0 318.30 +MLO 651113 7 0 319.20 +MLO 651120 7 0 318.90 +MLO 651127 7 0 319.10 +MLO 651204 7 0 319.00 +MLO 651211 5 0 319.30 +MLO 651218 6 0 319.30 +MLO 651225 6 0 319.70 +MLO 660101 7 0 319.60 +MLO 660108 7 0 320.40 +MLO 660115 7 0 320.60 +MLO 660122 7 0 321.00 +MLO 660129 7 0 321.10 +MLO 660205 7 0 321.20 +MLO 660212 6 0 321.70 +MLO 660219 7 0 321.60 +MLO 660226 7 0 321.80 +MLO 660305 4 0 322.10 +MLO 660312 5 0 322.10 +MLO 660319 6 0 322.50 +MLO 660326 5 0 322.80 +MLO 660402 7 0 323.50 +MLO 660409 3 0 323.60 +MLO 660416 7 0 323.80 +MLO 660423 4 0 323.90 +MLO 660430 6 0 323.50 +MLO 660507 6 0 324.00 +MLO 660514 7 0 324.10 +MLO 660521 7 0 323.70 +MLO 660528 7 0 324.30 +MLO 660604 7 0 324.00 +MLO 660611 7 0 323.80 +MLO 660618 7 0 323.70 +MLO 660625 6 0 323.30 +MLO 660702 5 0 322.80 +MLO 660709 6 0 322.90 +MLO 660806 4 0 321.30 +MLO 660813 3 0 320.80 +MLO 660820 3 0 319.10 +MLO 660827 7 0 319.60 +MLO 660903 4 0 319.90 +MLO 660910 3 0 318.20 +MLO 660917 7 0 318.40 +MLO 660924 5 0 318.30 +MLO 661001 6 0 317.90 +MLO 661008 7 0 317.90 +MLO 661015 4 0 318.20 +MLO 661022 4 0 318.60 +MLO 661029 6 0 318.30 +MLO 661112 4 0 319.50 +MLO 661119 5 0 320.00 +MLO 661126 6 0 320.20 +MLO 661203 3 0 320.80 +MLO 661210 7 0 320.80 +MLO 661217 5 0 321.10 +MLO 661224 4 0 321.30 +MLO 661231 7 0 321.30 +MLO 670107 6 0 321.90 +MLO 670114 2 0 322.90 +MLO 670204 5 0 322.10 +MLO 670211 5 0 322.20 +MLO 670218 6 0 322.80 +MLO 670225 4 0 322.60 +MLO 670304 6 0 322.90 +MLO 670311 6 0 322.60 +MLO 670318 4 0 323.30 +MLO 670325 2 0 323.20 +MLO 670401 3 0 323.10 +MLO 670408 7 0 324.20 +MLO 670415 5 0 324.40 +MLO 670422 3 0 324.60 +MLO 670429 6 0 325.10 +MLO 670506 1 0 325.20 +MLO 670513 5 0 324.70 +MLO 670520 5 0 325.00 +MLO 670527 5 0 324.90 +MLO 670603 4 0 324.90 +MLO 670610 6 0 324.60 +MLO 670617 4 0 323.30 +MLO 670624 6 0 323.50 +MLO 670701 6 0 322.80 +MLO 670708 7 0 322.80 +MLO 670715 5 0 322.40 +MLO 670722 5 0 322.40 +MLO 670729 6 0 322.00 +MLO 670805 7 0 321.60 +MLO 670812 5 0 321.40 +MLO 670819 5 0 320.40 +MLO 670826 5 0 320.00 +MLO 670902 4 0 320.00 +MLO 670909 6 0 319.40 +MLO 670916 7 0 319.30 +MLO 670923 7 0 319.00 +MLO 670930 7 0 318.80 +MLO 671007 7 0 318.80 +MLO 671014 6 0 319.80 +MLO 671021 7 0 319.40 +MLO 671028 7 0 319.80 +MLO 671104 7 0 320.00 +MLO 671111 7 0 320.30 +MLO 671118 7 0 320.90 +MLO 671125 7 0 321.50 +MLO 671202 7 0 321.40 +MLO 671209 7 0 321.80 +MLO 671216 7 0 322.20 +MLO 671223 7 0 321.90 +MLO 671230 7 0 322.30 +MLO 680106 7 0 322.40 +MLO 680113 7 0 322.50 +MLO 680120 6 0 322.50 +MLO 680127 7 0 322.80 +MLO 680203 7 0 322.60 +MLO 680210 7 0 323.10 +MLO 680217 7 0 323.40 +MLO 680224 7 0 323.10 +MLO 680302 6 0 323.10 +MLO 680309 4 0 323.80 +MLO 680316 6 0 323.80 +MLO 680323 6 0 324.20 +MLO 680330 5 0 324.70 +MLO 680406 7 0 324.70 +MLO 680413 6 0 325.00 +MLO 680420 5 0 324.80 +MLO 680427 7 0 325.40 +MLO 680504 7 0 325.60 +MLO 680511 7 0 325.00 +MLO 680518 6 0 325.50 +MLO 680525 7 0 325.80 +MLO 680601 5 0 325.60 +MLO 680608 7 0 325.70 +MLO 680615 4 0 325.50 +MLO 680622 4 0 324.90 +MLO 680629 5 0 324.60 +MLO 680706 6 0 324.70 +MLO 680713 7 0 324.10 +MLO 680720 7 0 323.90 +MLO 680727 7 0 323.40 +MLO 680803 5 0 322.40 +MLO 680810 5 0 322.20 +MLO 680817 3 0 322.00 +MLO 680824 6 0 321.70 +MLO 680831 6 0 321.40 +MLO 680907 7 0 320.40 +MLO 680914 7 0 321.10 +MLO 680921 7 0 319.70 +MLO 680928 7 0 319.80 +MLO 681005 7 0 320.50 +MLO 681012 6 0 320.50 +MLO 681019 7 0 320.20 +MLO 681026 7 0 319.90 +MLO 681102 5 0 320.70 +MLO 681109 7 0 320.80 +MLO 681116 7 0 321.40 +MLO 681123 7 0 321.70 +MLO 681130 6 0 322.00 +MLO 681207 4 0 322.40 +MLO 681214 7 0 322.90 +MLO 681221 5 0 323.30 +MLO 681228 6 0 323.10 +MLO 690104 6 0 323.30 +MLO 690111 6 0 324.00 +MLO 690118 6 0 324.30 +MLO 690125 7 0 324.10 +MLO 690201 7 0 324.10 +MLO 690208 5 0 323.90 +MLO 690215 5 0 324.30 +MLO 690222 5 0 324.80 +MLO 690301 7 0 325.10 +MLO 690308 7 0 325.50 +MLO 690315 7 0 325.70 +MLO 690322 6 0 325.90 +MLO 690329 7 0 325.80 +MLO 690405 7 0 326.20 +MLO 690412 7 0 327.10 +MLO 690419 6 0 326.50 +MLO 690426 6 0 326.50 +MLO 690503 7 0 327.50 +MLO 690510 7 0 327.80 +MLO 690517 6 0 326.80 +MLO 690524 7 0 326.90 +MLO 690531 5 0 327.40 +MLO 690607 6 0 326.50 +MLO 690614 4 0 326.70 +MLO 690621 5 0 326.70 +MLO 690628 7 0 326.30 +MLO 690705 6 0 326.10 +MLO 690712 7 0 326.00 +MLO 690719 6 0 325.70 +MLO 690726 4 0 325.40 +MLO 690802 5 0 324.50 +MLO 690809 7 0 324.50 +MLO 690816 7 0 323.10 +MLO 690823 5 0 322.50 +MLO 690830 7 0 323.10 +MLO 690906 6 0 322.20 +MLO 690913 6 0 322.70 +MLO 690920 4 0 322.80 +MLO 690927 7 0 321.90 +MLO 691004 7 0 321.50 +MLO 691011 7 0 321.80 +MLO 691018 7 0 322.00 +MLO 691025 7 0 321.90 +MLO 691101 7 0 322.20 +MLO 691108 7 0 322.60 +MLO 691115 7 0 322.70 +MLO 691122 7 0 323.10 +MLO 691129 7 0 323.50 +MLO 691206 7 0 323.90 +MLO 691213 7 0 323.90 +MLO 691220 7 0 324.20 +MLO 691227 7 0 324.50 +MLO 700103 7 0 324.70 +MLO 700110 7 0 325.40 +MLO 700117 7 0 325.00 +MLO 700124 7 0 324.80 +MLO 700131 7 0 325.50 +MLO 700207 7 0 325.70 +MLO 700214 7 0 326.00 +MLO 700221 6 0 326.30 +MLO 700228 7 0 326.10 +MLO 700307 7 0 326.80 +MLO 700314 7 0 326.80 +MLO 700321 7 0 327.50 +MLO 700328 7 0 326.90 +MLO 700404 7 0 328.20 +MLO 700411 7 0 327.80 +MLO 700418 7 0 327.80 +MLO 700425 7 0 328.50 +MLO 700502 7 0 327.90 +MLO 700509 5 0 327.50 +MLO 700516 5 0 328.00 +MLO 700523 7 0 328.30 +MLO 700530 6 0 327.90 +MLO 700606 7 0 327.50 +MLO 700613 7 0 327.80 +MLO 700620 7 0 327.70 +MLO 700627 6 0 327.20 +MLO 700704 6 0 327.20 +MLO 700711 6 0 326.20 +MLO 700718 6 0 326.20 +MLO 700725 7 0 325.60 +MLO 700801 5 0 325.20 +MLO 700808 3 0 325.20 +MLO 700815 6 0 324.80 +MLO 700822 5 0 324.80 +MLO 700829 5 0 323.30 +MLO 700905 7 0 322.90 +MLO 700912 4 0 323.50 +MLO 700919 4 0 323.10 +MLO 700926 5 0 323.10 +MLO 701003 5 0 323.20 +MLO 701010 6 0 323.50 +MLO 701017 4 0 322.90 +MLO 701024 7 0 323.00 +MLO 701031 5 0 323.10 +MLO 701107 7 0 323.60 +MLO 701114 5 0 323.70 +MLO 701121 7 0 324.20 +MLO 701128 7 0 324.70 +MLO 701205 7 0 324.70 +MLO 701212 7 0 325.00 +MLO 701219 7 0 325.20 +MLO 701226 3 0 325.50 +MLO 710102 6 0 325.70 +MLO 710109 7 0 325.80 +MLO 710116 7 0 325.90 +MLO 710123 6 0 326.70 +MLO 710130 7 0 326.60 +MLO 710206 7 0 326.50 +MLO 710213 7 0 326.40 +MLO 710220 7 0 326.70 +MLO 710227 7 0 327.00 +MLO 710306 6 0 327.10 +MLO 710313 6 0 327.30 +MLO 710320 7 0 327.00 +MLO 710327 7 0 327.40 +MLO 710403 6 0 327.40 +MLO 710410 6 0 327.10 +MLO 710417 7 0 327.70 +MLO 710424 7 0 328.50 +MLO 710501 7 0 328.20 +MLO 710508 7 0 329.00 +MLO 710515 7 0 329.20 +MLO 710522 7 0 328.90 +MLO 710529 6 0 328.80 +MLO 710605 6 0 328.50 +MLO 710612 7 0 328.80 +MLO 710619 7 0 328.10 +MLO 710626 7 0 328.50 +MLO 710703 7 0 327.90 +MLO 710710 6 0 327.80 +MLO 710717 7 0 327.50 +MLO 710724 6 0 326.20 +MLO 710731 2 0 326.70 +MLO 710807 7 0 326.10 +MLO 710814 2 0 325.60 +MLO 710821 6 0 325.30 +MLO 710828 6 0 324.00 +MLO 710904 7 0 323.60 +MLO 710911 7 0 323.50 +MLO 710918 4 0 323.20 +MLO 710925 7 0 323.30 +MLO 711002 7 0 323.30 +MLO 711009 1 0 322.90 +MLO 711016 7 0 323.50 +MLO 711023 7 0 323.60 +MLO 711030 7 0 324.40 +MLO 711106 7 0 324.30 +MLO 711113 7 0 324.50 +MLO 711120 7 0 325.00 +MLO 711127 7 0 325.50 +MLO 711204 7 0 325.30 +MLO 711211 7 0 325.90 +MLO 711218 7 0 326.20 +MLO 711225 7 0 326.30 +MLO 720101 6 0 326.60 +MLO 720108 7 0 326.60 +MLO 720115 7 0 326.60 +MLO 720122 7 0 326.60 +MLO 720129 7 0 327.20 +MLO 720205 7 0 327.40 +MLO 720212 7 0 327.90 +MLO 720219 7 0 327.80 +MLO 720226 7 0 327.40 +MLO 720304 7 0 327.50 +MLO 720311 6 0 327.10 +MLO 720318 7 0 327.70 +MLO 720325 4 0 328.60 +MLO 720401 6 0 328.90 +MLO 720408 7 0 329.40 +MLO 720415 7 0 329.80 +MLO 720422 7 0 330.10 +MLO 720429 6 0 330.00 +MLO 720506 7 0 330.00 +MLO 720513 7 0 329.70 +MLO 720520 7 0 330.10 +MLO 720527 7 0 330.20 +MLO 720603 7 0 329.70 +MLO 720610 5 0 329.10 +MLO 720617 7 0 329.00 +MLO 720624 7 0 328.50 +MLO 720701 7 0 328.60 +MLO 720708 7 0 328.30 +MLO 720715 7 0 327.70 +MLO 720722 5 0 328.10 +MLO 720729 5 0 327.50 +MLO 720805 7 0 326.90 +MLO 720812 7 0 326.60 +MLO 720819 7 0 326.50 +MLO 720826 7 0 325.00 +MLO 720902 7 0 325.40 +MLO 720909 7 0 325.70 +MLO 720916 7 0 324.80 +MLO 720923 7 0 324.20 +MLO 720930 6 0 324.20 +MLO 721007 6 0 324.80 +MLO 721014 5 0 325.50 +MLO 721021 7 0 325.10 +MLO 721028 7 0 325.80 +MLO 721104 7 0 326.30 +MLO 721111 6 0 326.10 +MLO 721118 7 0 326.40 +MLO 721125 7 0 326.90 +MLO 721202 7 0 326.90 +MLO 721209 7 0 327.10 +MLO 721216 7 0 327.60 +MLO 721223 6 0 327.90 +MLO 721230 7 0 328.20 +MLO 730106 5 0 328.40 +MLO 730113 7 0 328.40 +MLO 730120 5 0 328.60 +MLO 730127 7 0 328.80 +MLO 730203 6 0 329.10 +MLO 730210 7 0 329.50 +MLO 730217 7 0 329.60 +MLO 730224 7 0 329.70 +MLO 730303 6 0 329.90 +MLO 730310 7 0 330.10 +MLO 730317 5 0 330.50 +MLO 730324 4 0 330.80 +MLO 730331 7 0 330.60 +MLO 730407 7 0 331.20 +MLO 730414 7 0 331.10 +MLO 730421 6 0 331.90 +MLO 730428 4 0 332.10 +MLO 730505 7 0 332.20 +MLO 730512 7 0 332.30 +MLO 730519 7 0 332.60 +MLO 730526 6 0 332.50 +MLO 730602 6 0 332.20 +MLO 730609 7 0 332.50 +MLO 730616 7 0 332.00 +MLO 730623 7 0 331.60 +MLO 730630 4 0 331.40 +MLO 730707 6 0 331.50 +MLO 730714 5 0 331.00 +MLO 730721 5 0 330.00 +MLO 730728 3 0 330.10 +MLO 730804 4 0 330.00 +MLO 730811 5 0 329.50 +MLO 730818 4 0 329.30 +MLO 730825 6 0 328.50 +MLO 730901 5 0 328.40 +MLO 730908 5 0 327.60 +MLO 730915 5 0 327.80 +MLO 730922 5 0 327.10 +MLO 730929 2 0 326.60 +MLO 731006 7 0 327.00 +MLO 731013 4 0 327.40 +MLO 731020 7 0 327.40 +MLO 731027 6 0 327.10 +MLO 731103 4 0 327.50 +MLO 731110 5 0 328.00 +MLO 731117 6 0 328.20 +MLO 731124 5 0 328.50 +MLO 731201 6 0 329.00 +MLO 731208 2 0 328.70 +MLO 731215 7 0 328.60 +MLO 731222 7 0 328.20 +MLO 731229 5 0 328.70 +MLO 740105 7 0 328.90 +MLO 740112 7 0 329.20 +MLO 740119 6 0 329.40 +MLO 740126 6 0 329.80 +MLO 740202 7 0 330.50 +MLO 740209 7 0 330.80 +MLO 740216 7 0 330.60 +MLO 740223 7 0 330.60 +MLO 740302 7 0 330.70 +MLO 740309 6 0 331.20 +MLO 740316 7 0 332.10 +MLO 740323 7 0 332.00 +MLO 740330 7 0 331.50 +MLO 740406 7 0 332.40 +MLO 740413 7 0 332.10 +MLO 740420 7 0 332.90 +MLO 740427 7 0 333.10 +MLO 740504 7 0 332.90 +MLO 740511 7 0 333.00 +MLO 740518 7 0 333.20 +MLO 740525 7 0 332.80 +MLO 740601 7 0 332.90 +MLO 740608 6 0 332.00 +MLO 740615 5 0 332.00 +MLO 740622 6 0 332.20 +MLO 740629 5 0 331.70 +MLO 740706 6 0 331.70 +MLO 740713 7 0 331.20 +MLO 740720 5 0 330.40 +MLO 740727 3 0 331.00 +MLO 740803 6 0 330.00 +MLO 740810 5 0 329.90 +MLO 740817 6 0 329.20 +MLO 740824 6 0 328.90 +MLO 740831 7 0 328.10 +MLO 740907 7 0 328.00 +MLO 740914 7 0 327.30 +MLO 740921 7 0 326.90 +MLO 740928 7 0 327.30 +MLO 741005 6 0 327.30 +MLO 741012 6 0 327.00 +MLO 741019 7 0 327.50 +MLO 741026 7 0 327.70 +MLO 741102 7 0 327.90 +MLO 741109 7 0 328.00 +MLO 741116 6 0 328.80 +MLO 741123 6 0 328.60 +MLO 741130 3 0 328.70 +MLO 741207 2 0 329.50 +MLO 741214 4 0 329.70 +MLO 741221 7 0 329.80 +MLO 741228 7 0 329.70 +MLO 750104 4 0 329.90 +MLO 750111 4 0 329.80 +MLO 750118 4 0 330.20 +MLO 750125 7 0 331.10 +MLO 750201 6 0 331.10 +MLO 750208 7 0 331.40 +MLO 750215 7 0 331.00 +MLO 750222 5 0 331.70 +MLO 750301 7 0 331.80 +MLO 750308 7 0 331.60 +MLO 750315 7 0 331.90 +MLO 750322 7 0 332.20 +MLO 750329 6 0 332.50 +MLO 750405 7 0 333.00 +MLO 750412 6 0 333.50 +MLO 750419 7 0 333.50 +MLO 750426 7 0 333.10 +MLO 750503 7 0 333.90 +MLO 750510 7 0 333.90 +MLO 750517 7 0 333.70 +MLO 750524 7 0 333.70 +MLO 750531 7 0 334.10 +MLO 750607 7 0 333.80 +MLO 750614 6 0 333.30 +MLO 750621 7 0 333.40 +MLO 750628 7 0 333.10 +MLO 750705 5 0 332.70 +MLO 750712 7 0 332.00 +MLO 750719 5 0 331.00 +MLO 750726 6 0 331.50 +MLO 750802 7 0 330.80 +MLO 750809 7 0 330.70 +MLO 750816 5 0 330.30 +MLO 750823 6 0 329.30 +MLO 750830 6 0 328.80 +MLO 750906 6 0 329.40 +MLO 750913 6 0 328.50 +MLO 750920 7 0 328.00 +MLO 750927 6 0 328.20 +MLO 751004 6 0 328.00 +MLO 751011 5 0 328.00 +MLO 751018 6 0 328.50 +MLO 751025 6 0 328.80 +MLO 751101 4 0 329.30 +MLO 751108 6 0 329.20 +MLO 751115 5 0 329.10 +MLO 751122 3 0 329.50 +MLO 751129 5 0 330.10 +MLO 751206 7 0 330.30 +MLO 751213 7 0 330.50 +MLO 751220 5 0 331.10 +MLO 751227 5 0 331.20 +MLO 760103 7 0 331.50 +MLO 760110 7 0 331.50 +MLO 760117 7 0 331.70 +MLO 760124 7 0 331.80 +MLO 760131 5 0 332.20 +MLO 760207 6 0 332.10 +MLO 760214 7 0 332.50 +MLO 760221 6 0 333.20 +MLO 760228 5 0 332.40 +MLO 760306 7 0 332.80 +MLO 760313 7 0 333.60 +MLO 760320 3 0 333.10 +MLO 760327 7 0 334.30 +MLO 760403 7 0 334.70 +MLO 760410 6 0 334.20 +MLO 760417 6 0 334.40 +MLO 760424 6 0 334.50 +MLO 760501 6 0 334.70 +MLO 760508 5 0 334.30 +MLO 760515 7 0 334.60 +MLO 760522 6 0 335.40 +MLO 760529 7 0 334.80 +MLO 760605 7 0 334.30 +MLO 760612 7 0 334.60 +MLO 760619 6 0 334.30 +MLO 760703 6 0 333.60 +MLO 760710 6 0 333.40 +MLO 760717 4 0 332.80 +MLO 760724 7 0 332.40 +MLO 760731 6 0 332.10 +MLO 760807 6 0 331.70 +MLO 760814 6 0 330.60 +MLO 760821 5 0 330.60 +MLO 760828 1 0 330.00 +MLO 760904 5 0 329.70 +MLO 760911 4 0 330.00 +MLO 760918 7 0 329.30 +MLO 760925 5 0 328.40 +MLO 761002 4 0 328.80 +MLO 761009 4 0 329.00 +MLO 761016 3 0 329.60 +MLO 761023 6 0 329.10 +MLO 761030 7 0 329.00 +MLO 761106 5 0 329.80 +MLO 761113 5 0 330.40 +MLO 761120 7 0 330.50 +MLO 761127 7 0 330.70 +MLO 761204 7 0 331.10 +MLO 761211 6 0 331.30 +MLO 761218 6 0 331.90 +MLO 761225 7 0 332.20 +MLO 770101 7 0 332.50 +MLO 770108 7 0 332.40 +MLO 770115 5 0 333.10 +MLO 770122 7 0 333.20 +MLO 770129 5 0 333.20 +MLO 770205 5 0 333.40 +MLO 770212 6 0 333.30 +MLO 770219 7 0 333.40 +MLO 770226 7 0 333.60 +MLO 770305 6 0 334.10 +MLO 770312 7 0 334.60 +MLO 770319 7 0 335.10 +MLO 770326 7 0 335.00 +MLO 770402 7 0 335.50 +MLO 770409 7 0 335.90 +MLO 770416 7 0 336.00 +MLO 770423 7 0 336.10 +MLO 770430 7 0 336.70 +MLO 770507 7 0 336.80 +MLO 770514 7 0 336.40 +MLO 770521 7 0 336.80 +MLO 770528 7 0 336.70 +MLO 770604 7 0 336.40 +MLO 770611 6 0 336.30 +MLO 770618 7 0 336.10 +MLO 770625 7 0 336.00 +MLO 770702 6 0 335.50 +MLO 770709 6 0 335.10 +MLO 770716 4 0 335.10 +MLO 770723 5 0 334.60 +MLO 770730 3 0 333.70 +MLO 770806 7 0 333.00 +MLO 770813 2 0 332.90 +MLO 770820 1 0 332.80 +MLO 770827 2 0 332.80 +MLO 770903 3 0 332.10 +MLO 770910 1 0 331.20 +MLO 770917 2 0 332.10 +MLO 770924 2 0 330.90 +MLO 771001 3 0 330.40 +MLO 771008 5 0 330.90 +MLO 771015 4 0 331.50 +MLO 771022 1 0 331.50 +MLO 771029 2 0 331.70 +MLO 771105 4 0 332.10 +MLO 771112 2 0 332.00 +MLO 771119 2 0 332.50 +MLO 771126 5 0 332.80 +MLO 771203 6 0 333.20 +MLO 771210 6 0 333.50 +MLO 771217 7 0 333.80 +MLO 771224 6 0 334.20 +MLO 771231 7 0 334.60 +MLO 780107 7 0 334.20 +MLO 780114 7 0 334.60 +MLO 780121 7 0 335.40 +MLO 780128 5 0 335.90 +MLO 780204 7 0 335.00 +MLO 780211 6 0 335.10 +MLO 780218 7 0 335.60 +MLO 780225 7 0 335.70 +MLO 780304 7 0 336.20 +MLO 780311 7 0 336.10 +MLO 780318 5 0 336.80 +MLO 780325 7 0 337.30 +MLO 780401 4 0 337.00 +MLO 780408 6 0 337.90 +MLO 780415 6 0 337.90 +MLO 780422 5 0 337.40 +MLO 780429 7 0 338.00 +MLO 780506 6 0 338.00 +MLO 780513 7 0 338.10 +MLO 780520 7 0 337.80 +MLO 780527 7 0 337.90 +MLO 780603 1 0 338.40 +MLO 780610 2 0 338.20 +MLO 780617 4 0 337.80 +MLO 780624 5 0 337.30 +MLO 780701 2 0 337.60 +MLO 780708 6 0 336.70 +MLO 780715 7 0 336.70 +MLO 780722 7 0 335.90 +MLO 780729 6 0 335.60 +MLO 780805 7 0 335.10 +MLO 780812 7 0 334.80 +MLO 780819 2 0 334.40 +MLO 780826 4 0 334.30 +MLO 780902 4 0 333.80 +MLO 780909 4 0 332.80 +MLO 780916 5 0 332.10 +MLO 780923 3 0 332.30 +MLO 780930 6 0 332.70 +MLO 781007 5 0 332.10 +MLO 781014 4 0 332.40 +MLO 781021 4 0 333.00 +MLO 781028 3 0 333.10 +MLO 781104 6 0 333.50 +MLO 781111 5 0 333.80 +MLO 781118 4 0 333.80 +MLO 781125 5 0 334.20 +MLO 781202 2 0 334.50 +MLO 781209 6 0 334.80 +MLO 781216 6 0 335.10 +MLO 781223 6 0 335.10 +MLO 781230 7 0 335.30 +MLO 790106 7 0 335.30 +MLO 790113 6 0 335.90 +MLO 790120 7 0 336.80 +MLO 790127 5 0 336.90 +MLO 790203 6 0 336.90 +MLO 790210 5 0 336.50 +MLO 790217 7 0 336.70 +MLO 790224 7 0 336.70 +MLO 790303 6 0 337.10 +MLO 790310 5 0 337.70 +MLO 790317 4 0 337.40 +MLO 790324 5 0 339.00 +MLO 790331 7 0 338.80 +MLO 790407 4 0 338.10 +MLO 790414 7 0 338.60 +MLO 790421 7 0 339.20 +MLO 790428 6 0 339.60 +MLO 790505 7 0 339.30 +MLO 790512 5 0 338.80 +MLO 790519 5 0 339.80 +MLO 790526 7 0 339.60 +MLO 790602 4 0 339.90 +MLO 790609 6 0 339.50 +MLO 790616 5 0 338.90 +MLO 790623 5 0 338.90 +MLO 790630 2 0 339.00 +MLO 790707 4 0 338.20 +MLO 790714 6 0 337.80 +MLO 790721 6 0 337.30 +MLO 790728 5 0 336.80 +MLO 790804 5 0 337.00 +MLO 790811 7 0 336.50 +MLO 790818 6 0 336.10 +MLO 790825 5 0 334.50 +MLO 790901 7 0 334.40 +MLO 790908 3 0 334.00 +MLO 790915 4 0 334.20 +MLO 790922 5 0 333.20 +MLO 790929 5 0 334.10 +MLO 791006 4 0 334.10 +MLO 791013 6 0 333.90 +MLO 791020 7 0 333.70 +MLO 791027 5 0 334.10 +MLO 791103 6 0 334.70 +MLO 791110 6 0 334.80 +MLO 791117 6 0 335.50 +MLO 791124 5 0 335.60 +MLO 791201 6 0 335.90 +MLO 791208 4 0 336.50 +MLO 791215 6 0 336.70 +MLO 791222 6 0 336.80 +MLO 791229 7 0 337.40 +MLO 800105 7 0 337.60 +MLO 800112 6 0 337.40 +MLO 800119 7 0 338.30 +MLO 800126 7 0 338.40 +MLO 800202 6 0 338.00 +MLO 800209 5 0 338.10 +MLO 800216 7 0 338.60 +MLO 800223 6 0 338.20 +MLO 800301 6 0 339.30 +MLO 800308 6 0 339.50 +MLO 800315 6 0 340.00 +MLO 800322 6 0 340.50 +MLO 800329 7 0 341.00 +MLO 800405 4 0 340.40 +MLO 800412 4 0 340.90 +MLO 800419 6 0 340.70 +MLO 800426 6 0 341.00 +MLO 800503 5 0 341.50 +MLO 800510 6 0 341.30 +MLO 800517 5 0 341.30 +MLO 800524 5 0 340.90 +MLO 800531 7 0 341.70 +MLO 800607 3 0 341.30 +MLO 800614 7 0 341.30 +MLO 800621 6 0 340.80 +MLO 800628 3 0 340.40 +MLO 800705 6 0 340.40 +MLO 800712 5 0 339.70 +MLO 800719 3 0 338.50 +MLO 800726 6 0 338.90 +MLO 800802 6 0 337.90 +MLO 800809 5 0 337.70 +MLO 800816 4 0 337.70 +MLO 800823 3 0 337.70 +MLO 800830 3 0 337.00 +MLO 800906 4 0 336.60 +MLO 800913 4 0 335.70 +MLO 800920 5 0 335.20 +MLO 800927 4 0 336.00 +MLO 801004 4 0 335.80 +MLO 801011 7 0 335.80 +MLO 801018 7 0 336.10 +MLO 801025 5 0 336.40 +MLO 801101 7 0 336.60 +MLO 801108 7 0 336.90 +MLO 801115 6 0 337.10 +MLO 801122 7 0 337.30 +MLO 801129 7 0 337.40 +MLO 801206 4 0 337.70 +MLO 801213 7 0 338.10 +MLO 801220 7 0 338.30 +MLO 801227 7 0 338.70 +MLO 810103 7 0 338.90 +MLO 810110 7 0 339.10 +MLO 810117 7 0 339.30 +MLO 810124 7 0 339.30 +MLO 810131 6 0 339.50 +MLO 810207 7 0 340.50 +MLO 810214 4 0 340.00 +MLO 810221 5 0 340.20 +MLO 810228 6 0 341.10 +MLO 810307 4 0 340.70 +MLO 810314 6 0 341.00 +MLO 810321 5 0 341.80 +MLO 810328 6 0 342.10 +MLO 810404 5 0 342.40 +MLO 810411 6 0 342.40 +MLO 810418 7 0 342.70 +MLO 810425 7 0 342.30 +MLO 810502 7 0 342.90 +MLO 810509 7 0 343.00 +MLO 810516 7 0 342.80 +MLO 810523 7 0 342.70 +MLO 810530 7 0 342.70 +MLO 810606 7 0 342.60 +MLO 810613 7 0 342.50 +MLO 810620 7 0 341.80 +MLO 810627 5 0 341.60 +MLO 810704 5 0 341.00 +MLO 810711 7 0 340.80 +MLO 810718 4 0 339.70 +MLO 810725 4 0 340.20 +MLO 810801 5 0 339.50 +MLO 810808 5 0 338.90 +MLO 810815 6 0 338.40 +MLO 810822 5 0 337.50 +MLO 810829 4 0 337.70 +MLO 810905 7 0 337.20 +MLO 810912 3 0 337.00 +MLO 810919 7 0 336.70 +MLO 810926 5 0 335.90 +MLO 811003 6 0 336.30 +MLO 811010 4 0 336.60 +MLO 811017 7 0 337.10 +MLO 811024 5 0 337.20 +MLO 811031 6 0 337.50 +MLO 811107 6 0 337.80 +MLO 811114 6 0 338.10 +MLO 811121 4 0 338.50 +MLO 811128 6 0 339.30 +MLO 811205 5 0 339.20 +MLO 811212 7 0 339.40 +MLO 811219 6 0 339.60 +MLO 811226 4 0 340.20 +MLO 820102 5 0 340.20 +MLO 820109 7 0 340.30 +MLO 820116 5 0 340.70 +MLO 820123 6 0 341.10 +MLO 820130 7 0 341.20 +MLO 820206 7 0 341.90 +MLO 820213 6 0 341.10 +MLO 820220 4 0 341.10 +MLO 820227 5 0 342.10 +MLO 820306 6 0 342.60 +MLO 820313 4 0 342.60 +MLO 820320 1 0 342.70 +MLO 820327 4 0 342.80 +MLO 820403 6 0 342.90 +MLO 820410 6 0 343.30 +MLO 820417 6 0 343.50 +MLO 820424 5 0 344.20 +MLO 820501 4 0 343.80 +MLO 820508 1 0 343.60 +MLO 820515 3 0 344.20 +MLO 820522 6 0 344.10 +MLO 820529 6 0 344.10 +MLO 820605 6 0 343.40 +MLO 820612 7 0 343.50 +MLO 820619 3 0 343.40 +MLO 820626 4 0 342.90 +MLO 820703 7 0 342.50 +MLO 820710 6 0 342.00 +MLO 820717 5 0 342.00 +MLO 820724 4 0 341.80 +MLO 820731 6 0 341.30 +MLO 820807 6 0 340.50 +MLO 820814 6 0 340.00 +MLO 820821 3 0 339.70 +MLO 820828 5 0 338.30 +MLO 820904 5 0 338.80 +MLO 820911 6 0 338.60 +MLO 820918 2 0 337.80 +MLO 820925 6 0 336.90 +MLO 821002 4 0 337.30 +MLO 821009 5 0 338.00 +MLO 821016 4 0 337.60 +MLO 821023 4 0 337.90 +MLO 821030 5 0 338.70 +MLO 821106 5 0 338.40 +MLO 821113 6 0 339.20 +MLO 821120 6 0 339.70 +MLO 821127 4 0 339.80 +MLO 821204 6 0 339.80 +MLO 821211 5 0 340.40 +MLO 821218 7 0 340.70 +MLO 821225 5 0 340.80 +MLO 830101 5 0 340.90 +MLO 830108 5 0 341.40 +MLO 830115 6 0 341.50 +MLO 830122 7 0 341.20 +MLO 830129 7 0 341.70 +MLO 830205 6 0 342.00 +MLO 830212 7 0 342.70 +MLO 830219 6 0 342.50 +MLO 830226 6 0 342.80 +MLO 830305 7 0 342.30 +MLO 830312 7 0 342.50 +MLO 830319 5 0 344.00 +MLO 830326 5 0 343.80 +MLO 830402 7 0 344.00 +MLO 830409 6 0 344.80 +MLO 830416 7 0 345.00 +MLO 830423 7 0 345.30 +MLO 830430 7 0 345.40 +MLO 830507 5 0 345.40 +MLO 830514 6 0 345.70 +MLO 830521 6 0 345.80 +MLO 830528 7 0 345.70 +MLO 830604 5 0 345.60 +MLO 830611 5 0 345.60 +MLO 830618 7 0 345.00 +MLO 830625 6 0 344.90 +MLO 830702 6 0 344.70 +MLO 830709 4 0 344.50 +MLO 830716 3 0 343.70 +MLO 830723 6 0 343.60 +MLO 830730 4 0 342.60 +MLO 830806 5 0 343.00 +MLO 830813 2 0 341.70 +MLO 830820 3 0 342.10 +MLO 830827 6 0 341.80 +MLO 830903 3 0 339.90 +MLO 830910 5 0 339.90 +MLO 830917 5 0 339.80 +MLO 830924 4 0 339.90 +MLO 831001 6 0 339.80 +MLO 831008 7 0 339.70 +MLO 831015 6 0 340.10 +MLO 831022 6 0 340.20 +MLO 831029 7 0 340.30 +MLO 831105 7 0 340.80 +MLO 831112 7 0 341.00 +MLO 831119 6 0 341.10 +MLO 831126 7 0 341.70 +MLO 831203 6 0 341.80 +MLO 831210 2 0 342.80 +MLO 831217 7 0 343.30 +MLO 831224 7 0 343.60 +MLO 831231 7 0 343.40 +MLO 840107 7 0 343.70 +MLO 840114 5 0 343.40 +MLO 840121 5 0 343.50 +MLO 840128 5 0 344.10 +MLO 840204 5 0 344.30 +MLO 840211 7 0 344.50 +MLO 840218 5 0 344.30 +MLO 840225 6 0 344.60 +MLO 840303 7 0 344.80 +MLO 840310 6 0 344.90 +MLO 840317 6 0 345.40 +MLO 840324 5 0 345.60 +MLO 840428 2 0 347.40 +MLO 840505 6 0 347.40 +MLO 840512 3 0 347.70 +MLO 840519 5 0 347.30 +MLO 840526 5 0 347.00 +MLO 840602 5 0 347.00 +MLO 840609 6 0 347.00 +MLO 840616 3 0 346.80 +MLO 840623 5 0 346.30 +MLO 840630 6 0 346.20 +MLO 840707 4 0 345.80 +MLO 840714 5 0 345.40 +MLO 840721 3 0 345.20 +MLO 840728 6 0 344.40 +MLO 840804 2 0 344.00 +MLO 840811 2 0 344.10 +MLO 840818 5 0 343.10 +MLO 840825 3 0 342.00 +MLO 840901 3 0 341.60 +MLO 840908 6 0 340.60 +MLO 840915 6 0 341.30 +MLO 840922 6 0 341.30 +MLO 840929 3 0 340.80 +MLO 841006 5 0 341.10 +MLO 841013 4 0 341.30 +MLO 841020 1 0 341.90 +MLO 841027 5 0 341.60 +MLO 841103 5 0 342.00 +MLO 841110 6 0 342.60 +MLO 841117 6 0 343.10 +MLO 841124 6 0 343.70 +MLO 841201 4 0 343.60 +MLO 841208 6 0 343.90 +MLO 841215 4 0 344.20 +MLO 841222 5 0 344.50 +MLO 841229 3 0 344.50 +MLO 850105 7 0 344.70 +MLO 850112 6 0 345.00 +MLO 850119 7 0 345.00 +MLO 850126 5 0 345.00 +MLO 850202 5 0 345.90 +MLO 850209 4 0 345.50 +MLO 850216 5 0 345.80 +MLO 850223 5 0 346.30 +MLO 850302 6 0 346.70 +MLO 850309 6 0 347.10 +MLO 850316 7 0 347.50 +MLO 850323 4 0 347.70 +MLO 850330 5 0 348.20 +MLO 850406 7 0 348.00 +MLO 850413 4 0 348.00 +MLO 850420 5 0 348.50 +MLO 850427 4 0 348.80 +MLO 850504 5 0 348.80 +MLO 850511 5 0 349.30 +MLO 850518 7 0 349.10 +MLO 850525 6 0 348.10 +MLO 850601 4 0 349.00 +MLO 850608 7 0 348.40 +MLO 850615 3 0 348.20 +MLO 850622 5 0 347.90 +MLO 850629 6 0 347.40 +MLO 850706 6 0 346.90 +MLO 850713 5 0 346.80 +MLO 850720 3 0 346.40 +MLO 850727 6 0 345.70 +MLO 850810 6 0 344.70 +MLO 850817 3 0 344.50 +MLO 850824 5 0 344.30 +MLO 850831 5 0 343.70 +MLO 850907 5 0 344.20 +MLO 850914 6 0 343.30 +MLO 850921 5 0 342.40 +MLO 850928 5 0 342.10 +MLO 851005 4 0 342.40 +MLO 851012 4 0 342.50 +MLO 851019 7 0 343.10 +MLO 851026 6 0 343.20 +MLO 851102 5 0 343.30 +MLO 851109 5 0 343.70 +MLO 851116 7 0 344.20 +MLO 851123 6 0 344.60 +MLO 851130 6 0 345.30 +MLO 851207 5 0 345.30 +MLO 851214 6 0 345.60 +MLO 851221 6 0 345.10 +MLO 851228 7 0 346.30 +MLO 860104 4 0 346.40 +MLO 860111 7 0 346.00 +MLO 860118 4 0 346.20 +MLO 860125 7 0 346.40 +MLO 860201 6 0 346.20 +MLO 860208 6 0 346.80 +MLO 860215 7 0 347.10 +MLO 860222 7 0 347.20 +MLO 860301 7 0 347.00 +MLO 860308 3 0 346.60 +MLO 860315 6 0 347.20 +MLO 860322 6 0 349.10 +MLO 860329 6 0 348.80 +MLO 860405 7 0 349.20 +MLO 860412 4 0 349.40 +MLO 860419 6 0 349.30 +MLO 860426 6 0 350.20 +MLO 860503 4 0 349.90 +MLO 860510 5 0 350.10 +MLO 860517 5 0 350.20 +MLO 860524 6 0 350.10 +MLO 860531 6 0 350.10 +MLO 860607 4 0 349.70 +MLO 860614 6 0 349.50 +MLO 860621 7 0 349.40 +MLO 860628 7 0 348.90 +MLO 860705 7 0 348.60 +MLO 860712 5 0 347.70 +MLO 860719 6 0 347.60 +MLO 860726 6 0 347.40 +MLO 860802 3 0 346.60 +MLO 860809 5 0 346.20 +MLO 860816 7 0 345.50 +MLO 860823 5 0 345.60 +MLO 860830 4 0 345.20 +MLO 860906 4 0 345.00 +MLO 860913 7 0 345.30 +MLO 860920 5 0 344.40 +MLO 860927 6 0 344.50 +MLO 861004 7 0 343.90 +MLO 861011 7 0 344.10 +MLO 861018 3 0 343.90 +MLO 861025 7 0 344.50 +MLO 861101 6 0 345.10 +MLO 861108 5 0 345.30 +MLO 861115 7 0 345.60 +MLO 861122 6 0 345.70 +MLO 861129 7 0 346.40 +MLO 861206 7 0 346.90 +MLO 861213 7 0 346.70 +MLO 861220 7 0 346.90 +MLO 861227 6 0 347.00 +MLO 870103 6 0 347.60 +MLO 870110 6 0 348.30 +MLO 870117 7 0 348.20 +MLO 870124 5 0 347.90 +MLO 870131 6 0 348.00 +MLO 870207 7 0 347.90 +MLO 870214 6 0 348.20 +MLO 870221 7 0 348.50 +MLO 870228 7 0 349.40 +MLO 870307 7 0 348.80 +MLO 870314 7 0 349.20 +MLO 870321 7 0 349.70 +MLO 870328 7 0 350.20 +MLO 870404 6 0 350.80 +MLO 870411 5 0 350.20 +MLO 870418 7 0 351.10 +MLO 870425 7 0 351.30 +MLO 870502 6 0 351.40 +MLO 870509 7 0 352.00 +MLO 870516 7 0 351.70 +MLO 870523 7 0 351.90 +MLO 870530 7 0 351.70 +MLO 870606 6 0 351.60 +MLO 870613 7 0 351.10 +MLO 870620 6 0 351.00 +MLO 870627 5 0 350.90 +MLO 870704 7 0 349.70 +MLO 870711 7 0 349.80 +MLO 870718 3 0 348.80 +MLO 870725 5 0 349.50 +MLO 870801 4 0 349.00 +MLO 870808 2 0 348.10 +MLO 870815 3 0 348.60 +MLO 870822 5 0 348.00 +MLO 870829 5 0 346.70 +MLO 870905 4 0 347.00 +MLO 870912 6 0 346.60 +MLO 870919 6 0 346.20 +MLO 870926 3 0 345.80 +MLO 871003 4 0 345.70 +MLO 871010 5 0 346.30 +MLO 871017 5 0 346.50 +MLO 871024 7 0 346.80 +MLO 871031 6 0 346.90 +MLO 871107 4 0 347.30 +MLO 871114 7 0 347.60 +MLO 871121 3 0 348.10 +MLO 871128 3 0 348.70 +MLO 871205 5 0 348.60 +MLO 871212 5 0 348.80 +MLO 871219 5 0 349.10 +MLO 871226 5 0 349.20 +MLO 880102 6 0 349.70 +MLO 880109 7 0 350.20 +MLO 880116 5 0 350.20 +MLO 880123 5 0 350.70 +MLO 880130 5 0 351.20 +MLO 880206 4 0 351.80 +MLO 880213 7 0 351.30 +MLO 880220 6 0 351.50 +MLO 880227 7 0 352.50 +MLO 880305 6 0 352.80 +MLO 880312 7 0 351.80 +MLO 880319 4 0 351.70 +MLO 880326 5 0 352.20 +MLO 880402 6 0 353.10 +MLO 880409 7 0 353.50 +MLO 880416 7 0 353.10 +MLO 880423 5 0 354.00 +MLO 880430 4 0 354.20 +MLO 880507 7 0 353.70 +MLO 880514 5 0 354.30 +MLO 880521 6 0 354.50 +MLO 880528 6 0 354.20 +MLO 880604 5 0 354.10 +MLO 880611 6 0 354.20 +MLO 880618 6 0 353.60 +MLO 880625 7 0 353.10 +MLO 880702 4 0 353.00 +MLO 880709 4 0 352.50 +MLO 880716 4 0 352.60 +MLO 880723 5 0 351.90 +MLO 880730 3 0 351.10 +MLO 880806 5 0 350.90 +MLO 880813 3 0 350.30 +MLO 880820 4 0 350.40 +MLO 880827 6 0 349.60 +MLO 880903 5 0 349.30 +MLO 880910 5 0 348.70 +MLO 880917 5 0 348.90 +MLO 880924 4 0 348.10 +MLO 881001 4 0 348.80 +MLO 881008 3 0 348.80 +MLO 881015 7 0 348.60 +MLO 881022 3 0 349.40 +MLO 881029 5 0 349.20 +MLO 881105 7 0 349.70 +MLO 881112 7 0 349.80 +MLO 881119 5 0 350.10 +MLO 881126 7 0 350.40 +MLO 881203 5 0 350.50 +MLO 881210 5 0 351.00 +MLO 881217 4 0 351.60 +MLO 881224 6 0 351.30 +MLO 881231 7 0 352.40 +MLO 890107 7 0 352.70 +MLO 890114 6 0 352.90 +MLO 890121 7 0 352.50 +MLO 890128 7 0 353.00 +MLO 890204 5 0 352.80 +MLO 890211 5 0 352.60 +MLO 890218 6 0 353.20 +MLO 890225 7 0 353.40 +MLO 890304 7 0 353.10 +MLO 890311 6 0 353.40 +MLO 890318 6 0 353.50 +MLO 890325 7 0 354.40 +MLO 890401 7 0 354.50 +MLO 890408 7 0 355.00 +MLO 890415 4 0 355.40 +MLO 890422 7 0 356.00 +MLO 890429 6 0 355.90 +MLO 890506 6 0 355.30 +MLO 890513 5 0 355.80 +MLO 890520 6 0 355.60 +MLO 890527 4 0 355.70 +MLO 890603 6 0 355.80 +MLO 890610 6 0 355.00 +MLO 890617 7 0 354.80 +MLO 890624 5 0 354.90 +MLO 890701 6 0 354.50 +MLO 890708 4 0 354.70 +MLO 890715 7 0 353.80 +MLO 890722 6 0 353.10 +MLO 890729 6 0 353.20 +MLO 890805 6 0 352.60 +MLO 890812 6 0 352.20 +MLO 890819 5 0 351.10 +MLO 890826 5 0 350.40 +MLO 890902 7 0 350.70 +MLO 890909 5 0 350.20 +MLO 890916 6 0 349.40 +MLO 890923 7 0 349.30 +MLO 890930 1 0 349.70 +MLO 891007 6 0 349.90 +MLO 891014 6 0 349.70 +MLO 891021 6 0 350.20 +MLO 891028 7 0 350.40 +MLO 891104 7 0 350.60 +MLO 891111 6 0 351.20 +MLO 891118 7 0 351.60 +MLO 891125 5 0 351.40 +MLO 891202 6 0 352.00 +MLO 891209 4 0 352.10 +MLO 891216 6 0 352.40 +MLO 891223 5 0 352.50 +MLO 891230 4 0 353.40 +MLO 900106 7 0 353.40 +MLO 900113 7 0 353.50 +MLO 900120 7 0 353.80 +MLO 900127 7 0 353.90 +MLO 900203 7 0 354.10 +MLO 900210 5 0 355.00 +MLO 900217 7 0 354.80 +MLO 900224 7 0 354.70 +MLO 900303 3 0 355.70 +MLO 900310 5 0 354.90 +MLO 900317 7 0 355.80 +MLO 900324 6 0 355.10 +MLO 900331 6 0 355.90 +MLO 900407 7 0 356.10 +MLO 900414 7 0 355.90 +MLO 900421 6 0 356.60 +MLO 900428 4 0 356.10 +MLO 900505 5 0 357.30 +MLO 900512 5 0 357.00 +MLO 900519 7 0 356.90 +MLO 900526 6 0 357.10 +MLO 900602 6 0 357.00 +MLO 900609 7 0 356.60 +MLO 900616 5 0 355.60 +MLO 900623 7 0 355.50 +MLO 900630 7 0 355.70 +MLO 900707 7 0 355.50 +MLO 900714 7 0 354.00 +MLO 900721 6 0 354.50 +MLO 900728 5 0 354.70 +MLO 900804 5 0 353.50 +MLO 900811 5 0 353.20 +MLO 900818 7 0 352.90 +MLO 900825 5 0 352.00 +MLO 900901 4 0 350.90 +MLO 900908 3 0 350.70 +MLO 900915 6 0 351.30 +MLO 900922 6 0 350.90 +MLO 900929 3 0 350.90 +MLO 901006 2 0 351.10 +MLO 901013 7 0 351.00 +MLO 901020 4 0 351.40 +MLO 901027 3 0 351.40 +MLO 901103 5 0 352.10 +MLO 901110 7 0 352.60 +MLO 901117 6 0 353.00 +MLO 901124 5 0 353.10 +MLO 901201 7 0 353.60 +MLO 901208 6 0 354.00 +MLO 901215 6 0 353.80 +MLO 901222 7 0 354.50 +MLO 901229 6 0 354.80 +MLO 910105 7 0 354.20 +MLO 910112 7 0 354.70 +MLO 910119 6 0 354.80 +MLO 910126 7 0 355.00 +MLO 910202 7 0 355.20 +MLO 910209 6 0 355.20 +MLO 910216 7 0 356.40 +MLO 910223 6 0 355.80 +MLO 910302 7 0 356.40 +MLO 910309 7 0 357.20 +MLO 910316 6 0 357.60 +MLO 910323 7 0 356.90 +MLO 910330 5 0 357.90 +MLO 910406 7 0 358.30 +MLO 910413 7 0 357.80 +MLO 910420 6 0 359.10 +MLO 910427 7 0 359.20 +MLO 910504 7 0 359.10 +MLO 910511 7 0 358.90 +MLO 910518 7 0 360.00 +MLO 910525 7 0 359.00 +MLO 910601 7 0 358.50 +MLO 910608 6 0 358.40 +MLO 910615 6 0 358.20 +MLO 910622 5 0 358.10 +MLO 910629 5 0 357.70 +MLO 910706 6 0 357.20 +MLO 910713 5 0 356.50 +MLO 910720 7 0 355.20 +MLO 910727 5 0 355.30 +MLO 910803 4 0 354.80 +MLO 910810 5 0 354.60 +MLO 910817 5 0 353.70 +MLO 910824 7 0 353.00 +MLO 910831 6 0 353.20 +MLO 910907 4 0 353.00 +MLO 910914 7 0 352.10 +MLO 910921 6 0 351.80 +MLO 910928 5 0 351.60 +MLO 911005 7 0 351.70 +MLO 911012 6 0 352.10 +MLO 911019 6 0 352.50 +MLO 911026 7 0 352.70 +MLO 911102 6 0 353.40 +MLO 911109 7 0 353.70 +MLO 911116 7 0 353.50 +MLO 911123 7 0 353.80 +MLO 911130 7 0 354.30 +MLO 911207 4 0 354.50 +MLO 911214 7 0 354.90 +MLO 911221 6 0 355.20 +MLO 911228 6 0 355.50 +MLO 920104 6 0 355.60 +MLO 920111 7 0 356.00 +MLO 920118 4 0 356.10 +MLO 920125 7 0 355.90 +MLO 920201 5 0 356.00 +MLO 920208 7 0 356.70 +MLO 920215 6 0 357.30 +MLO 920222 4 0 356.90 +MLO 920229 7 0 356.50 +MLO 920307 7 0 357.30 +MLO 920314 5 0 357.80 +MLO 920321 6 0 358.10 +MLO 920328 6 0 358.40 +MLO 920404 7 0 358.50 +MLO 920411 5 0 358.90 +MLO 920418 5 0 359.70 +MLO 920425 6 0 359.20 +MLO 920502 7 0 359.60 +MLO 920509 7 0 359.70 +MLO 920516 7 0 358.60 +MLO 920523 7 0 359.60 +MLO 920530 7 0 360.20 +MLO 920606 7 0 360.00 +MLO 920613 4 0 359.40 +MLO 920620 7 0 358.70 +MLO 920627 7 0 358.40 +MLO 920704 5 0 358.40 +MLO 920711 5 0 357.20 +MLO 920718 5 0 356.30 +MLO 920725 5 0 356.10 +MLO 920801 2 0 354.90 +MLO 920808 6 0 355.30 +MLO 920815 6 0 355.30 +MLO 920822 4 0 354.50 +MLO 920829 3 0 354.30 +MLO 920905 5 0 353.50 +MLO 920912 6 0 353.60 +MLO 920919 7 0 352.30 +MLO 920926 7 0 352.70 +MLO 921003 6 0 353.60 +MLO 921010 5 0 353.30 +MLO 921017 7 0 353.20 +MLO 921024 7 0 353.50 +MLO 921031 7 0 353.50 +MLO 921107 7 0 353.90 +MLO 921114 6 0 353.80 +MLO 921121 7 0 354.50 +MLO 921128 7 0 354.60 +MLO 921205 7 0 354.80 +MLO 921212 7 0 355.30 +MLO 921219 7 0 355.40 +MLO 921226 6 0 355.90 +MLO 930102 6 0 356.20 +MLO 930109 5 0 356.90 +MLO 930116 6 0 356.70 +MLO 930123 6 0 356.60 +MLO 930130 7 0 357.00 +MLO 930206 7 0 356.60 +MLO 930213 7 0 357.20 +MLO 930220 7 0 357.30 +MLO 930227 5 0 357.60 +MLO 930306 6 0 358.30 +MLO 930313 5 0 358.50 +MLO 930320 7 0 358.10 +MLO 930327 4 0 358.80 +MLO 930403 7 0 359.10 +MLO 930410 6 0 358.80 +MLO 930417 7 0 359.40 +MLO 930424 7 0 360.00 +MLO 930501 6 0 359.60 +MLO 930508 7 0 359.70 +MLO 930515 6 0 360.70 +MLO 930522 6 0 360.60 +MLO 930529 7 0 360.30 +MLO 930605 7 0 359.70 +MLO 930612 7 0 359.90 +MLO 930619 7 0 359.30 +MLO 930626 6 0 359.10 +MLO 930703 6 0 357.90 +MLO 930710 7 0 358.00 +MLO 930717 4 0 358.10 +MLO 930724 5 0 356.60 +MLO 930731 5 0 356.50 +MLO 930807 6 0 355.80 +MLO 930814 5 0 355.90 +MLO 930821 4 0 354.90 +MLO 930828 4 0 354.70 +MLO 930904 1 0 354.30 +MLO 930911 6 0 353.20 +MLO 930918 6 0 353.80 +MLO 930925 6 0 353.80 +MLO 931002 5 0 353.80 +MLO 931009 6 0 353.80 +MLO 931016 6 0 354.00 +MLO 931023 6 0 354.40 +MLO 931030 7 0 354.30 +MLO 931106 6 0 354.70 +MLO 931113 7 0 355.10 +MLO 931120 7 0 355.60 +MLO 931127 7 0 356.00 +MLO 931204 6 0 356.20 +MLO 931211 7 0 356.50 +MLO 931218 7 0 356.90 +MLO 931225 2 0 357.50 +MLO 940101 6 0 358.10 +MLO 940108 6 0 358.10 +MLO 940115 7 0 358.40 +MLO 940122 7 0 358.30 +MLO 940129 7 0 358.70 +MLO 940205 5 0 358.40 +MLO 940212 6 0 358.60 +MLO 940219 7 0 359.00 +MLO 940226 5 0 359.60 +MLO 940305 6 0 358.70 +MLO 940312 7 0 359.80 +MLO 940319 7 0 360.40 +MLO 940326 6 0 360.80 +MLO 940402 7 0 360.60 +MLO 940409 7 0 361.00 +MLO 940416 7 0 361.00 +MLO 940423 5 0 361.30 +MLO 940430 6 0 362.20 +MLO 940507 5 0 361.60 +MLO 940514 6 0 361.40 +MLO 940521 2 0 361.70 +MLO 940528 4 0 361.90 +MLO 940604 6 0 361.00 +MLO 940611 6 0 361.00 +MLO 940618 6 0 360.90 +MLO 940625 6 0 360.70 +MLO 940702 6 0 360.20 +MLO 940709 7 0 359.90 +MLO 940716 7 0 359.40 +MLO 940723 7 0 359.00 +MLO 940730 5 0 358.80 +MLO 940806 6 0 358.10 +MLO 940813 1 0 357.50 +MLO 940820 4 0 357.60 +MLO 940827 6 0 356.30 +MLO 940903 7 0 356.40 +MLO 940910 6 0 356.40 +MLO 940917 7 0 355.40 +MLO 940924 7 0 355.50 +MLO 941001 7 0 355.40 +MLO 941008 7 0 355.80 +MLO 941015 7 0 356.00 +MLO 941022 7 0 356.30 +MLO 941029 7 0 356.60 +MLO 941105 7 0 356.90 +MLO 941112 5 0 357.40 +MLO 941119 7 0 357.90 +MLO 941126 7 0 358.10 +MLO 941203 7 0 358.40 +MLO 941210 7 0 359.10 +MLO 941217 7 0 359.20 +MLO 941224 7 0 359.10 +MLO 941231 7 0 359.50 +MLO 950107 4 0 359.60 +MLO 950114 7 0 360.20 +MLO 950121 6 0 360.10 +MLO 950128 7 0 360.00 +MLO 950204 6 0 360.60 +MLO 950211 6 0 361.00 +MLO 950218 7 0 360.80 +MLO 950225 7 0 361.30 +MLO 950304 6 0 362.20 +MLO 950311 7 0 361.20 +MLO 950318 5 0 360.90 +MLO 950325 5 0 362.00 +MLO 950401 7 0 363.80 +MLO 950408 7 0 363.40 +MLO 950415 7 0 363.30 +MLO 950422 7 0 362.80 +MLO 950429 6 0 363.50 +MLO 950506 7 0 363.20 +MLO 950513 7 0 364.10 +MLO 950520 7 0 364.10 +MLO 950527 7 0 363.40 +MLO 950603 6 0 363.90 +MLO 950610 7 0 363.40 +MLO 950617 6 0 362.90 +MLO 950624 7 0 362.80 +MLO 950701 6 0 362.50 +MLO 950708 5 0 362.20 +MLO 950715 6 0 361.90 +MLO 950722 6 0 361.50 +MLO 950729 7 0 360.90 +MLO 950805 7 0 360.40 +MLO 950812 5 0 359.20 +MLO 950819 7 0 358.70 +MLO 950826 6 0 359.20 +MLO 950902 4 0 357.30 +MLO 950909 7 0 358.50 +MLO 950916 6 0 358.50 +MLO 950923 6 0 358.20 +MLO 950930 7 0 357.50 +MLO 951007 7 0 357.60 +MLO 951014 7 0 357.60 +MLO 951021 7 0 358.00 +MLO 951028 6 0 358.20 +MLO 951104 6 0 359.10 +MLO 951111 6 0 359.40 +MLO 951118 7 0 359.60 +MLO 951125 7 0 359.80 +MLO 951202 7 0 360.10 +MLO 951209 7 0 360.40 +MLO 951216 7 0 360.50 +MLO 951223 6 0 360.80 +MLO 951230 5 0 361.70 +MLO 960106 7 0 361.80 +MLO 960113 7 0 362.00 +MLO 960120 7 0 362.10 +MLO 960127 4 0 362.20 +MLO 960203 7 0 362.60 +MLO 960210 7 0 363.10 +MLO 960217 7 0 363.00 +MLO 960224 7 0 364.00 +MLO 960302 6 0 363.80 +MLO 960309 7 0 363.60 +MLO 960316 7 0 364.10 +MLO 960323 6 0 364.50 +MLO 960330 7 0 364.30 +MLO 960406 7 0 364.50 +MLO 960413 7 0 364.80 +MLO 960420 7 0 364.40 +MLO 960427 7 0 365.10 +MLO 960504 7 0 364.90 +MLO 960511 6 0 365.30 +MLO 960518 7 0 365.70 +MLO 960525 7 0 365.40 +MLO 960601 7 0 364.80 +MLO 960608 5 0 365.10 +MLO 960615 7 0 365.20 +MLO 960622 7 0 365.00 +MLO 960629 7 0 364.30 +MLO 960706 7 0 364.10 +MLO 960713 7 0 363.70 +MLO 960720 7 0 363.30 +MLO 960727 7 0 362.80 +MLO 960803 7 0 361.70 +MLO 960810 6 0 362.10 +MLO 960817 7 0 361.20 +MLO 960824 7 0 360.80 +MLO 960831 7 0 360.80 +MLO 960907 4 0 359.80 +MLO 960914 6 0 359.80 +MLO 960921 7 0 359.00 +MLO 960928 6 0 359.00 +MLO 961005 7 0 359.40 +MLO 961012 5 0 359.50 +MLO 961019 4 0 359.80 +MLO 961026 6 0 359.80 +MLO 961102 4 0 359.90 +MLO 961109 7 0 360.50 +MLO 961116 5 0 360.70 +MLO 961123 7 0 361.20 +MLO 961130 4 0 361.40 +MLO 961207 6 0 361.90 +MLO 961214 5 0 362.60 +MLO 961221 7 0 362.40 +MLO 961228 7 0 362.60 +MLO 970104 7 0 362.90 +MLO 970111 7 0 363.00 +MLO 970118 5 0 363.10 +MLO 970125 7 0 363.50 +MLO 970201 7 0 363.20 +MLO 970208 6 0 364.10 +MLO 970215 6 0 364.00 +MLO 970222 5 0 364.20 +MLO 970301 4 0 364.50 +MLO 970308 4 0 364.10 +MLO 970315 7 0 364.10 +MLO 970322 6 0 364.70 +MLO 970329 7 0 365.40 +MLO 970405 7 0 365.80 +MLO 970412 6 0 366.20 +MLO 970419 3 0 366.60 +MLO 970426 6 0 366.70 +MLO 970503 7 0 366.70 +MLO 970510 7 0 366.80 +MLO 970517 7 0 367.00 +MLO 970524 6 0 366.60 +MLO 970531 6 0 366.30 +MLO 970607 7 0 365.70 +MLO 970614 5 0 365.60 +MLO 970621 7 0 365.50 +MLO 970628 6 0 365.10 +MLO 970705 7 0 365.00 +MLO 970712 7 0 364.60 +MLO 970719 6 0 364.10 +MLO 970726 7 0 363.80 +MLO 970802 5 0 363.30 +MLO 970809 4 0 363.30 +MLO 970816 4 0 362.60 +MLO 970823 7 0 361.50 +MLO 970830 6 0 361.60 +MLO 970906 7 0 360.60 +MLO 970913 7 0 360.20 +MLO 970920 7 0 360.00 +MLO 970927 7 0 359.80 +MLO 971004 7 0 360.50 +MLO 971011 7 0 360.40 +MLO 971018 7 0 361.00 +MLO 971025 6 0 361.10 +MLO 971101 7 0 361.70 +MLO 971108 7 0 362.10 +MLO 971115 7 0 362.00 +MLO 971122 6 0 362.60 +MLO 971129 7 0 363.50 +MLO 971206 7 0 363.90 +MLO 971213 6 0 363.90 +MLO 971220 7 0 364.20 +MLO 971227 7 0 365.00 +MLO 980103 6 0 365.20 +MLO 980110 7 0 365.30 +MLO 980117 7 0 365.30 +MLO 980124 7 0 365.30 +MLO 980131 7 0 365.60 +MLO 980207 7 0 366.00 +MLO 980214 7 0 365.50 +MLO 980221 3 0 366.00 +MLO 980228 5 0 367.30 +MLO 980307 7 0 367.00 +MLO 980314 7 0 366.60 +MLO 980321 7 0 367.40 +MLO 980328 7 0 368.50 +MLO 980404 7 0 368.60 +MLO 980411 6 0 368.60 +MLO 980418 7 0 368.00 +MLO 980425 7 0 368.90 +MLO 980502 6 0 369.10 +MLO 980509 4 0 368.80 +MLO 980516 6 0 368.50 +MLO 980523 7 0 369.60 +MLO 980530 7 0 369.70 +MLO 980606 6 0 369.40 +MLO 980613 7 0 368.80 +MLO 980620 6 0 368.50 +MLO 980627 6 0 368.30 +MLO 980704 6 0 368.00 +MLO 980711 7 0 367.50 +MLO 980718 5 0 367.60 +MLO 980725 7 0 367.30 +MLO 980801 7 0 366.80 +MLO 980808 6 0 366.40 +MLO 980815 6 0 365.60 +MLO 980822 3 0 365.60 +MLO 980829 4 0 364.20 +MLO 980905 7 0 364.70 +MLO 980912 7 0 363.90 +MLO 980919 7 0 363.50 +MLO 980926 7 0 363.60 +MLO 981003 7 0 364.00 +MLO 981010 7 0 364.10 +MLO 981017 7 0 364.40 +MLO 981024 7 0 364.40 +MLO 981031 6 0 364.70 +MLO 981107 7 0 365.00 +MLO 981114 7 0 365.40 +MLO 981121 7 0 365.80 +MLO 981128 7 0 366.00 +MLO 981205 7 0 366.40 +MLO 981212 6 0 366.70 +MLO 981219 7 0 367.30 +MLO 981226 7 0 367.30 +MLO 990102 7 0 367.50 +MLO 990109 7 0 367.80 +MLO 990116 7 0 367.80 +MLO 990123 7 0 368.30 +MLO 990130 7 0 369.20 +MLO 990206 7 0 369.10 +MLO 990213 7 0 368.80 +MLO 990220 7 0 369.00 +MLO 990227 7 0 368.50 +MLO 990306 7 0 368.10 +MLO 990313 7 0 369.50 +MLO 990320 7 0 370.20 +MLO 990327 7 0 370.60 +MLO 990403 7 0 371.10 +MLO 990410 7 0 371.50 +MLO 990417 7 0 371.00 +MLO 990424 6 0 370.30 +MLO 990501 6 0 370.80 +MLO 990508 7 0 371.30 +MLO 990515 6 0 371.00 +MLO 990522 4 0 370.80 +MLO 990529 6 0 370.30 +MLO 990605 6 0 370.90 +MLO 990612 7 0 370.30 +MLO 990619 7 0 369.90 +MLO 990626 7 0 369.90 +MLO 990703 5 0 369.40 +MLO 990710 7 0 370.10 +MLO 990717 7 0 369.50 +MLO 990724 6 0 368.60 +MLO 990731 6 0 367.40 +MLO 990807 7 0 367.60 +MLO 990814 6 0 366.70 +MLO 990821 7 0 366.40 +MLO 990828 7 0 366.10 +MLO 990904 7 0 364.10 +MLO 990911 7 0 364.70 +MLO 990918 6 0 365.20 +MLO 990925 7 0 364.70 +MLO 991002 7 0 364.50 +MLO 991009 6 0 365.00 +MLO 991016 7 0 364.90 +MLO 991023 7 0 365.60 +MLO 991030 7 0 365.70 +MLO 991106 7 0 366.20 +MLO 991113 7 0 366.70 +MLO 991120 5 0 366.60 +MLO 991127 7 0 367.10 +MLO 991204 7 0 367.40 +MLO 991211 7 0 368.00 +MLO 991218 7 0 368.00 +MLO 991225 7 0 368.20 +MLO 000101 7 0 368.60 +MLO 000108 7 0 368.50 +MLO 000115 6 0 369.00 +MLO 000122 5 0 369.80 +MLO 000129 6 0 369.20 +MLO 000205 5 0 369.10 +MLO 000212 7 0 369.60 +MLO 000219 7 0 369.30 +MLO 000226 7 0 369.50 +MLO 000304 6 0 370.00 +MLO 000311 7 0 370.00 +MLO 000318 7 0 370.90 +MLO 000325 7 0 370.70 +MLO 000401 7 0 370.90 +MLO 000408 6 0 371.70 +MLO 000415 6 0 371.80 +MLO 000422 7 0 372.00 +MLO 000429 7 0 371.30 +MLO 000506 7 0 371.20 +MLO 000513 7 0 371.70 +MLO 000520 7 0 371.90 +MLO 000527 7 0 371.80 +MLO 000603 6 0 371.90 +MLO 000610 7 0 371.60 +MLO 000617 7 0 371.70 +MLO 000624 4 0 371.30 +MLO 000701 7 0 370.80 +MLO 000708 6 0 370.00 +MLO 000715 7 0 370.20 +MLO 000722 7 0 369.70 +MLO 000729 6 0 369.00 +MLO 000805 6 0 368.70 +MLO 000812 7 0 368.30 +MLO 000819 5 0 367.70 +MLO 000826 6 0 367.10 +MLO 000902 7 0 367.20 +MLO 000909 4 0 366.70 +MLO 000916 4 0 366.20 +MLO 000923 7 0 366.20 +MLO 000930 7 0 366.40 +MLO 001007 7 0 366.30 +MLO 001014 7 0 366.60 +MLO 001021 7 0 366.70 +MLO 001028 7 0 367.30 +MLO 001104 6 0 367.60 +MLO 001111 7 0 368.00 +MLO 001118 7 0 368.60 +MLO 001125 7 0 368.30 +MLO 001202 5 0 369.00 +MLO 001209 6 0 369.60 +MLO 001216 6 0 369.30 +MLO 001223 7 0 369.50 +MLO 001230 7 0 369.80 +MLO 010106 6 0 369.80 +MLO 010113 4 0 370.20 +MLO 010120 7 0 369.90 +MLO 010127 7 0 370.80 +MLO 010203 6 0 371.30 +MLO 010210 7 0 371.10 +MLO 010217 7 0 371.70 +MLO 010224 7 0 371.20 +MLO 010303 6 0 372.20 +MLO 010310 7 0 372.20 +MLO 010317 6 0 372.10 +MLO 010324 6 0 371.80 +MLO 010331 6 0 372.00 +MLO 010407 7 0 372.70 +MLO 010414 7 0 372.70 +MLO 010421 7 0 373.00 +MLO 010428 7 0 372.70 +MLO 010505 5 0 373.70 +MLO 010512 7 0 373.90 +MLO 010519 5 0 373.70 +MLO 010526 7 0 373.90 +MLO 010602 6 0 373.80 +MLO 010609 7 0 373.10 +MLO 010616 7 0 372.80 +MLO 010623 7 0 372.90 +MLO 010630 6 0 372.70 +MLO 010707 4 0 372.10 +MLO 010714 7 0 371.30 +MLO 010721 4 0 371.20 +MLO 010728 6 0 370.60 +MLO 010804 6 0 369.90 +MLO 010811 7 0 369.50 +MLO 010818 6 0 369.30 +MLO 010825 7 0 369.00 +MLO 010901 6 0 368.40 +MLO 010908 7 0 368.20 +MLO 010915 7 0 368.00 +MLO 010922 7 0 367.40 +MLO 010929 7 0 367.40 +MLO 011006 7 0 367.80 +MLO 011013 7 0 367.60 +MLO 011020 7 0 368.10 +MLO 011027 6 0 368.70 +MLO 011103 7 0 368.70 +MLO 011110 3 0 368.80 +MLO 011117 7 0 369.70 +MLO 011124 7 0 370.30 +MLO 011201 7 0 370.30 +MLO 011208 7 0 370.80 +MLO 011215 7 0 371.20 +MLO 011222 6 0 371.30 +MLO 011229 6 0 371.50 diff --git a/shared/package-files/35/353671b74a80bbe1c88c36db733a7dd6c294268250073e3ccfe23170a9fd6fac/ipc.pxi b/shared/package-files/35/353671b74a80bbe1c88c36db733a7dd6c294268250073e3ccfe23170a9fd6fac/ipc.pxi new file mode 100644 index 0000000000000000000000000000000000000000..6477579af21d776b39f6b974d51e07f205f458f1 --- /dev/null +++ b/shared/package-files/35/353671b74a80bbe1c88c36db733a7dd6c294268250073e3ccfe23170a9fd6fac/ipc.pxi @@ -0,0 +1,1504 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from cpython.pycapsule cimport PyCapsule_CheckExact, PyCapsule_GetPointer, PyCapsule_New + +from collections import namedtuple +import warnings +from cython import sizeof + +cpdef enum MetadataVersion: + V1 = CMetadataVersion_V1 + V2 = CMetadataVersion_V2 + V3 = CMetadataVersion_V3 + V4 = CMetadataVersion_V4 + V5 = CMetadataVersion_V5 + + +cdef object _wrap_metadata_version(CMetadataVersion version): + return MetadataVersion( version) + + +cdef CMetadataVersion _unwrap_metadata_version( + MetadataVersion version) except *: + if version == MetadataVersion.V1: + return CMetadataVersion_V1 + elif version == MetadataVersion.V2: + return CMetadataVersion_V2 + elif version == MetadataVersion.V3: + return CMetadataVersion_V3 + elif version == MetadataVersion.V4: + return CMetadataVersion_V4 + elif version == MetadataVersion.V5: + return CMetadataVersion_V5 + raise ValueError("Not a metadata version: " + repr(version)) + + +cpdef enum Alignment: + Any = CAlignment_Any + DataTypeSpecific = CAlignment_DataTypeSpecific + At64Byte = CAlignment_64Byte + + +cdef object _wrap_alignment(CAlignment alignment): + return Alignment( alignment) + + +cdef CAlignment _unwrap_alignment(Alignment alignment) except *: + if alignment == Alignment.Any: + return CAlignment_Any + elif alignment == Alignment.DataTypeSpecific: + return CAlignment_DataTypeSpecific + elif alignment == Alignment.At64Byte: + return CAlignment_64Byte + raise ValueError("Not an alignment: " + repr(alignment)) + + +_WriteStats = namedtuple( + 'WriteStats', + ('num_messages', 'num_record_batches', 'num_dictionary_batches', + 'num_dictionary_deltas', 'num_replaced_dictionaries')) + + +class WriteStats(_WriteStats): + """IPC write statistics + + Parameters + ---------- + num_messages : int + Number of messages. + num_record_batches : int + Number of record batches. + num_dictionary_batches : int + Number of dictionary batches. + num_dictionary_deltas : int + Delta of dictionaries. + num_replaced_dictionaries : int + Number of replaced dictionaries. + """ + __slots__ = () + + +@staticmethod +cdef _wrap_write_stats(CIpcWriteStats c): + return WriteStats(c.num_messages, c.num_record_batches, + c.num_dictionary_batches, c.num_dictionary_deltas, + c.num_replaced_dictionaries) + + +_ReadStats = namedtuple( + 'ReadStats', + ('num_messages', 'num_record_batches', 'num_dictionary_batches', + 'num_dictionary_deltas', 'num_replaced_dictionaries')) + + +class ReadStats(_ReadStats): + """IPC read statistics + + Parameters + ---------- + num_messages : int + Number of messages. + num_record_batches : int + Number of record batches. + num_dictionary_batches : int + Number of dictionary batches. + num_dictionary_deltas : int + Delta of dictionaries. + num_replaced_dictionaries : int + Number of replaced dictionaries. + """ + __slots__ = () + + +cdef _wrap_read_stats(CIpcReadStats c): + return ReadStats(c.num_messages, c.num_record_batches, + c.num_dictionary_batches, c.num_dictionary_deltas, + c.num_replaced_dictionaries) + + +cdef class IpcReadOptions(_Weakrefable): + """ + Serialization options for reading IPC format. + + Parameters + ---------- + ensure_native_endian : bool, default True + Whether to convert incoming data to platform-native endianness. + ensure_alignment : Alignment, default Alignment.Any + Data is copied to aligned memory locations if mis-aligned. + Some use cases might require data to have a specific alignment, for example, + for the data buffer of an int32 array to be aligned on a 4-byte boundary. + use_threads : bool + Whether to use the global CPU thread pool to parallelize any + computational tasks like decompression + included_fields : list + If empty (the default), return all deserialized fields. + If non-empty, the values are the indices of fields to read on + the top-level schema + """ + __slots__ = () + + # cdef block is in lib.pxd + + def __init__(self, *, bint ensure_native_endian=True, + Alignment ensure_alignment=Alignment.Any, + bint use_threads=True, list included_fields=None): + self.c_options = CIpcReadOptions.Defaults() + self.ensure_native_endian = ensure_native_endian + self.ensure_alignment = ensure_alignment + self.use_threads = use_threads + if included_fields is not None: + self.included_fields = included_fields + + @property + def ensure_native_endian(self): + return self.c_options.ensure_native_endian + + @ensure_native_endian.setter + def ensure_native_endian(self, bint value): + self.c_options.ensure_native_endian = value + + @property + def ensure_alignment(self): + return _wrap_alignment(self.c_options.ensure_alignment) + + @ensure_alignment.setter + def ensure_alignment(self, Alignment value): + self.c_options.ensure_alignment = _unwrap_alignment(value) + + @property + def use_threads(self): + return self.c_options.use_threads + + @use_threads.setter + def use_threads(self, bint value): + self.c_options.use_threads = value + + @property + def included_fields(self): + return self.c_options.included_fields + + @included_fields.setter + def included_fields(self, list value not None): + self.c_options.included_fields = value + + def __repr__(self): + alignment = Alignment(self.ensure_alignment).name + + return (f"") + + +cdef IpcReadOptions wrap_ipc_read_options(CIpcReadOptions c): + """Get Python's IpcReadOptions from C++'s IpcReadOptions + """ + + return IpcReadOptions( + ensure_native_endian=c.ensure_native_endian, + ensure_alignment=c.ensure_alignment, + use_threads=c.use_threads, + included_fields=c.included_fields, + ) + + +cdef object _get_compression_from_codec(shared_ptr[CCodec] codec): + if codec == nullptr: + return None + else: + return frombytes(codec.get().name()) + + +cdef class IpcWriteOptions(_Weakrefable): + """ + Serialization options for the IPC format. + + Parameters + ---------- + metadata_version : MetadataVersion, default MetadataVersion.V5 + The metadata version to write. V5 is the current and latest, + V4 is the pre-1.0 metadata version (with incompatible Union layout). + allow_64bit : bool, default False + If true, allow field lengths that don't fit in a signed 32-bit int. + use_legacy_format : bool, default False + Whether to use the pre-Arrow 0.15 IPC format. + compression : str, Codec, or None + compression codec to use for record batch buffers. + If None then batch buffers will be uncompressed. + Must be "lz4", "zstd" or None. + To specify a compression_level use `pyarrow.Codec` + use_threads : bool + Whether to use the global CPU thread pool to parallelize any + computational tasks like compression. + emit_dictionary_deltas : bool + Whether to emit dictionary deltas. Default is false for maximum + stream compatibility. + unify_dictionaries : bool + If true then calls to write_table will attempt to unify dictionaries + across all batches in the table. This can help avoid the need for + replacement dictionaries (which the file format does not support) + but requires computing the unified dictionary and then remapping + the indices arrays. + + This parameter is ignored when writing to the IPC stream format as + the IPC stream format can support replacement dictionaries. + """ + __slots__ = () + + # cdef block is in lib.pxd + + def __init__(self, *, metadata_version=MetadataVersion.V5, + bint allow_64bit=False, use_legacy_format=False, + compression=None, bint use_threads=True, + bint emit_dictionary_deltas=False, + bint unify_dictionaries=False): + self.c_options = CIpcWriteOptions.Defaults() + self.allow_64bit = allow_64bit + self.use_legacy_format = use_legacy_format + self.metadata_version = metadata_version + if compression is not None: + self.compression = compression + self.use_threads = use_threads + self.emit_dictionary_deltas = emit_dictionary_deltas + self.unify_dictionaries = unify_dictionaries + + @property + def allow_64bit(self): + return self.c_options.allow_64bit + + @allow_64bit.setter + def allow_64bit(self, bint value): + self.c_options.allow_64bit = value + + @property + def use_legacy_format(self): + return self.c_options.write_legacy_ipc_format + + @use_legacy_format.setter + def use_legacy_format(self, bint value): + self.c_options.write_legacy_ipc_format = value + + @property + def metadata_version(self): + return _wrap_metadata_version(self.c_options.metadata_version) + + @metadata_version.setter + def metadata_version(self, value): + self.c_options.metadata_version = _unwrap_metadata_version(value) + + @property + def compression(self): + return _get_compression_from_codec(self.c_options.codec) + + @compression.setter + def compression(self, value): + if value is None: + self.c_options.codec.reset() + elif isinstance(value, str): + codec_type = _ensure_compression(value) + if codec_type != CCompressionType_ZSTD and codec_type != CCompressionType_LZ4_FRAME: + raise ValueError("Compression type must be lz4, zstd or None") + self.c_options.codec = shared_ptr[CCodec](GetResultValue( + CCodec.Create(codec_type)).release()) + elif isinstance(value, Codec): + if value.name != "lz4" and value.name != "zstd": + raise ValueError("Compression type must be lz4, zstd or None") + self.c_options.codec = (value).wrapped + else: + raise TypeError( + "Property `compression` must be None, str, or pyarrow.Codec") + + @property + def use_threads(self): + return self.c_options.use_threads + + @use_threads.setter + def use_threads(self, bint value): + self.c_options.use_threads = value + + @property + def emit_dictionary_deltas(self): + return self.c_options.emit_dictionary_deltas + + @emit_dictionary_deltas.setter + def emit_dictionary_deltas(self, bint value): + self.c_options.emit_dictionary_deltas = value + + @property + def unify_dictionaries(self): + return self.c_options.unify_dictionaries + + @unify_dictionaries.setter + def unify_dictionaries(self, bint value): + self.c_options.unify_dictionaries = value + + def __repr__(self): + compression_repr = f"compression=\"{self.compression}\" " \ + if self.compression is not None else "" + + metadata_version = MetadataVersion(self.metadata_version).name + + return (f"") + + +cdef IpcWriteOptions wrap_ipc_write_options(CIpcWriteOptions c): + """Get Python's IpcWriteOptions from C++'s IpcWriteOptions + """ + + return IpcWriteOptions( + metadata_version=c.metadata_version, + allow_64bit=c.allow_64bit, + use_legacy_format=c.write_legacy_ipc_format, + compression=_get_compression_from_codec(c.codec), + use_threads=c.use_threads, + emit_dictionary_deltas=c.emit_dictionary_deltas, + unify_dictionaries=c.unify_dictionaries, + ) + + +cdef class Message(_Weakrefable): + """ + Container for an Arrow IPC message with metadata and optional body + """ + + def __cinit__(self): + pass + + def __init__(self): + raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly, use " + "`pyarrow.ipc.read_message` function instead.") + + @property + def type(self): + return frombytes(FormatMessageType(self.message.get().type())) + + @property + def metadata(self): + return pyarrow_wrap_buffer(self.message.get().metadata()) + + @property + def metadata_version(self): + return _wrap_metadata_version(self.message.get().metadata_version()) + + @property + def body(self): + cdef shared_ptr[CBuffer] body = self.message.get().body() + if body.get() == NULL: + return None + else: + return pyarrow_wrap_buffer(body) + + def equals(self, Message other): + """ + Returns True if the message contents (metadata and body) are identical + + Parameters + ---------- + other : Message + + Returns + ------- + are_equal : bool + """ + cdef c_bool result + with nogil: + result = self.message.get().Equals(deref(other.message.get())) + return result + + def serialize_to(self, NativeFile sink, alignment=8, memory_pool=None): + """ + Write message to generic OutputStream + + Parameters + ---------- + sink : NativeFile + alignment : int, default 8 + Byte alignment for metadata and body + memory_pool : MemoryPool, default None + Uses default memory pool if not specified + """ + cdef: + int64_t output_length = 0 + COutputStream* out + CIpcWriteOptions options + + options.alignment = alignment + out = sink.get_output_stream().get() + with nogil: + check_status(self.message.get() + .SerializeTo(out, options, &output_length)) + + def serialize(self, alignment=8, memory_pool=None): + """ + Write message as encapsulated IPC message + + Parameters + ---------- + alignment : int, default 8 + Byte alignment for metadata and body + memory_pool : MemoryPool, default None + Uses default memory pool if not specified + + Returns + ------- + serialized : Buffer + """ + stream = BufferOutputStream(memory_pool) + self.serialize_to(stream, alignment=alignment, memory_pool=memory_pool) + return stream.getvalue() + + def __repr__(self): + if self.message == nullptr: + return """pyarrow.Message(uninitialized)""" + + metadata_len = self.metadata.size + body = self.body + body_len = 0 if body is None else body.size + + return f"""pyarrow.Message +type: {self.type} +metadata length: {metadata_len} +body length: {body_len}""" + + +cdef class MessageReader(_Weakrefable): + """ + Interface for reading Message objects from some source (like an + InputStream) + """ + cdef: + unique_ptr[CMessageReader] reader + + def __cinit__(self): + pass + + def __init__(self): + raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly, use " + "`pyarrow.ipc.MessageReader.open_stream` function " + "instead.") + + @staticmethod + def open_stream(source): + """ + Open stream from source, if you want to use memory map use + MemoryMappedFile as source. + + Parameters + ---------- + source : bytes/buffer-like, pyarrow.NativeFile, or file-like Python object + A readable source, like an InputStream + """ + cdef: + MessageReader result = MessageReader.__new__(MessageReader) + shared_ptr[CInputStream] in_stream + unique_ptr[CMessageReader] reader + + _get_input_stream(source, &in_stream) + with nogil: + reader = CMessageReader.Open(in_stream) + result.reader.reset(reader.release()) + + return result + + def __iter__(self): + return self + + def __next__(self): + return self.read_next_message() + + def read_next_message(self): + """ + Read next Message from the stream. + + Raises + ------ + StopIteration + At end of stream + """ + cdef Message result = Message.__new__(Message) + + with nogil: + result.message = move(GetResultValue(self.reader.get() + .ReadNextMessage())) + + if result.message.get() == NULL: + raise StopIteration + + return result + +# ---------------------------------------------------------------------- +# File and stream readers and writers + +cdef class _CRecordBatchWriter(_Weakrefable): + """The base RecordBatchWriter wrapper. + + Provides common implementations of convenience methods. Should not + be instantiated directly by user code. + """ + + # cdef block is in lib.pxd + + def write(self, table_or_batch): + """ + Write RecordBatch or Table to stream. + + Parameters + ---------- + table_or_batch : {RecordBatch, Table} + """ + if isinstance(table_or_batch, RecordBatch): + self.write_batch(table_or_batch) + elif isinstance(table_or_batch, Table): + self.write_table(table_or_batch) + else: + raise ValueError(type(table_or_batch)) + + def write_batch(self, RecordBatch batch, custom_metadata=None): + """ + Write RecordBatch to stream. + + Parameters + ---------- + batch : RecordBatch + custom_metadata : mapping or KeyValueMetadata + Keys and values must be string-like / coercible to bytes + """ + metadata = ensure_metadata(custom_metadata, allow_none=True) + c_meta = pyarrow_unwrap_metadata(metadata) + + with nogil: + check_status(self.writer.get() + .WriteRecordBatch(deref(batch.batch), c_meta)) + + def write_table(self, Table table, max_chunksize=None): + """ + Write Table to stream in (contiguous) RecordBatch objects. + + Parameters + ---------- + table : Table + max_chunksize : int, default None + Maximum number of rows for RecordBatch chunks. Individual chunks may + be smaller depending on the chunk layout of individual columns. + """ + cdef: + # max_chunksize must be > 0 to have any impact + int64_t c_max_chunksize = -1 + + if max_chunksize is not None: + c_max_chunksize = max_chunksize + + with nogil: + check_status(self.writer.get().WriteTable(table.table[0], + c_max_chunksize)) + + def close(self): + """ + Close stream and write end-of-stream 0 marker. + """ + with nogil: + check_status(self.writer.get().Close()) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + @property + def stats(self): + """ + Current IPC write statistics. + """ + if not self.writer: + raise ValueError("Operation on closed writer") + return _wrap_write_stats(self.writer.get().stats()) + + +cdef class _RecordBatchStreamWriter(_CRecordBatchWriter): + cdef: + CIpcWriteOptions options + bint closed + + def __cinit__(self): + pass + + def __dealloc__(self): + pass + + @property + def _use_legacy_format(self): + # For testing (see test_ipc.py) + return self.options.write_legacy_ipc_format + + @property + def _metadata_version(self): + # For testing (see test_ipc.py) + return _wrap_metadata_version(self.options.metadata_version) + + def _open(self, sink, Schema schema not None, + IpcWriteOptions options=IpcWriteOptions()): + cdef: + shared_ptr[COutputStream] c_sink + + self.options = options.c_options + get_writer(sink, &c_sink) + with nogil: + self.writer = GetResultValue( + MakeStreamWriter(c_sink, schema.sp_schema, + self.options)) + + +cdef _get_input_stream(object source, shared_ptr[CInputStream]* out): + try: + source = as_buffer(source) + except TypeError: + # Non-buffer-like + pass + + get_input_stream(source, True, out) + + +class _ReadPandasMixin: + + def read_pandas(self, **options): + """ + Read contents of stream to a pandas.DataFrame. + + Read all record batches as a pyarrow.Table then convert it to a + pandas.DataFrame using Table.to_pandas. + + Parameters + ---------- + **options + Arguments to forward to :meth:`Table.to_pandas`. + + Returns + ------- + df : pandas.DataFrame + """ + table = self.read_all() + return table.to_pandas(**options) + + +cdef class RecordBatchReader(_Weakrefable): + """Base class for reading stream of record batches. + + Record batch readers function as iterators of record batches that also + provide the schema (without the need to get any batches). + + Warnings + -------- + Do not call this class's constructor directly, use one of the + ``RecordBatchReader.from_*`` functions instead. + + Notes + ----- + To import and export using the Arrow C stream interface, use the + ``_import_from_c`` and ``_export_to_c`` methods. However, keep in mind this + interface is intended for expert users. + + Examples + -------- + >>> import pyarrow as pa + >>> schema = pa.schema([('x', pa.int64())]) + >>> def iter_record_batches(): + ... for i in range(2): + ... yield pa.RecordBatch.from_arrays([pa.array([1, 2, 3])], schema=schema) + >>> reader = pa.RecordBatchReader.from_batches(schema, iter_record_batches()) + >>> print(reader.schema) + x: int64 + >>> for batch in reader: + ... print(batch) + pyarrow.RecordBatch + x: int64 + ---- + x: [1,2,3] + pyarrow.RecordBatch + x: int64 + ---- + x: [1,2,3] + """ + + # cdef block is in lib.pxd + + def __init__(self): + raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly, " + "use one of the RecordBatchReader.from_* functions instead.") + + def __iter__(self): + return self + + def __next__(self): + return self.read_next_batch() + + @property + def schema(self): + """ + Shared schema of the record batches in the stream. + + Returns + ------- + Schema + """ + cdef shared_ptr[CSchema] c_schema + + with nogil: + c_schema = self.reader.get().schema() + + return pyarrow_wrap_schema(c_schema) + + def read_next_batch(self): + """ + Read next RecordBatch from the stream. + + Raises + ------ + StopIteration: + At end of stream. + + Returns + ------- + RecordBatch + """ + cdef shared_ptr[CRecordBatch] batch + + with nogil: + check_status(self.reader.get().ReadNext(&batch)) + + if batch.get() == NULL: + raise StopIteration + + return pyarrow_wrap_batch(batch) + + def read_next_batch_with_custom_metadata(self): + """ + Read next RecordBatch from the stream along with its custom metadata. + + Raises + ------ + StopIteration: + At end of stream. + + Returns + ------- + batch : RecordBatch + custom_metadata : KeyValueMetadata + """ + cdef: + CRecordBatchWithMetadata batch_with_metadata + + with nogil: + batch_with_metadata = GetResultValue(self.reader.get().ReadNext()) + + if batch_with_metadata.batch.get() == NULL: + raise StopIteration + + return _wrap_record_batch_with_metadata(batch_with_metadata) + + def iter_batches_with_custom_metadata(self): + """ + Iterate over record batches from the stream along with their custom + metadata. + + Yields + ------ + RecordBatchWithMetadata + """ + while True: + try: + yield self.read_next_batch_with_custom_metadata() + except StopIteration: + return + + def read_all(self): + """ + Read all record batches as a pyarrow.Table. + + Returns + ------- + Table + """ + cdef shared_ptr[CTable] table + with nogil: + check_status(self.reader.get().ToTable().Value(&table)) + return pyarrow_wrap_table(table) + + read_pandas = _ReadPandasMixin.read_pandas + + def close(self): + """ + Release any resources associated with the reader. + """ + with nogil: + check_status(self.reader.get().Close()) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def cast(self, target_schema): + """ + Wrap this reader with one that casts each batch lazily as it is pulled. + Currently only a safe cast to target_schema is implemented. + + Parameters + ---------- + target_schema : Schema + Schema to cast to, the names and order of fields must match. + + Returns + ------- + RecordBatchReader + """ + cdef: + shared_ptr[CSchema] c_schema + shared_ptr[CRecordBatchReader] c_reader + RecordBatchReader out + + if self.schema.names != target_schema.names: + raise ValueError("Target schema's field names are not matching " + f"the table's field names: {self.schema.names}, " + f"{target_schema.names}") + + c_schema = pyarrow_unwrap_schema(target_schema) + c_reader = GetResultValue(CCastingRecordBatchReader.Make( + self.reader, c_schema)) + + out = RecordBatchReader.__new__(RecordBatchReader) + out.reader = c_reader + return out + + def _export_to_c(self, out_ptr): + """ + Export to a C ArrowArrayStream struct, given its pointer. + + Parameters + ---------- + out_ptr: int + The raw pointer to a C ArrowArrayStream struct. + + Be careful: if you don't pass the ArrowArrayStream struct to a + consumer, array memory will leak. This is a low-level function + intended for expert users. + """ + cdef: + void* c_ptr = _as_c_pointer(out_ptr) + with nogil: + check_status(ExportRecordBatchReader( + self.reader, c_ptr)) + + @staticmethod + def _import_from_c(in_ptr): + """ + Import RecordBatchReader from a C ArrowArrayStream struct, + given its pointer. + + Parameters + ---------- + in_ptr: int + The raw pointer to a C ArrowArrayStream struct. + + This is a low-level function intended for expert users. + """ + cdef: + void* c_ptr = _as_c_pointer(in_ptr) + shared_ptr[CRecordBatchReader] c_reader + RecordBatchReader self + + with nogil: + c_reader = GetResultValue(ImportRecordBatchReader( + c_ptr)) + + self = RecordBatchReader.__new__(RecordBatchReader) + self.reader = c_reader + return self + + def __arrow_c_stream__(self, requested_schema=None): + """ + Export to a C ArrowArrayStream PyCapsule. + + Parameters + ---------- + requested_schema : PyCapsule, default None + The schema to which the stream should be casted, passed as a + PyCapsule containing a C ArrowSchema representation of the + requested schema. + + Returns + ------- + PyCapsule + A capsule containing a C ArrowArrayStream struct. + """ + cdef: + ArrowArrayStream* c_stream + + if requested_schema is not None: + out_schema = Schema._import_from_c_capsule(requested_schema) + if self.schema != out_schema: + return self.cast(out_schema).__arrow_c_stream__() + + stream_capsule = alloc_c_stream(&c_stream) + + with nogil: + check_status(ExportRecordBatchReader(self.reader, c_stream)) + + return stream_capsule + + @staticmethod + def _import_from_c_capsule(stream): + """ + Import RecordBatchReader from a C ArrowArrayStream PyCapsule. + + Parameters + ---------- + stream: PyCapsule + A capsule containing a C ArrowArrayStream PyCapsule. + + Returns + ------- + RecordBatchReader + """ + cdef: + ArrowArrayStream* c_stream + shared_ptr[CRecordBatchReader] c_reader + RecordBatchReader self + + c_stream = PyCapsule_GetPointer( + stream, 'arrow_array_stream' + ) + + with nogil: + c_reader = GetResultValue(ImportRecordBatchReader(c_stream)) + + self = RecordBatchReader.__new__(RecordBatchReader) + self.reader = c_reader + return self + + @staticmethod + def from_stream(data, schema=None): + """ + Create RecordBatchReader from a Arrow-compatible stream object. + + This accepts objects implementing the Arrow PyCapsule Protocol for + streams, i.e. objects that have a ``__arrow_c_stream__`` method. + + Parameters + ---------- + data : Arrow-compatible stream object + Any object that implements the Arrow PyCapsule Protocol for + streams. + schema : Schema, default None + The schema to which the stream should be casted, if supported + by the stream object. + + Returns + ------- + RecordBatchReader + """ + + if not hasattr(data, "__arrow_c_stream__"): + raise TypeError( + "Expected an object implementing the Arrow PyCapsule Protocol for " + "streams (i.e. having a `__arrow_c_stream__` method), " + f"got {type(data)!r}." + ) + + if schema is not None: + if not hasattr(schema, "__arrow_c_schema__"): + raise TypeError( + "Expected an object implementing the Arrow PyCapsule Protocol for " + "schema (i.e. having a `__arrow_c_schema__` method), " + f"got {type(schema)!r}." + ) + requested = schema.__arrow_c_schema__() + else: + requested = None + + capsule = data.__arrow_c_stream__(requested) + return RecordBatchReader._import_from_c_capsule(capsule) + + @staticmethod + def from_batches(Schema schema not None, batches): + """ + Create RecordBatchReader from an iterable of batches. + + Parameters + ---------- + schema : Schema + The shared schema of the record batches + batches : Iterable[RecordBatch] + The batches that this reader will return. + + Returns + ------- + reader : RecordBatchReader + """ + cdef: + shared_ptr[CSchema] c_schema + shared_ptr[CRecordBatchReader] c_reader + RecordBatchReader self + + c_schema = pyarrow_unwrap_schema(schema) + c_reader = GetResultValue(CPyRecordBatchReader.Make( + c_schema, batches)) + + self = RecordBatchReader.__new__(RecordBatchReader) + self.reader = c_reader + return self + + +cdef class _RecordBatchStreamReader(RecordBatchReader): + cdef: + shared_ptr[CInputStream] in_stream + CIpcReadOptions options + CRecordBatchStreamReader* stream_reader + + def __cinit__(self): + pass + + def _open(self, source, IpcReadOptions options=IpcReadOptions(), + MemoryPool memory_pool=None): + self.options = options.c_options + self.options.memory_pool = maybe_unbox_memory_pool(memory_pool) + _get_input_stream(source, &self.in_stream) + with nogil: + self.reader = GetResultValue(CRecordBatchStreamReader.Open( + self.in_stream, self.options)) + self.stream_reader = self.reader.get() + + @property + def stats(self): + """ + Current IPC read statistics. + """ + if not self.reader: + raise ValueError("Operation on closed reader") + return _wrap_read_stats(self.stream_reader.stats()) + + +cdef class _RecordBatchFileWriter(_RecordBatchStreamWriter): + + def _open(self, sink, Schema schema not None, + IpcWriteOptions options=IpcWriteOptions(), + metadata=None): + cdef: + shared_ptr[COutputStream] c_sink + shared_ptr[const CKeyValueMetadata] c_meta + + self.options = options.c_options + get_writer(sink, &c_sink) + + metadata = ensure_metadata(metadata, allow_none=True) + c_meta = pyarrow_unwrap_metadata(metadata) + + with nogil: + self.writer = GetResultValue( + MakeFileWriter(c_sink, schema.sp_schema, self.options, c_meta)) + +_RecordBatchWithMetadata = namedtuple( + 'RecordBatchWithMetadata', + ('batch', 'custom_metadata')) + + +class RecordBatchWithMetadata(_RecordBatchWithMetadata): + """RecordBatch with its custom metadata + + Parameters + ---------- + batch : RecordBatch + custom_metadata : KeyValueMetadata + """ + __slots__ = () + + +@staticmethod +cdef _wrap_record_batch_with_metadata(CRecordBatchWithMetadata c): + return RecordBatchWithMetadata(pyarrow_wrap_batch(c.batch), + pyarrow_wrap_metadata(c.custom_metadata)) + + +cdef class _RecordBatchFileReader(_Weakrefable): + cdef: + SharedPtrNoGIL[CRecordBatchFileReader] reader + shared_ptr[CRandomAccessFile] file + CIpcReadOptions options + + cdef readonly: + Schema schema + + def __cinit__(self): + pass + + def _open(self, source, footer_offset=None, + IpcReadOptions options=IpcReadOptions(), + MemoryPool memory_pool=None): + self.options = options.c_options + self.options.memory_pool = maybe_unbox_memory_pool(memory_pool) + try: + source = as_buffer(source) + except TypeError: + pass + + get_reader(source, False, &self.file) + + cdef int64_t offset = 0 + if footer_offset is not None: + offset = footer_offset + + with nogil: + if offset != 0: + self.reader = GetResultValue( + CRecordBatchFileReader.Open2(self.file.get(), offset, + self.options)) + + else: + self.reader = GetResultValue( + CRecordBatchFileReader.Open(self.file.get(), + self.options)) + + self.schema = pyarrow_wrap_schema(self.reader.get().schema()) + + @property + def num_record_batches(self): + """ + The number of record batches in the IPC file. + """ + return self.reader.get().num_record_batches() + + def get_batch(self, int i): + """ + Read the record batch with the given index. + + Parameters + ---------- + i : int + The index of the record batch in the IPC file. + + Returns + ------- + batch : RecordBatch + """ + cdef shared_ptr[CRecordBatch] batch + + if i < 0 or i >= self.num_record_batches: + raise ValueError(f'Batch number {i} out of range') + + with nogil: + batch = GetResultValue(self.reader.get().ReadRecordBatch(i)) + + return pyarrow_wrap_batch(batch) + + # TODO(wesm): ARROW-503: Function was renamed. Remove after a period of + # time has passed + get_record_batch = get_batch + + def get_batch_with_custom_metadata(self, int i): + """ + Read the record batch with the given index along with + its custom metadata + + Parameters + ---------- + i : int + The index of the record batch in the IPC file. + + Returns + ------- + batch : RecordBatch + custom_metadata : KeyValueMetadata + """ + cdef: + CRecordBatchWithMetadata batch_with_metadata + + if i < 0 or i >= self.num_record_batches: + raise ValueError(f'Batch number {i} out of range') + + with nogil: + batch_with_metadata = GetResultValue( + self.reader.get().ReadRecordBatchWithCustomMetadata(i)) + + return _wrap_record_batch_with_metadata(batch_with_metadata) + + def read_all(self): + """ + Read all record batches as a pyarrow.Table + """ + cdef: + vector[shared_ptr[CRecordBatch]] batches + shared_ptr[CTable] table + int i, nbatches + + nbatches = self.num_record_batches + + batches.resize(nbatches) + with nogil: + for i in range(nbatches): + batches[i] = GetResultValue(self.reader.get() + .ReadRecordBatch(i)) + table = GetResultValue( + CTable.FromRecordBatches(self.schema.sp_schema, move(batches))) + + return pyarrow_wrap_table(table) + + read_pandas = _ReadPandasMixin.read_pandas + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + pass + + @property + def stats(self): + """ + Current IPC read statistics. + """ + if not self.reader: + raise ValueError("Operation on closed reader") + return _wrap_read_stats(self.reader.get().stats()) + + @property + def metadata(self): + """ + File-level custom metadata as dict, where both keys and values are byte-like. + This kind of metadata can be written via ``ipc.new_file(..., metadata=...)``. + """ + wrapped = pyarrow_wrap_metadata(self.reader.get().metadata()) + return wrapped.to_dict() if wrapped is not None else None + + +def get_tensor_size(Tensor tensor): + """ + Return total size of serialized Tensor including metadata and padding. + + Parameters + ---------- + tensor : Tensor + The tensor for which we want to known the size. + """ + cdef int64_t size + with nogil: + check_status(GetTensorSize(deref(tensor.tp), &size)) + return size + + +def get_record_batch_size(RecordBatch batch): + """ + Return total size of serialized RecordBatch including metadata and padding. + + Parameters + ---------- + batch : RecordBatch + The recordbatch for which we want to know the size. + """ + cdef int64_t size + with nogil: + check_status(GetRecordBatchSize(deref(batch.batch), &size)) + return size + + +def write_tensor(Tensor tensor, NativeFile dest): + """ + Write pyarrow.Tensor to pyarrow.NativeFile object its current position. + + Parameters + ---------- + tensor : pyarrow.Tensor + dest : pyarrow.NativeFile + + Returns + ------- + bytes_written : int + Total number of bytes written to the file + """ + cdef: + int32_t metadata_length + int64_t body_length + + handle = dest.get_output_stream() + + with nogil: + check_status( + WriteTensor(deref(tensor.tp), handle.get(), + &metadata_length, &body_length)) + + return metadata_length + body_length + + +cdef NativeFile as_native_file(source): + if not isinstance(source, NativeFile): + if hasattr(source, 'read'): + source = PythonFile(source) + else: + source = BufferReader(source) + + if not isinstance(source, NativeFile): + raise ValueError( + f'Unable to read message from object with type: {type(source)}') + return source + + +def read_tensor(source): + """Read pyarrow.Tensor from pyarrow.NativeFile object from current + position. If the file source supports zero copy (e.g. a memory map), then + this operation does not allocate any memory. This function not assume that + the stream is aligned + + Parameters + ---------- + source : pyarrow.NativeFile + + Returns + ------- + tensor : Tensor + + """ + cdef: + shared_ptr[CTensor] sp_tensor + CInputStream* c_stream + NativeFile nf = as_native_file(source) + + c_stream = nf.get_input_stream().get() + with nogil: + sp_tensor = GetResultValue(ReadTensor(c_stream)) + return pyarrow_wrap_tensor(sp_tensor) + + +def read_message(source): + """ + Read length-prefixed message from file or buffer-like object + + Parameters + ---------- + source : pyarrow.NativeFile, file-like object, or buffer-like object + + Returns + ------- + message : Message + """ + cdef: + Message result = Message.__new__(Message) + CInputStream* c_stream + + cdef NativeFile nf = as_native_file(source) + c_stream = nf.get_input_stream().get() + + with nogil: + result.message = move( + GetResultValue(ReadMessage(c_stream, c_default_memory_pool()))) + + if result.message == nullptr: + raise EOFError("End of Arrow stream") + + return result + + +def read_schema(obj, DictionaryMemo dictionary_memo=None): + """ + Read Schema from message or buffer + + Parameters + ---------- + obj : buffer or Message + dictionary_memo : DictionaryMemo, optional + Needed to be able to reconstruct dictionary-encoded fields + with read_record_batch + + Returns + ------- + schema : Schema + """ + cdef: + shared_ptr[CSchema] result + shared_ptr[CRandomAccessFile] cpp_file + Message message + CDictionaryMemo temp_memo + CDictionaryMemo* arg_dict_memo + + if dictionary_memo is not None: + arg_dict_memo = dictionary_memo.memo + else: + arg_dict_memo = &temp_memo + + if isinstance(obj, Message): + message = obj + with nogil: + result = GetResultValue(ReadSchema( + deref(message.message.get()), arg_dict_memo)) + else: + get_reader(obj, False, &cpp_file) + with nogil: + result = GetResultValue(ReadSchema(cpp_file.get(), arg_dict_memo)) + + return pyarrow_wrap_schema(result) + + +def read_record_batch(obj, Schema schema, + DictionaryMemo dictionary_memo=None): + """ + Read RecordBatch from message, given a known schema. If reading data from a + complete IPC stream, use ipc.open_stream instead + + Parameters + ---------- + obj : Message or Buffer-like + schema : Schema + dictionary_memo : DictionaryMemo, optional + If message contains dictionaries, must pass a populated + DictionaryMemo + + Returns + ------- + batch : RecordBatch + """ + cdef: + shared_ptr[CRecordBatch] result + Message message + CDictionaryMemo temp_memo + CDictionaryMemo* arg_dict_memo + + if isinstance(obj, Message): + message = obj + else: + message = read_message(obj) + + if dictionary_memo is not None: + arg_dict_memo = dictionary_memo.memo + else: + arg_dict_memo = &temp_memo + + with nogil: + result = GetResultValue( + ReadRecordBatch(deref(message.message.get()), + schema.sp_schema, + arg_dict_memo, + CIpcReadOptions.Defaults())) + + return pyarrow_wrap_batch(result) diff --git a/shared/package-files/35/353726794e9c00f8cd21fcdc7adfff643e2d3d9216da0a57cb6ed4d03429acfa/autograd_registration.py b/shared/package-files/35/353726794e9c00f8cd21fcdc7adfff643e2d3d9216da0a57cb6ed4d03429acfa/autograd_registration.py new file mode 100644 index 0000000000000000000000000000000000000000..25df4f1d03fcf50fc5869d8af93cd128f98e9c72 --- /dev/null +++ b/shared/package-files/35/353726794e9c00f8cd21fcdc7adfff643e2d3d9216da0a57cb6ed4d03429acfa/autograd_registration.py @@ -0,0 +1,132 @@ +# mypy: ignore-errors + +import contextlib + +import torch +import torch.utils._pytree as pytree + + +@contextlib.contextmanager +def set_autograd_fallback_mode(mode): + prev = torch._C._get_autograd_fallback_mode() + try: + torch._C._set_autograd_fallback_mode(mode) + yield + finally: + torch._C._set_autograd_fallback_mode(prev) + + +def autograd_registration_check(op, args, kwargs): + """Check if autograd was registered correctly (for the operator). + + Operators should have "autograd support" registered directly to an + autograd dispatch key. + An incorrect registration may lead to unexpected silent incorrectness. + Note that this check won't catch all problems but will catch + the most common ones. + + Example usage: + >>> x = torch.randn(3, requires_grad=True) + >>> autograd_registration_check(torch.ops.aten.sin.default, (x,), {}) + + Here are some best practices if you do find your autograd is + registered incorrectly: + - If the operator is composite (i.e. consists of other PyTorch ops) + and you wish the operator to decompose and get autograd support + that way, then please register the implementation to + DispatchKey::CompositeImplicitAutograd + - If you're adding an autograd formula for the operator, the correct + thing to do is to register an autograd.Function to + DispatchKey::Autograd (preferred) or one of the + DispatchKey::Autograd keys. It is NOT OK to register + an autograd.Function to a backend (e.g. CPU/CUDA) key. + - If your operator is non-differentiable, then you should register + an implementation to the Autograd key that uses + AutoDispatchBelowAutograd and re-invokes the operator. + + """ + assert isinstance(op, torch._ops.OpOverload) + # Implementation details + # ----------------------------------------------- + # If an operator doesn't have an autograd kernel at an autograd key, + # and the operator does not return inputs as-is, then all of + # the outputs should have requires_grad=False before we apply + # special behaviors of our default autograd fallback. + # (The default autograd fallback may set requires_grad=True on output + # tensors in certain modes so that when they are backpropped through, + # they raise an error). + # + # Our strategy for detecting if an operator doesn't have an autograd + # kernel at the autograd key is: + # - set the autograd fallback mode to "nothing" (so it does not change + # the required-gradness of outputs) + # - run the operator + # - Check if any outputs of the operator (that are not inputs) require + # grad. This would only happen if the user calls regular PyTorch + # operations in their backend key (this op should instead be + # CompositeImplicitAutograd or not an op) or if the user invokes + # an autograd.Function in the backend key. + # + # Note that it's already likely a bug if the operator directly returns + # an input as output (because custom ops don't have a good way of + # constructing true in-place or out variants), but we defer that + # responsibility to a different test (schema_check). + + flat_args = pytree.arg_tree_leaves(*args, **kwargs) + all_tensors = [arg for arg in flat_args if isinstance(arg, torch.Tensor)] + if not any(t.requires_grad for t in all_tensors): + raise RuntimeError( + "autograd_registration_check: no inputs have requires_grad=True so " + "we are unable to actually perform this test. Please pass inputs " + "that do require grad." + ) + + # Determine which AutogradBACKEND key to check + all_device_types = {arg.device.type for arg in all_tensors} + if not all_device_types.issubset(["cpu", "cuda"]): + # Don't want to support other keys yet + raise NotImplementedError( + f"autograd_registration_check: NYI devices other than CPU/CUDA, got {all_device_types}" + ) + if "cuda" in all_device_types: + key = "AutogradCUDA" + elif "cpu" in all_device_types: + key = "AutogradCPU" + + if torch._C._dispatch_has_kernel_for_dispatch_key(op.name(), key): + return + if torch._C._dispatch_has_kernel_for_dispatch_key(op.name(), "Autograd"): + return + if torch._C._dispatch_has_kernel_for_dispatch_key( + op.name(), "CompositeImplicitAutograd" + ): + return + + # At this point, we know the operator doesn't have a kernel registered to an + # autograd key. Let's proceed with our test. + with set_autograd_fallback_mode("nothing"): + all_outs = op(*args, **kwargs) + + inp_ids = {id(arg) for arg in flat_args} + + def not_an_input_and_requires_grad(tensor): + if not tensor.requires_grad: + return False + if id(tensor) in inp_ids: + return False + return True + + if not pytree.tree_any_only(torch.Tensor, not_an_input_and_requires_grad, all_outs): + return + + raise AssertionError( + f"{op.name()}: at least one output of this operator has requires_grad=True " + f"but the operator does not have an autograd kernel defined at an autograd " + f"key (e.g. DispatchKey::Autograd). This could mean that you have " + f"incorrectly registered an autograd kernel to a non-Autograd DispatchKey, " + f"which may lead to silently incorrect results. If your operator consists " + f"of regular PyTorch operations, consider not using an operator at all " + f"or registering your operator as CompositeImplicitAutograd. If you have " + f"an autograd.Function registered to a backend (CPU/CUDA) key, the correct " + f"location for it is the Autograd key." + ) diff --git a/shared/package-files/35/3537734cabc6d94eff5b253f228414b4ccd4de412f0c7dfd0a09d1e95ce14e4c/pcg64-testset-2.csv b/shared/package-files/35/3537734cabc6d94eff5b253f228414b4ccd4de412f0c7dfd0a09d1e95ce14e4c/pcg64-testset-2.csv new file mode 100644 index 0000000000000000000000000000000000000000..7c13e3172d0e7798200f58cde9362ad0bd4a22e1 --- /dev/null +++ b/shared/package-files/35/3537734cabc6d94eff5b253f228414b4ccd4de412f0c7dfd0a09d1e95ce14e4c/pcg64-testset-2.csv @@ -0,0 +1,1001 @@ +seed, 0x0 +0, 0xa30febcfd9c2825f +1, 0x4510bdf882d9d721 +2, 0xa7d3da94ecde8b8 +3, 0x43b27b61342f01d +4, 0xd0327a782cde513b +5, 0xe9aa5979a6401c4e +6, 0x9b4c7b7180edb27f +7, 0xbac0495ff8829a45 +8, 0x8b2b01e7a1dc7fbf +9, 0xef60e8078f56bfed +10, 0xd0dbc74d4700374c +11, 0xb37868abbe90b0 +12, 0xdb7ed8bf64e6f5f0 +13, 0x89910738de7951f +14, 0xbacab307c3cfd379 +15, 0x2cf7c449d8b927a6 +16, 0xdcf94b3a16db7f0e +17, 0x8a9d33d905a8792e +18, 0x4cb9eb2014951238 +19, 0x6c353acf7b26d6f1 +20, 0x73ff53d673aa30c +21, 0x1fd10760015eca68 +22, 0xabae0aa9021eeba8 +23, 0xa5ae363a868ee2bb +24, 0x9d89e0f041de6631 +25, 0x6238b133c3991a65 +26, 0xff49267d75fef51a +27, 0xfb180656ce13c53f +28, 0xaf7fadf36128712d +29, 0xa6847fc6f339c63e +30, 0xb03e0b80d71ea5bc +31, 0x63905abcb43969af +32, 0x2295af3ee00a3bba +33, 0xb8b375b994330415 +34, 0x867d9ef1d8716a3b +35, 0x4f6c02f5601b4e18 +36, 0x7c5fb4c16c470d18 +37, 0xe3b57986b804b343 +38, 0xef1d79d212aca692 +39, 0x5b98774c8806209c +40, 0x924fc76bac38a5d1 +41, 0x5266084c412ddeed +42, 0x98240bf9b831d6a3 +43, 0x5681599e81219442 +44, 0x6441248fc2ba92bc +45, 0xe3e9051a540349ea +46, 0x3a2700034390baa3 +47, 0x9f893155b6d402bc +48, 0x158207910c6d8aef +49, 0xd5282ab7608c2cbc +50, 0xc97f4651669dee4f +51, 0x3d4750d95103ed60 +52, 0xe0614542caac1f04 +53, 0xefe5092144cfc6c +54, 0x560bc486abd7e9ae +55, 0x2678b71392daa4b8 +56, 0x734970d3dc2ba416 +57, 0xcbdbe849e51e4aaf +58, 0x3b0b5e28b491556c +59, 0xd51449ac45abd88 +60, 0x6790b59991f1b7ab +61, 0x32d1c039ff2415bc +62, 0x173b9772f24f72e0 +63, 0x9490a9ca9f883b1b +64, 0x4c775989e6214222 +65, 0xac07db37e6ee6114 +66, 0x331371b2e3f10aee +67, 0xf12e5326c21c28e4 +68, 0x5d77dc280c70d614 +69, 0x1b01bd17a2f281ec +70, 0xa10d3b5882938487 +71, 0xed5a0033c394ae8f +72, 0x70bc8ea568ea44b4 +73, 0xf4600ae77965e730 +74, 0x7ff92c0b321ce233 +75, 0x6cdbc87d0cc1d670 +76, 0x9ec64f0cf2000eb1 +77, 0xfebea50259800f68 +78, 0xf2edf9019a8fd343 +79, 0x75c584ac042e5468 +80, 0xc1fa8481d5bf9a1d +81, 0x7f57180168514ac2 +82, 0x878100716b94f81e +83, 0xc929406e3af17fd2 +84, 0x6a26e2c013e4bf4d +85, 0xbc071d8848280955 +86, 0xb60d75abbfd1bdac +87, 0xee9b76afeca9fa69 +88, 0x1d6c399d2f452810 +89, 0xbaa0bc1621e25c83 +90, 0xed6ba792f8671ba5 +91, 0xf7ca02c2ab11d8d7 +92, 0x3c3cadadf0b21e3 +93, 0xdd1784571e864e9c +94, 0xfb2f992015157509 +95, 0xf50bb9f0d3ced743 +96, 0x261565f75c3e185f +97, 0xf8fe33b284513e60 +98, 0xe3d2d10b5e024664 +99, 0xd28717566242cf35 +100, 0x7ae07d133ac5b789 +101, 0x3b7ccaaa53ac338e +102, 0xcd480bace4871650 +103, 0xec6c78f923c080e9 +104, 0x44211d0ff8919d59 +105, 0x89f79af76d2a45fe +106, 0x71583fd8a837548b +107, 0xee57269c261511f5 +108, 0xa5ee8f3b128c5d1 +109, 0xbb64c20ed0765a17 +110, 0x9d4790ab2eeaf7e4 +111, 0x742f3db806d9e98 +112, 0xb81ec97aed6a0d1b +113, 0x41808b34f6a8a23 +114, 0xc20913af175dfd4d +115, 0x834427db263b22bb +116, 0xedd9c632e611828a +117, 0x10eac8524496f571 +118, 0xd76091b97eb00ab7 +119, 0x111298ae9fe95666 +120, 0x5824b2e2a6719c43 +121, 0x6e280ec539e934ed +122, 0xf74fd832df90083e +123, 0x8fee6d0f241c2e97 +124, 0x4244f331c2f19c3c +125, 0x3dde75a845cce97f +126, 0xe35bb8e635a9915b +127, 0x39d2943037f7932e +128, 0x1fe2d134201d0970 +129, 0x49d00b63c749b804 +130, 0x960c2942cd4e4e04 +131, 0x8dd8e009dbc0435f +132, 0xcf493495c3a055cd +133, 0x8f7b5a1c0f9fe9cd +134, 0x49d5f90374641a25 +135, 0x69b3932073d3524c +136, 0xd170603e7de84ee2 +137, 0xa062ba3ed3539948 +138, 0xf5861cc5b5d56c82 +139, 0x5e914998a30c7e76 +140, 0x8d77f2ad1503c0f1 +141, 0x980b6a9e3b4181fb +142, 0xd9299cd50694c084 +143, 0x253dc0f8f1cec4c5 +144, 0x68110fb9d1b3e695 +145, 0xe8f3120d0aabc461 +146, 0xb066e7df0dfb042 +147, 0xd29ce0f797e6b60b +148, 0x6a569bb7ca33bd42 +149, 0xd46e08b2dc2385f8 +150, 0x28c61d11d055767 +151, 0x5d73aa3d1a2bb725 +152, 0x1421191e1c14829a +153, 0xa711bfb6423df35e +154, 0x461af97a86308006 +155, 0xb3e1018ff3519367 +156, 0xf19cf866a268ef2b +157, 0x207715eac9199d1d +158, 0xdd621c410975b78c +159, 0xf390aea68683610 +160, 0x617a2d107a0047d9 +161, 0x6e05ac416e5bebf0 +162, 0x7d253e70506c1bed +163, 0xf9f96f4a7dd53810 +164, 0xc693b29cb1573f73 +165, 0x4f1146b0020ea544 +166, 0x45140608fbd40579 +167, 0xdcf57219828ce6be +168, 0xe19d58cca37b5b32 +169, 0x82bda95b2a161235 +170, 0x5823c3d8a2b6c9ba +171, 0xfeb2e74092fdf89a +172, 0x50e1ad1abc8f869d +173, 0x2ec63d0c105eb8da +174, 0xe14e1c4845a3264a +175, 0xcff53670455eb6aa +176, 0xaafaccd24619fa3e +177, 0xf55a988486e2422a +178, 0xecfba16a90ff4d04 +179, 0xbf8d36c2f644757a +180, 0xdc56ed75a0dd6249 +181, 0x3f45023eff17c3bb +182, 0x2428bbfe90023fab +183, 0xab892c611adcb70c +184, 0xb6f13d8c0c2b9d74 +185, 0x2ac3fb11d224f2a8 +186, 0x65433dcfae2d9351 +187, 0xe906859ae4b45f82 +188, 0x8fb7f5f093d76a3b +189, 0x940dd290b5e88d1a +190, 0x31b27d21bef116e7 +191, 0x86a964e2c83b5296 +192, 0x85ffd17bc079a9e8 +193, 0x16c47c724e7ab7f1 +194, 0xfb6098a9867e7d7f +195, 0x9246fb69092c6cb2 +196, 0x1a4033572760f32 +197, 0xc5cc568a8b273b84 +198, 0xfa6f9f2fbdd44abc +199, 0x9701b8e087718ba3 +200, 0x51d6a7dcf73f8f3a +201, 0x30008172cc6a972d +202, 0xac2ab49a5ca6ac81 +203, 0x31f28ef79461e54c +204, 0x93e35a8da8cc6132 +205, 0x9a2c58beeba3d5b9 +206, 0xf6615c1de266ac39 +207, 0x127ff9f8166b766b +208, 0x7ffe380e80a69556 +209, 0xbe7d2c228e1542f7 +210, 0x2d5ebb4e50ba1746 +211, 0x63585761ae1bf684 +212, 0x1019eb5cee022fea +213, 0xb9d3540ab58da30d +214, 0x1677f4cb45620eb9 +215, 0x6524baee51783822 +216, 0xdf9f2ddcfabb0adc +217, 0x78e8acc43b287935 +218, 0xe9a1974e999222b5 +219, 0xc41324ec2291e780 +220, 0xea52abc9ecdcbc9f +221, 0x209d7bcd46ec6b04 +222, 0x12d504c09803db2e +223, 0x1200e6bf21475d81 +224, 0xde6d3c2b35fd2cfc +225, 0xa2526900ac33bd3c +226, 0x7f1f5290fc432bc5 +227, 0x29ddfb380a3d69c8 +228, 0xac79cb6942a2909d +229, 0x516996685b67a92a +230, 0xb5fc39041cb828bb +231, 0x75d9d8ca0644a276 +232, 0x81e98b76be92a3e9 +233, 0xca27888fafe12179 +234, 0x17be2ae039925765 +235, 0x9429846c0e6d0342 +236, 0x327dfd50439815e9 +237, 0xcee20cd7bc254aeb +238, 0x7d250389f453f29e +239, 0xfd1b232a85c95569 +240, 0x2ed55fac80f3e9e9 +241, 0xf6886c20417a1be7 +242, 0xcd08e61f0b0fdfde +243, 0x7b33e34da5c27bff +244, 0xd043c4b7d5603dd5 +245, 0x9a544e4c70a3b686 +246, 0xa7b60398c381f771 +247, 0xe9e7a3487c4bd4f2 +248, 0x10b58fdfe1ff112c +249, 0xd5c1c9748c0f4ceb +250, 0x61be9d09159d54ff +251, 0x5356f51e8239f510 +252, 0xfe7889d9b202ecef +253, 0xc7fc19ca5d263d5d +254, 0x7c4c07e61dfd9f69 +255, 0x6c315fe5015f300a +256, 0xe0a5bc00039747b4 +257, 0x16397fdcf829ee80 +258, 0xb55aee80d16a5169 +259, 0xca0609944d007eea +260, 0xcc982249f65a02ce +261, 0x528161feb149c148 +262, 0xcbf08ba49b41c006 +263, 0x39af1ff0b6f14138 +264, 0x5cc036be69799aec +265, 0x6adde125b1db21c5 +266, 0x8a99d83d6b613b67 +267, 0x1cd43fca9451f74c +268, 0x682dbb26ecc96365 +269, 0x13b4be2ceb43e3 +270, 0xbe8fbc3b6f4f581e +271, 0xda148a2f4bda5719 +272, 0x239106ca3319f393 +273, 0xb42b4dde641f0dd5 +274, 0xd233cfdf4cb0af74 +275, 0xfb5919d905589afc +276, 0xd802a8860c10b66a +277, 0x6c923e1d00e7b5bc +278, 0xfacce1134f383b89 +279, 0xf9570abda7a6d553 +280, 0x80f0f9796a208f18 +281, 0xc0e1df5280951c57 +282, 0xe9f143f08257bbe0 +283, 0x79e4c6463123d588 +284, 0xdd2118583f2b1684 +285, 0xb399ff5f2329fa18 +286, 0x4b3e9ebae96f813c +287, 0xc484dbf247787384 +288, 0x921865eb97603f2c +289, 0x18063c68e257d300 +290, 0x643181f345e7fc26 +291, 0x12e0b0e8eadf9fa7 +292, 0x79e613fe73dfa354 +293, 0x6db4c59203b7217a +294, 0x6c7a0e9ba6139eaf +295, 0x9617c7ac4e3f6d97 +296, 0x1f68a7b4fb1b4b75 +297, 0xef0b7ab24944f466 +298, 0xaf1dee1f4be1bc89 +299, 0xd2e355c959f5fd8d +300, 0xe594c3fb95d96efc +301, 0x9554766ca3342906 +302, 0xa4bbdc77d12842c +303, 0xb62400211ee489a8 +304, 0x91abadaaa3bbe67c +305, 0xd371eeb91deb42bb +306, 0x883bab35cbd2b6e5 +307, 0xd030c3d9411a9041 +308, 0xff3c110a858ff000 +309, 0x59bdf5ca47d0bde7 +310, 0x2bc80fa3cdba1853 +311, 0x6444ccb652662cb8 +312, 0xc0c7e256b9e90339 +313, 0x70714ea9c9d72302 +314, 0x96a0142f9d897d27 +315, 0x209a9097c5a91ef7 +316, 0xb9e33afc5171e009 +317, 0x47b37af433a58d40 +318, 0x30cc4ffbfa831d26 +319, 0xdcea4a85ff815466 +320, 0x907d5bd027f2e5cc +321, 0x7c081f6852e04a4b +322, 0xe61950749c1d502b +323, 0x1604e937ee69834a +324, 0xb2372d952dd25309 +325, 0x53f6a5b834c72577 +326, 0x2ce7a74395e0b694 +327, 0xacbf9ab4fe91f225 +328, 0x5ce1e63d3a2bb90f +329, 0x54740da3a5ed139b +330, 0xf194ddb39f29880b +331, 0x3305374f5d8ec08b +332, 0x831dd0164927ff4a +333, 0x625baa78e4458cf +334, 0x29d27dc0a4a71152 +335, 0xe227bae9a1401034 +336, 0xca0c209831846b2b +337, 0x8e8cc54b08b5a411 +338, 0x38f2b4acaac27db6 +339, 0x8ec88baac814e86b +340, 0x31c08e46b007bde +341, 0xb686c02722794c09 +342, 0xb77cf8fc682e3907 +343, 0xa56334e7f606f4b2 +344, 0x9c80b127bddd5f4f +345, 0x12df14834cd858bf +346, 0x3f14762a9cf5fb9f +347, 0x930a70941ef5779e +348, 0x64e96c849c30c080 +349, 0xfdf53bfba1300484 +350, 0xec7a9363c21bc616 +351, 0x26e9fd6a115ecb47 +352, 0x9707a84b5bc77fbb +353, 0xb23b2737b20d5903 +354, 0x22f4825ae80f6501 +355, 0x500644b12be6a01b +356, 0xb746645b2af082db +357, 0xe6af051f697892f8 +358, 0x577c724248a1cfc6 +359, 0x3d2b6a434c84eed3 +360, 0xd260f5efd7328314 +361, 0x95c16cc84bb3f55c +362, 0x7a01b2e4e0e80ca7 +363, 0x41930c3ce70a0935 +364, 0x1299bccf39d4e110 +365, 0x494883ba1a8a87f +366, 0x9478ecfe2d918e60 +367, 0x30ec9a5670cda8af +368, 0xf9bc877e833e2b99 +369, 0x1b83a0acfbb4a8db +370, 0x73bc1740c0d18880 +371, 0x65086ca9773cb3e1 +372, 0x3b78c3ccd63cff2e +373, 0xbfae748795acfb31 +374, 0xa4c9d5d56a15ba20 +375, 0xb9cb41721e52b71e +376, 0x1532f15d4dc47748 +377, 0x5a4d647a4b9ee632 +378, 0x8513c7c5a50898d9 +379, 0x6d3d98ccd5461b2e +380, 0xa65e99be2fe98d6 +381, 0x31abc8855334a0e5 +382, 0xf1ed22a661dca5b8 +383, 0x299e2b63229e03be +384, 0xda201a06687bce48 +385, 0xd27794b302142c55 +386, 0x642bd3e1c7898a9d +387, 0x777f1ff00afa1a87 +388, 0xd2f1c84fb3877baa +389, 0xae417583289191fd +390, 0xd641f1d88e0e2d55 +391, 0xc1f1d98fb5d18ebf +392, 0xb0f72aecdadce97b +393, 0xe9b8abc764f6018a +394, 0xd2a37cff8e890594 +395, 0x2dd70d631a528771 +396, 0xbf8ba0478c18e336 +397, 0x1630bf47f372ce0a +398, 0x6d04ea20dc3f46b8 +399, 0x6591881bf34337f2 +400, 0x33c149c7eb5b4103 +401, 0xf01a8c9857c86748 +402, 0x184348cdfc16d215 +403, 0x141168b253d2ed7 +404, 0x52aaf012ef50a6f1 +405, 0xfda1722387e16f4c +406, 0x43c30f57d6c038fa +407, 0xd4a8611f5f96d214 +408, 0x2c512ce17e987f2c +409, 0x961ce450f0fa2822 +410, 0xf55a506ec6cea9cd +411, 0xb76d694d9c7f5ef6 +412, 0xfb029216dbd8e988 +413, 0x93162501896a0081 +414, 0xfbbbd2c5ab300f5c +415, 0xd648b6da7387d491 +416, 0xc73b4697471d9d98 +417, 0xe37412bf1c93ee76 +418, 0xa1a96d96570e6637 +419, 0x5b3ab4f82428f65c +420, 0x873d849b188aa36f +421, 0x39fbee0ffc9fa9ff +422, 0xc70d21b744d677fe +423, 0x2b8a43c23043d209 +424, 0x93c33eaa37370d16 +425, 0x8930ac1880f2b0ef +426, 0xac01d27707036af0 +427, 0xc2af3fee504343a0 +428, 0x1c1dae2ad5535d97 +429, 0x9ffc21804b76a480 +430, 0x69f903412cc13563 +431, 0x9d3c4e2759a0c47d +432, 0xb1a8f894be6302b9 +433, 0x95e1fd7951479506 +434, 0xbb9e6c03cd4ae8e3 +435, 0x85206010c9b737cf +436, 0x767e813694d6238c +437, 0x4969af329ccbb30a +438, 0x3aa9af1075aaea5c +439, 0xb1ff519e8118a993 +440, 0xb21a23a3c91180fe +441, 0x320b24582ca3fd88 +442, 0xf8ca56415fb4e453 +443, 0xabd0899c07205e77 +444, 0x87fdc7a44b4ad50f +445, 0xd75744911641a278 +446, 0x7c8c9a65df6fcb95 +447, 0x79d785e3c7a5b695 +448, 0x421e4565ba1f592f +449, 0x27f87eb2517835cf +450, 0xb62cc4297441c83e +451, 0xd817a80ac815ca6d +452, 0xad84388130df2aa8 +453, 0x5e6b1640452d6ac8 +454, 0x936285e15edce2a3 +455, 0x903bccc4969768e8 +456, 0xefc2cb7b109d3140 +457, 0x633e9dfdda2d903a +458, 0x2a2f3225925678a1 +459, 0xe07eac91a27f8547 +460, 0xe50ced40eda78cb3 +461, 0xc5b22500e1c7441 +462, 0x32becf61bca3aa72 +463, 0xa2e37c4b30671344 +464, 0xc9f1c1910f45d544 +465, 0x9b50333b2dcdf730 +466, 0x310bfd53a1684b94 +467, 0x1e1dc21e66ac6455 +468, 0x81876c2bfb1ed5a1 +469, 0xd0c54a3e25eadc7b +470, 0x3791b6fbbd5c7ba0 +471, 0x133be57356c599fc +472, 0x8d1148eb8e83fdea +473, 0x311aedba0d8b42cc +474, 0x1142ae52745f94bb +475, 0xc5f4ab2fbde8c4a3 +476, 0xd23be827b5b24f6d +477, 0x65f95194cd122715 +478, 0x4b48969d73125922 +479, 0x46f165052b8ff988 +480, 0x5c689f94b9275ff4 +481, 0x93b03823ff2d536b +482, 0x871f3775aa4e3523 +483, 0x5af829f7cc0f66a5 +484, 0xa32e05739cbeac8c +485, 0xacff1856ddace0fe +486, 0x8eeb5e7f991a5322 +487, 0x6325c2720e0dbdea +488, 0x9fb817bc4fdf5200 +489, 0x9786f0d850e43d78 +490, 0x571f76dd7f9fb77a +491, 0x4d9e94e181cbc63f +492, 0x8bb632d3376c547a +493, 0x9cc26d9efd1c88b9 +494, 0x9c5d49579df52b0b +495, 0x6201abf7e1cda07b +496, 0x90d68f0c6c884963 +497, 0xfc5b66188ef7f561 +498, 0x6d9303cf2e0e0f95 +499, 0xd7cfcff535f5ed07 +500, 0x14d1a1228daa4ac6 +501, 0xe00ef5762f66ae50 +502, 0xf113a79471582978 +503, 0x430985281785dc7a +504, 0x31914108c206ed5 +505, 0x7ba6707b6419971c +506, 0x2ec63b033ce112e5 +507, 0xf8bcd36ced3b41e3 +508, 0xe5cf908c8010414b +509, 0xf5ee224b7c703e30 +510, 0x9a9733af0b12338b +511, 0x83e18cc00ace34f8 +512, 0xd52cff39e23008b8 +513, 0xa700578136b9c0c5 +514, 0x3fa179d32ac51f99 +515, 0xef2d5eab6d4ad380 +516, 0x709024a5abd032df +517, 0xc607c7ee349ede87 +518, 0x803d784e9731eb5f +519, 0x2ef06f4ba769282d +520, 0x4bc1dca1e9f07eb9 +521, 0x930c958a7a72f94d +522, 0x249bc8db2cc7a3bf +523, 0x3845305798f9a5d +524, 0x6f137eca9ab6f948 +525, 0xc31f5a963d31bd67 +526, 0x9d39693d5383626f +527, 0x52fb41c335a8b98e +528, 0xb79d1a29a06006ec +529, 0x7c0926a7a3eda2cc +530, 0xffdf5214406fd53e +531, 0xc6aa02a7e94282b9 +532, 0xd4a4431b4aa301ee +533, 0x4271cc0f9420d3ab +534, 0x26fccd7cc7fc2485 +535, 0x330594bb945b8d5a +536, 0x6ea8eaad12e5cb8c +537, 0x831c3467726bede3 +538, 0x31d1eb10017eaa61 +539, 0xc7aa75e41508f5cb +540, 0xde51810f0cadd0b5 +541, 0x50e5b3e73692f80b +542, 0x82107ec55636e188 +543, 0x9828ef175d843ab4 +544, 0xb8edc6a860dd421e +545, 0x25c0c138fd537ac3 +546, 0x47e72a771e8eb563 +547, 0xbb0f8c5333f4a2cc +548, 0x91750d2fb9b2d479 +549, 0xe662d8f6fe38df36 +550, 0x72a6d879fb5619f0 +551, 0x6817c7878dcbf077 +552, 0x4e7741cb484661e8 +553, 0x3b3b3ba0be5711bf +554, 0xa6989f5d25868765 +555, 0x43c276398997e4e0 +556, 0xdcbe16a94da28870 +557, 0x454936980a699c99 +558, 0xac614bfa8f0266c6 +559, 0x9174841392e213d5 +560, 0xa0e2acffc5fc9d1f +561, 0xe53a08a7a0e6521a +562, 0x2b845cf7c24172e0 +563, 0x265a4fc5f7adec0d +564, 0x1f34fbe5f1e49420 +565, 0x139181f6fb647f20 +566, 0x88c35d46e2fcd05e +567, 0x2a6d5b55903c0459 +568, 0xcea28eb621ad7bf1 +569, 0x5c9cdc13e7aaa30 +570, 0x5fe63e14746e7103 +571, 0x7923e53d73835db9 +572, 0x376e661210bf1b06 +573, 0x5b1cab85450efdd5 +574, 0x3908dc096c70b452 +575, 0x4825e303cd1f396f +576, 0xed476bfd702957c3 +577, 0x6acc013aff5db743 +578, 0x62c80b776343d488 +579, 0x9c75edcd5b012697 +580, 0xaa053362a3b9770a +581, 0xa907e236c7c07e94 +582, 0x15b2c380451692c0 +583, 0x94f79142697bd61f +584, 0xbc657d31ea98d44f +585, 0xcbaa5e52517a1f5e +586, 0x96aa2e44a7c4a03f +587, 0x216d3c66db2b515d +588, 0x157001807e3ca88a +589, 0x52b3a596bdd3859a +590, 0xed747e7fc5e3adac +591, 0x78fd765ddb2c448d +592, 0xe53dc7299ed8614e +593, 0x75ad41fb1d7a790a +594, 0xc14f6b944b0e6cb1 +595, 0x7c314b69fce3df1c +596, 0xb56d82eb740d7abc +597, 0x5132a93c41251fdb +598, 0xe3ce35bd2a82f958 +599, 0x440571a981c722f2 +600, 0x194cdfd9f186bc9 +601, 0xb89e522a5db00939 +602, 0xad35f339f68df3c8 +603, 0xa82ab18420322293 +604, 0xaffa6df9b72b27c4 +605, 0x9615694d23beaa2c +606, 0x1d82ebe563abad91 +607, 0xab50ef65fbd94385 +608, 0x1b070dbd70a9a14 +609, 0x2ececa796abbadf0 +610, 0x6bbeafe9e81ab2a2 +611, 0x60dcd0d2a9b76914 +612, 0x1e748039ef05c33f +613, 0x6d4d17f2213ccdff +614, 0x9fa56132957bc987 +615, 0x60a17185de2428eb +616, 0xb56038ddf306479c +617, 0x3b1db5df92d06d8b +618, 0x24d1bba8bdedf580 +619, 0xbfb7e6740ebaa4d9 +620, 0xab31c4473e46f61d +621, 0x6deb3cdd8fd5869f +622, 0x23032e47746d72d6 +623, 0xa9e72d734e10f2e8 +624, 0xbffd199b6157bc23 +625, 0x29f8254df273fb62 +626, 0xb076142130ee55ec +627, 0x5b0b08374126c309 +628, 0xea4536aae979521f +629, 0xc064e7abec91a174 +630, 0x46133ef80c59d935 +631, 0xf0227e2da1b14160 +632, 0x675a76641e1af5a +633, 0x2f50a069b33d198c +634, 0x3ded5a65e1d657eb +635, 0xbb6999b020694f6b +636, 0x86b2f2b33487aed7 +637, 0x76e14e85f8bfb4cf +638, 0x38f7f1e44bd4e0db +639, 0xc1a7d41b7e80d4ae +640, 0x1dfaaf80bbceb42e +641, 0x3f51c11497720c2b +642, 0xce6da1415ddb8b80 +643, 0x7377d8bcd359b5f3 +644, 0xe077208f3f810aca +645, 0x9a06a8a2dacbffce +646, 0xca1f99156b09b735 +647, 0x2ff9a93064d91451 +648, 0x50f3ea93f351a7ef +649, 0x606fceccb07054de +650, 0x7e83d6d2f8f6685d +651, 0x78f3995291c5d407 +652, 0xd28d2460e22d0228 +653, 0x2c5636f68a0054dd +654, 0xd9fafb1c56c8f6cb +655, 0xe39889b5f9d74464 +656, 0x1355372bf5db2cc1 +657, 0x26768426b9ac323 +658, 0x4af1dbdc1111fd89 +659, 0x66973587943b927f +660, 0xf86f5f50684dfb1d +661, 0x1247d574ff79b534 +662, 0xc8039f3259210fe2 +663, 0x79b573235c92a9f5 +664, 0x213f642d8450e2f0 +665, 0x5db7706973376566 +666, 0x6182c12e69b373d7 +667, 0x3e5ac47300aec07f +668, 0x4b5b6c57b1574376 +669, 0x6b7fcceefd56b17c +670, 0xf656c3455cb9d4b8 +671, 0x7577e2e13329721f +672, 0xf33c0c53ce956e8d +673, 0x7d0f328ee356174 +674, 0x10ec9a168088686e +675, 0x71ef1776d062dfa +676, 0xaa7b590a488a6bc4 +677, 0x38612b6dd8049a1c +678, 0x939045e36874f731 +679, 0xcb9d1d74c56d5ac9 +680, 0x54f1c1c8fef1d8ff +681, 0x3ee4b85c8c7e939e +682, 0xb9b4608e019f352c +683, 0x79d4701275d12e6a +684, 0x2632a2d9835c7f19 +685, 0x1662cd9fba293692 +686, 0xbcb70265115ee944 +687, 0xdc43fb9761468604 +688, 0xe3eec4e7d3871352 +689, 0x829531753226989d +690, 0x2748cc67f540e074 +691, 0x39c4af25d607837d +692, 0x741a243f4cb5df99 +693, 0xda1353287e18b49a +694, 0xa6735689d751ea74 +695, 0x46326d587340ce0b +696, 0xc18531df4550012b +697, 0x6f7901e05dd4b818 +698, 0xfb966afc4c001d63 +699, 0x6dc10fca67a9cfdb +700, 0xd6527ffadf0feaae +701, 0x3b900172045e25d +702, 0xb7dd594cdded6a46 +703, 0x6602aee7ec1599fc +704, 0x7fbf12f23747546a +705, 0x32e63f662bd2de0d +706, 0xedf47770b67ed641 +707, 0x331bef83481c5c2a +708, 0x8fc4256fdf05158c +709, 0x98eba48dabccf5e0 +710, 0xdbc2f2cdb7b1c154 +711, 0x7777755616517ad3 +712, 0xd473c147d2628ac1 +713, 0x861e15d1d760b5a7 +714, 0xf4d25926405ecb07 +715, 0xb7739c69effff86e +716, 0xe97fbafa6f96830c +717, 0xf13e8a334e8bede1 +718, 0xcd60010cba4ee4f9 +719, 0x1f537ac2b82e6008 +720, 0x1fda8d781a89140a +721, 0x9dc204f3f4a463f0 +722, 0x456dcd18eb56a1ab +723, 0x629957bc87bd16a1 +724, 0x2c8000ddb8c75253 +725, 0xc31dae9ec8449284 +726, 0xdac05c8baa2b691a +727, 0x21ff7be9ffa3e7ac +728, 0x844f4b5ed4ee08d0 +729, 0x651f913fd636c994 +730, 0xca3e71a2110b2d49 +731, 0x7709bc42253ed09d +732, 0xbb164d45b6569d43 +733, 0x90ec2f040c20a112 +734, 0xfa6e77e9166f5be4 +735, 0x6b6d12c1842d587d +736, 0xfcd7ff8466e25e2a +737, 0x6a5a2ed8bd971297 +738, 0x2ec35f6bba5adcbc +739, 0xc83676e16651249a +740, 0x458f6064cefe10ba +741, 0x90d54d527e6cd028 +742, 0xa5613e88db27c388 +743, 0x331e0c7d85aa1abc +744, 0x8cee4977e210358 +745, 0xfcae379aa6cbff8e +746, 0xd1407afc97a57e86 +747, 0x1fab25c864f094ae +748, 0xd914864a63004552 +749, 0x4214d226a20f1384 +750, 0x3f4e0d80c488b715 +751, 0xc5ca2f654024b7c8 +752, 0xc1e27a124e7c821c +753, 0xd890a915ffc7918c +754, 0x22fba040ce51a9f8 +755, 0xbf61cebd8891617a +756, 0x7846609ee228e319 +757, 0x536d1854375509b8 +758, 0xbbfb45fc6e666f50 +759, 0xd85b4c0527f9d7d6 +760, 0x528cc9c7fa2a84c8 +761, 0x27a1baece647f2cb +762, 0xfddf0cb92fe09dc3 +763, 0xeb5008fe965d8d96 +764, 0x4a3307937eb2e5c8 +765, 0xd07d74c240c6c363 +766, 0x16f62290179d1bbf +767, 0xe99c9bcc9cb1ece7 +768, 0xc64f9be03c8a93be +769, 0x32659effaf666c1f +770, 0x4bb228cfb30b6672 +771, 0x98764870842068a5 +772, 0x5b12ef2d2cd8bdcc +773, 0xbc79d1c1b41f28b8 +774, 0x97a517cf3279fc9a +775, 0x34ffd46c1d4d6025 +776, 0x9c302307ee25c8f0 +777, 0x399604eed1f18a8 +778, 0x1c9b813c2043142a +779, 0x2944ea5e55267fe9 +780, 0x5a8a9f5e728ea667 +781, 0x30c8440adb804a0 +782, 0xee0e6b627099a937 +783, 0x3d50757ada3c52da +784, 0x4548916b32c813ab +785, 0x602a186fe5bf109b +786, 0xf0d440a2227ba304 +787, 0x5a10d4e0ca9ea32b +788, 0x6e5eb90da13ba64c +789, 0x4c6af8fd04241ab2 +790, 0xf9eb31d26e093006 +791, 0x5d674878839fe3ea +792, 0x1562b55b2484e47c +793, 0xa87188c099c1cb61 +794, 0xb7736b8aa02a3392 +795, 0x5f4b301125abb20f +796, 0x361d566984637f44 +797, 0x68c4b3feac8bd0c3 +798, 0x7066c634dd2503c1 +799, 0xfecbf7c9441eb6ea +800, 0xdbc26ae0fc81436b +801, 0x9ef3e2b48252e7a4 +802, 0x31a49b4c339b37c7 +803, 0xb01b2a83cf346cf4 +804, 0xc24dc2347f82fbe3 +805, 0x134cad272dcd410f +806, 0x61260742823ba59c +807, 0x53ac4c193a97c730 +808, 0x9207c9833af34b52 +809, 0xa72e7ee77078d1f5 +810, 0x2e6f6e1b05936885 +811, 0x783b99ce5dbf9464 +812, 0xfdfeb6f0d027bb44 +813, 0x40eeb27096f92b0 +814, 0x5ef96ff5d4a4521f +815, 0x5595806ae873718a +816, 0x67d449eecf4ca1c3 +817, 0xde837ab611364f3f +818, 0x7034c24d2b139be9 +819, 0xe21166603e0a9c86 +820, 0x935694435c1f0d51 +821, 0x6cb3bec90c126088 +822, 0x4096ef662b7a9f89 +823, 0xd2d85b8d238d8c15 +824, 0xa4ea533ce3ec59b2 +825, 0x3654729d80a2db29 +826, 0x214c4cc3906d29d4 +827, 0x201c447e7588e373 +828, 0xe8b8f0ae25f683eb +829, 0x6744aaf5754e38af +830, 0xd1ffb10d6f27a061 +831, 0xe536733a7b3a6c30 +832, 0x39f0f66e47cbf2c9 +833, 0x856a9593526fde2 +834, 0x2e2a817a0098ea4b +835, 0xc5e1eeb551a0e3d3 +836, 0x3f21e2f5e2d50b2 +837, 0x906af56c66dd9f8c +838, 0x30f6dbd70329fac8 +839, 0xc443dfddf3c01a60 +840, 0x7ab85d9aa9675470 +841, 0x8c9080bd39717bfc +842, 0x4b1ccdb3c3597f6f +843, 0x74e2542d70ab5d67 +844, 0xbb3d236aad00f74 +845, 0xcf3cadf9a2804774 +846, 0xe851d9750e42bd07 +847, 0xc0ad82029b1c371f +848, 0x7ee119eb552d6c07 +849, 0xd8024049bd1d784a +850, 0xfa67a899760363 +851, 0xaa7c2f438b178197 +852, 0xc473674a47ffe064 +853, 0x539fbe3fc674c270 +854, 0xdb48484748a76f3b +855, 0xc73b2b092060d +856, 0xa1d2a15345016f5d +857, 0x4d0fe8599f9bba47 +858, 0xa0edc275e6f8f1d1 +859, 0x40590a8655bc8d72 +860, 0x35b4223161f05f75 +861, 0xa04c0c0f616752dc +862, 0x7f371ed2ca45432d +863, 0x2ff1a08f75ac6438 +864, 0xe2dc5c3682282f48 +865, 0xe1e4179fa98d9013 +866, 0x8cb083d6843a73d5 +867, 0xb4c2b5921b706854 +868, 0x738e14c0e7352445 +869, 0xcd2b646f91afd8c7 +870, 0xd5779a5b57a264fd +871, 0xc39ff855586c7d07 +872, 0x3e3f0098c631a859 +873, 0x644e02fae032110 +874, 0xa8834613c0a45278 +875, 0x69482f2c08e10657 +876, 0xe4ee475bdb87e69a +877, 0xdc1ef7b25c0d0019 +878, 0x88a3fa2be18d8744 +879, 0x60a02e0b21c5bec7 +880, 0xb6867b88aa19bc1a +881, 0xb599409affcf10eb +882, 0xaeaa1778a5e59daa +883, 0xd7a91a52c16663e3 +884, 0x93cb269affe07b1c +885, 0x841b6ced3a4ba815 +886, 0x84541768e1540a5c +887, 0xe3943c84f83b3020 +888, 0x5de366fbd7b45258 +889, 0xd787cc3bde91a661 +890, 0x814071446edecb57 +891, 0x15d8c602a1141514 +892, 0x72f07bc8002d1d0d +893, 0x4a8bd8dc9a1f0f3e +894, 0x8723796ae0f20d35 +895, 0xda7283c2051f73b2 +896, 0x2df0cc247f90bd3b +897, 0x79a8522b968f990a +898, 0x951ede190c8b9d02 +899, 0xc512f1a5b14b018a +900, 0xf0e3ddc03b9a4259 +901, 0x8cf4a35ad312e15f +902, 0xebef28926b11094b +903, 0x5628ba687325921c +904, 0xc3aa75e57edc49c3 +905, 0xc38382fa98e762ba +906, 0x8d209e896285848e +907, 0x2c7d6adf592b4a3e +908, 0x62de48e36f8338f3 +909, 0x4a752741e00de30e +910, 0xf7855b70f1f6ec2b +911, 0xa505fa4428199e43 +912, 0xe8b6b423b826bbac +913, 0x4bd1206cf8786d05 +914, 0x6dcf040391fe3bf4 +915, 0x913f500f87e1bba3 +916, 0x5acf775aa180a5d5 +917, 0x74dd28d9432ce739 +918, 0x996c2ff2f0dc2495 +919, 0x73dbfe6c56effe4 +920, 0x56fddd25196f5e40 +921, 0xe87810158f5b7 +922, 0x7b8795e996383f1f +923, 0x9ba5ee7c777c4c82 +924, 0x17ce3908d270fe1c +925, 0x3df9e613c1aedfae +926, 0xcdd26871b32fc8e1 +927, 0xd71cb13afc633979 +928, 0x63427c8ea9b1c79e +929, 0xd070f7664d3b405d +930, 0x46f2a9e32d9fb769 +931, 0xb4c3822a45e9fe9b +932, 0x8ba30b97fe6f5ec7 +933, 0x70aa554ee2fc11f9 +934, 0xa80c99dbe0cfcfaf +935, 0x36d9250cb2d68ed +936, 0x2995e4b9e1cd1db4 +937, 0x4b3803ba57fc570f +938, 0xae3959e7d740eaa5 +939, 0xb4cbd6662adbae08 +940, 0xae46576446e8dbc4 +941, 0xc4828e008a9a8a54 +942, 0x145d7db8e6554b2f +943, 0x1b1b8916a730c371 +944, 0xdaf84b2bebe31963 +945, 0x5b59b80ef23a2403 +946, 0x9180c7e89cab6fd3 +947, 0x80e58f5411babf34 +948, 0xa06cf55185b9b005 +949, 0x13b2c798424173ad +950, 0xc510f8e706311d49 +951, 0x1f974b83b6046d3a +952, 0xae6e8e85e822d1c3 +953, 0x66f2c8dc3274a31a +954, 0x7e04dbcbf65bd377 +955, 0xabf41ede01ec20a4 +956, 0x5efa0948f6bbb2ea +957, 0xbc91c99d8592255 +958, 0xf6d6917911d86d75 +959, 0x85ce273d54e9097a +960, 0xbdfd30f2420fff92 +961, 0x8802f02f610b537c +962, 0xd1d70037ed543229 +963, 0x908aaf97f9693a46 +964, 0x1f6cfeaa0834d53a +965, 0xa453fd1648ce04d2 +966, 0x2c38bb85ebc64af9 +967, 0xd2daff551c90c4f8 +968, 0xae5a0d949797d784 +969, 0xf0974c8552ac9593 +970, 0xa10b70499f65c693 +971, 0x39a449ebd594ddff +972, 0x8ea090f2b17b9b49 +973, 0xc592de318090fd83 +974, 0xb63e4fbc467b6912 +975, 0x57a0c1c5ce0e4dcc +976, 0xa7c517cf3d436b35 +977, 0xef6dcb0f3fad038b +978, 0xaf4fb60315b91287 +979, 0x5e0776f67304f331 +980, 0xe927753b8e6f7932 +981, 0xd3df2dd92559e304 +982, 0xdaed52aa6af44413 +983, 0x1b59f4dac1e181f8 +984, 0x4a73c2293877ef39 +985, 0xca45d0d015fe44de +986, 0x4659c8b7853735a8 +987, 0x12de6466bdf8adeb +988, 0xaeea857a09bfec15 +989, 0xcc9cf4b3c0b88a23 +990, 0xa44ae52396a5e1bf +991, 0x5847a724305d137f +992, 0x8f4d4de223956182 +993, 0x58254dfada867a8 +994, 0x900a98222c2f339e +995, 0xdb575260935d51d5 +996, 0x13fb4bfbbc0d7b53 +997, 0x62213850186bb92b +998, 0x2a34823312c00388 +999, 0x6148329042f743b0 diff --git a/shared/package-files/35/35398686f9bf7e573a83376d39e00e5ec3b76a2e8ade97b21f8efa4a3faa7cb0/test_sort_values.py b/shared/package-files/35/35398686f9bf7e573a83376d39e00e5ec3b76a2e8ade97b21f8efa4a3faa7cb0/test_sort_values.py new file mode 100644 index 0000000000000000000000000000000000000000..f2f02058a534e782a1fe1bd302512897218c1a1d --- /dev/null +++ b/shared/package-files/35/35398686f9bf7e573a83376d39e00e5ec3b76a2e8ade97b21f8efa4a3faa7cb0/test_sort_values.py @@ -0,0 +1,940 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + Categorical, + DataFrame, + NaT, + Timestamp, + date_range, +) +import pandas._testing as tm +from pandas.util.version import Version + + +class TestDataFrameSortValues: + @pytest.mark.parametrize("dtype", [np.uint8, bool]) + def test_sort_values_sparse_no_warning(self, dtype): + # GH#45618 + ser = pd.Series(Categorical(["a", "b", "a"], categories=["a", "b", "c"])) + df = pd.get_dummies(ser, dtype=dtype, sparse=True) + + with tm.assert_produces_warning(None): + # No warnings about constructing Index from SparseArray + df.sort_values(by=df.columns.tolist()) + + def test_sort_values(self): + frame = DataFrame( + [[1, 1, 2], [3, 1, 0], [4, 5, 6]], index=[1, 2, 3], columns=list("ABC") + ) + + # by column (axis=0) + sorted_df = frame.sort_values(by="A") + indexer = frame["A"].argsort().values + expected = frame.loc[frame.index[indexer]] + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.sort_values(by="A", ascending=False) + indexer = indexer[::-1] + expected = frame.loc[frame.index[indexer]] + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.sort_values(by="A", ascending=False) + tm.assert_frame_equal(sorted_df, expected) + + # GH4839 + sorted_df = frame.sort_values(by=["A"], ascending=[False]) + tm.assert_frame_equal(sorted_df, expected) + + # multiple bys + sorted_df = frame.sort_values(by=["B", "C"]) + expected = frame.loc[[2, 1, 3]] + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.sort_values(by=["B", "C"], ascending=False) + tm.assert_frame_equal(sorted_df, expected[::-1]) + + sorted_df = frame.sort_values(by=["B", "A"], ascending=[True, False]) + tm.assert_frame_equal(sorted_df, expected) + + msg = "No axis named 2 for object type DataFrame" + with pytest.raises(ValueError, match=msg): + frame.sort_values(by=["A", "B"], axis=2, inplace=True) + + # by row (axis=1): GH#10806 + sorted_df = frame.sort_values(by=3, axis=1) + expected = frame + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.sort_values(by=3, axis=1, ascending=False) + expected = frame.reindex(columns=["C", "B", "A"]) + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.sort_values(by=[1, 2], axis="columns") + expected = frame.reindex(columns=["B", "A", "C"]) + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.sort_values(by=[1, 3], axis=1, ascending=[True, False]) + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.sort_values(by=[1, 3], axis=1, ascending=False) + expected = frame.reindex(columns=["C", "B", "A"]) + tm.assert_frame_equal(sorted_df, expected) + + msg = r"Length of ascending \(5\) != length of by \(2\)" + with pytest.raises(ValueError, match=msg): + frame.sort_values(by=["A", "B"], axis=0, ascending=[True] * 5) + + def test_sort_values_by_empty_list(self): + # https://github.com/pandas-dev/pandas/issues/40258 + expected = DataFrame({"a": [1, 4, 2, 5, 3, 6]}) + result = expected.sort_values(by=[]) + tm.assert_frame_equal(result, expected) + assert result is not expected + + def test_sort_values_inplace(self): + frame = DataFrame( + np.random.default_rng(2).standard_normal((4, 4)), + index=[1, 2, 3, 4], + columns=["A", "B", "C", "D"], + ) + + sorted_df = frame.copy() + return_value = sorted_df.sort_values(by="A", inplace=True) + assert return_value is None + expected = frame.sort_values(by="A") + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.copy() + return_value = sorted_df.sort_values(by=1, axis=1, inplace=True) + assert return_value is None + expected = frame.sort_values(by=1, axis=1) + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.copy() + return_value = sorted_df.sort_values(by="A", ascending=False, inplace=True) + assert return_value is None + expected = frame.sort_values(by="A", ascending=False) + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.copy() + return_value = sorted_df.sort_values( + by=["A", "B"], ascending=False, inplace=True + ) + assert return_value is None + expected = frame.sort_values(by=["A", "B"], ascending=False) + tm.assert_frame_equal(sorted_df, expected) + + def test_sort_values_multicolumn(self): + A = np.arange(5).repeat(20) + B = np.tile(np.arange(5), 20) + np.random.default_rng(2).shuffle(A) + np.random.default_rng(2).shuffle(B) + frame = DataFrame( + {"A": A, "B": B, "C": np.random.default_rng(2).standard_normal(100)} + ) + + result = frame.sort_values(by=["A", "B"]) + indexer = np.lexsort((frame["B"], frame["A"])) + expected = frame.take(indexer) + tm.assert_frame_equal(result, expected) + + result = frame.sort_values(by=["A", "B"], ascending=False) + indexer = np.lexsort( + (frame["B"].rank(ascending=False), frame["A"].rank(ascending=False)) + ) + expected = frame.take(indexer) + tm.assert_frame_equal(result, expected) + + result = frame.sort_values(by=["B", "A"]) + indexer = np.lexsort((frame["A"], frame["B"])) + expected = frame.take(indexer) + tm.assert_frame_equal(result, expected) + + def test_sort_values_multicolumn_uint64(self): + # GH#9918 + # uint64 multicolumn sort + + df = DataFrame( + { + "a": pd.Series([18446637057563306014, 1162265347240853609]), + "b": pd.Series([1, 2]), + } + ) + df["a"] = df["a"].astype(np.uint64) + result = df.sort_values(["a", "b"]) + + expected = DataFrame( + { + "a": pd.Series([18446637057563306014, 1162265347240853609]), + "b": pd.Series([1, 2]), + }, + index=pd.Index([1, 0]), + ) + + tm.assert_frame_equal(result, expected) + + def test_sort_values_nan(self): + # GH#3917 + df = DataFrame( + {"A": [1, 2, np.nan, 1, 6, 8, 4], "B": [9, np.nan, 5, 2, 5, 4, 5]} + ) + + # sort one column only + expected = DataFrame( + {"A": [np.nan, 1, 1, 2, 4, 6, 8], "B": [5, 9, 2, np.nan, 5, 5, 4]}, + index=[2, 0, 3, 1, 6, 4, 5], + ) + sorted_df = df.sort_values(["A"], na_position="first") + tm.assert_frame_equal(sorted_df, expected) + + expected = DataFrame( + {"A": [np.nan, 8, 6, 4, 2, 1, 1], "B": [5, 4, 5, 5, np.nan, 9, 2]}, + index=[2, 5, 4, 6, 1, 0, 3], + ) + sorted_df = df.sort_values(["A"], na_position="first", ascending=False) + tm.assert_frame_equal(sorted_df, expected) + + expected = df.reindex(columns=["B", "A"]) + sorted_df = df.sort_values(by=1, axis=1, na_position="first") + tm.assert_frame_equal(sorted_df, expected) + + # na_position='last', order + expected = DataFrame( + {"A": [1, 1, 2, 4, 6, 8, np.nan], "B": [2, 9, np.nan, 5, 5, 4, 5]}, + index=[3, 0, 1, 6, 4, 5, 2], + ) + sorted_df = df.sort_values(["A", "B"]) + tm.assert_frame_equal(sorted_df, expected) + + # na_position='first', order + expected = DataFrame( + {"A": [np.nan, 1, 1, 2, 4, 6, 8], "B": [5, 2, 9, np.nan, 5, 5, 4]}, + index=[2, 3, 0, 1, 6, 4, 5], + ) + sorted_df = df.sort_values(["A", "B"], na_position="first") + tm.assert_frame_equal(sorted_df, expected) + + # na_position='first', not order + expected = DataFrame( + {"A": [np.nan, 1, 1, 2, 4, 6, 8], "B": [5, 9, 2, np.nan, 5, 5, 4]}, + index=[2, 0, 3, 1, 6, 4, 5], + ) + sorted_df = df.sort_values(["A", "B"], ascending=[1, 0], na_position="first") + tm.assert_frame_equal(sorted_df, expected) + + # na_position='last', not order + expected = DataFrame( + {"A": [8, 6, 4, 2, 1, 1, np.nan], "B": [4, 5, 5, np.nan, 2, 9, 5]}, + index=[5, 4, 6, 1, 3, 0, 2], + ) + sorted_df = df.sort_values(["A", "B"], ascending=[0, 1], na_position="last") + tm.assert_frame_equal(sorted_df, expected) + + def test_sort_values_stable_descending_sort(self): + # GH#6399 + df = DataFrame( + [[2, "first"], [2, "second"], [1, "a"], [1, "b"]], + columns=["sort_col", "order"], + ) + sorted_df = df.sort_values(by="sort_col", kind="mergesort", ascending=False) + tm.assert_frame_equal(df, sorted_df) + + @pytest.mark.parametrize( + "expected_idx_non_na, ascending", + [ + [ + [3, 4, 5, 0, 1, 8, 6, 9, 7, 10, 13, 14], + [True, True], + ], + [ + [0, 3, 4, 5, 1, 8, 6, 7, 10, 13, 14, 9], + [True, False], + ], + [ + [9, 7, 10, 13, 14, 6, 8, 1, 3, 4, 5, 0], + [False, True], + ], + [ + [7, 10, 13, 14, 9, 6, 8, 1, 0, 3, 4, 5], + [False, False], + ], + ], + ) + @pytest.mark.parametrize("na_position", ["first", "last"]) + def test_sort_values_stable_multicolumn_sort( + self, expected_idx_non_na, ascending, na_position + ): + # GH#38426 Clarify sort_values with mult. columns / labels is stable + df = DataFrame( + { + "A": [1, 2, np.nan, 1, 1, 1, 6, 8, 4, 8, 8, np.nan, np.nan, 8, 8], + "B": [9, np.nan, 5, 2, 2, 2, 5, 4, 5, 3, 4, np.nan, np.nan, 4, 4], + } + ) + # All rows with NaN in col "B" only have unique values in "A", therefore, + # only the rows with NaNs in "A" have to be treated individually: + expected_idx = ( + [11, 12, 2] + expected_idx_non_na + if na_position == "first" + else expected_idx_non_na + [2, 11, 12] + ) + expected = df.take(expected_idx) + sorted_df = df.sort_values( + ["A", "B"], ascending=ascending, na_position=na_position + ) + tm.assert_frame_equal(sorted_df, expected) + + def test_sort_values_stable_categorial(self): + # GH#16793 + df = DataFrame({"x": Categorical(np.repeat([1, 2, 3, 4], 5), ordered=True)}) + expected = df.copy() + sorted_df = df.sort_values("x", kind="mergesort") + tm.assert_frame_equal(sorted_df, expected) + + def test_sort_values_datetimes(self): + # GH#3461, argsort / lexsort differences for a datetime column + df = DataFrame( + ["a", "a", "a", "b", "c", "d", "e", "f", "g"], + columns=["A"], + index=date_range("20130101", periods=9), + ) + dts = [ + Timestamp(x) + for x in [ + "2004-02-11", + "2004-01-21", + "2004-01-26", + "2005-09-20", + "2010-10-04", + "2009-05-12", + "2008-11-12", + "2010-09-28", + "2010-09-28", + ] + ] + df["B"] = dts[::2] + dts[1::2] + df["C"] = 2.0 + df["A1"] = 3.0 + + df1 = df.sort_values(by="A") + df2 = df.sort_values(by=["A"]) + tm.assert_frame_equal(df1, df2) + + df1 = df.sort_values(by="B") + df2 = df.sort_values(by=["B"]) + tm.assert_frame_equal(df1, df2) + + df1 = df.sort_values(by="B") + + df2 = df.sort_values(by=["C", "B"]) + tm.assert_frame_equal(df1, df2) + + def test_sort_values_frame_column_inplace_sort_exception( + self, float_frame, using_copy_on_write + ): + s = float_frame["A"] + float_frame_orig = float_frame.copy() + if using_copy_on_write: + # INFO(CoW) Series is a new object, so can be changed inplace + # without modifying original datafame + s.sort_values(inplace=True) + tm.assert_series_equal(s, float_frame_orig["A"].sort_values()) + # column in dataframe is not changed + tm.assert_frame_equal(float_frame, float_frame_orig) + else: + with pytest.raises(ValueError, match="This Series is a view"): + s.sort_values(inplace=True) + + cp = s.copy() + cp.sort_values() # it works! + + def test_sort_values_nat_values_in_int_column(self): + # GH#14922: "sorting with large float and multiple columns incorrect" + + # cause was that the int64 value NaT was considered as "na". Which is + # only correct for datetime64 columns. + + int_values = (2, int(NaT._value)) + float_values = (2.0, -1.797693e308) + + df = DataFrame( + {"int": int_values, "float": float_values}, columns=["int", "float"] + ) + + df_reversed = DataFrame( + {"int": int_values[::-1], "float": float_values[::-1]}, + columns=["int", "float"], + index=[1, 0], + ) + + # NaT is not a "na" for int64 columns, so na_position must not + # influence the result: + df_sorted = df.sort_values(["int", "float"], na_position="last") + tm.assert_frame_equal(df_sorted, df_reversed) + + df_sorted = df.sort_values(["int", "float"], na_position="first") + tm.assert_frame_equal(df_sorted, df_reversed) + + # reverse sorting order + df_sorted = df.sort_values(["int", "float"], ascending=False) + tm.assert_frame_equal(df_sorted, df) + + # and now check if NaT is still considered as "na" for datetime64 + # columns: + df = DataFrame( + {"datetime": [Timestamp("2016-01-01"), NaT], "float": float_values}, + columns=["datetime", "float"], + ) + + df_reversed = DataFrame( + {"datetime": [NaT, Timestamp("2016-01-01")], "float": float_values[::-1]}, + columns=["datetime", "float"], + index=[1, 0], + ) + + df_sorted = df.sort_values(["datetime", "float"], na_position="first") + tm.assert_frame_equal(df_sorted, df_reversed) + + df_sorted = df.sort_values(["datetime", "float"], na_position="last") + tm.assert_frame_equal(df_sorted, df) + + # Ascending should not affect the results. + df_sorted = df.sort_values(["datetime", "float"], ascending=False) + tm.assert_frame_equal(df_sorted, df) + + def test_sort_nat(self): + # GH 16836 + + d1 = [Timestamp(x) for x in ["2016-01-01", "2015-01-01", np.nan, "2016-01-01"]] + d2 = [ + Timestamp(x) + for x in ["2017-01-01", "2014-01-01", "2016-01-01", "2015-01-01"] + ] + df = DataFrame({"a": d1, "b": d2}, index=[0, 1, 2, 3]) + + d3 = [Timestamp(x) for x in ["2015-01-01", "2016-01-01", "2016-01-01", np.nan]] + d4 = [ + Timestamp(x) + for x in ["2014-01-01", "2015-01-01", "2017-01-01", "2016-01-01"] + ] + expected = DataFrame({"a": d3, "b": d4}, index=[1, 3, 0, 2]) + sorted_df = df.sort_values(by=["a", "b"]) + tm.assert_frame_equal(sorted_df, expected) + + def test_sort_values_na_position_with_categories(self): + # GH#22556 + # Positioning missing value properly when column is Categorical. + categories = ["A", "B", "C"] + category_indices = [0, 2, 4] + list_of_nans = [np.nan, np.nan] + na_indices = [1, 3] + na_position_first = "first" + na_position_last = "last" + column_name = "c" + + reversed_categories = sorted(categories, reverse=True) + reversed_category_indices = sorted(category_indices, reverse=True) + reversed_na_indices = sorted(na_indices) + + df = DataFrame( + { + column_name: Categorical( + ["A", np.nan, "B", np.nan, "C"], categories=categories, ordered=True + ) + } + ) + # sort ascending with na first + result = df.sort_values( + by=column_name, ascending=True, na_position=na_position_first + ) + expected = DataFrame( + { + column_name: Categorical( + list_of_nans + categories, categories=categories, ordered=True + ) + }, + index=na_indices + category_indices, + ) + + tm.assert_frame_equal(result, expected) + + # sort ascending with na last + result = df.sort_values( + by=column_name, ascending=True, na_position=na_position_last + ) + expected = DataFrame( + { + column_name: Categorical( + categories + list_of_nans, categories=categories, ordered=True + ) + }, + index=category_indices + na_indices, + ) + + tm.assert_frame_equal(result, expected) + + # sort descending with na first + result = df.sort_values( + by=column_name, ascending=False, na_position=na_position_first + ) + expected = DataFrame( + { + column_name: Categorical( + list_of_nans + reversed_categories, + categories=categories, + ordered=True, + ) + }, + index=reversed_na_indices + reversed_category_indices, + ) + + tm.assert_frame_equal(result, expected) + + # sort descending with na last + result = df.sort_values( + by=column_name, ascending=False, na_position=na_position_last + ) + expected = DataFrame( + { + column_name: Categorical( + reversed_categories + list_of_nans, + categories=categories, + ordered=True, + ) + }, + index=reversed_category_indices + reversed_na_indices, + ) + + tm.assert_frame_equal(result, expected) + + def test_sort_values_nat(self): + # GH#16836 + + d1 = [Timestamp(x) for x in ["2016-01-01", "2015-01-01", np.nan, "2016-01-01"]] + d2 = [ + Timestamp(x) + for x in ["2017-01-01", "2014-01-01", "2016-01-01", "2015-01-01"] + ] + df = DataFrame({"a": d1, "b": d2}, index=[0, 1, 2, 3]) + + d3 = [Timestamp(x) for x in ["2015-01-01", "2016-01-01", "2016-01-01", np.nan]] + d4 = [ + Timestamp(x) + for x in ["2014-01-01", "2015-01-01", "2017-01-01", "2016-01-01"] + ] + expected = DataFrame({"a": d3, "b": d4}, index=[1, 3, 0, 2]) + sorted_df = df.sort_values(by=["a", "b"]) + tm.assert_frame_equal(sorted_df, expected) + + def test_sort_values_na_position_with_categories_raises(self): + df = DataFrame( + { + "c": Categorical( + ["A", np.nan, "B", np.nan, "C"], + categories=["A", "B", "C"], + ordered=True, + ) + } + ) + + with pytest.raises(ValueError, match="invalid na_position: bad_position"): + df.sort_values(by="c", ascending=False, na_position="bad_position") + + @pytest.mark.parametrize("inplace", [True, False]) + @pytest.mark.parametrize( + "original_dict, sorted_dict, ignore_index, output_index", + [ + ({"A": [1, 2, 3]}, {"A": [3, 2, 1]}, True, [0, 1, 2]), + ({"A": [1, 2, 3]}, {"A": [3, 2, 1]}, False, [2, 1, 0]), + ( + {"A": [1, 2, 3], "B": [2, 3, 4]}, + {"A": [3, 2, 1], "B": [4, 3, 2]}, + True, + [0, 1, 2], + ), + ( + {"A": [1, 2, 3], "B": [2, 3, 4]}, + {"A": [3, 2, 1], "B": [4, 3, 2]}, + False, + [2, 1, 0], + ), + ], + ) + def test_sort_values_ignore_index( + self, inplace, original_dict, sorted_dict, ignore_index, output_index + ): + # GH 30114 + df = DataFrame(original_dict) + expected = DataFrame(sorted_dict, index=output_index) + kwargs = {"ignore_index": ignore_index, "inplace": inplace} + + if inplace: + result_df = df.copy() + result_df.sort_values("A", ascending=False, **kwargs) + else: + result_df = df.sort_values("A", ascending=False, **kwargs) + + tm.assert_frame_equal(result_df, expected) + tm.assert_frame_equal(df, DataFrame(original_dict)) + + def test_sort_values_nat_na_position_default(self): + # GH 13230 + expected = DataFrame( + { + "A": [1, 2, 3, 4, 4], + "date": pd.DatetimeIndex( + [ + "2010-01-01 09:00:00", + "2010-01-01 09:00:01", + "2010-01-01 09:00:02", + "2010-01-01 09:00:03", + "NaT", + ] + ), + } + ) + result = expected.sort_values(["A", "date"]) + tm.assert_frame_equal(result, expected) + + def test_sort_values_item_cache(self, using_array_manager, using_copy_on_write): + # previous behavior incorrect retained an invalid _item_cache entry + df = DataFrame( + np.random.default_rng(2).standard_normal((4, 3)), columns=["A", "B", "C"] + ) + df["D"] = df["A"] * 2 + ser = df["A"] + if not using_array_manager: + assert len(df._mgr.blocks) == 2 + + df.sort_values(by="A") + + if using_copy_on_write: + ser.iloc[0] = 99 + assert df.iloc[0, 0] == df["A"][0] + assert df.iloc[0, 0] != 99 + else: + ser.values[0] = 99 + assert df.iloc[0, 0] == df["A"][0] + assert df.iloc[0, 0] == 99 + + def test_sort_values_reshaping(self): + # GH 39426 + values = list(range(21)) + expected = DataFrame([values], columns=values) + df = expected.sort_values(expected.index[0], axis=1, ignore_index=True) + + tm.assert_frame_equal(df, expected) + + def test_sort_values_no_by_inplace(self): + # GH#50643 + df = DataFrame({"a": [1, 2, 3]}) + expected = df.copy() + result = df.sort_values(by=[], inplace=True) + tm.assert_frame_equal(df, expected) + assert result is None + + def test_sort_values_no_op_reset_index(self): + # GH#52553 + df = DataFrame({"A": [10, 20], "B": [1, 5]}, index=[2, 3]) + result = df.sort_values(by="A", ignore_index=True) + expected = DataFrame({"A": [10, 20], "B": [1, 5]}) + tm.assert_frame_equal(result, expected) + + +class TestDataFrameSortKey: # test key sorting (issue 27237) + def test_sort_values_inplace_key(self, sort_by_key): + frame = DataFrame( + np.random.default_rng(2).standard_normal((4, 4)), + index=[1, 2, 3, 4], + columns=["A", "B", "C", "D"], + ) + + sorted_df = frame.copy() + return_value = sorted_df.sort_values(by="A", inplace=True, key=sort_by_key) + assert return_value is None + expected = frame.sort_values(by="A", key=sort_by_key) + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.copy() + return_value = sorted_df.sort_values( + by=1, axis=1, inplace=True, key=sort_by_key + ) + assert return_value is None + expected = frame.sort_values(by=1, axis=1, key=sort_by_key) + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.copy() + return_value = sorted_df.sort_values( + by="A", ascending=False, inplace=True, key=sort_by_key + ) + assert return_value is None + expected = frame.sort_values(by="A", ascending=False, key=sort_by_key) + tm.assert_frame_equal(sorted_df, expected) + + sorted_df = frame.copy() + sorted_df.sort_values( + by=["A", "B"], ascending=False, inplace=True, key=sort_by_key + ) + expected = frame.sort_values(by=["A", "B"], ascending=False, key=sort_by_key) + tm.assert_frame_equal(sorted_df, expected) + + def test_sort_values_key(self): + df = DataFrame(np.array([0, 5, np.nan, 3, 2, np.nan])) + + result = df.sort_values(0) + expected = df.iloc[[0, 4, 3, 1, 2, 5]] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(0, key=lambda x: x + 5) + expected = df.iloc[[0, 4, 3, 1, 2, 5]] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(0, key=lambda x: -x, ascending=False) + expected = df.iloc[[0, 4, 3, 1, 2, 5]] + tm.assert_frame_equal(result, expected) + + def test_sort_values_by_key(self): + df = DataFrame( + { + "a": np.array([0, 3, np.nan, 3, 2, np.nan]), + "b": np.array([0, 2, np.nan, 5, 2, np.nan]), + } + ) + + result = df.sort_values("a", key=lambda x: -x) + expected = df.iloc[[1, 3, 4, 0, 2, 5]] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(by=["a", "b"], key=lambda x: -x) + expected = df.iloc[[3, 1, 4, 0, 2, 5]] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(by=["a", "b"], key=lambda x: -x, ascending=False) + expected = df.iloc[[0, 4, 1, 3, 2, 5]] + tm.assert_frame_equal(result, expected) + + def test_sort_values_by_key_by_name(self): + df = DataFrame( + { + "a": np.array([0, 3, np.nan, 3, 2, np.nan]), + "b": np.array([0, 2, np.nan, 5, 2, np.nan]), + } + ) + + def key(col): + if col.name == "a": + return -col + else: + return col + + result = df.sort_values(by="a", key=key) + expected = df.iloc[[1, 3, 4, 0, 2, 5]] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(by=["a"], key=key) + expected = df.iloc[[1, 3, 4, 0, 2, 5]] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(by="b", key=key) + expected = df.iloc[[0, 1, 4, 3, 2, 5]] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(by=["a", "b"], key=key) + expected = df.iloc[[1, 3, 4, 0, 2, 5]] + tm.assert_frame_equal(result, expected) + + def test_sort_values_key_string(self): + df = DataFrame(np.array([["hello", "goodbye"], ["hello", "Hello"]])) + + result = df.sort_values(1) + expected = df[::-1] + tm.assert_frame_equal(result, expected) + + result = df.sort_values([0, 1], key=lambda col: col.str.lower()) + tm.assert_frame_equal(result, df) + + result = df.sort_values( + [0, 1], key=lambda col: col.str.lower(), ascending=False + ) + expected = df.sort_values(1, key=lambda col: col.str.lower(), ascending=False) + tm.assert_frame_equal(result, expected) + + def test_sort_values_key_empty(self, sort_by_key): + df = DataFrame(np.array([])) + + df.sort_values(0, key=sort_by_key) + df.sort_index(key=sort_by_key) + + def test_changes_length_raises(self): + df = DataFrame({"A": [1, 2, 3]}) + with pytest.raises(ValueError, match="change the shape"): + df.sort_values("A", key=lambda x: x[:1]) + + def test_sort_values_key_axes(self): + df = DataFrame({0: ["Hello", "goodbye"], 1: [0, 1]}) + + result = df.sort_values(0, key=lambda col: col.str.lower()) + expected = df[::-1] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(1, key=lambda col: -col) + expected = df[::-1] + tm.assert_frame_equal(result, expected) + + def test_sort_values_key_dict_axis(self): + df = DataFrame({0: ["Hello", 0], 1: ["goodbye", 1]}) + + result = df.sort_values(0, key=lambda col: col.str.lower(), axis=1) + expected = df.loc[:, ::-1] + tm.assert_frame_equal(result, expected) + + result = df.sort_values(1, key=lambda col: -col, axis=1) + expected = df.loc[:, ::-1] + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("ordered", [True, False]) + def test_sort_values_key_casts_to_categorical(self, ordered): + # https://github.com/pandas-dev/pandas/issues/36383 + categories = ["c", "b", "a"] + df = DataFrame({"x": [1, 1, 1], "y": ["a", "b", "c"]}) + + def sorter(key): + if key.name == "y": + return pd.Series( + Categorical(key, categories=categories, ordered=ordered) + ) + return key + + result = df.sort_values(by=["x", "y"], key=sorter) + expected = DataFrame( + {"x": [1, 1, 1], "y": ["c", "b", "a"]}, index=pd.Index([2, 1, 0]) + ) + + tm.assert_frame_equal(result, expected) + + +@pytest.fixture +def df_none(): + return DataFrame( + { + "outer": ["a", "a", "a", "b", "b", "b"], + "inner": [1, 2, 2, 2, 1, 1], + "A": np.arange(6, 0, -1), + ("B", 5): ["one", "one", "two", "two", "one", "one"], + } + ) + + +@pytest.fixture(params=[["outer"], ["outer", "inner"]]) +def df_idx(request, df_none): + levels = request.param + return df_none.set_index(levels) + + +@pytest.fixture( + params=[ + "inner", # index level + ["outer"], # list of index level + "A", # column + [("B", 5)], # list of column + ["inner", "outer"], # two index levels + [("B", 5), "outer"], # index level and column + ["A", ("B", 5)], # Two columns + ["inner", "outer"], # two index levels and column + ] +) +def sort_names(request): + return request.param + + +@pytest.fixture(params=[True, False]) +def ascending(request): + return request.param + + +class TestSortValuesLevelAsStr: + def test_sort_index_level_and_column_label( + self, df_none, df_idx, sort_names, ascending, request + ): + # GH#14353 + if ( + Version(np.__version__) >= Version("1.25") + and request.node.callspec.id == "df_idx0-inner-True" + ): + request.applymarker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) + + # Get index levels from df_idx + levels = df_idx.index.names + + # Compute expected by sorting on columns and the setting index + expected = df_none.sort_values( + by=sort_names, ascending=ascending, axis=0 + ).set_index(levels) + + # Compute result sorting on mix on columns and index levels + result = df_idx.sort_values(by=sort_names, ascending=ascending, axis=0) + + tm.assert_frame_equal(result, expected) + + def test_sort_column_level_and_index_label( + self, df_none, df_idx, sort_names, ascending, request + ): + # GH#14353 + + # Get levels from df_idx + levels = df_idx.index.names + + # Compute expected by sorting on axis=0, setting index levels, and then + # transposing. For some cases this will result in a frame with + # multiple column levels + expected = ( + df_none.sort_values(by=sort_names, ascending=ascending, axis=0) + .set_index(levels) + .T + ) + + # Compute result by transposing and sorting on axis=1. + result = df_idx.T.sort_values(by=sort_names, ascending=ascending, axis=1) + + if Version(np.__version__) >= Version("1.25"): + request.applymarker( + pytest.mark.xfail( + reason=( + "pandas default unstable sorting of duplicates" + "issue with numpy>=1.25 with AVX instructions" + ), + strict=False, + ) + ) + + tm.assert_frame_equal(result, expected) + + def test_sort_values_validate_ascending_for_value_error(self): + # GH41634 + df = DataFrame({"D": [23, 7, 21]}) + + msg = 'For argument "ascending" expected type bool, received type str.' + with pytest.raises(ValueError, match=msg): + df.sort_values(by="D", ascending="False") + + @pytest.mark.parametrize("ascending", [False, 0, 1, True]) + def test_sort_values_validate_ascending_functional(self, ascending): + df = DataFrame({"D": [23, 7, 21]}) + indexer = df["D"].argsort().values + + if not ascending: + indexer = indexer[::-1] + + expected = df.loc[df.index[indexer]] + result = df.sort_values(by="D", ascending=ascending) + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/35/353d237eefb63bb4f6c21603e998e425d0c7f57b2baf64bab07b37d9e2351635/max_cuda_dispatch.h b/shared/package-files/35/353d237eefb63bb4f6c21603e998e425d0c7f57b2baf64bab07b37d9e2351635/max_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..3741e1fcc10dc6bae759a6ddc1e950c2f79a7123 --- /dev/null +++ b/shared/package-files/35/353d237eefb63bb4f6c21603e998e425d0c7f57b2baf64bab07b37d9e2351635/max_cuda_dispatch.h @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::tuple max(const at::Tensor & self, int64_t dim, bool keepdim=false); +TORCH_API ::std::tuple max_out(at::Tensor & max, at::Tensor & max_values, const at::Tensor & self, int64_t dim, bool keepdim=false); +TORCH_API ::std::tuple max_outf(const at::Tensor & self, int64_t dim, bool keepdim, at::Tensor & max, at::Tensor & max_values); +TORCH_API at::Tensor max(const at::Tensor & self); +TORCH_API at::Tensor & max_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & max_outf(const at::Tensor & self, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/35/3540f87d529d483d36ae2efe75bd2d9ced15a8b3fd687bb3992b5c5bbb40974f/_ssl_constants.py b/shared/package-files/35/3540f87d529d483d36ae2efe75bd2d9ced15a8b3fd687bb3992b5c5bbb40974f/_ssl_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..b1ee7a3cb13a8a3482f2cb8cadef097087e3780b --- /dev/null +++ b/shared/package-files/35/3540f87d529d483d36ae2efe75bd2d9ced15a8b3fd687bb3992b5c5bbb40974f/_ssl_constants.py @@ -0,0 +1,31 @@ +import ssl +import sys +import typing + +# Hold on to the original class so we can create it consistently +# even if we inject our own SSLContext into the ssl module. +_original_SSLContext = ssl.SSLContext +_original_super_SSLContext = super(_original_SSLContext, _original_SSLContext) + +# CPython is known to be good, but non-CPython implementations +# may implement SSLContext differently so to be safe we don't +# subclass the SSLContext. + +# This is returned by truststore.SSLContext.__class__() +_truststore_SSLContext_dunder_class: typing.Optional[type] + +# This value is the superclass of truststore.SSLContext. +_truststore_SSLContext_super_class: type + +if sys.implementation.name == "cpython": + _truststore_SSLContext_super_class = _original_SSLContext + _truststore_SSLContext_dunder_class = None +else: + _truststore_SSLContext_super_class = object + _truststore_SSLContext_dunder_class = _original_SSLContext + + +def _set_ssl_context_verify_mode( + ssl_context: ssl.SSLContext, verify_mode: ssl.VerifyMode +) -> None: + _original_super_SSLContext.verify_mode.__set__(ssl_context, verify_mode) # type: ignore[attr-defined] diff --git a/shared/package-files/35/35421ced16cb1f738e3cc7ed1c6c99c9618484501d2c9245c78958ba4e89d20a/soft_margin_loss.h b/shared/package-files/35/35421ced16cb1f738e3cc7ed1c6c99c9618484501d2c9245c78958ba4e89d20a/soft_margin_loss.h new file mode 100644 index 0000000000000000000000000000000000000000..43a443e3cdcf87bdb3728e7dfddfcaa5f94c96a4 --- /dev/null +++ b/shared/package-files/35/35421ced16cb1f738e3cc7ed1c6c99c9618484501d2c9245c78958ba4e89d20a/soft_margin_loss.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::soft_margin_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & soft_margin_loss_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & target, int64_t reduction=at::Reduction::Mean) { + return at::_ops::soft_margin_loss_out::call(self, target, reduction, out); +} +// aten::soft_margin_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & soft_margin_loss_outf(const at::Tensor & self, const at::Tensor & target, int64_t reduction, at::Tensor & out) { + return at::_ops::soft_margin_loss_out::call(self, target, reduction, out); +} + +// aten::soft_margin_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor +inline at::Tensor soft_margin_loss(const at::Tensor & self, const at::Tensor & target, int64_t reduction=at::Reduction::Mean) { + return at::_ops::soft_margin_loss::call(self, target, reduction); +} + +} diff --git a/shared/package-files/35/354736cf06c517cd23ef8ea6acb4a3d39ebb421f69e54937d70c984ce04433fd/nanmean_ops.h b/shared/package-files/35/354736cf06c517cd23ef8ea6acb4a3d39ebb421f69e54937d70c984ce04433fd/nanmean_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..d3609ba96e04e68c18be6ed54cfb2bb50790153b --- /dev/null +++ b/shared/package-files/35/354736cf06c517cd23ef8ea6acb4a3d39ebb421f69e54937d70c984ce04433fd/nanmean_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API nanmean { + using schema = at::Tensor (const at::Tensor &, at::OptionalIntArrayRef, bool, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::nanmean") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "nanmean(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype); +}; + +struct TORCH_API nanmean_out { + using schema = at::Tensor & (const at::Tensor &, at::OptionalIntArrayRef, bool, c10::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::nanmean") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "nanmean.out(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/35/3548ed16f0263dd4e3c0943e89afb16c2afce3d33f33a36294fe481df90a6918/npyio.py b/shared/package-files/35/3548ed16f0263dd4e3c0943e89afb16c2afce3d33f33a36294fe481df90a6918/npyio.py new file mode 100644 index 0000000000000000000000000000000000000000..339b1dc6211377442f7c01b78c8b3c65c65be2b7 --- /dev/null +++ b/shared/package-files/35/3548ed16f0263dd4e3c0943e89afb16c2afce3d33f33a36294fe481df90a6918/npyio.py @@ -0,0 +1,2547 @@ +import os +import re +import functools +import itertools +import warnings +import weakref +import contextlib +import operator +from operator import itemgetter, index as opindex, methodcaller +from collections.abc import Mapping + +import numpy as np +from . import format +from ._datasource import DataSource +from numpy.core import overrides +from numpy.core.multiarray import packbits, unpackbits +from numpy.core._multiarray_umath import _load_from_filelike +from numpy.core.overrides import set_array_function_like_doc, set_module +from ._iotools import ( + LineSplitter, NameValidator, StringConverter, ConverterError, + ConverterLockError, ConversionWarning, _is_string_like, + has_nested_fields, flatten_dtype, easy_dtype, _decode_line + ) + +from numpy.compat import ( + asbytes, asstr, asunicode, os_fspath, os_PathLike, + pickle + ) + + +__all__ = [ + 'savetxt', 'loadtxt', 'genfromtxt', + 'recfromtxt', 'recfromcsv', 'load', 'save', 'savez', + 'savez_compressed', 'packbits', 'unpackbits', 'fromregex', 'DataSource' + ] + + +array_function_dispatch = functools.partial( + overrides.array_function_dispatch, module='numpy') + + +class BagObj: + """ + BagObj(obj) + + Convert attribute look-ups to getitems on the object passed in. + + Parameters + ---------- + obj : class instance + Object on which attribute look-up is performed. + + Examples + -------- + >>> from numpy.lib.npyio import BagObj as BO + >>> class BagDemo: + ... def __getitem__(self, key): # An instance of BagObj(BagDemo) + ... # will call this method when any + ... # attribute look-up is required + ... result = "Doesn't matter what you want, " + ... return result + "you're gonna get this" + ... + >>> demo_obj = BagDemo() + >>> bagobj = BO(demo_obj) + >>> bagobj.hello_there + "Doesn't matter what you want, you're gonna get this" + >>> bagobj.I_can_be_anything + "Doesn't matter what you want, you're gonna get this" + + """ + + def __init__(self, obj): + # Use weakref to make NpzFile objects collectable by refcount + self._obj = weakref.proxy(obj) + + def __getattribute__(self, key): + try: + return object.__getattribute__(self, '_obj')[key] + except KeyError: + raise AttributeError(key) from None + + def __dir__(self): + """ + Enables dir(bagobj) to list the files in an NpzFile. + + This also enables tab-completion in an interpreter or IPython. + """ + return list(object.__getattribute__(self, '_obj').keys()) + + +def zipfile_factory(file, *args, **kwargs): + """ + Create a ZipFile. + + Allows for Zip64, and the `file` argument can accept file, str, or + pathlib.Path objects. `args` and `kwargs` are passed to the zipfile.ZipFile + constructor. + """ + if not hasattr(file, 'read'): + file = os_fspath(file) + import zipfile + kwargs['allowZip64'] = True + return zipfile.ZipFile(file, *args, **kwargs) + + +class NpzFile(Mapping): + """ + NpzFile(fid) + + A dictionary-like object with lazy-loading of files in the zipped + archive provided on construction. + + `NpzFile` is used to load files in the NumPy ``.npz`` data archive + format. It assumes that files in the archive have a ``.npy`` extension, + other files are ignored. + + The arrays and file strings are lazily loaded on either + getitem access using ``obj['key']`` or attribute lookup using + ``obj.f.key``. A list of all files (without ``.npy`` extensions) can + be obtained with ``obj.files`` and the ZipFile object itself using + ``obj.zip``. + + Attributes + ---------- + files : list of str + List of all files in the archive with a ``.npy`` extension. + zip : ZipFile instance + The ZipFile object initialized with the zipped archive. + f : BagObj instance + An object on which attribute can be performed as an alternative + to getitem access on the `NpzFile` instance itself. + allow_pickle : bool, optional + Allow loading pickled data. Default: False + + .. versionchanged:: 1.16.3 + Made default False in response to CVE-2019-6446. + + pickle_kwargs : dict, optional + Additional keyword arguments to pass on to pickle.load. + These are only useful when loading object arrays saved on + Python 2 when using Python 3. + max_header_size : int, optional + Maximum allowed size of the header. Large headers may not be safe + to load securely and thus require explicitly passing a larger value. + See :py:func:`ast.literal_eval()` for details. + This option is ignored when `allow_pickle` is passed. In that case + the file is by definition trusted and the limit is unnecessary. + + Parameters + ---------- + fid : file or str + The zipped archive to open. This is either a file-like object + or a string containing the path to the archive. + own_fid : bool, optional + Whether NpzFile should close the file handle. + Requires that `fid` is a file-like object. + + Examples + -------- + >>> from tempfile import TemporaryFile + >>> outfile = TemporaryFile() + >>> x = np.arange(10) + >>> y = np.sin(x) + >>> np.savez(outfile, x=x, y=y) + >>> _ = outfile.seek(0) + + >>> npz = np.load(outfile) + >>> isinstance(npz, np.lib.npyio.NpzFile) + True + >>> npz + NpzFile 'object' with keys x, y + >>> sorted(npz.files) + ['x', 'y'] + >>> npz['x'] # getitem access + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + >>> npz.f.x # attribute lookup + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + + """ + # Make __exit__ safe if zipfile_factory raises an exception + zip = None + fid = None + _MAX_REPR_ARRAY_COUNT = 5 + + def __init__(self, fid, own_fid=False, allow_pickle=False, + pickle_kwargs=None, *, + max_header_size=format._MAX_HEADER_SIZE): + # Import is postponed to here since zipfile depends on gzip, an + # optional component of the so-called standard library. + _zip = zipfile_factory(fid) + self._files = _zip.namelist() + self.files = [] + self.allow_pickle = allow_pickle + self.max_header_size = max_header_size + self.pickle_kwargs = pickle_kwargs + for x in self._files: + if x.endswith('.npy'): + self.files.append(x[:-4]) + else: + self.files.append(x) + self.zip = _zip + self.f = BagObj(self) + if own_fid: + self.fid = fid + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + def close(self): + """ + Close the file. + + """ + if self.zip is not None: + self.zip.close() + self.zip = None + if self.fid is not None: + self.fid.close() + self.fid = None + self.f = None # break reference cycle + + def __del__(self): + self.close() + + # Implement the Mapping ABC + def __iter__(self): + return iter(self.files) + + def __len__(self): + return len(self.files) + + def __getitem__(self, key): + # FIXME: This seems like it will copy strings around + # more than is strictly necessary. The zipfile + # will read the string and then + # the format.read_array will copy the string + # to another place in memory. + # It would be better if the zipfile could read + # (or at least uncompress) the data + # directly into the array memory. + member = False + if key in self._files: + member = True + elif key in self.files: + member = True + key += '.npy' + if member: + bytes = self.zip.open(key) + magic = bytes.read(len(format.MAGIC_PREFIX)) + bytes.close() + if magic == format.MAGIC_PREFIX: + bytes = self.zip.open(key) + return format.read_array(bytes, + allow_pickle=self.allow_pickle, + pickle_kwargs=self.pickle_kwargs, + max_header_size=self.max_header_size) + else: + return self.zip.read(key) + else: + raise KeyError(f"{key} is not a file in the archive") + + def __contains__(self, key): + return (key in self._files or key in self.files) + + def __repr__(self): + # Get filename or default to `object` + if isinstance(self.fid, str): + filename = self.fid + else: + filename = getattr(self.fid, "name", "object") + + # Get the name of arrays + array_names = ', '.join(self.files[:self._MAX_REPR_ARRAY_COUNT]) + if len(self.files) > self._MAX_REPR_ARRAY_COUNT: + array_names += "..." + return f"NpzFile {filename!r} with keys: {array_names}" + + +@set_module('numpy') +def load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, + encoding='ASCII', *, max_header_size=format._MAX_HEADER_SIZE): + """ + Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files. + + .. warning:: Loading files that contain object arrays uses the ``pickle`` + module, which is not secure against erroneous or maliciously + constructed data. Consider passing ``allow_pickle=False`` to + load data that is known not to contain object arrays for the + safer handling of untrusted sources. + + Parameters + ---------- + file : file-like object, string, or pathlib.Path + The file to read. File-like objects must support the + ``seek()`` and ``read()`` methods and must always + be opened in binary mode. Pickled files require that the + file-like object support the ``readline()`` method as well. + mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional + If not None, then memory-map the file, using the given mode (see + `numpy.memmap` for a detailed description of the modes). A + memory-mapped array is kept on disk. However, it can be accessed + and sliced like any ndarray. Memory mapping is especially useful + for accessing small fragments of large files without reading the + entire file into memory. + allow_pickle : bool, optional + Allow loading pickled object arrays stored in npy files. Reasons for + disallowing pickles include security, as loading pickled data can + execute arbitrary code. If pickles are disallowed, loading object + arrays will fail. Default: False + + .. versionchanged:: 1.16.3 + Made default False in response to CVE-2019-6446. + + fix_imports : bool, optional + Only useful when loading Python 2 generated pickled files on Python 3, + which includes npy/npz files containing object arrays. If `fix_imports` + is True, pickle will try to map the old Python 2 names to the new names + used in Python 3. + encoding : str, optional + What encoding to use when reading Python 2 strings. Only useful when + loading Python 2 generated pickled files in Python 3, which includes + npy/npz files containing object arrays. Values other than 'latin1', + 'ASCII', and 'bytes' are not allowed, as they can corrupt numerical + data. Default: 'ASCII' + max_header_size : int, optional + Maximum allowed size of the header. Large headers may not be safe + to load securely and thus require explicitly passing a larger value. + See :py:func:`ast.literal_eval()` for details. + This option is ignored when `allow_pickle` is passed. In that case + the file is by definition trusted and the limit is unnecessary. + + Returns + ------- + result : array, tuple, dict, etc. + Data stored in the file. For ``.npz`` files, the returned instance + of NpzFile class must be closed to avoid leaking file descriptors. + + Raises + ------ + OSError + If the input file does not exist or cannot be read. + UnpicklingError + If ``allow_pickle=True``, but the file cannot be loaded as a pickle. + ValueError + The file contains an object array, but ``allow_pickle=False`` given. + EOFError + When calling ``np.load`` multiple times on the same file handle, + if all data has already been read + + See Also + -------- + save, savez, savez_compressed, loadtxt + memmap : Create a memory-map to an array stored in a file on disk. + lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file. + + Notes + ----- + - If the file contains pickle data, then whatever object is stored + in the pickle is returned. + - If the file is a ``.npy`` file, then a single array is returned. + - If the file is a ``.npz`` file, then a dictionary-like object is + returned, containing ``{filename: array}`` key-value pairs, one for + each file in the archive. + - If the file is a ``.npz`` file, the returned value supports the + context manager protocol in a similar fashion to the open function:: + + with load('foo.npz') as data: + a = data['a'] + + The underlying file descriptor is closed when exiting the 'with' + block. + + Examples + -------- + Store data to disk, and load it again: + + >>> np.save('/tmp/123', np.array([[1, 2, 3], [4, 5, 6]])) + >>> np.load('/tmp/123.npy') + array([[1, 2, 3], + [4, 5, 6]]) + + Store compressed data to disk, and load it again: + + >>> a=np.array([[1, 2, 3], [4, 5, 6]]) + >>> b=np.array([1, 2]) + >>> np.savez('/tmp/123.npz', a=a, b=b) + >>> data = np.load('/tmp/123.npz') + >>> data['a'] + array([[1, 2, 3], + [4, 5, 6]]) + >>> data['b'] + array([1, 2]) + >>> data.close() + + Mem-map the stored array, and then access the second row + directly from disk: + + >>> X = np.load('/tmp/123.npy', mmap_mode='r') + >>> X[1, :] + memmap([4, 5, 6]) + + """ + if encoding not in ('ASCII', 'latin1', 'bytes'): + # The 'encoding' value for pickle also affects what encoding + # the serialized binary data of NumPy arrays is loaded + # in. Pickle does not pass on the encoding information to + # NumPy. The unpickling code in numpy.core.multiarray is + # written to assume that unicode data appearing where binary + # should be is in 'latin1'. 'bytes' is also safe, as is 'ASCII'. + # + # Other encoding values can corrupt binary data, and we + # purposefully disallow them. For the same reason, the errors= + # argument is not exposed, as values other than 'strict' + # result can similarly silently corrupt numerical data. + raise ValueError("encoding must be 'ASCII', 'latin1', or 'bytes'") + + pickle_kwargs = dict(encoding=encoding, fix_imports=fix_imports) + + with contextlib.ExitStack() as stack: + if hasattr(file, 'read'): + fid = file + own_fid = False + else: + fid = stack.enter_context(open(os_fspath(file), "rb")) + own_fid = True + + # Code to distinguish from NumPy binary files and pickles. + _ZIP_PREFIX = b'PK\x03\x04' + _ZIP_SUFFIX = b'PK\x05\x06' # empty zip files start with this + N = len(format.MAGIC_PREFIX) + magic = fid.read(N) + if not magic: + raise EOFError("No data left in file") + # If the file size is less than N, we need to make sure not + # to seek past the beginning of the file + fid.seek(-min(N, len(magic)), 1) # back-up + if magic.startswith(_ZIP_PREFIX) or magic.startswith(_ZIP_SUFFIX): + # zip-file (assume .npz) + # Potentially transfer file ownership to NpzFile + stack.pop_all() + ret = NpzFile(fid, own_fid=own_fid, allow_pickle=allow_pickle, + pickle_kwargs=pickle_kwargs, + max_header_size=max_header_size) + return ret + elif magic == format.MAGIC_PREFIX: + # .npy file + if mmap_mode: + if allow_pickle: + max_header_size = 2**64 + return format.open_memmap(file, mode=mmap_mode, + max_header_size=max_header_size) + else: + return format.read_array(fid, allow_pickle=allow_pickle, + pickle_kwargs=pickle_kwargs, + max_header_size=max_header_size) + else: + # Try a pickle + if not allow_pickle: + raise ValueError("Cannot load file containing pickled data " + "when allow_pickle=False") + try: + return pickle.load(fid, **pickle_kwargs) + except Exception as e: + raise pickle.UnpicklingError( + f"Failed to interpret file {file!r} as a pickle") from e + + +def _save_dispatcher(file, arr, allow_pickle=None, fix_imports=None): + return (arr,) + + +@array_function_dispatch(_save_dispatcher) +def save(file, arr, allow_pickle=True, fix_imports=True): + """ + Save an array to a binary file in NumPy ``.npy`` format. + + Parameters + ---------- + file : file, str, or pathlib.Path + File or filename to which the data is saved. If file is a file-object, + then the filename is unchanged. If file is a string or Path, a ``.npy`` + extension will be appended to the filename if it does not already + have one. + arr : array_like + Array data to be saved. + allow_pickle : bool, optional + Allow saving object arrays using Python pickles. Reasons for disallowing + pickles include security (loading pickled data can execute arbitrary + code) and portability (pickled objects may not be loadable on different + Python installations, for example if the stored objects require libraries + that are not available, and not all pickled data is compatible between + Python 2 and Python 3). + Default: True + fix_imports : bool, optional + Only useful in forcing objects in object arrays on Python 3 to be + pickled in a Python 2 compatible way. If `fix_imports` is True, pickle + will try to map the new Python 3 names to the old module names used in + Python 2, so that the pickle data stream is readable with Python 2. + + See Also + -------- + savez : Save several arrays into a ``.npz`` archive + savetxt, load + + Notes + ----- + For a description of the ``.npy`` format, see :py:mod:`numpy.lib.format`. + + Any data saved to the file is appended to the end of the file. + + Examples + -------- + >>> from tempfile import TemporaryFile + >>> outfile = TemporaryFile() + + >>> x = np.arange(10) + >>> np.save(outfile, x) + + >>> _ = outfile.seek(0) # Only needed here to simulate closing & reopening file + >>> np.load(outfile) + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + + + >>> with open('test.npy', 'wb') as f: + ... np.save(f, np.array([1, 2])) + ... np.save(f, np.array([1, 3])) + >>> with open('test.npy', 'rb') as f: + ... a = np.load(f) + ... b = np.load(f) + >>> print(a, b) + # [1 2] [1 3] + """ + if hasattr(file, 'write'): + file_ctx = contextlib.nullcontext(file) + else: + file = os_fspath(file) + if not file.endswith('.npy'): + file = file + '.npy' + file_ctx = open(file, "wb") + + with file_ctx as fid: + arr = np.asanyarray(arr) + format.write_array(fid, arr, allow_pickle=allow_pickle, + pickle_kwargs=dict(fix_imports=fix_imports)) + + +def _savez_dispatcher(file, *args, **kwds): + yield from args + yield from kwds.values() + + +@array_function_dispatch(_savez_dispatcher) +def savez(file, *args, **kwds): + """Save several arrays into a single file in uncompressed ``.npz`` format. + + Provide arrays as keyword arguments to store them under the + corresponding name in the output file: ``savez(fn, x=x, y=y)``. + + If arrays are specified as positional arguments, i.e., ``savez(fn, + x, y)``, their names will be `arr_0`, `arr_1`, etc. + + Parameters + ---------- + file : str or file + Either the filename (string) or an open file (file-like object) + where the data will be saved. If file is a string or a Path, the + ``.npz`` extension will be appended to the filename if it is not + already there. + args : Arguments, optional + Arrays to save to the file. Please use keyword arguments (see + `kwds` below) to assign names to arrays. Arrays specified as + args will be named "arr_0", "arr_1", and so on. + kwds : Keyword arguments, optional + Arrays to save to the file. Each array will be saved to the + output file with its corresponding keyword name. + + Returns + ------- + None + + See Also + -------- + save : Save a single array to a binary file in NumPy format. + savetxt : Save an array to a file as plain text. + savez_compressed : Save several arrays into a compressed ``.npz`` archive + + Notes + ----- + The ``.npz`` file format is a zipped archive of files named after the + variables they contain. The archive is not compressed and each file + in the archive contains one variable in ``.npy`` format. For a + description of the ``.npy`` format, see :py:mod:`numpy.lib.format`. + + When opening the saved ``.npz`` file with `load` a `NpzFile` object is + returned. This is a dictionary-like object which can be queried for + its list of arrays (with the ``.files`` attribute), and for the arrays + themselves. + + Keys passed in `kwds` are used as filenames inside the ZIP archive. + Therefore, keys should be valid filenames; e.g., avoid keys that begin with + ``/`` or contain ``.``. + + When naming variables with keyword arguments, it is not possible to name a + variable ``file``, as this would cause the ``file`` argument to be defined + twice in the call to ``savez``. + + Examples + -------- + >>> from tempfile import TemporaryFile + >>> outfile = TemporaryFile() + >>> x = np.arange(10) + >>> y = np.sin(x) + + Using `savez` with \\*args, the arrays are saved with default names. + + >>> np.savez(outfile, x, y) + >>> _ = outfile.seek(0) # Only needed here to simulate closing & reopening file + >>> npzfile = np.load(outfile) + >>> npzfile.files + ['arr_0', 'arr_1'] + >>> npzfile['arr_0'] + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + + Using `savez` with \\**kwds, the arrays are saved with the keyword names. + + >>> outfile = TemporaryFile() + >>> np.savez(outfile, x=x, y=y) + >>> _ = outfile.seek(0) + >>> npzfile = np.load(outfile) + >>> sorted(npzfile.files) + ['x', 'y'] + >>> npzfile['x'] + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + + """ + _savez(file, args, kwds, False) + + +def _savez_compressed_dispatcher(file, *args, **kwds): + yield from args + yield from kwds.values() + + +@array_function_dispatch(_savez_compressed_dispatcher) +def savez_compressed(file, *args, **kwds): + """ + Save several arrays into a single file in compressed ``.npz`` format. + + Provide arrays as keyword arguments to store them under the + corresponding name in the output file: ``savez(fn, x=x, y=y)``. + + If arrays are specified as positional arguments, i.e., ``savez(fn, + x, y)``, their names will be `arr_0`, `arr_1`, etc. + + Parameters + ---------- + file : str or file + Either the filename (string) or an open file (file-like object) + where the data will be saved. If file is a string or a Path, the + ``.npz`` extension will be appended to the filename if it is not + already there. + args : Arguments, optional + Arrays to save to the file. Please use keyword arguments (see + `kwds` below) to assign names to arrays. Arrays specified as + args will be named "arr_0", "arr_1", and so on. + kwds : Keyword arguments, optional + Arrays to save to the file. Each array will be saved to the + output file with its corresponding keyword name. + + Returns + ------- + None + + See Also + -------- + numpy.save : Save a single array to a binary file in NumPy format. + numpy.savetxt : Save an array to a file as plain text. + numpy.savez : Save several arrays into an uncompressed ``.npz`` file format + numpy.load : Load the files created by savez_compressed. + + Notes + ----- + The ``.npz`` file format is a zipped archive of files named after the + variables they contain. The archive is compressed with + ``zipfile.ZIP_DEFLATED`` and each file in the archive contains one variable + in ``.npy`` format. For a description of the ``.npy`` format, see + :py:mod:`numpy.lib.format`. + + + When opening the saved ``.npz`` file with `load` a `NpzFile` object is + returned. This is a dictionary-like object which can be queried for + its list of arrays (with the ``.files`` attribute), and for the arrays + themselves. + + Examples + -------- + >>> test_array = np.random.rand(3, 2) + >>> test_vector = np.random.rand(4) + >>> np.savez_compressed('/tmp/123', a=test_array, b=test_vector) + >>> loaded = np.load('/tmp/123.npz') + >>> print(np.array_equal(test_array, loaded['a'])) + True + >>> print(np.array_equal(test_vector, loaded['b'])) + True + + """ + _savez(file, args, kwds, True) + + +def _savez(file, args, kwds, compress, allow_pickle=True, pickle_kwargs=None): + # Import is postponed to here since zipfile depends on gzip, an optional + # component of the so-called standard library. + import zipfile + + if not hasattr(file, 'write'): + file = os_fspath(file) + if not file.endswith('.npz'): + file = file + '.npz' + + namedict = kwds + for i, val in enumerate(args): + key = 'arr_%d' % i + if key in namedict.keys(): + raise ValueError( + "Cannot use un-named variables and keyword %s" % key) + namedict[key] = val + + if compress: + compression = zipfile.ZIP_DEFLATED + else: + compression = zipfile.ZIP_STORED + + zipf = zipfile_factory(file, mode="w", compression=compression) + + for key, val in namedict.items(): + fname = key + '.npy' + val = np.asanyarray(val) + # always force zip64, gh-10776 + with zipf.open(fname, 'w', force_zip64=True) as fid: + format.write_array(fid, val, + allow_pickle=allow_pickle, + pickle_kwargs=pickle_kwargs) + + zipf.close() + + +def _ensure_ndmin_ndarray_check_param(ndmin): + """Just checks if the param ndmin is supported on + _ensure_ndmin_ndarray. It is intended to be used as + verification before running anything expensive. + e.g. loadtxt, genfromtxt + """ + # Check correctness of the values of `ndmin` + if ndmin not in [0, 1, 2]: + raise ValueError(f"Illegal value of ndmin keyword: {ndmin}") + +def _ensure_ndmin_ndarray(a, *, ndmin: int): + """This is a helper function of loadtxt and genfromtxt to ensure + proper minimum dimension as requested + + ndim : int. Supported values 1, 2, 3 + ^^ whenever this changes, keep in sync with + _ensure_ndmin_ndarray_check_param + """ + # Verify that the array has at least dimensions `ndmin`. + # Tweak the size and shape of the arrays - remove extraneous dimensions + if a.ndim > ndmin: + a = np.squeeze(a) + # and ensure we have the minimum number of dimensions asked for + # - has to be in this order for the odd case ndmin=1, a.squeeze().ndim=0 + if a.ndim < ndmin: + if ndmin == 1: + a = np.atleast_1d(a) + elif ndmin == 2: + a = np.atleast_2d(a).T + + return a + + +# amount of lines loadtxt reads in one chunk, can be overridden for testing +_loadtxt_chunksize = 50000 + + +def _check_nonneg_int(value, name="argument"): + try: + operator.index(value) + except TypeError: + raise TypeError(f"{name} must be an integer") from None + if value < 0: + raise ValueError(f"{name} must be nonnegative") + + +def _preprocess_comments(iterable, comments, encoding): + """ + Generator that consumes a line iterated iterable and strips out the + multiple (or multi-character) comments from lines. + This is a pre-processing step to achieve feature parity with loadtxt + (we assume that this feature is a nieche feature). + """ + for line in iterable: + if isinstance(line, bytes): + # Need to handle conversion here, or the splitting would fail + line = line.decode(encoding) + + for c in comments: + line = line.split(c, 1)[0] + + yield line + + +# The number of rows we read in one go if confronted with a parametric dtype +_loadtxt_chunksize = 50000 + + +def _read(fname, *, delimiter=',', comment='#', quote='"', + imaginary_unit='j', usecols=None, skiplines=0, + max_rows=None, converters=None, ndmin=None, unpack=False, + dtype=np.float64, encoding="bytes"): + r""" + Read a NumPy array from a text file. + + Parameters + ---------- + fname : str or file object + The filename or the file to be read. + delimiter : str, optional + Field delimiter of the fields in line of the file. + Default is a comma, ','. If None any sequence of whitespace is + considered a delimiter. + comment : str or sequence of str or None, optional + Character that begins a comment. All text from the comment + character to the end of the line is ignored. + Multiple comments or multiple-character comment strings are supported, + but may be slower and `quote` must be empty if used. + Use None to disable all use of comments. + quote : str or None, optional + Character that is used to quote string fields. Default is '"' + (a double quote). Use None to disable quote support. + imaginary_unit : str, optional + Character that represent the imaginay unit `sqrt(-1)`. + Default is 'j'. + usecols : array_like, optional + A one-dimensional array of integer column numbers. These are the + columns from the file to be included in the array. If this value + is not given, all the columns are used. + skiplines : int, optional + Number of lines to skip before interpreting the data in the file. + max_rows : int, optional + Maximum number of rows of data to read. Default is to read the + entire file. + converters : dict or callable, optional + A function to parse all columns strings into the desired value, or + a dictionary mapping column number to a parser function. + E.g. if column 0 is a date string: ``converters = {0: datestr2num}``. + Converters can also be used to provide a default value for missing + data, e.g. ``converters = lambda s: float(s.strip() or 0)`` will + convert empty fields to 0. + Default: None + ndmin : int, optional + Minimum dimension of the array returned. + Allowed values are 0, 1 or 2. Default is 0. + unpack : bool, optional + If True, the returned array is transposed, so that arguments may be + unpacked using ``x, y, z = read(...)``. When used with a structured + data-type, arrays are returned for each field. Default is False. + dtype : numpy data type + A NumPy dtype instance, can be a structured dtype to map to the + columns of the file. + encoding : str, optional + Encoding used to decode the inputfile. The special value 'bytes' + (the default) enables backwards-compatible behavior for `converters`, + ensuring that inputs to the converter functions are encoded + bytes objects. The special value 'bytes' has no additional effect if + ``converters=None``. If encoding is ``'bytes'`` or ``None``, the + default system encoding is used. + + Returns + ------- + ndarray + NumPy array. + + Examples + -------- + First we create a file for the example. + + >>> s1 = '1.0,2.0,3.0\n4.0,5.0,6.0\n' + >>> with open('example1.csv', 'w') as f: + ... f.write(s1) + >>> a1 = read_from_filename('example1.csv') + >>> a1 + array([[1., 2., 3.], + [4., 5., 6.]]) + + The second example has columns with different data types, so a + one-dimensional array with a structured data type is returned. + The tab character is used as the field delimiter. + + >>> s2 = '1.0\t10\talpha\n2.3\t25\tbeta\n4.5\t16\tgamma\n' + >>> with open('example2.tsv', 'w') as f: + ... f.write(s2) + >>> a2 = read_from_filename('example2.tsv', delimiter='\t') + >>> a2 + array([(1. , 10, b'alpha'), (2.3, 25, b'beta'), (4.5, 16, b'gamma')], + dtype=[('f0', '= 0: + max_rows -= chunk_size + if len(next_arr) < chunk_size: + # There was less data than requested, so we are done. + break + + # Need at least one chunk, but if empty, the last one may have + # the wrong shape. + if len(chunks) > 1 and len(chunks[-1]) == 0: + del chunks[-1] + if len(chunks) == 1: + arr = chunks[0] + else: + arr = np.concatenate(chunks, axis=0) + + # NOTE: ndmin works as advertised for structured dtypes, but normally + # these would return a 1D result plus the structured dimension, + # so ndmin=2 adds a third dimension even when no squeezing occurs. + # A `squeeze=False` could be a better solution (pandas uses squeeze). + arr = _ensure_ndmin_ndarray(arr, ndmin=ndmin) + + if arr.shape: + if arr.shape[0] == 0: + warnings.warn( + f'loadtxt: input contained no data: "{fname}"', + category=UserWarning, + stacklevel=3 + ) + + if unpack: + # Unpack structured dtypes if requested: + dt = arr.dtype + if dt.names is not None: + # For structured arrays, return an array for each field. + return [arr[field] for field in dt.names] + else: + return arr.T + else: + return arr + + +@set_array_function_like_doc +@set_module('numpy') +def loadtxt(fname, dtype=float, comments='#', delimiter=None, + converters=None, skiprows=0, usecols=None, unpack=False, + ndmin=0, encoding='bytes', max_rows=None, *, quotechar=None, + like=None): + r""" + Load data from a text file. + + Parameters + ---------- + fname : file, str, pathlib.Path, list of str, generator + File, filename, list, or generator to read. If the filename + extension is ``.gz`` or ``.bz2``, the file is first decompressed. Note + that generators must return bytes or strings. The strings + in a list or produced by a generator are treated as lines. + dtype : data-type, optional + Data-type of the resulting array; default: float. If this is a + structured data-type, the resulting array will be 1-dimensional, and + each row will be interpreted as an element of the array. In this + case, the number of columns used must match the number of fields in + the data-type. + comments : str or sequence of str or None, optional + The characters or list of characters used to indicate the start of a + comment. None implies no comments. For backwards compatibility, byte + strings will be decoded as 'latin1'. The default is '#'. + delimiter : str, optional + The character used to separate the values. For backwards compatibility, + byte strings will be decoded as 'latin1'. The default is whitespace. + + .. versionchanged:: 1.23.0 + Only single character delimiters are supported. Newline characters + cannot be used as the delimiter. + + converters : dict or callable, optional + Converter functions to customize value parsing. If `converters` is + callable, the function is applied to all columns, else it must be a + dict that maps column number to a parser function. + See examples for further details. + Default: None. + + .. versionchanged:: 1.23.0 + The ability to pass a single callable to be applied to all columns + was added. + + skiprows : int, optional + Skip the first `skiprows` lines, including comments; default: 0. + usecols : int or sequence, optional + Which columns to read, with 0 being the first. For example, + ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns. + The default, None, results in all columns being read. + + .. versionchanged:: 1.11.0 + When a single column has to be read it is possible to use + an integer instead of a tuple. E.g ``usecols = 3`` reads the + fourth column the same way as ``usecols = (3,)`` would. + unpack : bool, optional + If True, the returned array is transposed, so that arguments may be + unpacked using ``x, y, z = loadtxt(...)``. When used with a + structured data-type, arrays are returned for each field. + Default is False. + ndmin : int, optional + The returned array will have at least `ndmin` dimensions. + Otherwise mono-dimensional axes will be squeezed. + Legal values: 0 (default), 1 or 2. + + .. versionadded:: 1.6.0 + encoding : str, optional + Encoding used to decode the inputfile. Does not apply to input streams. + The special value 'bytes' enables backward compatibility workarounds + that ensures you receive byte arrays as results if possible and passes + 'latin1' encoded strings to converters. Override this value to receive + unicode arrays and pass strings as input to converters. If set to None + the system default is used. The default value is 'bytes'. + + .. versionadded:: 1.14.0 + max_rows : int, optional + Read `max_rows` rows of content after `skiprows` lines. The default is + to read all the rows. Note that empty rows containing no data such as + empty lines and comment lines are not counted towards `max_rows`, + while such lines are counted in `skiprows`. + + .. versionadded:: 1.16.0 + + .. versionchanged:: 1.23.0 + Lines containing no data, including comment lines (e.g., lines + starting with '#' or as specified via `comments`) are not counted + towards `max_rows`. + quotechar : unicode character or None, optional + The character used to denote the start and end of a quoted item. + Occurrences of the delimiter or comment characters are ignored within + a quoted item. The default value is ``quotechar=None``, which means + quoting support is disabled. + + If two consecutive instances of `quotechar` are found within a quoted + field, the first is treated as an escape character. See examples. + + .. versionadded:: 1.23.0 + ${ARRAY_FUNCTION_LIKE} + + .. versionadded:: 1.20.0 + + Returns + ------- + out : ndarray + Data read from the text file. + + See Also + -------- + load, fromstring, fromregex + genfromtxt : Load data with missing values handled as specified. + scipy.io.loadmat : reads MATLAB data files + + Notes + ----- + This function aims to be a fast reader for simply formatted files. The + `genfromtxt` function provides more sophisticated handling of, e.g., + lines with missing values. + + Each row in the input text file must have the same number of values to be + able to read all values. If all rows do not have same number of values, a + subset of up to n columns (where n is the least number of values present + in all rows) can be read by specifying the columns via `usecols`. + + .. versionadded:: 1.10.0 + + The strings produced by the Python float.hex method can be used as + input for floats. + + Examples + -------- + >>> from io import StringIO # StringIO behaves like a file object + >>> c = StringIO("0 1\n2 3") + >>> np.loadtxt(c) + array([[0., 1.], + [2., 3.]]) + + >>> d = StringIO("M 21 72\nF 35 58") + >>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'), + ... 'formats': ('S1', 'i4', 'f4')}) + array([(b'M', 21, 72.), (b'F', 35, 58.)], + dtype=[('gender', 'S1'), ('age', '>> c = StringIO("1,0,2\n3,0,4") + >>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True) + >>> x + array([1., 3.]) + >>> y + array([2., 4.]) + + The `converters` argument is used to specify functions to preprocess the + text prior to parsing. `converters` can be a dictionary that maps + preprocessing functions to each column: + + >>> s = StringIO("1.618, 2.296\n3.141, 4.669\n") + >>> conv = { + ... 0: lambda x: np.floor(float(x)), # conversion fn for column 0 + ... 1: lambda x: np.ceil(float(x)), # conversion fn for column 1 + ... } + >>> np.loadtxt(s, delimiter=",", converters=conv) + array([[1., 3.], + [3., 5.]]) + + `converters` can be a callable instead of a dictionary, in which case it + is applied to all columns: + + >>> s = StringIO("0xDE 0xAD\n0xC0 0xDE") + >>> import functools + >>> conv = functools.partial(int, base=16) + >>> np.loadtxt(s, converters=conv) + array([[222., 173.], + [192., 222.]]) + + This example shows how `converters` can be used to convert a field + with a trailing minus sign into a negative number. + + >>> s = StringIO('10.01 31.25-\n19.22 64.31\n17.57- 63.94') + >>> def conv(fld): + ... return -float(fld[:-1]) if fld.endswith(b'-') else float(fld) + ... + >>> np.loadtxt(s, converters=conv) + array([[ 10.01, -31.25], + [ 19.22, 64.31], + [-17.57, 63.94]]) + + Using a callable as the converter can be particularly useful for handling + values with different formatting, e.g. floats with underscores: + + >>> s = StringIO("1 2.7 100_000") + >>> np.loadtxt(s, converters=float) + array([1.e+00, 2.7e+00, 1.e+05]) + + This idea can be extended to automatically handle values specified in + many different formats: + + >>> def conv(val): + ... try: + ... return float(val) + ... except ValueError: + ... return float.fromhex(val) + >>> s = StringIO("1, 2.5, 3_000, 0b4, 0x1.4000000000000p+2") + >>> np.loadtxt(s, delimiter=",", converters=conv, encoding=None) + array([1.0e+00, 2.5e+00, 3.0e+03, 1.8e+02, 5.0e+00]) + + Note that with the default ``encoding="bytes"``, the inputs to the + converter function are latin-1 encoded byte strings. To deactivate the + implicit encoding prior to conversion, use ``encoding=None`` + + >>> s = StringIO('10.01 31.25-\n19.22 64.31\n17.57- 63.94') + >>> conv = lambda x: -float(x[:-1]) if x.endswith('-') else float(x) + >>> np.loadtxt(s, converters=conv, encoding=None) + array([[ 10.01, -31.25], + [ 19.22, 64.31], + [-17.57, 63.94]]) + + Support for quoted fields is enabled with the `quotechar` parameter. + Comment and delimiter characters are ignored when they appear within a + quoted item delineated by `quotechar`: + + >>> s = StringIO('"alpha, #42", 10.0\n"beta, #64", 2.0\n') + >>> dtype = np.dtype([("label", "U12"), ("value", float)]) + >>> np.loadtxt(s, dtype=dtype, delimiter=",", quotechar='"') + array([('alpha, #42', 10.), ('beta, #64', 2.)], + dtype=[('label', '>> s = StringIO('"alpha, #42" 10.0\n"beta, #64" 2.0\n') + >>> dtype = np.dtype([("label", "U12"), ("value", float)]) + >>> np.loadtxt(s, dtype=dtype, delimiter=None, quotechar='"') + array([('alpha, #42', 10.), ('beta, #64', 2.)], + dtype=[('label', '>> s = StringIO('"Hello, my name is ""Monty""!"') + >>> np.loadtxt(s, dtype="U", delimiter=",", quotechar='"') + array('Hello, my name is "Monty"!', dtype='>> d = StringIO("1 2\n2 4\n3 9 12\n4 16 20") + >>> np.loadtxt(d, usecols=(0, 1)) + array([[ 1., 2.], + [ 2., 4.], + [ 3., 9.], + [ 4., 16.]]) + + """ + + if like is not None: + return _loadtxt_with_like( + like, fname, dtype=dtype, comments=comments, delimiter=delimiter, + converters=converters, skiprows=skiprows, usecols=usecols, + unpack=unpack, ndmin=ndmin, encoding=encoding, + max_rows=max_rows + ) + + if isinstance(delimiter, bytes): + delimiter.decode("latin1") + + if dtype is None: + dtype = np.float64 + + comment = comments + # Control character type conversions for Py3 convenience + if comment is not None: + if isinstance(comment, (str, bytes)): + comment = [comment] + comment = [ + x.decode('latin1') if isinstance(x, bytes) else x for x in comment] + if isinstance(delimiter, bytes): + delimiter = delimiter.decode('latin1') + + arr = _read(fname, dtype=dtype, comment=comment, delimiter=delimiter, + converters=converters, skiplines=skiprows, usecols=usecols, + unpack=unpack, ndmin=ndmin, encoding=encoding, + max_rows=max_rows, quote=quotechar) + + return arr + + +_loadtxt_with_like = array_function_dispatch()(loadtxt) + + +def _savetxt_dispatcher(fname, X, fmt=None, delimiter=None, newline=None, + header=None, footer=None, comments=None, + encoding=None): + return (X,) + + +@array_function_dispatch(_savetxt_dispatcher) +def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', + footer='', comments='# ', encoding=None): + """ + Save an array to a text file. + + Parameters + ---------- + fname : filename or file handle + If the filename ends in ``.gz``, the file is automatically saved in + compressed gzip format. `loadtxt` understands gzipped files + transparently. + X : 1D or 2D array_like + Data to be saved to a text file. + fmt : str or sequence of strs, optional + A single format (%10.5f), a sequence of formats, or a + multi-format string, e.g. 'Iteration %d -- %10.5f', in which + case `delimiter` is ignored. For complex `X`, the legal options + for `fmt` are: + + * a single specifier, `fmt='%.4e'`, resulting in numbers formatted + like `' (%s+%sj)' % (fmt, fmt)` + * a full string specifying every real and imaginary part, e.g. + `' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'` for 3 columns + * a list of specifiers, one per column - in this case, the real + and imaginary part must have separate specifiers, + e.g. `['%.3e + %.3ej', '(%.15e%+.15ej)']` for 2 columns + delimiter : str, optional + String or character separating columns. + newline : str, optional + String or character separating lines. + + .. versionadded:: 1.5.0 + header : str, optional + String that will be written at the beginning of the file. + + .. versionadded:: 1.7.0 + footer : str, optional + String that will be written at the end of the file. + + .. versionadded:: 1.7.0 + comments : str, optional + String that will be prepended to the ``header`` and ``footer`` strings, + to mark them as comments. Default: '# ', as expected by e.g. + ``numpy.loadtxt``. + + .. versionadded:: 1.7.0 + encoding : {None, str}, optional + Encoding used to encode the outputfile. Does not apply to output + streams. If the encoding is something other than 'bytes' or 'latin1' + you will not be able to load the file in NumPy versions < 1.14. Default + is 'latin1'. + + .. versionadded:: 1.14.0 + + + See Also + -------- + save : Save an array to a binary file in NumPy ``.npy`` format + savez : Save several arrays into an uncompressed ``.npz`` archive + savez_compressed : Save several arrays into a compressed ``.npz`` archive + + Notes + ----- + Further explanation of the `fmt` parameter + (``%[flag]width[.precision]specifier``): + + flags: + ``-`` : left justify + + ``+`` : Forces to precede result with + or -. + + ``0`` : Left pad the number with zeros instead of space (see width). + + width: + Minimum number of characters to be printed. The value is not truncated + if it has more characters. + + precision: + - For integer specifiers (eg. ``d,i,o,x``), the minimum number of + digits. + - For ``e, E`` and ``f`` specifiers, the number of digits to print + after the decimal point. + - For ``g`` and ``G``, the maximum number of significant digits. + - For ``s``, the maximum number of characters. + + specifiers: + ``c`` : character + + ``d`` or ``i`` : signed decimal integer + + ``e`` or ``E`` : scientific notation with ``e`` or ``E``. + + ``f`` : decimal floating point + + ``g,G`` : use the shorter of ``e,E`` or ``f`` + + ``o`` : signed octal + + ``s`` : string of characters + + ``u`` : unsigned decimal integer + + ``x,X`` : unsigned hexadecimal integer + + This explanation of ``fmt`` is not complete, for an exhaustive + specification see [1]_. + + References + ---------- + .. [1] `Format Specification Mini-Language + `_, + Python Documentation. + + Examples + -------- + >>> x = y = z = np.arange(0.0,5.0,1.0) + >>> np.savetxt('test.out', x, delimiter=',') # X is an array + >>> np.savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays + >>> np.savetxt('test.out', x, fmt='%1.4e') # use exponential notation + + """ + + # Py3 conversions first + if isinstance(fmt, bytes): + fmt = asstr(fmt) + delimiter = asstr(delimiter) + + class WriteWrap: + """Convert to bytes on bytestream inputs. + + """ + def __init__(self, fh, encoding): + self.fh = fh + self.encoding = encoding + self.do_write = self.first_write + + def close(self): + self.fh.close() + + def write(self, v): + self.do_write(v) + + def write_bytes(self, v): + if isinstance(v, bytes): + self.fh.write(v) + else: + self.fh.write(v.encode(self.encoding)) + + def write_normal(self, v): + self.fh.write(asunicode(v)) + + def first_write(self, v): + try: + self.write_normal(v) + self.write = self.write_normal + except TypeError: + # input is probably a bytestream + self.write_bytes(v) + self.write = self.write_bytes + + own_fh = False + if isinstance(fname, os_PathLike): + fname = os_fspath(fname) + if _is_string_like(fname): + # datasource doesn't support creating a new file ... + open(fname, 'wt').close() + fh = np.lib._datasource.open(fname, 'wt', encoding=encoding) + own_fh = True + elif hasattr(fname, 'write'): + # wrap to handle byte output streams + fh = WriteWrap(fname, encoding or 'latin1') + else: + raise ValueError('fname must be a string or file handle') + + try: + X = np.asarray(X) + + # Handle 1-dimensional arrays + if X.ndim == 0 or X.ndim > 2: + raise ValueError( + "Expected 1D or 2D array, got %dD array instead" % X.ndim) + elif X.ndim == 1: + # Common case -- 1d array of numbers + if X.dtype.names is None: + X = np.atleast_2d(X).T + ncol = 1 + + # Complex dtype -- each field indicates a separate column + else: + ncol = len(X.dtype.names) + else: + ncol = X.shape[1] + + iscomplex_X = np.iscomplexobj(X) + # `fmt` can be a string with multiple insertion points or a + # list of formats. E.g. '%10.5f\t%10d' or ('%10.5f', '$10d') + if type(fmt) in (list, tuple): + if len(fmt) != ncol: + raise AttributeError('fmt has wrong shape. %s' % str(fmt)) + format = asstr(delimiter).join(map(asstr, fmt)) + elif isinstance(fmt, str): + n_fmt_chars = fmt.count('%') + error = ValueError('fmt has wrong number of %% formats: %s' % fmt) + if n_fmt_chars == 1: + if iscomplex_X: + fmt = [' (%s+%sj)' % (fmt, fmt), ] * ncol + else: + fmt = [fmt, ] * ncol + format = delimiter.join(fmt) + elif iscomplex_X and n_fmt_chars != (2 * ncol): + raise error + elif ((not iscomplex_X) and n_fmt_chars != ncol): + raise error + else: + format = fmt + else: + raise ValueError('invalid fmt: %r' % (fmt,)) + + if len(header) > 0: + header = header.replace('\n', '\n' + comments) + fh.write(comments + header + newline) + if iscomplex_X: + for row in X: + row2 = [] + for number in row: + row2.append(number.real) + row2.append(number.imag) + s = format % tuple(row2) + newline + fh.write(s.replace('+-', '-')) + else: + for row in X: + try: + v = format % tuple(row) + newline + except TypeError as e: + raise TypeError("Mismatch between array dtype ('%s') and " + "format specifier ('%s')" + % (str(X.dtype), format)) from e + fh.write(v) + + if len(footer) > 0: + footer = footer.replace('\n', '\n' + comments) + fh.write(comments + footer + newline) + finally: + if own_fh: + fh.close() + + +@set_module('numpy') +def fromregex(file, regexp, dtype, encoding=None): + r""" + Construct an array from a text file, using regular expression parsing. + + The returned array is always a structured array, and is constructed from + all matches of the regular expression in the file. Groups in the regular + expression are converted to fields of the structured array. + + Parameters + ---------- + file : path or file + Filename or file object to read. + + .. versionchanged:: 1.22.0 + Now accepts `os.PathLike` implementations. + regexp : str or regexp + Regular expression used to parse the file. + Groups in the regular expression correspond to fields in the dtype. + dtype : dtype or list of dtypes + Dtype for the structured array; must be a structured datatype. + encoding : str, optional + Encoding used to decode the inputfile. Does not apply to input streams. + + .. versionadded:: 1.14.0 + + Returns + ------- + output : ndarray + The output array, containing the part of the content of `file` that + was matched by `regexp`. `output` is always a structured array. + + Raises + ------ + TypeError + When `dtype` is not a valid dtype for a structured array. + + See Also + -------- + fromstring, loadtxt + + Notes + ----- + Dtypes for structured arrays can be specified in several forms, but all + forms specify at least the data type and field name. For details see + `basics.rec`. + + Examples + -------- + >>> from io import StringIO + >>> text = StringIO("1312 foo\n1534 bar\n444 qux") + + >>> regexp = r"(\d+)\s+(...)" # match [digits, whitespace, anything] + >>> output = np.fromregex(text, regexp, + ... [('num', np.int64), ('key', 'S3')]) + >>> output + array([(1312, b'foo'), (1534, b'bar'), ( 444, b'qux')], + dtype=[('num', '>> output['num'] + array([1312, 1534, 444]) + + """ + own_fh = False + if not hasattr(file, "read"): + file = os.fspath(file) + file = np.lib._datasource.open(file, 'rt', encoding=encoding) + own_fh = True + + try: + if not isinstance(dtype, np.dtype): + dtype = np.dtype(dtype) + if dtype.names is None: + raise TypeError('dtype must be a structured datatype.') + + content = file.read() + if isinstance(content, bytes) and isinstance(regexp, str): + regexp = asbytes(regexp) + elif isinstance(content, str) and isinstance(regexp, bytes): + regexp = asstr(regexp) + + if not hasattr(regexp, 'match'): + regexp = re.compile(regexp) + seq = regexp.findall(content) + if seq and not isinstance(seq[0], tuple): + # Only one group is in the regexp. + # Create the new array as a single data-type and then + # re-interpret as a single-field structured array. + newdtype = np.dtype(dtype[dtype.names[0]]) + output = np.array(seq, dtype=newdtype) + output.dtype = dtype + else: + output = np.array(seq, dtype=dtype) + + return output + finally: + if own_fh: + file.close() + + +#####-------------------------------------------------------------------------- +#---- --- ASCII functions --- +#####-------------------------------------------------------------------------- + + +@set_array_function_like_doc +@set_module('numpy') +def genfromtxt(fname, dtype=float, comments='#', delimiter=None, + skip_header=0, skip_footer=0, converters=None, + missing_values=None, filling_values=None, usecols=None, + names=None, excludelist=None, + deletechars=''.join(sorted(NameValidator.defaultdeletechars)), + replace_space='_', autostrip=False, case_sensitive=True, + defaultfmt="f%i", unpack=None, usemask=False, loose=True, + invalid_raise=True, max_rows=None, encoding='bytes', + *, ndmin=0, like=None): + """ + Load data from a text file, with missing values handled as specified. + + Each line past the first `skip_header` lines is split at the `delimiter` + character, and characters following the `comments` character are discarded. + + Parameters + ---------- + fname : file, str, pathlib.Path, list of str, generator + File, filename, list, or generator to read. If the filename + extension is ``.gz`` or ``.bz2``, the file is first decompressed. Note + that generators must return bytes or strings. The strings + in a list or produced by a generator are treated as lines. + dtype : dtype, optional + Data type of the resulting array. + If None, the dtypes will be determined by the contents of each + column, individually. + comments : str, optional + The character used to indicate the start of a comment. + All the characters occurring on a line after a comment are discarded. + delimiter : str, int, or sequence, optional + The string used to separate values. By default, any consecutive + whitespaces act as delimiter. An integer or sequence of integers + can also be provided as width(s) of each field. + skiprows : int, optional + `skiprows` was removed in numpy 1.10. Please use `skip_header` instead. + skip_header : int, optional + The number of lines to skip at the beginning of the file. + skip_footer : int, optional + The number of lines to skip at the end of the file. + converters : variable, optional + The set of functions that convert the data of a column to a value. + The converters can also be used to provide a default value + for missing data: ``converters = {3: lambda s: float(s or 0)}``. + missing : variable, optional + `missing` was removed in numpy 1.10. Please use `missing_values` + instead. + missing_values : variable, optional + The set of strings corresponding to missing data. + filling_values : variable, optional + The set of values to be used as default when the data are missing. + usecols : sequence, optional + Which columns to read, with 0 being the first. For example, + ``usecols = (1, 4, 5)`` will extract the 2nd, 5th and 6th columns. + names : {None, True, str, sequence}, optional + If `names` is True, the field names are read from the first line after + the first `skip_header` lines. This line can optionally be preceded + by a comment delimiter. If `names` is a sequence or a single-string of + comma-separated names, the names will be used to define the field names + in a structured dtype. If `names` is None, the names of the dtype + fields will be used, if any. + excludelist : sequence, optional + A list of names to exclude. This list is appended to the default list + ['return','file','print']. Excluded names are appended with an + underscore: for example, `file` would become `file_`. + deletechars : str, optional + A string combining invalid characters that must be deleted from the + names. + defaultfmt : str, optional + A format used to define default field names, such as "f%i" or "f_%02i". + autostrip : bool, optional + Whether to automatically strip white spaces from the variables. + replace_space : char, optional + Character(s) used in replacement of white spaces in the variable + names. By default, use a '_'. + case_sensitive : {True, False, 'upper', 'lower'}, optional + If True, field names are case sensitive. + If False or 'upper', field names are converted to upper case. + If 'lower', field names are converted to lower case. + unpack : bool, optional + If True, the returned array is transposed, so that arguments may be + unpacked using ``x, y, z = genfromtxt(...)``. When used with a + structured data-type, arrays are returned for each field. + Default is False. + usemask : bool, optional + If True, return a masked array. + If False, return a regular array. + loose : bool, optional + If True, do not raise errors for invalid values. + invalid_raise : bool, optional + If True, an exception is raised if an inconsistency is detected in the + number of columns. + If False, a warning is emitted and the offending lines are skipped. + max_rows : int, optional + The maximum number of rows to read. Must not be used with skip_footer + at the same time. If given, the value must be at least 1. Default is + to read the entire file. + + .. versionadded:: 1.10.0 + encoding : str, optional + Encoding used to decode the inputfile. Does not apply when `fname` is + a file object. The special value 'bytes' enables backward compatibility + workarounds that ensure that you receive byte arrays when possible + and passes latin1 encoded strings to converters. Override this value to + receive unicode arrays and pass strings as input to converters. If set + to None the system default is used. The default value is 'bytes'. + + .. versionadded:: 1.14.0 + ndmin : int, optional + Same parameter as `loadtxt` + + .. versionadded:: 1.23.0 + ${ARRAY_FUNCTION_LIKE} + + .. versionadded:: 1.20.0 + + Returns + ------- + out : ndarray + Data read from the text file. If `usemask` is True, this is a + masked array. + + See Also + -------- + numpy.loadtxt : equivalent function when no data is missing. + + Notes + ----- + * When spaces are used as delimiters, or when no delimiter has been given + as input, there should not be any missing data between two fields. + * When the variables are named (either by a flexible dtype or with `names`), + there must not be any header in the file (else a ValueError + exception is raised). + * Individual values are not stripped of spaces by default. + When using a custom converter, make sure the function does remove spaces. + + References + ---------- + .. [1] NumPy User Guide, section `I/O with NumPy + `_. + + Examples + -------- + >>> from io import StringIO + >>> import numpy as np + + Comma delimited file with mixed dtype + + >>> s = StringIO(u"1,1.3,abcde") + >>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'), + ... ('mystring','S5')], delimiter=",") + >>> data + array((1, 1.3, b'abcde'), + dtype=[('myint', '>> _ = s.seek(0) # needed for StringIO example only + >>> data = np.genfromtxt(s, dtype=None, + ... names = ['myint','myfloat','mystring'], delimiter=",") + >>> data + array((1, 1.3, b'abcde'), + dtype=[('myint', '>> _ = s.seek(0) + >>> data = np.genfromtxt(s, dtype="i8,f8,S5", + ... names=['myint','myfloat','mystring'], delimiter=",") + >>> data + array((1, 1.3, b'abcde'), + dtype=[('myint', '>> s = StringIO(u"11.3abcde") + >>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'], + ... delimiter=[1,3,5]) + >>> data + array((1, 1.3, b'abcde'), + dtype=[('intvar', '>> f = StringIO(''' + ... text,# of chars + ... hello world,11 + ... numpy,5''') + >>> np.genfromtxt(f, dtype='S12,S12', delimiter=',') + array([(b'text', b''), (b'hello world', b'11'), (b'numpy', b'5')], + dtype=[('f0', 'S12'), ('f1', 'S12')]) + + """ + + if like is not None: + return _genfromtxt_with_like( + like, fname, dtype=dtype, comments=comments, delimiter=delimiter, + skip_header=skip_header, skip_footer=skip_footer, + converters=converters, missing_values=missing_values, + filling_values=filling_values, usecols=usecols, names=names, + excludelist=excludelist, deletechars=deletechars, + replace_space=replace_space, autostrip=autostrip, + case_sensitive=case_sensitive, defaultfmt=defaultfmt, + unpack=unpack, usemask=usemask, loose=loose, + invalid_raise=invalid_raise, max_rows=max_rows, encoding=encoding, + ndmin=ndmin, + ) + + _ensure_ndmin_ndarray_check_param(ndmin) + + if max_rows is not None: + if skip_footer: + raise ValueError( + "The keywords 'skip_footer' and 'max_rows' can not be " + "specified at the same time.") + if max_rows < 1: + raise ValueError("'max_rows' must be at least 1.") + + if usemask: + from numpy.ma import MaskedArray, make_mask_descr + # Check the input dictionary of converters + user_converters = converters or {} + if not isinstance(user_converters, dict): + raise TypeError( + "The input argument 'converter' should be a valid dictionary " + "(got '%s' instead)" % type(user_converters)) + + if encoding == 'bytes': + encoding = None + byte_converters = True + else: + byte_converters = False + + # Initialize the filehandle, the LineSplitter and the NameValidator + if isinstance(fname, os_PathLike): + fname = os_fspath(fname) + if isinstance(fname, str): + fid = np.lib._datasource.open(fname, 'rt', encoding=encoding) + fid_ctx = contextlib.closing(fid) + else: + fid = fname + fid_ctx = contextlib.nullcontext(fid) + try: + fhd = iter(fid) + except TypeError as e: + raise TypeError( + "fname must be a string, a filehandle, a sequence of strings,\n" + f"or an iterator of strings. Got {type(fname)} instead." + ) from e + with fid_ctx: + split_line = LineSplitter(delimiter=delimiter, comments=comments, + autostrip=autostrip, encoding=encoding) + validate_names = NameValidator(excludelist=excludelist, + deletechars=deletechars, + case_sensitive=case_sensitive, + replace_space=replace_space) + + # Skip the first `skip_header` rows + try: + for i in range(skip_header): + next(fhd) + + # Keep on until we find the first valid values + first_values = None + + while not first_values: + first_line = _decode_line(next(fhd), encoding) + if (names is True) and (comments is not None): + if comments in first_line: + first_line = ( + ''.join(first_line.split(comments)[1:])) + first_values = split_line(first_line) + except StopIteration: + # return an empty array if the datafile is empty + first_line = '' + first_values = [] + warnings.warn('genfromtxt: Empty input file: "%s"' % fname, stacklevel=2) + + # Should we take the first values as names ? + if names is True: + fval = first_values[0].strip() + if comments is not None: + if fval in comments: + del first_values[0] + + # Check the columns to use: make sure `usecols` is a list + if usecols is not None: + try: + usecols = [_.strip() for _ in usecols.split(",")] + except AttributeError: + try: + usecols = list(usecols) + except TypeError: + usecols = [usecols, ] + nbcols = len(usecols or first_values) + + # Check the names and overwrite the dtype.names if needed + if names is True: + names = validate_names([str(_.strip()) for _ in first_values]) + first_line = '' + elif _is_string_like(names): + names = validate_names([_.strip() for _ in names.split(',')]) + elif names: + names = validate_names(names) + # Get the dtype + if dtype is not None: + dtype = easy_dtype(dtype, defaultfmt=defaultfmt, names=names, + excludelist=excludelist, + deletechars=deletechars, + case_sensitive=case_sensitive, + replace_space=replace_space) + # Make sure the names is a list (for 2.5) + if names is not None: + names = list(names) + + if usecols: + for (i, current) in enumerate(usecols): + # if usecols is a list of names, convert to a list of indices + if _is_string_like(current): + usecols[i] = names.index(current) + elif current < 0: + usecols[i] = current + len(first_values) + # If the dtype is not None, make sure we update it + if (dtype is not None) and (len(dtype) > nbcols): + descr = dtype.descr + dtype = np.dtype([descr[_] for _ in usecols]) + names = list(dtype.names) + # If `names` is not None, update the names + elif (names is not None) and (len(names) > nbcols): + names = [names[_] for _ in usecols] + elif (names is not None) and (dtype is not None): + names = list(dtype.names) + + # Process the missing values ............................... + # Rename missing_values for convenience + user_missing_values = missing_values or () + if isinstance(user_missing_values, bytes): + user_missing_values = user_missing_values.decode('latin1') + + # Define the list of missing_values (one column: one list) + missing_values = [list(['']) for _ in range(nbcols)] + + # We have a dictionary: process it field by field + if isinstance(user_missing_values, dict): + # Loop on the items + for (key, val) in user_missing_values.items(): + # Is the key a string ? + if _is_string_like(key): + try: + # Transform it into an integer + key = names.index(key) + except ValueError: + # We couldn't find it: the name must have been dropped + continue + # Redefine the key as needed if it's a column number + if usecols: + try: + key = usecols.index(key) + except ValueError: + pass + # Transform the value as a list of string + if isinstance(val, (list, tuple)): + val = [str(_) for _ in val] + else: + val = [str(val), ] + # Add the value(s) to the current list of missing + if key is None: + # None acts as default + for miss in missing_values: + miss.extend(val) + else: + missing_values[key].extend(val) + # We have a sequence : each item matches a column + elif isinstance(user_missing_values, (list, tuple)): + for (value, entry) in zip(user_missing_values, missing_values): + value = str(value) + if value not in entry: + entry.append(value) + # We have a string : apply it to all entries + elif isinstance(user_missing_values, str): + user_value = user_missing_values.split(",") + for entry in missing_values: + entry.extend(user_value) + # We have something else: apply it to all entries + else: + for entry in missing_values: + entry.extend([str(user_missing_values)]) + + # Process the filling_values ............................... + # Rename the input for convenience + user_filling_values = filling_values + if user_filling_values is None: + user_filling_values = [] + # Define the default + filling_values = [None] * nbcols + # We have a dictionary : update each entry individually + if isinstance(user_filling_values, dict): + for (key, val) in user_filling_values.items(): + if _is_string_like(key): + try: + # Transform it into an integer + key = names.index(key) + except ValueError: + # We couldn't find it: the name must have been dropped, + continue + # Redefine the key if it's a column number and usecols is defined + if usecols: + try: + key = usecols.index(key) + except ValueError: + pass + # Add the value to the list + filling_values[key] = val + # We have a sequence : update on a one-to-one basis + elif isinstance(user_filling_values, (list, tuple)): + n = len(user_filling_values) + if (n <= nbcols): + filling_values[:n] = user_filling_values + else: + filling_values = user_filling_values[:nbcols] + # We have something else : use it for all entries + else: + filling_values = [user_filling_values] * nbcols + + # Initialize the converters ................................ + if dtype is None: + # Note: we can't use a [...]*nbcols, as we would have 3 times the same + # ... converter, instead of 3 different converters. + converters = [StringConverter(None, missing_values=miss, default=fill) + for (miss, fill) in zip(missing_values, filling_values)] + else: + dtype_flat = flatten_dtype(dtype, flatten_base=True) + # Initialize the converters + if len(dtype_flat) > 1: + # Flexible type : get a converter from each dtype + zipit = zip(dtype_flat, missing_values, filling_values) + converters = [StringConverter(dt, locked=True, + missing_values=miss, default=fill) + for (dt, miss, fill) in zipit] + else: + # Set to a default converter (but w/ different missing values) + zipit = zip(missing_values, filling_values) + converters = [StringConverter(dtype, locked=True, + missing_values=miss, default=fill) + for (miss, fill) in zipit] + # Update the converters to use the user-defined ones + uc_update = [] + for (j, conv) in user_converters.items(): + # If the converter is specified by column names, use the index instead + if _is_string_like(j): + try: + j = names.index(j) + i = j + except ValueError: + continue + elif usecols: + try: + i = usecols.index(j) + except ValueError: + # Unused converter specified + continue + else: + i = j + # Find the value to test - first_line is not filtered by usecols: + if len(first_line): + testing_value = first_values[j] + else: + testing_value = None + if conv is bytes: + user_conv = asbytes + elif byte_converters: + # converters may use decode to workaround numpy's old behaviour, + # so encode the string again before passing to the user converter + def tobytes_first(x, conv): + if type(x) is bytes: + return conv(x) + return conv(x.encode("latin1")) + user_conv = functools.partial(tobytes_first, conv=conv) + else: + user_conv = conv + converters[i].update(user_conv, locked=True, + testing_value=testing_value, + default=filling_values[i], + missing_values=missing_values[i],) + uc_update.append((i, user_conv)) + # Make sure we have the corrected keys in user_converters... + user_converters.update(uc_update) + + # Fixme: possible error as following variable never used. + # miss_chars = [_.missing_values for _ in converters] + + # Initialize the output lists ... + # ... rows + rows = [] + append_to_rows = rows.append + # ... masks + if usemask: + masks = [] + append_to_masks = masks.append + # ... invalid + invalid = [] + append_to_invalid = invalid.append + + # Parse each line + for (i, line) in enumerate(itertools.chain([first_line, ], fhd)): + values = split_line(line) + nbvalues = len(values) + # Skip an empty line + if nbvalues == 0: + continue + if usecols: + # Select only the columns we need + try: + values = [values[_] for _ in usecols] + except IndexError: + append_to_invalid((i + skip_header + 1, nbvalues)) + continue + elif nbvalues != nbcols: + append_to_invalid((i + skip_header + 1, nbvalues)) + continue + # Store the values + append_to_rows(tuple(values)) + if usemask: + append_to_masks(tuple([v.strip() in m + for (v, m) in zip(values, + missing_values)])) + if len(rows) == max_rows: + break + + # Upgrade the converters (if needed) + if dtype is None: + for (i, converter) in enumerate(converters): + current_column = [itemgetter(i)(_m) for _m in rows] + try: + converter.iterupgrade(current_column) + except ConverterLockError: + errmsg = "Converter #%i is locked and cannot be upgraded: " % i + current_column = map(itemgetter(i), rows) + for (j, value) in enumerate(current_column): + try: + converter.upgrade(value) + except (ConverterError, ValueError): + errmsg += "(occurred line #%i for value '%s')" + errmsg %= (j + 1 + skip_header, value) + raise ConverterError(errmsg) + + # Check that we don't have invalid values + nbinvalid = len(invalid) + if nbinvalid > 0: + nbrows = len(rows) + nbinvalid - skip_footer + # Construct the error message + template = " Line #%%i (got %%i columns instead of %i)" % nbcols + if skip_footer > 0: + nbinvalid_skipped = len([_ for _ in invalid + if _[0] > nbrows + skip_header]) + invalid = invalid[:nbinvalid - nbinvalid_skipped] + skip_footer -= nbinvalid_skipped +# +# nbrows -= skip_footer +# errmsg = [template % (i, nb) +# for (i, nb) in invalid if i < nbrows] +# else: + errmsg = [template % (i, nb) + for (i, nb) in invalid] + if len(errmsg): + errmsg.insert(0, "Some errors were detected !") + errmsg = "\n".join(errmsg) + # Raise an exception ? + if invalid_raise: + raise ValueError(errmsg) + # Issue a warning ? + else: + warnings.warn(errmsg, ConversionWarning, stacklevel=2) + + # Strip the last skip_footer data + if skip_footer > 0: + rows = rows[:-skip_footer] + if usemask: + masks = masks[:-skip_footer] + + # Convert each value according to the converter: + # We want to modify the list in place to avoid creating a new one... + if loose: + rows = list( + zip(*[[conv._loose_call(_r) for _r in map(itemgetter(i), rows)] + for (i, conv) in enumerate(converters)])) + else: + rows = list( + zip(*[[conv._strict_call(_r) for _r in map(itemgetter(i), rows)] + for (i, conv) in enumerate(converters)])) + + # Reset the dtype + data = rows + if dtype is None: + # Get the dtypes from the types of the converters + column_types = [conv.type for conv in converters] + # Find the columns with strings... + strcolidx = [i for (i, v) in enumerate(column_types) + if v == np.str_] + + if byte_converters and strcolidx: + # convert strings back to bytes for backward compatibility + warnings.warn( + "Reading unicode strings without specifying the encoding " + "argument is deprecated. Set the encoding, use None for the " + "system default.", + np.VisibleDeprecationWarning, stacklevel=2) + def encode_unicode_cols(row_tup): + row = list(row_tup) + for i in strcolidx: + row[i] = row[i].encode('latin1') + return tuple(row) + + try: + data = [encode_unicode_cols(r) for r in data] + except UnicodeEncodeError: + pass + else: + for i in strcolidx: + column_types[i] = np.bytes_ + + # Update string types to be the right length + sized_column_types = column_types[:] + for i, col_type in enumerate(column_types): + if np.issubdtype(col_type, np.character): + n_chars = max(len(row[i]) for row in data) + sized_column_types[i] = (col_type, n_chars) + + if names is None: + # If the dtype is uniform (before sizing strings) + base = { + c_type + for c, c_type in zip(converters, column_types) + if c._checked} + if len(base) == 1: + uniform_type, = base + (ddtype, mdtype) = (uniform_type, bool) + else: + ddtype = [(defaultfmt % i, dt) + for (i, dt) in enumerate(sized_column_types)] + if usemask: + mdtype = [(defaultfmt % i, bool) + for (i, dt) in enumerate(sized_column_types)] + else: + ddtype = list(zip(names, sized_column_types)) + mdtype = list(zip(names, [bool] * len(sized_column_types))) + output = np.array(data, dtype=ddtype) + if usemask: + outputmask = np.array(masks, dtype=mdtype) + else: + # Overwrite the initial dtype names if needed + if names and dtype.names is not None: + dtype.names = names + # Case 1. We have a structured type + if len(dtype_flat) > 1: + # Nested dtype, eg [('a', int), ('b', [('b0', int), ('b1', 'f4')])] + # First, create the array using a flattened dtype: + # [('a', int), ('b1', int), ('b2', float)] + # Then, view the array using the specified dtype. + if 'O' in (_.char for _ in dtype_flat): + if has_nested_fields(dtype): + raise NotImplementedError( + "Nested fields involving objects are not supported...") + else: + output = np.array(data, dtype=dtype) + else: + rows = np.array(data, dtype=[('', _) for _ in dtype_flat]) + output = rows.view(dtype) + # Now, process the rowmasks the same way + if usemask: + rowmasks = np.array( + masks, dtype=np.dtype([('', bool) for t in dtype_flat])) + # Construct the new dtype + mdtype = make_mask_descr(dtype) + outputmask = rowmasks.view(mdtype) + # Case #2. We have a basic dtype + else: + # We used some user-defined converters + if user_converters: + ishomogeneous = True + descr = [] + for i, ttype in enumerate([conv.type for conv in converters]): + # Keep the dtype of the current converter + if i in user_converters: + ishomogeneous &= (ttype == dtype.type) + if np.issubdtype(ttype, np.character): + ttype = (ttype, max(len(row[i]) for row in data)) + descr.append(('', ttype)) + else: + descr.append(('', dtype)) + # So we changed the dtype ? + if not ishomogeneous: + # We have more than one field + if len(descr) > 1: + dtype = np.dtype(descr) + # We have only one field: drop the name if not needed. + else: + dtype = np.dtype(ttype) + # + output = np.array(data, dtype) + if usemask: + if dtype.names is not None: + mdtype = [(_, bool) for _ in dtype.names] + else: + mdtype = bool + outputmask = np.array(masks, dtype=mdtype) + # Try to take care of the missing data we missed + names = output.dtype.names + if usemask and names: + for (name, conv) in zip(names, converters): + missing_values = [conv(_) for _ in conv.missing_values + if _ != ''] + for mval in missing_values: + outputmask[name] |= (output[name] == mval) + # Construct the final array + if usemask: + output = output.view(MaskedArray) + output._mask = outputmask + + output = _ensure_ndmin_ndarray(output, ndmin=ndmin) + + if unpack: + if names is None: + return output.T + elif len(names) == 1: + # squeeze single-name dtypes too + return output[names[0]] + else: + # For structured arrays with multiple fields, + # return an array for each field. + return [output[field] for field in names] + return output + + +_genfromtxt_with_like = array_function_dispatch()(genfromtxt) + + +def recfromtxt(fname, **kwargs): + """ + Load ASCII data from a file and return it in a record array. + + If ``usemask=False`` a standard `recarray` is returned, + if ``usemask=True`` a MaskedRecords array is returned. + + Parameters + ---------- + fname, kwargs : For a description of input parameters, see `genfromtxt`. + + See Also + -------- + numpy.genfromtxt : generic function + + Notes + ----- + By default, `dtype` is None, which means that the data-type of the output + array will be determined from the data. + + """ + kwargs.setdefault("dtype", None) + usemask = kwargs.get('usemask', False) + output = genfromtxt(fname, **kwargs) + if usemask: + from numpy.ma.mrecords import MaskedRecords + output = output.view(MaskedRecords) + else: + output = output.view(np.recarray) + return output + + +def recfromcsv(fname, **kwargs): + """ + Load ASCII data stored in a comma-separated file. + + The returned array is a record array (if ``usemask=False``, see + `recarray`) or a masked record array (if ``usemask=True``, + see `ma.mrecords.MaskedRecords`). + + Parameters + ---------- + fname, kwargs : For a description of input parameters, see `genfromtxt`. + + See Also + -------- + numpy.genfromtxt : generic function to load ASCII data. + + Notes + ----- + By default, `dtype` is None, which means that the data-type of the output + array will be determined from the data. + + """ + # Set default kwargs for genfromtxt as relevant to csv import. + kwargs.setdefault("case_sensitive", "lower") + kwargs.setdefault("names", True) + kwargs.setdefault("delimiter", ",") + kwargs.setdefault("dtype", None) + output = genfromtxt(fname, **kwargs) + + usemask = kwargs.get("usemask", False) + if usemask: + from numpy.ma.mrecords import MaskedRecords + output = output.view(MaskedRecords) + else: + output = output.view(np.recarray) + return output diff --git a/shared/package-files/35/354bb81b5a5c059678f3dfc36a6cbba84714ca180b1cadef7b300d0cb327bb51/cpython-launcher-c-mods-for-setuptools.3.7.patch b/shared/package-files/35/354bb81b5a5c059678f3dfc36a6cbba84714ca180b1cadef7b300d0cb327bb51/cpython-launcher-c-mods-for-setuptools.3.7.patch new file mode 100644 index 0000000000000000000000000000000000000000..0310c65ca9ad28f00a942a26bafd3c3bca0912da --- /dev/null +++ b/shared/package-files/35/354bb81b5a5c059678f3dfc36a6cbba84714ca180b1cadef7b300d0cb327bb51/cpython-launcher-c-mods-for-setuptools.3.7.patch @@ -0,0 +1,303 @@ +--- launcher.c.orig 2020-02-23 11:24:16.544939800 +0100 ++++ launcher.c 2020-02-23 11:32:24.454773100 +0100 +@@ -8,11 +8,71 @@ + * Curt Hagenlocher (job management) + */ + ++#if defined(_MSC_VER) ++#ifdef NDEBUG ++// /Og (global optimizations), /Os (favor small code), /Oy (no frame pointers) ++#pragma optimize("gsy",on) ++ ++// Note that merging the .rdata section will result in LARGER exe's if you using ++// MFC (esp. static link). If this is desirable, define _MERGE_RDATA_ in your project. ++#ifdef _MERGE_RDATA_ ++#pragma comment(linker,"/merge:.rdata=.data") ++#endif // _MERGE_RDATA_ ++ ++#endif // NDEBUG ++#endif ++ + #include + #include + #include + #include + ++/* To build on MSYS2 use the following script: ++#!/usr/bin/env bash ++ ++wget -c https://raw.githubusercontent.com/python/cpython/3.7/PC/launcher.c -O launcher.c ++patch -p0 < $(dirname ${BASH_SOURCE[0]})/cpython-launcher-c-mods-for-setuptools.3.7.patch ++RCFILE=$(dirname ${BASH_SOURCE[0]})/resources.rc ++[[ -f ${RCFILE} ]] && rm -f ${RCFILE} ++echo "#include \"winuser.h\"" > ${RCFILE} ++echo "1 RT_MANIFEST manifest.xml" >> ${RCFILE} ++for _BITS in 64 32; do ++ [[ -f resources-${_BITS}.res ]] && rm -f resources-${_BITS}.res ++ PATH=/mingw${_BITS}/bin:$PATH windres --input ${RCFILE} --output resources-${_BITS}.res --output-format=coff ++ for _TYPE in cli gui; do ++ if [[ ${_TYPE} == cli ]]; then ++ CPPFLAGS= ++ LDFLAGS= ++ else ++ CPPFLAGS="-D_WINDOWS -mwindows" ++ LDFLAGS="-mwindows" ++ fi ++ # You *could* use MSVC 2008 here, but you'd end up with much larger (~230k) executables. ++ # cl.exe -opt:nowin98 -D NDEBUG -D "GUI=0" -D "WIN32_LEAN_AND_MEAN" -ZI -Gy -MT -MERGE launcher.c -Os -link -MACHINE:x64 -SUBSYSTEM:CONSOLE version.lib advapi32.lib shell32.lib ++ PATH=/mingw${_BITS}/bin:$PATH gcc -O2 -DSCRIPT_WRAPPER -DUNICODE -D_UNICODE -DMINGW_HAS_SECURE_API ${CPPFLAGS} launcher.c -c -o ${_TYPE}-${_BITS}.o ++ PATH=/mingw${_BITS}/bin:$PATH gcc -Wl,-s --static -static-libgcc -municode ${LDFLAGS} ${_TYPE}-${_BITS}.o resources-${_BITS}.res -o ${_TYPE}-${_BITS}.exe ++ done ++done ++ls -l *.exe ++echo "Debug this from cmd.exe via:" ++echo "set PYLAUNCH_DEBUG=1" ++ */ ++ ++/* Previosuly GetFileVersionInfoW was used here, but I would rather save ++ * the 1.5k that costs. If we bring this back, add -lversion to the link ++ * command line. ++ */ ++ ++#define VERSION_HIGH 0 ++#define VERSION_LOW 1 ++ ++/* Previously BUFSIZE was used for this but 256 is not enough for even 260 ++ * ASCII characters and far too little for unicode (it is a char array, not ++ * a wchar_t array, though it needs to be even bigger than 260 wchar_ts as ++ * the source script file could contain UTF-8 or UTF-32 (wchar_t is 2-byte) ++ */ ++#define SHEBANG_BUFSIZE 2048 ++ + #define BUFSIZE 256 + #define MSGSIZE 1024 + +@@ -742,6 +802,7 @@ + { L"/usr/bin/env python", TRUE }, + { L"/usr/bin/python", FALSE }, + { L"/usr/local/bin/python", FALSE }, ++ { L"python_d", FALSE }, + { L"python", FALSE }, + { NULL, FALSE }, + }; +@@ -796,6 +857,25 @@ + + static COMMAND path_command; + ++#if !defined(_MSC_VER) ++errno_t _wdupenv_s_emulated(wchar_t **buffer, ++ size_t *numberOfElements, ++ const wchar_t *varname) ++{ ++ size_t szreq; ++ ++ errno_t err = _wgetenv_s(&szreq, NULL, 0, varname); ++ if (szreq == 0) ++ return 1; ++ *buffer = (wchar_t*) malloc(sizeof(wchar_t) * szreq); ++ if (!*buffer) ++ return 1; ++ err = _wgetenv_s(&szreq, *buffer, szreq, varname); ++ return err; ++} ++#define _wdupenv_s _wdupenv_s_emulated ++#endif ++ + static COMMAND * find_on_path(wchar_t * name) + { + wchar_t * pathext; +@@ -919,7 +999,7 @@ + + static BOOL + parse_shebang(wchar_t * shebang_line, int nchars, wchar_t ** command, +- wchar_t ** suffix, BOOL *search) ++ wchar_t ** suffix, BOOL *search, wchar_t * argv0) + { + BOOL rc = FALSE; + SHEBANG * vpp; +@@ -929,11 +1009,40 @@ + wchar_t * endp = shebang_line + nchars - 1; + COMMAND * cp; + wchar_t * skipped; ++ wchar_t tidied[_MAX_DRIVE+_MAX_DIR+_MAX_FNAME+_MAX_EXT] = L""; + + *command = NULL; /* failure return */ + *suffix = NULL; + *search = FALSE; + ++ if ((shebang_line[0] != L'#') || (shebang_line[1] != L'!')) { ++ /* This is deliberately very similar to find_exe() in: ++ * https://raw.githubusercontent.com/pypa/setuptools/master/launcher.c ++ * I was tempted to use _wsplitpath_s twice to get the parent dir, but ++ * any change of behaviour here would cause big trouble. ++ */ ++ wchar_t drive[_MAX_DRIVE]; ++ wchar_t dir[_MAX_DIR]; ++ wchar_t fname[_MAX_FNAME]; ++ wchar_t ext[_MAX_EXT]; ++ wchar_t * tmp, wc; ++ debug(L"parse_shebang called without a valid shebang %s (for argv0 %s)\n", shebang_line, argv0); ++ if (wcslen(argv0)-1 < _countof(tidied)) { ++ wcsncpy_s(tidied, _countof(tidied), argv0, _TRUNCATE); ++ tmp = &tidied[0]; ++ while (wc = *tmp++) { ++ if (wc == L'/') tmp[-1] = L'\\'; ++ } ++ _wsplitpath_s(tidied, drive, _countof(drive), dir, _countof(dir), fname, _countof(fname), ext, _countof(ext)); ++ tmp = dir+wcslen(dir)-1; ++ if (*tmp == L'\\') tmp--; ++ while (*tmp != L'\\' && tmp>=dir) *tmp-- = 0; ++ _snwprintf_s(tidied, _countof(tidied), _TRUNCATE, L"#!%s%s%s", drive, dir, PYTHON_EXECUTABLE); ++ debug(L"invented shebang: %s\n", tidied); ++ shebang_line = tidied; ++ } ++ } ++ + if ((*shebang_line++ == L'#') && (*shebang_line++ == L'!')) { + shebang_line = skip_whitespace(shebang_line); + if (*shebang_line) { +@@ -947,6 +1056,7 @@ + * "python". + */ + *command = wcsstr(shebang_line, L"python"); ++ debug(L"found in builtin_virtual_paths: %s, command: %s\n", vpp->shebang, *command); + break; + } + } +@@ -1072,10 +1182,13 @@ + validate_version(wchar_t * p) + { + /* ++ Optionally _d, + Version information should start with the major version, + Optionally followed by a period and a minor version, + Optionally followed by a minus and one of 32 or 64. + Valid examples: ++ _d ++ _d3 + 2 + 3 + 2.7 +@@ -1089,6 +1202,20 @@ + */ + BOOL result = (p != NULL); /* Default to False if null pointer. */ + ++ /* Skip _d for Windows debug. Interestingly, the name-script.py files from a release build ++ do not end up containing a shebang while debug builds have #!python_d */ ++ if (result) ++ debug(L"validate_version: in: %ls\n", p); ++ if (result && p[0] == '_' && p[1] == 'd') ++ { ++ debug(L"validate_version: Windows _d shebang\n"); ++ p += 2; ++ } ++ if (!*p) ++ { ++ debug(L"validate_version: No version number provided\n"); ++ return TRUE; ++ } + result = result && iswdigit(*p); /* Result = False if first string element is not a digit. */ + + while (result && iswdigit(*p)) /* Require a major version */ +@@ -1171,7 +1298,7 @@ + */ + FILE * fp; + errno_t rc = _wfopen_s(&fp, *argv, L"rb"); +- char buffer[BUFSIZE]; ++ char buffer[SHEBANG_BUFSIZE]; + wchar_t shebang_line[BUFSIZE + 1]; + size_t read; + char *p; +@@ -1188,7 +1315,7 @@ + INSTALLED_PYTHON * ip; + + if (rc == 0) { +- read = fread(buffer, sizeof(char), BUFSIZE, fp); ++ read = fread(buffer, sizeof(char), SHEBANG_BUFSIZE, fp); + debug(L"maybe_handle_shebang: read %zd bytes\n", read); + fclose(fp); + +@@ -1213,7 +1340,7 @@ + bom->code_page); + start = &buffer[bom->length]; + } +- p = find_terminator(start, BUFSIZE, bom); ++ p = find_terminator(start, SHEBANG_BUFSIZE, bom); + /* + * If no CR or LF was found in the heading, + * we assume it's not a shebang file. +@@ -1297,10 +1424,10 @@ + if (nchars > 0) { + shebang_line[--nchars] = L'\0'; + is_virt = parse_shebang(shebang_line, nchars, &command, +- &suffix, &search); ++ &suffix, &search, *argv); + if (command != NULL) { + debug(L"parse_shebang: found command: %ls\n", command); +- if (!is_virt) { ++ if (!is_virt) { /* || !wcsncmp(command, L"python_d", 8)) { */ + invoke_child(command, suffix, cmdline); + } + else { +@@ -1409,7 +1536,7 @@ + + get_version_info(version_text, MAX_PATH); + fwprintf(stdout, L"\ +-Python Launcher for Windows Version %ls\n\n", version_text); ++Python Launcher for Windows (Anaconda/Setuptools variant) Version %ls\n\n", version_text); + fwprintf(stdout, L"\ + usage:\n\ + %ls [launcher-args] [python-args] script [script-args]\n\n", argv[0]); +@@ -1584,6 +1711,7 @@ + int newlen; + HRESULT hr; + int index; ++ int quoted = 0; + #else + HRESULT hr; + int index; +@@ -1624,6 +1752,7 @@ + } + #endif + argv0 = get_process_name(); ++/* + size = GetFileVersionInfoSizeW(argv0, &size); + if (size == 0) { + winerror(GetLastError(), message, MSGSIZE); +@@ -1649,6 +1778,9 @@ + free(version_data); + } + } ++*/ ++ version_high = VERSION_HIGH; ++ version_low = VERSION_LOW; + + #if defined(VENV_REDIRECT) + /* Allocate some extra space for new filenames */ +@@ -1731,13 +1863,24 @@ + locate_wrapped_script(); + + /* Add the wrapped script to the start of command */ +- newlen = wcslen(wrapped_script_path) + wcslen(command) + 2; /* ' ' + NUL */ ++ p = wcsrchr(wrapped_script_path, L' '); ++ if (p != NULL) ++ quoted = 1; ++ newlen = wcslen(wrapped_script_path) + wcslen(command) + 2 + (2 * quoted); /* ' ' + NUL */ + newcommand = malloc(sizeof(wchar_t) * newlen); + if (!newcommand) { + error(RC_NO_MEMORY, L"Could not allocate new command line"); + } + else { +- wcscpy_s(newcommand, newlen, wrapped_script_path); ++ /* This probably breaks already-quoted things. */ ++ newcommand[0] = L'\0'; ++ if (quoted) { ++ wcscpy_s(newcommand, newlen, L"\""); ++ } ++ wcscat_s(newcommand, newlen, wrapped_script_path); ++ if (quoted) { ++ wcscat_s(newcommand, newlen, L"\""); ++ } + wcscat_s(newcommand, newlen, L" "); + wcscat_s(newcommand, newlen, command); + debug(L"Running wrapped script with command line '%ls'\n", newcommand); diff --git a/shared/package-files/35/354bbeae3ffa24a49947e719269a6903f08b9a5242316d3ac85fefb8b4db5676/operator.py b/shared/package-files/35/354bbeae3ffa24a49947e719269a6903f08b9a5242316d3ac85fefb8b4db5676/operator.py new file mode 100644 index 0000000000000000000000000000000000000000..9a465f66a5213f5b6f440d45e93228eb75383fa7 --- /dev/null +++ b/shared/package-files/35/354bbeae3ffa24a49947e719269a6903f08b9a5242316d3ac85fefb8b4db5676/operator.py @@ -0,0 +1,118 @@ +from __future__ import annotations + +import inspect +from collections.abc import Mapping +from enum import Enum +from typing import Any, Callable, Optional, Union + +from .token import Token + + +class Operator: + """ + Specification for how an operator in a formula string should behave. + + Attributes: + symbol: The operator for which the configuration applies. + arity: The number of arguments that this operator consumes. + precedence: How tightly this operator binds its arguments (the higher + the number, the more tightly it binds). Operators with higher + precedence will be evaluated first. + associativity: One of 'left', 'right', or 'none'; indicating how + operators of the same precedence should be evaluated in the absence + of explicit grouping parentheses. If left associative, groups are + formed from the left [e.g. a % b % c -> ((a % b) % c)]; and + similarly for right. + fixity: One of 'prefix', 'infix', or 'postfix'; indicating how the + operator is positioned relative to its arguments. If 'prefix', the + operator comes before its arguments; if 'infix', the operator comes + between its arguments (and there must be exactly two of them); and + if 'postfix', the operator comes after its arguments. + to_terms: A callable that maps the arguments pass to the operator to + an iterable of `Term` instances. + accepts_context: A callable that will receive a list of Operator and + Token instances that describe the context in which the operator + would be applied if this callable returns `True`. + structural: Whether this operator adds structure to the terms sets, in + which case `Structured._merge` will not be used in the + `ASTNode.to_terms()`, and the termsets will be directly passed to + `Operator.to_terms()`. + disabled: Whether this operator is disabled and should not be used. This + is useful for restricting the set of formula that can be parsed in + certain contexts. + """ + + class Associativity(Enum): + LEFT = "left" + RIGHT = "right" + NONE = "none" + + class Fixity(Enum): + PREFIX = "prefix" + INFIX = "infix" + POSTFIX = "postfix" + + def __init__( + self, + symbol: str, + *, + arity: int, + precedence: float, + associativity: Union[None, str, Associativity] = Associativity.NONE, + fixity: Union[str, Fixity] = Fixity.INFIX, + to_terms: Optional[Callable[..., Any]] = None, + accepts_context: Optional[ + Callable[[list[Union[Token, Operator]]], bool] + ] = None, + structural: bool = False, + disabled: bool = False, + ): + self.symbol = symbol + self.arity = arity + self.precedence = precedence + self.associativity = associativity # type: ignore + self.fixity = fixity # type: ignore + self._to_terms = to_terms + self._accepts_context = accepts_context + self.structural = structural + self.disabled = disabled + + @property + def associativity(self) -> Operator.Associativity: + return self._associativity + + @associativity.setter + def associativity(self, associativity: Union[str, Operator.Associativity]) -> None: + self._associativity = Operator.Associativity(associativity or "none") + + @property + def fixity(self) -> Operator.Fixity: + return self._fixity + + @fixity.setter + def fixity(self, fixity: Union[str, Operator.Fixity]) -> None: + self._fixity = Operator.Fixity(fixity) + + def to_terms(self, *args: Any, context: Optional[Mapping[str, Any]] = None) -> Any: + if self._to_terms is None: + raise RuntimeError(f"`to_terms` is not implemented for '{self.symbol}'.") + if inspect.signature(self._to_terms).parameters.get("context"): + return self._to_terms(*args, context=context or {}) + return self._to_terms(*args) + + def accepts_context(self, context: list[Union[Token, Operator]]) -> bool: + if self._accepts_context: + # We only need to pass on tokens and operators with precedence less + # than or equal to ourselves, since all other operators will be + # evaluated before us. + return self._accepts_context( + [ + c + for c in context + if isinstance(c, Token) or c.precedence <= self.precedence + ] + ) + return True + + def __repr__(self) -> str: + return self.symbol diff --git a/shared/package-files/35/354e95bf775f86854c3b9ce90b229c94242bfc451aecdef55b1fc9506ed8ca01/xnuppc+80x25 b/shared/package-files/35/354e95bf775f86854c3b9ce90b229c94242bfc451aecdef55b1fc9506ed8ca01/xnuppc+80x25 new file mode 100644 index 0000000000000000000000000000000000000000..b70c340bfdb8df1f4f44d1427c0250d8946e7ec3 Binary files /dev/null and b/shared/package-files/35/354e95bf775f86854c3b9ce90b229c94242bfc451aecdef55b1fc9506ed8ca01/xnuppc+80x25 differ diff --git a/shared/package-files/35/35507400e1e6331d2d90a68d1c79c72dfc496ae987556342dce457808acb844e/reduction.h b/shared/package-files/35/35507400e1e6331d2d90a68d1c79c72dfc496ae987556342dce457808acb844e/reduction.h new file mode 100644 index 0000000000000000000000000000000000000000..6265c4d2658583ed5dc7b858e19d23d9160ae265 --- /dev/null +++ b/shared/package-files/35/35507400e1e6331d2d90a68d1c79c72dfc496ae987556342dce457808acb844e/reduction.h @@ -0,0 +1,36 @@ +#pragma once + +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +TORCH_API Tensor computeSum( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const c10::optional& outputType, + at::Device device); +TORCH_API Tensor computeMean( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const c10::optional& outputType, + at::Device device); +TORCH_API Tensor computeAdaptiveAvgPool2d( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const c10::optional& outputType, + at::Device device); +Tensor computeMax( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const c10::optional& outputType, + at::Device device); + +} // namespace tensorexpr +} // namespace jit +} // namespace torch diff --git a/shared/package-files/35/3559cf140e766a6365dea339e46d55f5e2fd6653fd370ba00653dffb37a44c55/si2_b06_m200.A99 b/shared/package-files/35/3559cf140e766a6365dea339e46d55f5e2fd6653fd370ba00653dffb37a44c55/si2_b06_m200.A99 new file mode 100644 index 0000000000000000000000000000000000000000..60c3a3ce1bdb54a61ead043f0adaf24b1fe24e93 Binary files /dev/null and b/shared/package-files/35/3559cf140e766a6365dea339e46d55f5e2fd6653fd370ba00653dffb37a44c55/si2_b06_m200.A99 differ diff --git a/shared/package-files/35/355b31f384bd0223f0c226efbc02eefdd646d5de69806ab52cdc178de273e467/connected.py b/shared/package-files/35/355b31f384bd0223f0c226efbc02eefdd646d5de69806ab52cdc178de273e467/connected.py new file mode 100644 index 0000000000000000000000000000000000000000..192d0b841c94aab9e7512eb7cf77dd7806a484eb --- /dev/null +++ b/shared/package-files/35/355b31f384bd0223f0c226efbc02eefdd646d5de69806ab52cdc178de273e467/connected.py @@ -0,0 +1,203 @@ +"""Connected components.""" +import networkx as nx +from networkx.utils.decorators import not_implemented_for + +from ...utils import arbitrary_element + +__all__ = [ + "number_connected_components", + "connected_components", + "is_connected", + "node_connected_component", +] + + +@nx._dispatch +@not_implemented_for("directed") +def connected_components(G): + """Generate connected components. + + Parameters + ---------- + G : NetworkX graph + An undirected graph + + Returns + ------- + comp : generator of sets + A generator of sets of nodes, one for each component of G. + + Raises + ------ + NetworkXNotImplemented + If G is directed. + + Examples + -------- + Generate a sorted list of connected components, largest first. + + >>> G = nx.path_graph(4) + >>> nx.add_path(G, [10, 11, 12]) + >>> [len(c) for c in sorted(nx.connected_components(G), key=len, reverse=True)] + [4, 3] + + If you only want the largest connected component, it's more + efficient to use max instead of sort. + + >>> largest_cc = max(nx.connected_components(G), key=len) + + To create the induced subgraph of each component use: + + >>> S = [G.subgraph(c).copy() for c in nx.connected_components(G)] + + See Also + -------- + strongly_connected_components + weakly_connected_components + + Notes + ----- + For undirected graphs only. + + """ + seen = set() + for v in G: + if v not in seen: + c = _plain_bfs(G, v) + seen.update(c) + yield c + + +def number_connected_components(G): + """Returns the number of connected components. + + Parameters + ---------- + G : NetworkX graph + An undirected graph. + + Returns + ------- + n : integer + Number of connected components + + Examples + -------- + >>> G = nx.Graph([(0, 1), (1, 2), (5, 6), (3, 4)]) + >>> nx.number_connected_components(G) + 3 + + See Also + -------- + connected_components + number_weakly_connected_components + number_strongly_connected_components + + Notes + ----- + For undirected graphs only. + + """ + return sum(1 for cc in connected_components(G)) + + +@nx._dispatch +@not_implemented_for("directed") +def is_connected(G): + """Returns True if the graph is connected, False otherwise. + + Parameters + ---------- + G : NetworkX Graph + An undirected graph. + + Returns + ------- + connected : bool + True if the graph is connected, false otherwise. + + Raises + ------ + NetworkXNotImplemented + If G is directed. + + Examples + -------- + >>> G = nx.path_graph(4) + >>> print(nx.is_connected(G)) + True + + See Also + -------- + is_strongly_connected + is_weakly_connected + is_semiconnected + is_biconnected + connected_components + + Notes + ----- + For undirected graphs only. + + """ + if len(G) == 0: + raise nx.NetworkXPointlessConcept( + "Connectivity is undefined ", "for the null graph." + ) + return sum(1 for node in _plain_bfs(G, arbitrary_element(G))) == len(G) + + +@nx._dispatch +@not_implemented_for("directed") +def node_connected_component(G, n): + """Returns the set of nodes in the component of graph containing node n. + + Parameters + ---------- + G : NetworkX Graph + An undirected graph. + + n : node label + A node in G + + Returns + ------- + comp : set + A set of nodes in the component of G containing node n. + + Raises + ------ + NetworkXNotImplemented + If G is directed. + + Examples + -------- + >>> G = nx.Graph([(0, 1), (1, 2), (5, 6), (3, 4)]) + >>> nx.node_connected_component(G, 0) # nodes of component that contains node 0 + {0, 1, 2} + + See Also + -------- + connected_components + + Notes + ----- + For undirected graphs only. + + """ + return _plain_bfs(G, n) + + +def _plain_bfs(G, source): + """A fast BFS node generator""" + G_adj = G.adj + seen = set() + nextlevel = {source} + while nextlevel: + thislevel = nextlevel + nextlevel = set() + for v in thislevel: + if v not in seen: + seen.add(v) + nextlevel.update(G_adj[v]) + return seen diff --git a/shared/package-files/35/355b5fe478ae78e7004fdc0fb5cb298ad0f94b94272166a91c11910b876635b2/builtin.py b/shared/package-files/35/355b5fe478ae78e7004fdc0fb5cb298ad0f94b94272166a91c11910b876635b2/builtin.py new file mode 100644 index 0000000000000000000000000000000000000000..7f9625d196fa3cfc712ee0270a887667595d1b87 --- /dev/null +++ b/shared/package-files/35/355b5fe478ae78e7004fdc0fb5cb298ad0f94b94272166a91c11910b876635b2/builtin.py @@ -0,0 +1,1748 @@ +# mypy: ignore-errors + +import contextlib +import functools +import inspect +import itertools +import logging +import math +import operator +import types +from collections import defaultdict, OrderedDict +from typing import Dict, List + +import torch +from torch import sym_float, sym_int + +from .. import config, polyfill, variables +from ..exc import ( + AttributeMutationError, + unimplemented, + Unsupported, + UserError, + UserErrorType, +) +from ..guards import GuardBuilder, install_guard +from ..replay_record import DummyModule +from ..source import AttrSource, GetItemSource, is_constant_source, TypeSource +from ..utils import ( + check_constant_args, + check_numpy_ndarray_args, + check_unspec_python_args, + extract_fake_example_value, + get_fake_value, + guard_if_dyn, + istype, + numpy_operator_wrapper, + proxy_args_kwargs, + tensortype_to_dtype, +) +from .base import MutableLocal, typestr, VariableTracker +from .constant import ConstantVariable +from .ctx_manager import EventVariable, StreamVariable +from .dicts import ( + ConstDictVariable, + DefaultDictVariable, + DictView, + is_hashable, + SetVariable, +) +from .lists import ( + BaseListVariable, + ListIteratorVariable, + ListVariable, + SizeVariable, + TupleIteratorVariable, + TupleVariable, +) +from .tensor import ( + FakeItemVariable, + SymNodeVariable, + TensorVariable, + UnspecializedPythonVariable, +) +from .user_defined import UserDefinedVariable + +log = logging.getLogger(__name__) + + +IN_PLACE_DESUGARING_MAP = { + operator.iadd: operator.add, + operator.isub: operator.sub, + operator.imul: operator.mul, + operator.ifloordiv: operator.floordiv, + operator.itruediv: operator.truediv, + operator.imod: operator.mod, + operator.imatmul: operator.imatmul, + operator.ilshift: operator.lshift, + operator.irshift: operator.rshift, + operator.ipow: operator.pow, + operator.iand: operator.and_, + operator.ior: operator.or_, + operator.ixor: operator.xor, +} + + +def _polyfill_call_impl(name): + """Create a BuiltinVariable.call_{name} method that inlines through polyfill.{name}""" + + def call_fn(self, tx, *args, **kwargs): + return tx.inline_user_function_return( + variables.UserFunctionVariable(fn), args, kwargs + ) + + fn = getattr(polyfill, name) + call_fn.__name__ = f"call_{name}" + return call_fn + + +class BuiltinVariable(VariableTracker): + _SENTINEL = object() + + @classmethod + def create_with_source(cls, value, source): + install_guard(source.make_guard(GuardBuilder.BUILTIN_MATCH)) + return BuiltinVariable(value, source=source) + + @staticmethod + @functools.lru_cache(None) + def _constant_fold_functions(): + fns = { + abs, + all, + any, + bool, + callable, + chr, + divmod, + float, + getattr, + int, + len, + max, + min, + ord, + pow, + repr, + round, + str, + str.format, + sum, + type, + operator.abs, + operator.pos, + operator.neg, + operator.not_, + operator.truth, + operator.invert, + operator.pow, + operator.mul, + operator.matmul, + operator.floordiv, + operator.truediv, + operator.mod, + operator.add, + operator.sub, + operator.getitem, + operator.length_hint, + operator.lshift, + operator.rshift, + operator.and_, + operator.or_, + operator.xor, + operator.ipow, + operator.imul, + operator.imatmul, + operator.ifloordiv, + operator.itruediv, + operator.imod, + operator.iadd, + operator.isub, + operator.ilshift, + operator.irshift, + operator.iand, + operator.ixor, + operator.ior, + operator.index, + } + fns.update(x for x in math.__dict__.values() if isinstance(x, type(math.sqrt))) + return fns + + def can_constant_fold_through(self): + return self.fn in self._constant_fold_functions() + + @staticmethod + @functools.lru_cache(None) + def _fx_graph_functions(): + fns = { + operator.abs, + operator.pos, + operator.neg, + operator.not_, + operator.invert, + operator.pow, + operator.mul, + operator.matmul, + operator.floordiv, + operator.truediv, + operator.mod, + operator.add, + operator.lt, + operator.gt, + operator.ge, + operator.le, + operator.ne, + operator.eq, + operator.sub, + operator.getitem, + operator.length_hint, + operator.lshift, + operator.rshift, + operator.and_, + operator.or_, + operator.xor, + operator.ipow, + operator.imul, + operator.imatmul, + operator.ifloordiv, + operator.itruediv, + operator.imod, + operator.iadd, + operator.isub, + operator.ilshift, + operator.irshift, + operator.iand, + operator.ixor, + operator.ior, + } + return fns + + @staticmethod + @functools.lru_cache(None) + def _binops(): + # function -> ([forward name, reverse name, in-place name], in-place op) + fns = { + operator.add: (["__add__", "__radd__", "__iadd__"], operator.iadd), + operator.sub: (["__sub__", "__rsub__", "__isub__"], operator.isub), + operator.mul: (["__mul__", "__rmul__", "__imul__"], operator.imul), + operator.truediv: ( + ["__truediv__", "__rtruediv__", "__itruediv__"], + operator.itruediv, + ), + operator.floordiv: ( + ["__floordiv__", "__rfloordiv__", "__ifloordiv__"], + operator.ifloordiv, + ), + operator.mod: (["__mod__", "__rmod__", "__imod__"], operator.imod), + pow: (["__pow__", "__rpow__", "__ipow__"], operator.ipow), + operator.pow: (["__pow__", "__rpow__", "__ipow__"], operator.ipow), + operator.lshift: ( + ["__lshift__", "__rlshift__", "__ilshift__"], + operator.ilshift, + ), + operator.rshift: ( + ["__rshift__", "__rrshift__", "__irshift__"], + operator.irshift, + ), + # NB: The follow binary operators are not supported for now, since the + # corresponding magic methods aren't defined on SymInt / SymFloat: + # operator.matmul + # divmod + # operator.and_ + # operator.or_ + # operator.xor + } + return fns + + @staticmethod + @functools.lru_cache(None) + def _binop_handlers(): + # Multiple dispatch mechanism defining custom binop behavior for certain type + # combinations. Handlers are attempted in order, and will be used if the type checks + # match. They are expected to have the signature: + # fn(tx, arg0: VariableTracker, arg1: VariableTracker, options) -> VariableTracker + + # Override table contains: op_fn -> [list of handlers] + op_handlers = {} + for ( + op, + (magic_method_names, in_place_op), + ) in BuiltinVariable._binops().items(): + op_handlers[op] = [] + op_handlers[in_place_op] = [] + + forward_name, reverse_name, inplace_name = magic_method_names + + # User-defined args (highest precedence) + def user_defined_handler( + tx, + a, + b, + options, + forward_name=forward_name, + reverse_name=reverse_name, + ): + # Manually handle reversing logic if needed (e.g. call __radd__) + + # TODO: If we expand this to handle tensor args, we need to manually + # handle cases like this: + # + # class A(int): + # def __radd__(self, other): + # print("woof") + # torch.randn(3) + A(3) + # + # In this example, A.__radd__() is not called -> nothing is printed, because + # Tensor.__add__ only does a subtype test against int, ignoring the subclass. + # To be fully correct, we should not call A.__radd__() here, and there may be + # other cases to reason about and add exceptions for. + if isinstance(a, UserDefinedVariable): + return a.call_method(tx, forward_name, [b], {}) + else: + return b.call_method(tx, reverse_name, [a], {}) + + op_handlers[op].append( + ((UserDefinedVariable, VariableTracker), user_defined_handler) + ) + op_handlers[op].append( + ((VariableTracker, UserDefinedVariable), user_defined_handler) + ) + + def user_defined_inplace_handler( + tx, a, b, options, forward_name=inplace_name + ): + return a.call_method(tx, forward_name, [b], {}) + + op_handlers[in_place_op].append( + ((UserDefinedVariable, VariableTracker), user_defined_inplace_handler) + ) + op_handlers[in_place_op].append( + ((VariableTracker, UserDefinedVariable), user_defined_inplace_handler) + ) + + # Dynamic shape args + def dynamic_handler(tx, a, b, options, fn=op): + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", fn, *proxy_args_kwargs([a, b], {}) + ), + **options, + ) + + op_handlers[op].append( + ((SymNodeVariable, VariableTracker), dynamic_handler) + ) + op_handlers[op].append( + ((VariableTracker, SymNodeVariable), dynamic_handler) + ) + + # NB: Prefer out-of-place op when calling in-place op to generate valid graph + op_handlers[in_place_op].append( + ((SymNodeVariable, VariableTracker), dynamic_handler) + ) + op_handlers[in_place_op].append( + ((VariableTracker, SymNodeVariable), dynamic_handler) + ) + + # Special cases - lower precedence but still prefer these over constant folding + + # List-like addition (e.g. [1, 2] + [3, 4]) + def tuple_add_handler(tx, a, b, options): + return TupleVariable(a.items + list(b.unpack_var_sequence(tx)), **options) + + def size_add_handler(tx, a, b, options): + return SizeVariable(a.items + list(b.unpack_var_sequence(tx)), **options) + + list_like_addition_handlers = [ + # NB: Prefer the tuple-specific logic over base logic because of + # some SizeVariable weirdness. Specifically, the tuple-specific logic + # drops the subclass type (e.g. SizeVariable) and returns TupleVariables. + ( + (SizeVariable, SizeVariable), + size_add_handler, + ), + ( + (TupleVariable, TupleVariable), + tuple_add_handler, + ), + ( + (TupleVariable, ConstantVariable), + tuple_add_handler, + ), + ( + (ConstantVariable, TupleVariable), + lambda tx, a, b, options: TupleVariable( + list(a.unpack_var_sequence(tx)) + b.items, **options + ), + ), + ( + (BaseListVariable, BaseListVariable), + lambda tx, a, b, options: type(a)(a.items + b.items, **options), + ), + ] + op_handlers[operator.add].extend(list_like_addition_handlers) + + def list_iadd_handler(tx, a, b, _): + if not a.mutable_local or not b.has_unpack_var_sequence(tx): + # Handler doesn't apply + return None + + seq = b.unpack_var_sequence(tx) + tx.output.side_effects.mutation(a) + a.items.extend(seq) + return a + + list_like_iadd_handlers = [ + ( + (ListVariable, VariableTracker), + list_iadd_handler, + ), + ( + (TupleVariable, TupleVariable), + tuple_add_handler, + ), + ( + (TupleVariable, ConstantVariable), + tuple_add_handler, + ), + ] + op_handlers[operator.iadd].extend(list_like_iadd_handlers) + + # List-like expansion (e.g. [1, 2, 3] * 3) + def expand_list_like(tx, lst, const, options): + return lst.__class__( + items=lst.items * const.as_python_constant(), + mutable_local=MutableLocal(), + **options, + ) + + list_like_expansion_handlers = [ + ((ListVariable, ConstantVariable), expand_list_like), + ((TupleVariable, ConstantVariable), expand_list_like), + ( + (ConstantVariable, ListVariable), + lambda tx, a, b, options: expand_list_like(tx, b, a, options), + ), + ( + (ConstantVariable, TupleVariable), + lambda tx, a, b, options: expand_list_like(tx, b, a, options), + ), + ] + op_handlers[operator.mul].extend(list_like_expansion_handlers) + + return op_handlers + + @staticmethod + def _find_binop_handler(op, a, b): + handlers = BuiltinVariable._binop_handlers() + if op not in handlers: + return None + + # Return first handler that matches the type checks + for (type1, type2), handler in handlers[op]: + if isinstance(a, type1) and isinstance(b, type2): + return handler + + return None + + def can_insert_in_graph(self): + return self.fn in self._fx_graph_functions() + + def __init__(self, fn, **kwargs): + super().__init__(**kwargs) + self.fn = fn + + def __str__(self): + if self.fn is None: + name = "None" + else: + name = self.fn.__name__ + + return f"{self.__class__.__name__}({name})" + + def python_type(self): + return type(self.fn) + + def as_python_constant(self): + return self.fn + + def as_proxy(self): + DTYPE = { + bool: torch.bool, + int: torch.int64, + float: torch.float64, + } + if self.fn in DTYPE: + return DTYPE[self.fn] + return super().as_proxy() + + def reconstruct(self, codegen): + name = self.fn.__name__ + assert self.fn.__module__ == "builtins" + assert name not in codegen.tx.f_globals, "shadowed global" + codegen.append_output(codegen.create_load_global(name, False, add=True)) + + def constant_args(self, *args, **kwargs): + return check_constant_args(args, kwargs) + + def tensor_args(self, *args, **kwargs): + return any( + isinstance(i, variables.TensorVariable) + for i in itertools.chain(args, kwargs.values()) + ) and not any( + isinstance(i, variables.GetAttrVariable) + for i in itertools.chain(args, kwargs.values()) + ) + + def python_and_tensor_constant_only(self, *args, **kwargs): + tensor_args = [] + non_tensor_args = [] + for i in itertools.chain(args, kwargs.values()): + if isinstance(i, variables.TensorVariable): + tensor_args.append(i) + else: + non_tensor_args.append(i) + return all( + is_constant_source(t.source) if t.source is not None else False + for t in tensor_args + ) and self.constant_args(*non_tensor_args) + + def unspec_python_args(self, *args, **kwargs): + return check_unspec_python_args(args, kwargs) + + @staticmethod + def unwrap_unspec_args_kwargs(args, kwargs): + return [x.as_python_constant() for x in args], { + k: v.as_python_constant() for k, v in kwargs.items() + } + + def has_constant_handler(self, args, kwargs): + constant_args = check_constant_args(args, kwargs) + unspec_python_args = self.unspec_python_args(*args, **kwargs) + return self.can_constant_fold_through() and ( + constant_args or unspec_python_args + ) + + def call_function( + self, tx, args: "List[VariableTracker]", kwargs: "Dict[str, VariableTracker]" + ) -> "VariableTracker": + from . import UserFunctionVariable + from .builder import wrap_fx_proxy, wrap_fx_proxy_cls + + args = [v.realize() for v in args] + kwargs = {k: v.realize() for k, v in kwargs.items()} + assert isinstance(args, (list, tuple)) + assert isinstance(kwargs, dict) + tensor_args = self.tensor_args(*args, **kwargs) + + # args[0] is list and args[1] is unspec + if self.fn is operator.getitem and not isinstance( + args[0], variables.TensorVariable + ): + tensor_args = False + + if ( + self.can_insert_in_graph() + and tensor_args + and not ( + self.fn is operator.getitem + and isinstance(args[0], ConstDictVariable) + and isinstance(args[1], variables.TensorVariable) + ) + ): + try: + fn = self.fn + + # Constant fold for constant tensor and python constants + if tensor_args and self.python_and_tensor_constant_only( + *args, **kwargs + ): + from ..bytecode_transformation import unique_id + from .functions import invoke_and_store_as_constant + + return invoke_and_store_as_constant( + tx, fn, unique_id(fn.__name__), args, kwargs + ) + + if self.fn in IN_PLACE_DESUGARING_MAP and isinstance( + args[0], variables.ConstantVariable + ): + # In-place operators like += usually mustate tensor + # values, but in the edge case of immutable values they + # re-bind the variable. + # + # The easiest way to keep the graph consistent in this + # scenario is to de-sugar eagerly. + fn, args = IN_PLACE_DESUGARING_MAP[self.fn], [args[0], args[1]] + + if self.fn is operator.getitem and isinstance(args[1], SymNodeVariable): + # Standard indexing will force specialization due to + # __index__. Rewrite as a regular torch op which will + # trace fine + fn, args = torch.select, [ + args[0], + variables.ConstantVariable.create(0), + args[1], + ] + + # Interaction between ndarray and tensors: + # We prefer the tensor op whenever there are tensors involved + if check_numpy_ndarray_args(args, kwargs) and not any( + type(arg) == variables.TensorVariable for arg in args + ): + proxy = tx.output.create_proxy( + "call_function", + numpy_operator_wrapper(self.fn), + *proxy_args_kwargs(args, kwargs), + ) + + return wrap_fx_proxy_cls(variables.NumpyNdarrayVariable, tx, proxy) + + proxy = tx.output.create_proxy( + "call_function", + fn, + *proxy_args_kwargs(args, kwargs), + ) + if any(isinstance(arg, FakeItemVariable) for arg in args): + return wrap_fx_proxy_cls( + FakeItemVariable, + tx, + proxy, + ) + elif self.unspec_python_args(*args, **kwargs): + _args, _kwargs = self.unwrap_unspec_args_kwargs(args, kwargs) + raw_value = self.fn(*_args, **_kwargs) + + need_unwrap = any( + x.need_unwrap + for x in itertools.chain(args, kwargs.values()) + if isinstance(x, variables.UnspecializedPythonVariable) + ) + + return wrap_fx_proxy_cls( + UnspecializedPythonVariable, + tx, + proxy, + raw_value=raw_value, + need_unwrap=need_unwrap, + ) + elif all(isinstance(x, SymNodeVariable) for x in args): + return SymNodeVariable.create(tx, proxy, None) + else: + # Work around for vision_maskrcnn due to precision difference + # specialize the dividend when float divide by tensor + if self.fn is operator.truediv and isinstance( + args[0], variables.UnspecializedPythonVariable + ): + args[0] = args[0].convert_to_constant(tx) + return wrap_fx_proxy(tx, proxy) + + except NotImplementedError: + unimplemented(f"partial tensor op: {self} {args} {kwargs}") + + # Handle cases like int(torch.seed()) + # Also handle sym_float to sym_int cases + if self.fn in (int, float) and isinstance( + args[0], (SymNodeVariable, variables.TensorVariable) + ): + if isinstance(args[0], variables.TensorVariable): + item = args[0].call_method(tx, "item", [], {}) + else: + item = args[0] + fn_ = sym_int if self.fn is int else sym_float + out = wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + fn_, + (item.as_proxy(),), + {}, + ), + ) + return out + + # Handle `str` on a user defined function + if self.fn == str and args and isinstance(args[0], (UserFunctionVariable)): + return variables.ConstantVariable.create(value=str(args[0].fn)) + + # Handle binary ops (e.g. __add__ / __radd__, __iadd__, etc.) + # NB: Tensor args are handled above and not here + if len(kwargs) == 0 and len(args) == 2: + # Try to find a handler for the arg types; otherwise, fall through to constant handler + binop_handler = BuiltinVariable._find_binop_handler( + self.fn, args[0], args[1] + ) + if binop_handler: + res = binop_handler(tx, args[0], args[1], {}) + if res is not None: + return res + + handler = getattr(self, f"call_{self.fn.__name__}", None) + + if handler: + try: + result = handler(tx, *args, **kwargs) + if result is not None: + return result + except TypeError: + # Check if binding is bad. inspect signature bind is expensive. + # So check only when handler call fails. + try: + inspect.signature(handler).bind(tx, *args, **kwargs) + except TypeError as e: + has_constant_handler = self.has_constant_handler(args, kwargs) + if not has_constant_handler: + log.warning( + "incorrect arg count %s %s and no constant handler", + handler, + e, + ) + unimplemented(f"invalid handler args {handler} {args} {kwargs}") + else: + raise + except Unsupported as exc: + has_constant_handler = self.has_constant_handler(args, kwargs) + if not has_constant_handler: + raise + # Actually, we will handle this just fine + exc.remove_from_stats() + + # NB: call to has_constant_handler is deliberately delayed post generic + # handler because has_constant_handler calls as_python_constant + # internally which realizes LazyVariableTracker for ConstantVariables, + # unnecessarily putting guards on objects which might not actually be used. + has_constant_handler = self.has_constant_handler(args, kwargs) + if has_constant_handler: + from .builder import SourcelessBuilder + + # constant fold + return SourcelessBuilder()( + tx, + self.as_python_constant()( + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ), + ) + + return super().call_function(tx, args, kwargs) + + def call_method( + self, + tx, + name, + args: "List[VariableTracker]", + kwargs: "Dict[str, VariableTracker]", + ) -> "VariableTracker": + if self.fn == dict and name == "fromkeys": + return BuiltinVariable.call_custom_dict_fromkeys(tx, dict, *args, **kwargs) + if self.fn == itertools.chain and name == "from_iterable": + assert len(args) == 1 + assert len(kwargs) == 0 + obj = args[0] + items = [] + for item in obj.unpack_var_sequence(tx): + items.extend(item.unpack_var_sequence(tx)) + return variables.TupleVariable(items) + + return super().call_method(tx, name, args, kwargs) + + def _call_min_max(self, tx, *args): + if len(args) == 1 and args[0].has_unpack_var_sequence(tx): + # expand iterable + items = args[0].unpack_var_sequence(tx) + return self._call_min_max_seq(tx, items) + elif len(args) == 2: + return self._call_min_max_binary(tx, args[0], args[1]) + elif len(args) > 2: + return self._call_min_max_seq(tx, args) + + def _call_min_max_seq(self, tx, items): + assert len(items) > 0 + if len(items) == 1: + return items[0] + + return functools.reduce(functools.partial(self._call_min_max_binary, tx), items) + + def _call_min_max_binary(self, tx, a, b): + if self.tensor_args(a, b): + if not isinstance(a, variables.TensorVariable): + a, b = b, a + assert isinstance(a, variables.TensorVariable) + + # result of an item call is a scalar convert to a tensor + if isinstance(a, FakeItemVariable): + a = variables.TorchInGraphFunctionVariable(torch.tensor).call_function( + tx, [a], {} + ) + + # Dynamic input does not get resolved, rather, gets stored as call_function + if isinstance(a, SymNodeVariable) or isinstance(b, SymNodeVariable): + from .builder import wrap_fx_proxy_cls + + return wrap_fx_proxy_cls( + type(a), + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.fn, + *proxy_args_kwargs([a, b], {}), + ), + ) + + # convert min/max to torch ops + if b.is_python_constant(): + if isinstance(a, variables.NumpyNdarrayVariable): + import numpy as np + + fn = variables.NumpyVariable(np.clip) + else: + fn = variables.TorchInGraphFunctionVariable(torch.clamp) + kwargs = {"min": b} if (self.fn is max) else {"max": b} + result = fn.call_function(tx, [a], kwargs) + else: + if isinstance(a, variables.NumpyNdarrayVariable): + import numpy as np + + fn = {max: np.maximum, min: np.minimum}[self.fn] + fn = variables.NumpyVariable(fn) + else: + fn = {max: torch.maximum, min: torch.minimum}[self.fn] + fn = variables.TorchInGraphFunctionVariable(fn) + result = fn.call_function(tx, [a, b], {}) + + # return unspec if both a, b are unspec or const + if all( + isinstance( + i, + ( + variables.UnspecializedPythonVariable, + variables.ConstantVariable, + ), + ) + for i in [a, b] + ): + if any(isinstance(val, FakeItemVariable) for val in [a, b]): + return variables.FakeItemVariable.from_tensor_variable(result) + + if b.is_python_constant(): + raw_b = b.as_python_constant() + else: + raw_b = b.raw_value + if self.fn is max: + raw_res = max(a.raw_value, raw_b) + else: + raw_res = min(a.raw_value, raw_b) + + need_unwrap = any( + x.need_unwrap + for x in [a, b] + if isinstance(x, variables.UnspecializedPythonVariable) + ) + return variables.UnspecializedPythonVariable.from_tensor_variable( + result, raw_res, need_unwrap + ) + # otherwise return tensor + else: + return result + elif isinstance(a, SymNodeVariable) or isinstance(b, SymNodeVariable): + fn = torch.sym_max if self.fn is max else torch.sym_min + proxy = tx.output.create_proxy( + "call_function", fn, *proxy_args_kwargs([a, b], {}) + ) + return SymNodeVariable.create(tx, proxy, None) + + call_min = _call_min_max + call_max = _call_min_max + + def call_abs(self, tx, arg: "VariableTracker"): + # Call arg.__abs__() + abs_method = BuiltinVariable(getattr).call_function( + tx, [arg, ConstantVariable.create("__abs__")], {} + ) + return abs_method.call_function(tx, [], {}) + + def call_pos(self, tx, arg: "VariableTracker"): + # Call arg.__pos__() + pos_method = BuiltinVariable(getattr).call_function( + tx, [arg, ConstantVariable.create("__pos__")], {} + ) + return pos_method.call_function(tx, [], {}) + + def call_round(self, tx, arg, *args, **kwargs): + # Call arg.__round__() + round_method = BuiltinVariable(getattr).call_function( + tx, [arg, ConstantVariable.create("__round__")], {} + ) + return round_method.call_function(tx, args, kwargs) + + def call_range(self, tx, *args): + if self.unspec_python_args(*args) or self.constant_args(*args): + return variables.RangeVariable(args) + elif self._dynamic_args(*args): + args = [ + variables.ConstantVariable.create(guard_if_dyn(arg)) for arg in args + ] + return variables.RangeVariable(args) + # None no-ops this handler and lets the driving function proceed + return None + + def _dynamic_args(self, *args, **kwargs): + return any(isinstance(x, SymNodeVariable) for x in args) or any( + isinstance(x, SymNodeVariable) for x in kwargs.values() + ) + + def call_slice(self, tx, *args): + return variables.SliceVariable(args) + + def _dyn_proxy(self, tx, *args, **kwargs): + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", self.fn, *proxy_args_kwargs(args, kwargs) + ), + ) + + def _call_iter_tuple_list(self, tx, obj=None, *args, **kwargs): + if self._dynamic_args(*args, **kwargs): + return self._dyn_proxy(tx, *args, **kwargs) + + if isinstance(obj, variables.IteratorVariable): + # For non-list iterators, we will guard on vars that + # determine the control flow + return obj + + cls = variables.BaseListVariable.cls_for(self.fn) + if obj is None: + return cls( + [], + mutable_local=MutableLocal(), + ) + elif obj.has_unpack_var_sequence(tx): + if obj.source and not is_constant_source(obj.source): + if isinstance(obj, TupleIteratorVariable): + install_guard( + obj.source.make_guard(GuardBuilder.TUPLE_ITERATOR_LEN) + ) + else: + install_guard(obj.source.make_guard(GuardBuilder.SEQUENCE_LENGTH)) + + return cls( + list(obj.unpack_var_sequence(tx)), + mutable_local=MutableLocal(), + ) + + def call_iter(self, tx, obj, *args, **kwargs): + # Handle the case where we are iterating over a tuple, list or iterator + ret = self._call_iter_tuple_list(tx, obj, *args, **kwargs) + + if ret is None: + # If the object doesn't implement a __iter__ method, it will be an error in eager mode when calling iter on it anyway. + # If the object implements a __iter__ method, inlining effectively forwards the call to another iter call + # (e.g. when __iter__ just returns iter(self.list)) or return a user-defined iterator. + return obj.call_method(tx, "__iter__", args, kwargs) + return ret + + call_tuple = _call_iter_tuple_list + call_list = _call_iter_tuple_list + + def call_callable(self, tx, arg): + from .functions import BaseUserFunctionVariable + + if isinstance( + arg, (variables.UserDefinedClassVariable, BaseUserFunctionVariable) + ): + return variables.ConstantVariable.create(True) + elif isinstance(arg, UserDefinedVariable): + return variables.ConstantVariable.create(callable(arg.value)) + elif isinstance(arg, (ConstantVariable, SymNodeVariable, TensorVariable)): + return variables.ConstantVariable.create(False) + + def call_cast(self, _, *args, **kwargs): + if len(args) == 2: + return args[1] + + unimplemented(f"unsupported args to builtin cast(): {args} {kwargs}") + + def call_dict(self, tx, *args, **kwargs): + return BuiltinVariable.call_custom_dict(tx, dict, *args, **kwargs) + + @staticmethod + def call_custom_dict(tx, user_cls, *args, **kwargs): + if not kwargs: + if not args: + args = ({},) + assert len(args) == 1 + arg = args[0] + if isinstance(arg, dict): + return ConstDictVariable(arg, user_cls, mutable_local=MutableLocal()) + elif isinstance(arg, variables.ConstDictVariable): + return arg.clone(user_cls=user_cls, mutable_local=MutableLocal()) + elif isinstance( + arg, + ( + ListVariable, + TupleVariable, + ListIteratorVariable, + ), + ): + items = dict( + x.unpack_var_sequence(tx) for x in arg.unpack_var_sequence(tx) + ) + return ConstDictVariable(items, user_cls, mutable_local=MutableLocal()) + elif not args and kwargs: + items = {ConstantVariable.create(k): v for k, v in kwargs.items()} + return variables.ConstDictVariable( + items, user_cls=user_cls, mutable_local=MutableLocal() + ) + unimplemented(f"{user_cls.__name__}(): {args} {kwargs}") + + @staticmethod + def call_custom_dict_fromkeys(tx, user_cls, *args, **kwargs): + assert user_cls in {dict, OrderedDict, defaultdict} + if kwargs: + # Only `OrderedDict.fromkeys` accepts `value` passed by keyword + assert user_cls is OrderedDict + assert len(args) == 1 and len(kwargs) == 1 and "value" in kwargs + args = (*args, kwargs.pop("value")) + if len(args) == 0: + raise UserError(TypeError, "fromkeys expected at least 1 argument, got 0") + if len(args) == 1: + args = (*args, ConstantVariable.create(None)) + assert len(args) == 2 + arg, value = args + DictVariableType = ( + ConstDictVariable if user_cls is not defaultdict else DefaultDictVariable + ) + + if isinstance(arg, dict): + arg = [ConstantVariable.create(k) for k in arg.keys()] + return DictVariableType( + dict.fromkeys(arg, value), user_cls, mutable_local=MutableLocal() + ) + elif arg.has_unpack_var_sequence(tx) and all( + is_hashable(v) for v in arg.unpack_var_sequence(tx) + ): + keys = arg.unpack_var_sequence(tx) + return DictVariableType( + dict.fromkeys(keys, value), user_cls, mutable_local=MutableLocal() + ) + unimplemented(f"{user_cls.__name__}.fromkeys(): {args} {kwargs}") + + def call_set(self, tx, *args, **kwargs): + # Can we merge this implementation and call_dict's one? + assert not kwargs + if not args: + return SetVariable([], mutable_local=MutableLocal()) + assert len(args) == 1 + arg = args[0] + if isinstance(arg, variables.SetVariable): + return arg.clone(mutable_local=MutableLocal()) + elif arg.has_unpack_var_sequence(tx): + items = arg.unpack_var_sequence(tx) + return SetVariable(items, mutable_local=MutableLocal()) + else: + unimplemented(f"set(): {args} {kwargs}") + + def call_zip(self, tx, *args, **kwargs): + if kwargs: + assert len(kwargs) == 1 and "strict" in kwargs + if all(x.has_unpack_var_sequence(tx) for x in args): + unpacked = [arg.unpack_var_sequence(tx) for arg in args] + if kwargs.pop("strict", False) and len(unpacked) > 0: + if not all(len(u) == len(unpacked[0]) for u in unpacked): + raise UserError( + ValueError, + "zip() has one argument of len differing from others", + ) + items = [variables.TupleVariable(list(item)) for item in zip(*unpacked)] + return variables.TupleVariable(items) + + def call_enumerate(self, tx, *args): + if len(args) == 1: + start = 0 + else: + assert len(args) == 2 + assert isinstance(args[1], variables.ConstantVariable) + start = args[1].as_python_constant() + if args[0].has_unpack_var_sequence(tx): + items = [ + variables.TupleVariable( + [variables.ConstantVariable.create(idx), var], + ) + for idx, var in enumerate(args[0].unpack_var_sequence(tx), start) + ] + return variables.TupleVariable(items) + + def call_len(self, tx, *args, **kwargs): + return args[0].call_method(tx, "__len__", args[1:], kwargs) + + def call_getitem(self, tx, *args, **kwargs): + return args[0].call_method(tx, "__getitem__", args[1:], kwargs) + + def call_isinstance(self, tx, arg, isinstance_type): + try: + arg_type = arg.python_type() + except NotImplementedError: + unimplemented( + f"isinstance({arg}, {isinstance_type}): can't determine type of {arg}" + ) + + isinstance_type = isinstance_type.as_python_constant() + + if isinstance(arg, variables.TensorVariable) and arg.dtype is not None: + + def _tensor_isinstance(tensor_var, tensor_type): + def check_type(ty): + if ty not in tensortype_to_dtype: + return issubclass(arg.python_type(), ty) + + dtypes = tensortype_to_dtype[ty] + return arg.dtype in dtypes + + if type(tensor_type) is tuple: + return any(check_type(ty) for ty in tensor_type) + else: + return check_type(tensor_type) + + return variables.ConstantVariable.create( + _tensor_isinstance(arg, isinstance_type) + ) + # UserDefinedObject with C extensions can have torch.Tensor attributes, + # so break graph. + if isinstance(arg, variables.UserDefinedObjectVariable) and isinstance( + arg.value, types.MemberDescriptorType + ): + unimplemented( + f"isinstance called on UserDefinedClass {arg} {isinstance_type}" + ) + # handle __instancecheck__ defined in user class + if ( + isinstance(arg, variables.UserDefinedObjectVariable) + and "__instancecheck__" in isinstance_type.__class__.__dict__ + ): + return variables.ConstantVariable.create( + isinstance_type.__class__.__instancecheck__(isinstance_type, arg.value) + ) + + try: + val = issubclass(arg_type, isinstance_type) + except TypeError: + val = arg_type is isinstance_type + return variables.ConstantVariable.create(val) + + def call_issubclass(self, tx, left_ty, right_ty): + """Checks if first arg is subclass of right arg""" + left_ty = left_ty.as_python_constant() + right_ty = right_ty.as_python_constant() + + return variables.ConstantVariable(issubclass(left_ty, right_ty)) + + def call_super(self, tx, a, b): + return variables.SuperVariable(a, b) + + def call_next(self, tx, arg): + if isinstance( + arg, (variables.ListIteratorVariable, variables.IteratorVariable) + ): + val, next_iter = arg.next_variables(tx) + return val + elif isinstance(arg, variables.BaseListVariable): + return arg.items[0] + + def call_hasattr(self, tx, obj, attr): + if attr.is_python_constant(): + name = attr.as_python_constant() + return obj.call_hasattr(tx, name) + + def call_map(self, tx, fn, seq): + if seq.has_unpack_var_sequence(tx): + items = [fn.call_function(tx, [x], {}) for x in seq.unpack_var_sequence(tx)] + return variables.TupleVariable(items) + + def call_sum(self, tx, seq, start=_SENTINEL): + # Special case for sum on tuple of floats and ints + if isinstance(seq, (variables.ListVariable, variables.TupleVariable)) and all( + isinstance(x, variables.ConstantVariable) + and isinstance(x.value, (int, float)) + for x in seq.items + ): + if start is self._SENTINEL: + return variables.ConstantVariable.create( + sum(x.value for x in seq.items), + ) + if isinstance(start, variables.ConstantVariable) and isinstance( + start.value, (int, float) + ): + return variables.ConstantVariable.create( + sum((x.value for x in seq.items), start=start.value), + ) + if seq.has_unpack_var_sequence(tx): + if start is self._SENTINEL: + start = variables.ConstantVariable.create(0) + items = seq.unpack_var_sequence(tx) + return BuiltinVariable(functools.reduce).call_function( + tx, + [ + BuiltinVariable(operator.add), + variables.TupleVariable(items), + start, + ], + {}, + ) + + def call_reduce(self, tx, function, iterable, initial=_SENTINEL): + if iterable.has_unpack_var_sequence(tx): + items = iterable.unpack_var_sequence(tx) + if initial is self._SENTINEL: + value, items = items[0], items[1:] + else: + value = initial + for element in items: + value = function.call_function(tx, [value, element], {}) + return value + + def call_getattr( + self, tx, obj: VariableTracker, name_var: VariableTracker, default=None + ): + from .. import trace_rules + from . import ( + ConstantVariable, + GetAttrVariable, + PythonModuleVariable, + TorchInGraphFunctionVariable, + UserFunctionVariable, + ) + from .builder import SourcelessBuilder, VariableBuilder + + name = name_var.as_python_constant() + + if not name_var.is_python_constant(): + unimplemented("non-const getattr() name") + + if tx.output.side_effects.is_attribute_mutation(obj): + try: + # re-read a pending side effect? + return tx.output.side_effects.load_attr(obj, name) + except KeyError: + pass + + if default is not None: + hasattr_var = self.call_hasattr(tx, obj, name_var) + assert hasattr_var.as_python_constant() in (True, False) + if not hasattr_var.as_python_constant(): + return default + + options = {} + if obj.source: + source = AttrSource(obj.source, name) + options["source"] = source + else: + source = None + + if name == "__bases__": + try: + value = obj.as_python_constant() + if isinstance(value, type): + bases = value.__bases__ + if source is not None: + tuple_args = [ + VariableBuilder(tx, GetItemSource(source, i))(b) + for i, b in enumerate(bases) + ] + else: + tuple_args = [SourcelessBuilder()(tx, b) for b in bases] + + return variables.TupleVariable(tuple_args, **options) + except NotImplementedError: + pass + + if isinstance(obj, variables.NNModuleVariable): + return obj.var_getattr(tx, name) + elif isinstance( + obj, + ( + variables.TensorVariable, + variables.NamedTupleVariable, + variables.ConstantVariable, + variables.UserDefinedClassVariable, + variables.UserDefinedObjectVariable, + ), + ): + try: + return obj.var_getattr(tx, name) + except NotImplementedError: + return GetAttrVariable(obj, name, **options) + elif isinstance(obj, TorchInGraphFunctionVariable): + # Get OpOverload from an OpOverloadPacket, e.g., torch.ops.aten.add.default. + member = getattr(obj.value, name) + if isinstance( + member, (torch._ops.OpOverloadPacket, torch._ops.OpOverload) + ) and trace_rules.is_aten_op_or_tensor_method(member): + return TorchInGraphFunctionVariable(member, **options) + elif isinstance(obj, (PythonModuleVariable, DummyModule)): + if obj.is_torch: + member = getattr(obj.value, name) + else: + member = obj.value.__dict__[name] + + if config.replay_record_enabled: + tx.exec_recorder.record_module_access(obj.value, name, member) + + if source is not None: + return VariableBuilder(tx, source)(member) + else: + return SourcelessBuilder()(tx, member) + elif istype(obj, UserFunctionVariable) and name in ("__name__", "__module__"): + return ConstantVariable.create(getattr(obj.fn, name)) + else: + try: + return obj.var_getattr(tx, name) + except NotImplementedError: + return GetAttrVariable(obj, name, **options) + + def call_setattr( + self, tx, obj: VariableTracker, name_var: VariableTracker, val: VariableTracker + ): + from .distributed import PlacementVariable + + if isinstance( + obj, + ( + variables.DataClassVariable, + variables.CustomizedDictVariable, + PlacementVariable, + ), + ): + return obj.call_method(tx, "__setattr__", [name_var, val], {}) + elif ( + tx.output.side_effects.is_attribute_mutation(obj) + and name_var.is_python_constant() + ): + name = name_var.as_python_constant() + if isinstance(obj, variables.TensorVariable): + from .builder import wrap_fx_proxy + + if name == "requires_grad": + # TODO(voz): Make it work properly + unimplemented( + "mutating requires_grad can introduce a new leaf from non-leaf or vice versa in " + "the middle of the graph, which aot_autograd does not currently know how to handle. " + ) + if name == "data": + # Remove the old reference in tracked fakes - if we don't do this + # new .data value size and shape differences will cause + # tracked fakes to produce incorrect guards. This is sound because the TensorVariable + # coming out of set_() below will be a new one, and get + # installed in tracked fakes. + to_remove = [] + for tf in tx.output.tracked_fakes: + if tf.source == obj.source: + to_remove.append(tf) + for tf in to_remove: + tx.output.tracked_fakes.remove(tf) + + # Step 1 - disable grads + with dynamo_disable_grad(tx), torch.no_grad(): + # Step 2 - call `set_` + out = wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + torch.Tensor.set_, + *proxy_args_kwargs([obj, val], {}), + ), + ) + + # Step 3 - drop the version counter - this is a step required to get + # .data setting to play correctly with the autograd engine. + # Esentially, dynamo is trying to faithful preserve the (absurd) + # behavior of .data= from eager mode + def _lower_version_count_by_1(x): + version = x._version + if version > 0: + version = version - 1 + torch._C._autograd._unsafe_set_version_counter(x, version) + return x + + tx.output.create_proxy( + "call_function", + _lower_version_count_by_1, + (out.as_proxy(),), + {}, + ) + _lower_version_count_by_1(obj.as_proxy().node.meta["example_value"]) + # This handles options prop, guards and ends with a clone + # Step 4 - replace all reference to the current object with the new one + return out + + tx.output.side_effects.store_attr(obj, name, val) + return val + elif isinstance(obj, variables.UserDefinedObjectVariable): + unimplemented( + f"setattr(UserDefinedObjectVariable) {type(obj.value).__setattr__}" + ) + elif isinstance(obj, variables.NNModuleVariable): + if not tx.output.is_root_tracer(): + raise AttributeMutationError( + "Can't inplace modify module params/buffers inside HigherOrderOp" + ) + if name_var.is_python_constant() and isinstance( + val, variables.TensorVariable + ): + assigning_fake_val = get_fake_value(val.as_proxy().node, tx) + + try: + getattr_var = obj.var_getattr(tx, name_var.as_python_constant()) + except AttributeError: + getattr_var = None + + if isinstance(getattr_var, variables.TensorVariable): + # get_fake_val will get the same fake tensor + existing_fake_attr = get_fake_value(getattr_var.as_proxy().node, tx) + + # same tensor identiy, setattr is a no-op + mod_setattr = inspect.getattr_static(obj.module_type, "__setattr__") + if ( + existing_fake_attr is assigning_fake_val + and mod_setattr is torch.nn.Module.__setattr__ + ): + return getattr_var + + obj.convert_to_unspecialized(tx) + # FIXME (tmanlaibaatar) this is utter hack to unblock HuggingFace export + # Export generally doesn't want to allow mutations on objects directly, + # but we don't have good way to do this rn. For now, we make it an undefined + # behaviour and just set attributes directly on the PretrainedConfig object + # for now. + elif isinstance(obj, variables.dicts.HFPretrainedConfigVariable) and tx.export: + if name_var.is_python_constant() and isinstance( + val, variables.ConstantVariable + ): + setattr( + obj.obj, name_var.as_python_constant(), val.as_python_constant() + ) + return ConstantVariable(None) + + def call_delattr(self, tx, obj: VariableTracker, name_var: VariableTracker): + return self.call_setattr(tx, obj, name_var, variables.DeletedVariable()) + + def call_type(self, tx, obj: VariableTracker): + from .builder import SourcelessBuilder, VariableBuilder + + try: + py_type = obj.python_type() + except NotImplementedError as error: + raise UserError( + UserErrorType.INVALID_INPUT, + str(error), + case_name="unknown_python_type", + ) from None + + if obj.source is None: + return SourcelessBuilder()(tx, py_type) + else: + return VariableBuilder(tx, TypeSource(obj.source))(py_type) + + def call_reversed(self, tx, obj: VariableTracker): + if obj.has_unpack_var_sequence(tx): + items = list(reversed(obj.unpack_var_sequence(tx))) + return variables.TupleVariable(items) + + def call_sorted(self, tx, obj: VariableTracker, **kwargs): + if ( + obj.has_unpack_var_sequence(tx) + and not isinstance(obj, variables.TensorVariable) + and all(x.is_python_constant() for x in obj.unpack_var_sequence(tx)) + ): + function = kwargs.pop("key", None) + reverse = kwargs.pop( + "reverse", ConstantVariable.create(False) + ).as_python_constant() + assert len(kwargs) == 0 + if function: + items = sorted( + obj.unpack_var_sequence(tx), + key=lambda x: function.call_function( + tx, [x], {} + ).as_python_constant(), + reverse=reverse, + ) + else: + items = sorted( + obj.unpack_var_sequence(tx), + key=lambda x: x.as_python_constant(), + reverse=reverse, + ) + return variables.ListVariable(items) + + def call_chain(self, tx, *args): + if all(obj.has_unpack_var_sequence(tx) for obj in args): + items = [] + for obj in args: + items.extend(obj.unpack_var_sequence(tx)) + return variables.TupleVariable(items) + + def call_islice(self, tx, iterable, *args): + if iterable.has_unpack_var_sequence(tx) and all( + x.is_python_constant() for x in args + ): + const_args = [x.as_python_constant() for x in args] + items = iterable.unpack_var_sequence(tx) + items = list(itertools.islice(items, *const_args)) + return variables.TupleVariable(items) + + # neg is a constant fold function, so we only get here if constant fold is not valid + def call_neg(self, tx, a): + if isinstance(a, SymNodeVariable): + return SymNodeVariable.create( + tx, + (operator.neg)(a.as_proxy()), + sym_num=None, + ) + # None no-ops this handler and lets the driving function proceed + return None + + def call_format(self, tx, _format_string, *args, **kwargs): + format_string = _format_string.as_python_constant() + return variables.StringFormatVariable.create(format_string, args, kwargs) + + def call_id(self, tx, *args): + if len(args) > 0 and isinstance(args[0], variables.NNModuleVariable): + nn_mod_variable = args[0] + mod = tx.output.get_submodule(nn_mod_variable.module_key) + return variables.ConstantVariable.create(id(mod)) + else: + unimplemented(f"call_id with args {args}") + + def call_deepcopy(self, tx, x): + unimplemented(f"copy.deepcopy {repr(x)}") + + def _comparison(self, tx, left, right): + """ + Used to implement comparison operators for different types. + For example, list1 < list2 is implemented differently from tensor1 < tensor2 + """ + from . import ( + BaseListVariable, + ConstantVariable, + NNModuleVariable, + TensorVariable, + UserDefinedObjectVariable, + UserFunctionVariable, + ) + from .lists import SizeVariable + from .tensor import ( + supported_const_comparison_ops, + supported_tensor_comparison_ops, + ) + + op = self.fn + + def _unimplemented(): + unimplemented(f"comparison {typestr(left)} {op} {typestr(right)}") + + if ( + all( + isinstance(x, (NNModuleVariable, ConstantVariable)) + for x in [left, right] + ) + and op in supported_const_comparison_ops.values() + ): + left = ( + tx.output.get_submodule(left.module_key) + if isinstance(left, NNModuleVariable) + else left.as_python_constant() + ) + right = ( + tx.output.get_submodule(right.module_key) + if isinstance(right, NNModuleVariable) + else right.as_python_constant() + ) + return ConstantVariable.create(op(left, right)) + + if isinstance(left, UserFunctionVariable): + if op not in supported_const_comparison_ops.values(): + _unimplemented() + if not isinstance(right, UserFunctionVariable): + _unimplemented() + return ConstantVariable.create(op(left.fn, right.fn)) + + # Note, we have a rare BaseListVariable subtype mismatch with valid comparison + # x = torch.randn([3, 3]) + # x.size() == (3, 3) # True + # (3, 3) == x.size() # True + if isinstance(left, (SizeVariable, TupleVariable)) and isinstance( + right, (TupleVariable, SizeVariable) + ): + return BaseListVariable.list_compare(tx, op, left, right) + + if isinstance(left, BaseListVariable): + if not type(left) == type(right): # Mismatch in BaseListVariable subclasses + _unimplemented() + return BaseListVariable.list_compare(tx, op, left, right) + + # If they implement set semantics (e.g. SetVariable or DictKeys) + if hasattr(left, "set_items") and hasattr(right, "set_items"): + return ConstantVariable.create(op(left.set_items, right.set_items)) + + if isinstance(left, TensorVariable) or isinstance(right, TensorVariable): + from .builder import wrap_fx_proxy_cls + + if op in [operator.is_, operator.is_not]: + is_result = ( + isinstance(left, TensorVariable) + and isinstance(right, TensorVariable) + and id(extract_fake_example_value(left.as_proxy().node)) + == id(extract_fake_example_value(right.as_proxy().node)) + ) + if op is operator.is_: + return ConstantVariable.create(is_result) + else: + return ConstantVariable.create(not is_result) + + if op not in supported_tensor_comparison_ops.values(): + _unimplemented() + if ( + isinstance(left, TensorVariable) + and isinstance(right, TensorVariable) + and (left.size and right.size) is not None + and left.size != right.size + ): + try: + torch.broadcast_shapes(left.size, right.size) + except RuntimeError: + # not broadcastable, can't be compared + _unimplemented() + tensor_cls = left if isinstance(left, TensorVariable) else right + proxy = tx.output.create_proxy( + "call_function", op, (left.as_proxy(), right.as_proxy()), {} + ) + return wrap_fx_proxy_cls( + type(tensor_cls), # handle Ndarrays and Tensors + tx, + proxy, + ) + + if isinstance(left, SymNodeVariable) or isinstance(right, SymNodeVariable): + if op not in supported_tensor_comparison_ops.values(): + _unimplemented() + + proxy = tx.output.create_proxy( + "call_function", op, (left.as_proxy(), right.as_proxy()), {} + ) + return SymNodeVariable.create( + tx, + proxy, + sym_num=None, + ) + + if isinstance(left, UserDefinedObjectVariable) and isinstance( + right, UserDefinedObjectVariable + ): + return ConstantVariable.create(op(left.value, right.value)) + + if isinstance(left, (StreamVariable, EventVariable)) or isinstance( + right, (StreamVariable, EventVariable) + ): + if type(left) == type(right) and op is operator.eq: + return ConstantVariable(op(left.value, right.value)) + + if isinstance(right, ConstantVariable) or isinstance( + left, ConstantVariable + ): + return ConstantVariable(op(left.value, right.value)) + + if op.__name__.startswith("is_"): + # If the two objects are of different type, we can safely return False and True for `is` and `is not`, respectively + if type(left) is not type(right): + return ConstantVariable.create(op.__name__ != "is_") + + if isinstance(left, BuiltinVariable) and isinstance(right, BuiltinVariable): + return ConstantVariable.create(op(left.fn, right.fn)) + + _unimplemented() + + def call_and_(self, tx, a, b): + # Rely on constant_handler + if isinstance(a, ConstantVariable) and isinstance(b, ConstantVariable): + return None + if isinstance(a, (SymNodeVariable, ConstantVariable)) and isinstance( + b, (SymNodeVariable, ConstantVariable) + ): + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.and_, *proxy_args_kwargs([a, b], {}) + ), + sym_num=None, + ) + if hasattr(a, "set_items") and hasattr(b, "set_items"): + return SetVariable(list(a.set_items & b.set_items)) + # None no-ops this handler and lets the driving function proceed + + def call_or_(self, tx, a, b): + # Rely on constant_handler + if isinstance(a, ConstantVariable) and isinstance(b, ConstantVariable): + return None + if isinstance(a, (SymNodeVariable, ConstantVariable)) and isinstance( + b, (SymNodeVariable, ConstantVariable) + ): + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.or_, *proxy_args_kwargs([a, b], {}) + ), + sym_num=None, + ) + if hasattr(a, "set_items") and hasattr(b, "set_items"): + return SetVariable(list(a.set_items | b.set_items)) + # None no-ops this handler and lets the driving function proceed + return None + + def call_not_(self, tx, a): + if isinstance(a, SymNodeVariable): + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.not_, *proxy_args_kwargs([a], {}) + ), + sym_num=None, + ) + + # Unwrap the underlying ConstDictVariable + if isinstance(a, DictView): + a = a.dv_dict + if isinstance(a, (ListVariable, ConstDictVariable)): + return ConstantVariable.create(len(a.items) == 0) + + return None + + call_eq = _comparison + call_gt = _comparison + call_lt = _comparison + call_ge = _comparison + call_le = _comparison + call_ne = _comparison + call_is_ = _comparison + call_is_not = _comparison + + call_all = _polyfill_call_impl("all") + call_any = _polyfill_call_impl("any") + + +@contextlib.contextmanager +def dynamo_disable_grad(tx): + from . import GradModeVariable + + org_value = torch.is_grad_enabled() + gmv = GradModeVariable.create(tx, False) + try: + gmv.enter(tx) + yield + finally: + gmv.exit(tx) diff --git a/shared/package-files/35/355f63fd14ee894e3b9af26f7ca13c75a5c7e4015827c2a2e20bc70494b1c8b7/Makassar b/shared/package-files/35/355f63fd14ee894e3b9af26f7ca13c75a5c7e4015827c2a2e20bc70494b1c8b7/Makassar new file mode 100644 index 0000000000000000000000000000000000000000..5990010b649745369501c7641c401bcad4345b85 Binary files /dev/null and b/shared/package-files/35/355f63fd14ee894e3b9af26f7ca13c75a5c7e4015827c2a2e20bc70494b1c8b7/Makassar differ diff --git a/shared/package-files/35/355f63fd14ee894e3b9af26f7ca13c75a5c7e4015827c2a2e20bc70494b1c8b7/Ujung_Pandang b/shared/package-files/35/355f63fd14ee894e3b9af26f7ca13c75a5c7e4015827c2a2e20bc70494b1c8b7/Ujung_Pandang new file mode 100644 index 0000000000000000000000000000000000000000..5990010b649745369501c7641c401bcad4345b85 Binary files /dev/null and b/shared/package-files/35/355f63fd14ee894e3b9af26f7ca13c75a5c7e4015827c2a2e20bc70494b1c8b7/Ujung_Pandang differ diff --git a/shared/package-files/35/35623922e1ffa9a0b5603d5139ea146e875b377c92d0cad928e8572e619f3c3a/rnn.py b/shared/package-files/35/35623922e1ffa9a0b5603d5139ea146e875b377c92d0cad928e8572e619f3c3a/rnn.py new file mode 100644 index 0000000000000000000000000000000000000000..a1a0076d13bc4e3ee29e9b3e410171d20e8e9a65 --- /dev/null +++ b/shared/package-files/35/35623922e1ffa9a0b5603d5139ea146e875b377c92d0cad928e8572e619f3c3a/rnn.py @@ -0,0 +1,11 @@ +# flake8: noqa: F401 +r"""Quantized Modules. + +This file is in the process of migration to `torch/ao/nn/quantized`, and +is kept here for compatibility while the migration process is ongoing. +If you are adding a new entry/functionality, please, add it to the +appropriate file under the `torch/ao/nn/quantized/modules`, +while adding an import statement here. +""" + +from torch.ao.nn.quantized.modules.rnn import LSTM diff --git a/shared/package-files/35/35649c80cd92c6519f0a14f19b465aeb10950b80f5ff3f19d06caceeede7780a/combinations.h b/shared/package-files/35/35649c80cd92c6519f0a14f19b465aeb10950b80f5ff3f19d06caceeede7780a/combinations.h new file mode 100644 index 0000000000000000000000000000000000000000..e0b54b1f663d89a1e6aeac801b16a38b763f0d45 --- /dev/null +++ b/shared/package-files/35/35649c80cd92c6519f0a14f19b465aeb10950b80f5ff3f19d06caceeede7780a/combinations.h @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::combinations(Tensor self, int r=2, bool with_replacement=False) -> Tensor +inline at::Tensor combinations(const at::Tensor & self, int64_t r=2, bool with_replacement=false) { + return at::_ops::combinations::call(self, r, with_replacement); +} + +} diff --git a/shared/package-files/35/3565f5a24c9b3bf9d90a5f48848384f1061a958d56a02d33973b2f060fc4d5e1/multidimensional.py b/shared/package-files/35/3565f5a24c9b3bf9d90a5f48848384f1061a958d56a02d33973b2f060fc4d5e1/multidimensional.py new file mode 100644 index 0000000000000000000000000000000000000000..133e0ab6cba6a87c627feb6f6034a6daed1128c5 --- /dev/null +++ b/shared/package-files/35/3565f5a24c9b3bf9d90a5f48848384f1061a958d56a02d33973b2f060fc4d5e1/multidimensional.py @@ -0,0 +1,131 @@ +""" +Provides functionality for multidimensional usage of scalar-functions. + +Read the vectorize docstring for more details. +""" + +from functools import wraps + + +def apply_on_element(f, args, kwargs, n): + """ + Returns a structure with the same dimension as the specified argument, + where each basic element is replaced by the function f applied on it. All + other arguments stay the same. + """ + # Get the specified argument. + if isinstance(n, int): + structure = args[n] + is_arg = True + elif isinstance(n, str): + structure = kwargs[n] + is_arg = False + + # Define reduced function that is only dependent on the specified argument. + def f_reduced(x): + if hasattr(x, "__iter__"): + return list(map(f_reduced, x)) + else: + if is_arg: + args[n] = x + else: + kwargs[n] = x + return f(*args, **kwargs) + + # f_reduced will call itself recursively so that in the end f is applied to + # all basic elements. + return list(map(f_reduced, structure)) + + +def iter_copy(structure): + """ + Returns a copy of an iterable object (also copying all embedded iterables). + """ + return [iter_copy(i) if hasattr(i, "__iter__") else i for i in structure] + + +def structure_copy(structure): + """ + Returns a copy of the given structure (numpy-array, list, iterable, ..). + """ + if hasattr(structure, "copy"): + return structure.copy() + return iter_copy(structure) + + +class vectorize: + """ + Generalizes a function taking scalars to accept multidimensional arguments. + + Examples + ======== + + >>> from sympy import vectorize, diff, sin, symbols, Function + >>> x, y, z = symbols('x y z') + >>> f, g, h = list(map(Function, 'fgh')) + + >>> @vectorize(0) + ... def vsin(x): + ... return sin(x) + + >>> vsin([1, x, y]) + [sin(1), sin(x), sin(y)] + + >>> @vectorize(0, 1) + ... def vdiff(f, y): + ... return diff(f, y) + + >>> vdiff([f(x, y, z), g(x, y, z), h(x, y, z)], [x, y, z]) + [[Derivative(f(x, y, z), x), Derivative(f(x, y, z), y), Derivative(f(x, y, z), z)], [Derivative(g(x, y, z), x), Derivative(g(x, y, z), y), Derivative(g(x, y, z), z)], [Derivative(h(x, y, z), x), Derivative(h(x, y, z), y), Derivative(h(x, y, z), z)]] + """ + def __init__(self, *mdargs): + """ + The given numbers and strings characterize the arguments that will be + treated as data structures, where the decorated function will be applied + to every single element. + If no argument is given, everything is treated multidimensional. + """ + for a in mdargs: + if not isinstance(a, (int, str)): + raise TypeError("a is of invalid type") + self.mdargs = mdargs + + def __call__(self, f): + """ + Returns a wrapper for the one-dimensional function that can handle + multidimensional arguments. + """ + @wraps(f) + def wrapper(*args, **kwargs): + # Get arguments that should be treated multidimensional + if self.mdargs: + mdargs = self.mdargs + else: + mdargs = range(len(args)) + kwargs.keys() + + arglength = len(args) + + for n in mdargs: + if isinstance(n, int): + if n >= arglength: + continue + entry = args[n] + is_arg = True + elif isinstance(n, str): + try: + entry = kwargs[n] + except KeyError: + continue + is_arg = False + if hasattr(entry, "__iter__"): + # Create now a copy of the given array and manipulate then + # the entries directly. + if is_arg: + args = list(args) + args[n] = structure_copy(entry) + else: + kwargs[n] = structure_copy(entry) + result = apply_on_element(wrapper, args, kwargs, n) + return result + return f(*args, **kwargs) + return wrapper diff --git a/shared/package-files/35/3566242fb8c8c1588d318c24ea3c759c3ebf71296ac0f78ad4376510b62f217f/test_grouping.py b/shared/package-files/35/3566242fb8c8c1588d318c24ea3c759c3ebf71296ac0f78ad4376510b62f217f/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0e67dea532bedac3a920f3c9bfa88e9d657f88 --- /dev/null +++ b/shared/package-files/35/3566242fb8c8c1588d318c24ea3c759c3ebf71296ac0f78ad4376510b62f217f/test_grouping.py @@ -0,0 +1,1238 @@ +""" +test where we are determining what we are grouping, or getting groups +""" +from datetime import ( + date, + timedelta, +) + +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + CategoricalIndex, + DataFrame, + Grouper, + Index, + MultiIndex, + Series, + Timestamp, + date_range, + period_range, +) +import pandas._testing as tm +from pandas.core.groupby.grouper import Grouping + +# selection +# -------------------------------- + + +class TestSelection: + def test_select_bad_cols(self): + df = DataFrame([[1, 2]], columns=["A", "B"]) + g = df.groupby("A") + with pytest.raises(KeyError, match="\"Columns not found: 'C'\""): + g[["C"]] + + with pytest.raises(KeyError, match="^[^A]+$"): + # A should not be referenced as a bad column... + # will have to rethink regex if you change message! + g[["A", "C"]] + + def test_groupby_duplicated_column_errormsg(self): + # GH7511 + df = DataFrame( + columns=["A", "B", "A", "C"], data=[range(4), range(2, 6), range(0, 8, 2)] + ) + + msg = "Grouper for 'A' not 1-dimensional" + with pytest.raises(ValueError, match=msg): + df.groupby("A") + with pytest.raises(ValueError, match=msg): + df.groupby(["A", "B"]) + + grouped = df.groupby("B") + c = grouped.count() + assert c.columns.nlevels == 1 + assert c.columns.size == 3 + + def test_column_select_via_attr(self, df): + result = df.groupby("A").C.sum() + expected = df.groupby("A")["C"].sum() + tm.assert_series_equal(result, expected) + + df["mean"] = 1.5 + result = df.groupby("A").mean(numeric_only=True) + expected = df.groupby("A")[["C", "D", "mean"]].agg("mean") + tm.assert_frame_equal(result, expected) + + def test_getitem_list_of_columns(self): + df = DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": ["one", "one", "two", "three", "two", "two", "one", "three"], + "C": np.random.default_rng(2).standard_normal(8), + "D": np.random.default_rng(2).standard_normal(8), + "E": np.random.default_rng(2).standard_normal(8), + } + ) + + result = df.groupby("A")[["C", "D"]].mean() + result2 = df.groupby("A")[df.columns[2:4]].mean() + + expected = df.loc[:, ["A", "C", "D"]].groupby("A").mean() + + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result2, expected) + + def test_getitem_numeric_column_names(self): + # GH #13731 + df = DataFrame( + { + 0: list("abcd") * 2, + 2: np.random.default_rng(2).standard_normal(8), + 4: np.random.default_rng(2).standard_normal(8), + 6: np.random.default_rng(2).standard_normal(8), + } + ) + result = df.groupby(0)[df.columns[1:3]].mean() + result2 = df.groupby(0)[[2, 4]].mean() + + expected = df.loc[:, [0, 2, 4]].groupby(0).mean() + + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result2, expected) + + # per GH 23566 enforced deprecation raises a ValueError + with pytest.raises(ValueError, match="Cannot subset columns with a tuple"): + df.groupby(0)[2, 4].mean() + + def test_getitem_single_tuple_of_columns_raises(self, df): + # per GH 23566 enforced deprecation raises a ValueError + with pytest.raises(ValueError, match="Cannot subset columns with a tuple"): + df.groupby("A")["C", "D"].mean() + + def test_getitem_single_column(self): + df = DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": ["one", "one", "two", "three", "two", "two", "one", "three"], + "C": np.random.default_rng(2).standard_normal(8), + "D": np.random.default_rng(2).standard_normal(8), + "E": np.random.default_rng(2).standard_normal(8), + } + ) + + result = df.groupby("A")["C"].mean() + + as_frame = df.loc[:, ["A", "C"]].groupby("A").mean() + as_series = as_frame.iloc[:, 0] + expected = as_series + + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "func", [lambda x: x.sum(), lambda x: x.agg(lambda y: y.sum())] + ) + def test_getitem_from_grouper(self, func): + # GH 50383 + df = DataFrame({"a": [1, 1, 2], "b": 3, "c": 4, "d": 5}) + gb = df.groupby(["a", "b"])[["a", "c"]] + + idx = MultiIndex.from_tuples([(1, 3), (2, 3)], names=["a", "b"]) + expected = DataFrame({"a": [2, 2], "c": [8, 4]}, index=idx) + result = func(gb) + + tm.assert_frame_equal(result, expected) + + def test_indices_grouped_by_tuple_with_lambda(self): + # GH 36158 + df = DataFrame( + { + "Tuples": ( + (x, y) + for x in [0, 1] + for y in np.random.default_rng(2).integers(3, 5, 5) + ) + } + ) + + gb = df.groupby("Tuples") + gb_lambda = df.groupby(lambda x: df.iloc[x, 0]) + + expected = gb.indices + result = gb_lambda.indices + + tm.assert_dict_equal(result, expected) + + +# grouping +# -------------------------------- + + +class TestGrouping: + @pytest.mark.parametrize( + "index", + [ + Index(list("abcde")), + Index(np.arange(5)), + Index(np.arange(5, dtype=float)), + date_range("2020-01-01", periods=5), + period_range("2020-01-01", periods=5), + ], + ) + def test_grouper_index_types(self, index): + # related GH5375 + # groupby misbehaving when using a Floatlike index + df = DataFrame(np.arange(10).reshape(5, 2), columns=list("AB"), index=index) + + df.groupby(list("abcde"), group_keys=False).apply(lambda x: x) + + df.index = df.index[::-1] + df.groupby(list("abcde"), group_keys=False).apply(lambda x: x) + + def test_grouper_multilevel_freq(self): + # GH 7885 + # with level and freq specified in a Grouper + d0 = date.today() - timedelta(days=14) + dates = date_range(d0, date.today()) + date_index = MultiIndex.from_product([dates, dates], names=["foo", "bar"]) + df = DataFrame(np.random.default_rng(2).integers(0, 100, 225), index=date_index) + + # Check string level + expected = ( + df.reset_index() + .groupby([Grouper(key="foo", freq="W"), Grouper(key="bar", freq="W")]) + .sum() + ) + # reset index changes columns dtype to object + expected.columns = Index([0], dtype="int64") + + result = df.groupby( + [Grouper(level="foo", freq="W"), Grouper(level="bar", freq="W")] + ).sum() + tm.assert_frame_equal(result, expected) + + # Check integer level + result = df.groupby( + [Grouper(level=0, freq="W"), Grouper(level=1, freq="W")] + ).sum() + tm.assert_frame_equal(result, expected) + + def test_grouper_creation_bug(self): + # GH 8795 + df = DataFrame({"A": [0, 0, 1, 1, 2, 2], "B": [1, 2, 3, 4, 5, 6]}) + g = df.groupby("A") + expected = g.sum() + + g = df.groupby(Grouper(key="A")) + result = g.sum() + tm.assert_frame_equal(result, expected) + + msg = "Grouper axis keyword is deprecated and will be removed" + with tm.assert_produces_warning(FutureWarning, match=msg): + gpr = Grouper(key="A", axis=0) + g = df.groupby(gpr) + result = g.sum() + tm.assert_frame_equal(result, expected) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = g.apply(lambda x: x.sum()) + expected["A"] = [0, 2, 4] + expected = expected.loc[:, ["A", "B"]] + tm.assert_frame_equal(result, expected) + + def test_grouper_creation_bug2(self): + # GH14334 + # Grouper(key=...) may be passed in a list + df = DataFrame( + {"A": [0, 0, 0, 1, 1, 1], "B": [1, 1, 2, 2, 3, 3], "C": [1, 2, 3, 4, 5, 6]} + ) + # Group by single column + expected = df.groupby("A").sum() + g = df.groupby([Grouper(key="A")]) + result = g.sum() + tm.assert_frame_equal(result, expected) + + # Group by two columns + # using a combination of strings and Grouper objects + expected = df.groupby(["A", "B"]).sum() + + # Group with two Grouper objects + g = df.groupby([Grouper(key="A"), Grouper(key="B")]) + result = g.sum() + tm.assert_frame_equal(result, expected) + + # Group with a string and a Grouper object + g = df.groupby(["A", Grouper(key="B")]) + result = g.sum() + tm.assert_frame_equal(result, expected) + + # Group with a Grouper object and a string + g = df.groupby([Grouper(key="A"), "B"]) + result = g.sum() + tm.assert_frame_equal(result, expected) + + def test_grouper_creation_bug3(self, unit): + # GH8866 + dti = date_range("20130101", periods=2, unit=unit) + mi = MultiIndex.from_product( + [list("ab"), range(2), dti], + names=["one", "two", "three"], + ) + ser = Series( + np.arange(8, dtype="int64"), + index=mi, + ) + result = ser.groupby(Grouper(level="three", freq="ME")).sum() + exp_dti = pd.DatetimeIndex( + [Timestamp("2013-01-31")], freq="ME", name="three" + ).as_unit(unit) + expected = Series( + [28], + index=exp_dti, + ) + tm.assert_series_equal(result, expected) + + # just specifying a level breaks + result = ser.groupby(Grouper(level="one")).sum() + expected = ser.groupby(level="one").sum() + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("func", [False, True]) + def test_grouper_returning_tuples(self, func): + # GH 22257 , both with dict and with callable + df = DataFrame({"X": ["A", "B", "A", "B"], "Y": [1, 4, 3, 2]}) + mapping = dict(zip(range(4), [("C", 5), ("D", 6)] * 2)) + + if func: + gb = df.groupby(by=lambda idx: mapping[idx], sort=False) + else: + gb = df.groupby(by=mapping, sort=False) + + name, expected = next(iter(gb)) + assert name == ("C", 5) + result = gb.get_group(name) + + tm.assert_frame_equal(result, expected) + + def test_grouper_column_and_index(self): + # GH 14327 + + # Grouping a multi-index frame by a column and an index level should + # be equivalent to resetting the index and grouping by two columns + idx = MultiIndex.from_tuples( + [("a", 1), ("a", 2), ("a", 3), ("b", 1), ("b", 2), ("b", 3)] + ) + idx.names = ["outer", "inner"] + df_multi = DataFrame( + {"A": np.arange(6), "B": ["one", "one", "two", "two", "one", "one"]}, + index=idx, + ) + result = df_multi.groupby(["B", Grouper(level="inner")]).mean(numeric_only=True) + expected = ( + df_multi.reset_index().groupby(["B", "inner"]).mean(numeric_only=True) + ) + tm.assert_frame_equal(result, expected) + + # Test the reverse grouping order + result = df_multi.groupby([Grouper(level="inner"), "B"]).mean(numeric_only=True) + expected = ( + df_multi.reset_index().groupby(["inner", "B"]).mean(numeric_only=True) + ) + tm.assert_frame_equal(result, expected) + + # Grouping a single-index frame by a column and the index should + # be equivalent to resetting the index and grouping by two columns + df_single = df_multi.reset_index("outer") + result = df_single.groupby(["B", Grouper(level="inner")]).mean( + numeric_only=True + ) + expected = ( + df_single.reset_index().groupby(["B", "inner"]).mean(numeric_only=True) + ) + tm.assert_frame_equal(result, expected) + + # Test the reverse grouping order + result = df_single.groupby([Grouper(level="inner"), "B"]).mean( + numeric_only=True + ) + expected = ( + df_single.reset_index().groupby(["inner", "B"]).mean(numeric_only=True) + ) + tm.assert_frame_equal(result, expected) + + def test_groupby_levels_and_columns(self): + # GH9344, GH9049 + idx_names = ["x", "y"] + idx = MultiIndex.from_tuples([(1, 1), (1, 2), (3, 4), (5, 6)], names=idx_names) + df = DataFrame(np.arange(12).reshape(-1, 3), index=idx) + + by_levels = df.groupby(level=idx_names).mean() + # reset_index changes columns dtype to object + by_columns = df.reset_index().groupby(idx_names).mean() + + # without casting, by_columns.columns is object-dtype + by_columns.columns = by_columns.columns.astype(np.int64) + tm.assert_frame_equal(by_levels, by_columns) + + def test_groupby_categorical_index_and_columns(self, observed): + # GH18432, adapted for GH25871 + columns = ["A", "B", "A", "B"] + categories = ["B", "A"] + data = np.array( + [[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]], int + ) + cat_columns = CategoricalIndex(columns, categories=categories, ordered=True) + df = DataFrame(data=data, columns=cat_columns) + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + result = df.groupby(axis=1, level=0, observed=observed).sum() + expected_data = np.array([[4, 2], [4, 2], [4, 2], [4, 2], [4, 2]], int) + expected_columns = CategoricalIndex( + categories, categories=categories, ordered=True + ) + expected = DataFrame(data=expected_data, columns=expected_columns) + tm.assert_frame_equal(result, expected) + + # test transposed version + df = DataFrame(data.T, index=cat_columns) + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby(axis=0, level=0, observed=observed).sum() + expected = DataFrame(data=expected_data.T, index=expected_columns) + tm.assert_frame_equal(result, expected) + + def test_grouper_getting_correct_binner(self): + # GH 10063 + # using a non-time-based grouper and a time-based grouper + # and specifying levels + df = DataFrame( + {"A": 1}, + index=MultiIndex.from_product( + [list("ab"), date_range("20130101", periods=80)], names=["one", "two"] + ), + ) + result = df.groupby( + [Grouper(level="one"), Grouper(level="two", freq="ME")] + ).sum() + expected = DataFrame( + {"A": [31, 28, 21, 31, 28, 21]}, + index=MultiIndex.from_product( + [list("ab"), date_range("20130101", freq="ME", periods=3)], + names=["one", "two"], + ), + ) + tm.assert_frame_equal(result, expected) + + def test_grouper_iter(self, df): + gb = df.groupby("A") + msg = "DataFrameGroupBy.grouper is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouper = gb.grouper + result = sorted(grouper) + expected = ["bar", "foo"] + assert result == expected + + def test_empty_groups(self, df): + # see gh-1048 + with pytest.raises(ValueError, match="No group keys passed!"): + df.groupby([]) + + def test_groupby_grouper(self, df): + grouped = df.groupby("A") + msg = "DataFrameGroupBy.grouper is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouper = grouped.grouper + result = df.groupby(grouper).mean(numeric_only=True) + expected = grouped.mean(numeric_only=True) + tm.assert_frame_equal(result, expected) + + def test_groupby_dict_mapping(self): + # GH #679 + s = Series({"T1": 5}) + result = s.groupby({"T1": "T2"}).agg("sum") + expected = s.groupby(["T2"]).agg("sum") + tm.assert_series_equal(result, expected) + + s = Series([1.0, 2.0, 3.0, 4.0], index=list("abcd")) + mapping = {"a": 0, "b": 0, "c": 1, "d": 1} + + result = s.groupby(mapping).mean() + result2 = s.groupby(mapping).agg("mean") + exp_key = np.array([0, 0, 1, 1], dtype=np.int64) + expected = s.groupby(exp_key).mean() + expected2 = s.groupby(exp_key).mean() + tm.assert_series_equal(result, expected) + tm.assert_series_equal(result, result2) + tm.assert_series_equal(result, expected2) + + @pytest.mark.parametrize( + "index", + [ + [0, 1, 2, 3], + ["a", "b", "c", "d"], + [Timestamp(2021, 7, 28 + i) for i in range(4)], + ], + ) + def test_groupby_series_named_with_tuple(self, frame_or_series, index): + # GH 42731 + obj = frame_or_series([1, 2, 3, 4], index=index) + groups = Series([1, 0, 1, 0], index=index, name=("a", "a")) + result = obj.groupby(groups).last() + expected = frame_or_series([4, 3]) + expected.index.name = ("a", "a") + tm.assert_equal(result, expected) + + def test_groupby_grouper_f_sanity_checked(self): + dates = date_range("01-Jan-2013", periods=12, freq="MS") + ts = Series(np.random.default_rng(2).standard_normal(12), index=dates) + + # GH51979 + # simple check that the passed function doesn't operates on the whole index + msg = "'Timestamp' object is not subscriptable" + with pytest.raises(TypeError, match=msg): + ts.groupby(lambda key: key[0:6]) + + result = ts.groupby(lambda x: x).sum() + expected = ts.groupby(ts.index).sum() + expected.index.freq = None + tm.assert_series_equal(result, expected) + + def test_groupby_with_datetime_key(self): + # GH 51158 + df = DataFrame( + { + "id": ["a", "b"] * 3, + "b": date_range("2000-01-01", "2000-01-03", freq="9h"), + } + ) + grouper = Grouper(key="b", freq="D") + gb = df.groupby([grouper, "id"]) + + # test number of groups + expected = { + (Timestamp("2000-01-01"), "a"): [0, 2], + (Timestamp("2000-01-01"), "b"): [1], + (Timestamp("2000-01-02"), "a"): [4], + (Timestamp("2000-01-02"), "b"): [3, 5], + } + tm.assert_dict_equal(gb.groups, expected) + + # test number of group keys + assert len(gb.groups.keys()) == 4 + + def test_grouping_error_on_multidim_input(self, df): + msg = "Grouper for '' not 1-dimensional" + with pytest.raises(ValueError, match=msg): + Grouping(df.index, df[["A", "A"]]) + + def test_multiindex_passthru(self): + # GH 7997 + # regression from 0.14.1 + df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + df.columns = MultiIndex.from_tuples([(0, 1), (1, 1), (2, 1)]) + + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + gb = df.groupby(axis=1, level=[0, 1]) + result = gb.first() + tm.assert_frame_equal(result, df) + + def test_multiindex_negative_level(self, multiindex_dataframe_random_data): + # GH 13901 + result = multiindex_dataframe_random_data.groupby(level=-1).sum() + expected = multiindex_dataframe_random_data.groupby(level="second").sum() + tm.assert_frame_equal(result, expected) + + result = multiindex_dataframe_random_data.groupby(level=-2).sum() + expected = multiindex_dataframe_random_data.groupby(level="first").sum() + tm.assert_frame_equal(result, expected) + + result = multiindex_dataframe_random_data.groupby(level=[-2, -1]).sum() + expected = multiindex_dataframe_random_data.sort_index() + tm.assert_frame_equal(result, expected) + + result = multiindex_dataframe_random_data.groupby(level=[-1, "first"]).sum() + expected = multiindex_dataframe_random_data.groupby( + level=["second", "first"] + ).sum() + tm.assert_frame_equal(result, expected) + + def test_multifunc_select_col_integer_cols(self, df): + df.columns = np.arange(len(df.columns)) + + # it works! + msg = "Passing a dictionary to SeriesGroupBy.agg is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + df.groupby(1, as_index=False)[2].agg({"Q": np.mean}) + + def test_multiindex_columns_empty_level(self): + lst = [["count", "values"], ["to filter", ""]] + midx = MultiIndex.from_tuples(lst) + + df = DataFrame([[1, "A"]], columns=midx) + + grouped = df.groupby("to filter").groups + assert grouped["A"] == [0] + + grouped = df.groupby([("to filter", "")]).groups + assert grouped["A"] == [0] + + df = DataFrame([[1, "A"], [2, "B"]], columns=midx) + + expected = df.groupby("to filter").groups + result = df.groupby([("to filter", "")]).groups + assert result == expected + + df = DataFrame([[1, "A"], [2, "A"]], columns=midx) + + expected = df.groupby("to filter").groups + result = df.groupby([("to filter", "")]).groups + tm.assert_dict_equal(result, expected) + + def test_groupby_multiindex_tuple(self): + # GH 17979 + df = DataFrame( + [[1, 2, 3, 4], [3, 4, 5, 6], [1, 4, 2, 3]], + columns=MultiIndex.from_arrays([["a", "b", "b", "c"], [1, 1, 2, 2]]), + ) + expected = df.groupby([("b", 1)]).groups + result = df.groupby(("b", 1)).groups + tm.assert_dict_equal(expected, result) + + df2 = DataFrame( + df.values, + columns=MultiIndex.from_arrays( + [["a", "b", "b", "c"], ["d", "d", "e", "e"]] + ), + ) + expected = df2.groupby([("b", "d")]).groups + result = df.groupby(("b", 1)).groups + tm.assert_dict_equal(expected, result) + + df3 = DataFrame(df.values, columns=[("a", "d"), ("b", "d"), ("b", "e"), "c"]) + expected = df3.groupby([("b", "d")]).groups + result = df.groupby(("b", 1)).groups + tm.assert_dict_equal(expected, result) + + def test_groupby_multiindex_partial_indexing_equivalence(self): + # GH 17977 + df = DataFrame( + [[1, 2, 3, 4], [3, 4, 5, 6], [1, 4, 2, 3]], + columns=MultiIndex.from_arrays([["a", "b", "b", "c"], [1, 1, 2, 2]]), + ) + + expected_mean = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].mean() + result_mean = df.groupby([("a", 1)])["b"].mean() + tm.assert_frame_equal(expected_mean, result_mean) + + expected_sum = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].sum() + result_sum = df.groupby([("a", 1)])["b"].sum() + tm.assert_frame_equal(expected_sum, result_sum) + + expected_count = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].count() + result_count = df.groupby([("a", 1)])["b"].count() + tm.assert_frame_equal(expected_count, result_count) + + expected_min = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].min() + result_min = df.groupby([("a", 1)])["b"].min() + tm.assert_frame_equal(expected_min, result_min) + + expected_max = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].max() + result_max = df.groupby([("a", 1)])["b"].max() + tm.assert_frame_equal(expected_max, result_max) + + expected_groups = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].groups + result_groups = df.groupby([("a", 1)])["b"].groups + tm.assert_dict_equal(expected_groups, result_groups) + + @pytest.mark.parametrize("sort", [True, False]) + def test_groupby_level(self, sort, multiindex_dataframe_random_data, df): + # GH 17537 + frame = multiindex_dataframe_random_data + deleveled = frame.reset_index() + + result0 = frame.groupby(level=0, sort=sort).sum() + result1 = frame.groupby(level=1, sort=sort).sum() + + expected0 = frame.groupby(deleveled["first"].values, sort=sort).sum() + expected1 = frame.groupby(deleveled["second"].values, sort=sort).sum() + + expected0.index.name = "first" + expected1.index.name = "second" + + assert result0.index.name == "first" + assert result1.index.name == "second" + + tm.assert_frame_equal(result0, expected0) + tm.assert_frame_equal(result1, expected1) + assert result0.index.name == frame.index.names[0] + assert result1.index.name == frame.index.names[1] + + # groupby level name + result0 = frame.groupby(level="first", sort=sort).sum() + result1 = frame.groupby(level="second", sort=sort).sum() + tm.assert_frame_equal(result0, expected0) + tm.assert_frame_equal(result1, expected1) + + # axis=1 + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result0 = frame.T.groupby(level=0, axis=1, sort=sort).sum() + result1 = frame.T.groupby(level=1, axis=1, sort=sort).sum() + tm.assert_frame_equal(result0, expected0.T) + tm.assert_frame_equal(result1, expected1.T) + + # raise exception for non-MultiIndex + msg = "level > 0 or level < -1 only valid with MultiIndex" + with pytest.raises(ValueError, match=msg): + df.groupby(level=1) + + def test_groupby_level_index_names(self, axis): + # GH4014 this used to raise ValueError since 'exp'>1 (in py2) + df = DataFrame({"exp": ["A"] * 3 + ["B"] * 3, "var1": range(6)}).set_index( + "exp" + ) + if axis in (1, "columns"): + df = df.T + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + else: + depr_msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + df.groupby(level="exp", axis=axis) + msg = f"level name foo is not the name of the {df._get_axis_name(axis)}" + with pytest.raises(ValueError, match=msg): + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + df.groupby(level="foo", axis=axis) + + @pytest.mark.parametrize("sort", [True, False]) + def test_groupby_level_with_nas(self, sort): + # GH 17537 + index = MultiIndex( + levels=[[1, 0], [0, 1, 2, 3]], + codes=[[1, 1, 1, 1, 0, 0, 0, 0], [0, 1, 2, 3, 0, 1, 2, 3]], + ) + + # factorizing doesn't confuse things + s = Series(np.arange(8.0), index=index) + result = s.groupby(level=0, sort=sort).sum() + expected = Series([6.0, 22.0], index=[0, 1]) + tm.assert_series_equal(result, expected) + + index = MultiIndex( + levels=[[1, 0], [0, 1, 2, 3]], + codes=[[1, 1, 1, 1, -1, 0, 0, 0], [0, 1, 2, 3, 0, 1, 2, 3]], + ) + + # factorizing doesn't confuse things + s = Series(np.arange(8.0), index=index) + result = s.groupby(level=0, sort=sort).sum() + expected = Series([6.0, 18.0], index=[0.0, 1.0]) + tm.assert_series_equal(result, expected) + + def test_groupby_args(self, multiindex_dataframe_random_data): + # PR8618 and issue 8015 + frame = multiindex_dataframe_random_data + + msg = "You have to supply one of 'by' and 'level'" + with pytest.raises(TypeError, match=msg): + frame.groupby() + + msg = "You have to supply one of 'by' and 'level'" + with pytest.raises(TypeError, match=msg): + frame.groupby(by=None, level=None) + + @pytest.mark.parametrize( + "sort,labels", + [ + [True, [2, 2, 2, 0, 0, 1, 1, 3, 3, 3]], + [False, [0, 0, 0, 1, 1, 2, 2, 3, 3, 3]], + ], + ) + def test_level_preserve_order(self, sort, labels, multiindex_dataframe_random_data): + # GH 17537 + grouped = multiindex_dataframe_random_data.groupby(level=0, sort=sort) + exp_labels = np.array(labels, np.intp) + tm.assert_almost_equal(grouped._grouper.codes[0], exp_labels) + + def test_grouping_labels(self, multiindex_dataframe_random_data): + grouped = multiindex_dataframe_random_data.groupby( + multiindex_dataframe_random_data.index.get_level_values(0) + ) + exp_labels = np.array([2, 2, 2, 0, 0, 1, 1, 3, 3, 3], dtype=np.intp) + tm.assert_almost_equal(grouped._grouper.codes[0], exp_labels) + + def test_list_grouper_with_nat(self): + # GH 14715 + df = DataFrame({"date": date_range("1/1/2011", periods=365, freq="D")}) + df.iloc[-1] = pd.NaT + grouper = Grouper(key="date", freq="YS") + + # Grouper in a list grouping + result = df.groupby([grouper]) + expected = {Timestamp("2011-01-01"): Index(list(range(364)))} + tm.assert_dict_equal(result.groups, expected) + + # Test case without a list + result = df.groupby(grouper) + expected = {Timestamp("2011-01-01"): 365} + tm.assert_dict_equal(result.groups, expected) + + @pytest.mark.parametrize( + "func,expected", + [ + ( + "transform", + Series(name=2, dtype=np.float64), + ), + ( + "agg", + Series( + name=2, dtype=np.float64, index=Index([], dtype=np.float64, name=1) + ), + ), + ( + "apply", + Series( + name=2, dtype=np.float64, index=Index([], dtype=np.float64, name=1) + ), + ), + ], + ) + def test_evaluate_with_empty_groups(self, func, expected): + # 26208 + # test transform'ing empty groups + # (not testing other agg fns, because they return + # different index objects. + df = DataFrame({1: [], 2: []}) + g = df.groupby(1, group_keys=False) + result = getattr(g[2], func)(lambda x: x) + tm.assert_series_equal(result, expected) + + def test_groupby_empty(self): + # https://github.com/pandas-dev/pandas/issues/27190 + s = Series([], name="name", dtype="float64") + gr = s.groupby([]) + + result = gr.mean() + expected = s.set_axis(Index([], dtype=np.intp)) + tm.assert_series_equal(result, expected) + + # check group properties + assert len(gr._grouper.groupings) == 1 + tm.assert_numpy_array_equal( + gr._grouper.group_info[0], np.array([], dtype=np.dtype(np.intp)) + ) + + tm.assert_numpy_array_equal( + gr._grouper.group_info[1], np.array([], dtype=np.dtype(np.intp)) + ) + + assert gr._grouper.group_info[2] == 0 + + # check name + gb = s.groupby(s) + msg = "SeriesGroupBy.grouper is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouper = gb.grouper + result = grouper.names + expected = ["name"] + assert result == expected + + def test_groupby_level_index_value_all_na(self): + # issue 20519 + df = DataFrame( + [["x", np.nan, 10], [None, np.nan, 20]], columns=["A", "B", "C"] + ).set_index(["A", "B"]) + result = df.groupby(level=["A", "B"]).sum() + expected = DataFrame( + data=[], + index=MultiIndex( + levels=[Index(["x"], dtype="str"), Index([], dtype="float64")], + codes=[[], []], + names=["A", "B"], + ), + columns=["C"], + dtype="int64", + ) + tm.assert_frame_equal(result, expected) + + def test_groupby_multiindex_level_empty(self): + # https://github.com/pandas-dev/pandas/issues/31670 + df = DataFrame( + [[123, "a", 1.0], [123, "b", 2.0]], columns=["id", "category", "value"] + ) + df = df.set_index(["id", "category"]) + empty = df[df.value < 0] + result = empty.groupby("id").sum() + expected = DataFrame( + dtype="float64", + columns=["value"], + index=Index([], dtype=np.int64, name="id"), + ) + tm.assert_frame_equal(result, expected) + + +# get_group +# -------------------------------- + + +class TestGetGroup: + def test_get_group(self): + # GH 5267 + # be datelike friendly + df = DataFrame( + { + "DATE": pd.to_datetime( + [ + "10-Oct-2013", + "10-Oct-2013", + "10-Oct-2013", + "11-Oct-2013", + "11-Oct-2013", + "11-Oct-2013", + ] + ), + "label": ["foo", "foo", "bar", "foo", "foo", "bar"], + "VAL": [1, 2, 3, 4, 5, 6], + } + ) + + g = df.groupby("DATE") + key = next(iter(g.groups)) + result1 = g.get_group(key) + result2 = g.get_group(Timestamp(key).to_pydatetime()) + result3 = g.get_group(str(Timestamp(key))) + tm.assert_frame_equal(result1, result2) + tm.assert_frame_equal(result1, result3) + + g = df.groupby(["DATE", "label"]) + + key = next(iter(g.groups)) + result1 = g.get_group(key) + result2 = g.get_group((Timestamp(key[0]).to_pydatetime(), key[1])) + result3 = g.get_group((str(Timestamp(key[0])), key[1])) + tm.assert_frame_equal(result1, result2) + tm.assert_frame_equal(result1, result3) + + # must pass a same-length tuple with multiple keys + msg = "must supply a tuple to get_group with multiple grouping keys" + with pytest.raises(ValueError, match=msg): + g.get_group("foo") + with pytest.raises(ValueError, match=msg): + g.get_group("foo") + msg = "must supply a same-length tuple to get_group with multiple grouping keys" + with pytest.raises(ValueError, match=msg): + g.get_group(("foo", "bar", "baz")) + + def test_get_group_empty_bins(self, observed): + d = DataFrame([3, 1, 7, 6]) + bins = [0, 5, 10, 15] + g = d.groupby(pd.cut(d[0], bins), observed=observed) + + # TODO: should prob allow a str of Interval work as well + # IOW '(0, 5]' + result = g.get_group(pd.Interval(0, 5)) + expected = DataFrame([3, 1], index=[0, 1]) + tm.assert_frame_equal(result, expected) + + msg = r"Interval\(10, 15, closed='right'\)" + with pytest.raises(KeyError, match=msg): + g.get_group(pd.Interval(10, 15)) + + def test_get_group_grouped_by_tuple(self): + # GH 8121 + df = DataFrame([[(1,), (1, 2), (1,), (1, 2)]], index=["ids"]).T + gr = df.groupby("ids") + expected = DataFrame({"ids": [(1,), (1,)]}, index=[0, 2]) + result = gr.get_group((1,)) + tm.assert_frame_equal(result, expected) + + dt = pd.to_datetime(["2010-01-01", "2010-01-02", "2010-01-01", "2010-01-02"]) + df = DataFrame({"ids": [(x,) for x in dt]}) + gr = df.groupby("ids") + result = gr.get_group(("2010-01-01",)) + expected = DataFrame({"ids": [(dt[0],), (dt[0],)]}, index=[0, 2]) + tm.assert_frame_equal(result, expected) + + def test_get_group_grouped_by_tuple_with_lambda(self): + # GH 36158 + df = DataFrame( + { + "Tuples": ( + (x, y) + for x in [0, 1] + for y in np.random.default_rng(2).integers(3, 5, 5) + ) + } + ) + + gb = df.groupby("Tuples") + gb_lambda = df.groupby(lambda x: df.iloc[x, 0]) + + expected = gb.get_group(next(iter(gb.groups.keys()))) + result = gb_lambda.get_group(next(iter(gb_lambda.groups.keys()))) + + tm.assert_frame_equal(result, expected) + + def test_groupby_with_empty(self): + index = pd.DatetimeIndex(()) + data = () + series = Series(data, index, dtype=object) + grouper = Grouper(freq="D") + grouped = series.groupby(grouper) + assert next(iter(grouped), None) is None + + def test_groupby_with_single_column(self): + df = DataFrame({"a": list("abssbab")}) + tm.assert_frame_equal(df.groupby("a").get_group("a"), df.iloc[[0, 5]]) + # GH 13530 + exp = DataFrame( + index=Index(["a", "b", "s"], name="a"), columns=Index([], dtype="str") + ) + tm.assert_frame_equal(df.groupby("a").count(), exp) + tm.assert_frame_equal(df.groupby("a").sum(), exp) + + exp = df.iloc[[3, 4, 5]] + tm.assert_frame_equal(df.groupby("a").nth(1), exp) + + def test_gb_key_len_equal_axis_len(self): + # GH16843 + # test ensures that index and column keys are recognized correctly + # when number of keys equals axis length of groupby + df = DataFrame( + [["foo", "bar", "B", 1], ["foo", "bar", "B", 2], ["foo", "baz", "C", 3]], + columns=["first", "second", "third", "one"], + ) + df = df.set_index(["first", "second"]) + df = df.groupby(["first", "second", "third"]).size() + assert df.loc[("foo", "bar", "B")] == 2 + assert df.loc[("foo", "baz", "C")] == 1 + + +# groups & iteration +# -------------------------------- + + +class TestIteration: + def test_groups(self, df): + grouped = df.groupby(["A"]) + groups = grouped.groups + assert groups is grouped.groups # caching works + + for k, v in grouped.groups.items(): + assert (df.loc[v]["A"] == k).all() + + grouped = df.groupby(["A", "B"]) + groups = grouped.groups + assert groups is grouped.groups # caching works + + for k, v in grouped.groups.items(): + assert (df.loc[v]["A"] == k[0]).all() + assert (df.loc[v]["B"] == k[1]).all() + + def test_grouping_is_iterable(self, tsframe): + # this code path isn't used anywhere else + # not sure it's useful + grouped = tsframe.groupby([lambda x: x.weekday(), lambda x: x.year]) + + # test it works + for g in grouped._grouper.groupings[0]: + pass + + def test_multi_iter(self): + s = Series(np.arange(6)) + k1 = np.array(["a", "a", "a", "b", "b", "b"]) + k2 = np.array(["1", "2", "1", "2", "1", "2"]) + + grouped = s.groupby([k1, k2]) + + iterated = list(grouped) + expected = [ + ("a", "1", s[[0, 2]]), + ("a", "2", s[[1]]), + ("b", "1", s[[4]]), + ("b", "2", s[[3, 5]]), + ] + for i, ((one, two), three) in enumerate(iterated): + e1, e2, e3 = expected[i] + assert e1 == one + assert e2 == two + tm.assert_series_equal(three, e3) + + def test_multi_iter_frame(self, three_group): + k1 = np.array(["b", "b", "b", "a", "a", "a"]) + k2 = np.array(["1", "2", "1", "2", "1", "2"]) + df = DataFrame( + { + "v1": np.random.default_rng(2).standard_normal(6), + "v2": np.random.default_rng(2).standard_normal(6), + "k1": k1, + "k2": k2, + }, + index=["one", "two", "three", "four", "five", "six"], + ) + + grouped = df.groupby(["k1", "k2"]) + + # things get sorted! + iterated = list(grouped) + idx = df.index + expected = [ + ("a", "1", df.loc[idx[[4]]]), + ("a", "2", df.loc[idx[[3, 5]]]), + ("b", "1", df.loc[idx[[0, 2]]]), + ("b", "2", df.loc[idx[[1]]]), + ] + for i, ((one, two), three) in enumerate(iterated): + e1, e2, e3 = expected[i] + assert e1 == one + assert e2 == two + tm.assert_frame_equal(three, e3) + + # don't iterate through groups with no data + df["k1"] = np.array(["b", "b", "b", "a", "a", "a"]) + df["k2"] = np.array(["1", "1", "1", "2", "2", "2"]) + grouped = df.groupby(["k1", "k2"]) + # calling `dict` on a DataFrameGroupBy leads to a TypeError, + # we need to use a dictionary comprehension here + # pylint: disable-next=unnecessary-comprehension + groups = {key: gp for key, gp in grouped} # noqa: C416 + assert len(groups) == 2 + + # axis = 1 + three_levels = three_group.groupby(["A", "B", "C"]).mean() + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + grouped = three_levels.T.groupby(axis=1, level=(1, 2)) + for key, group in grouped: + pass + + def test_dictify(self, df): + dict(iter(df.groupby("A"))) + dict(iter(df.groupby(["A", "B"]))) + dict(iter(df["C"].groupby(df["A"]))) + dict(iter(df["C"].groupby([df["A"], df["B"]]))) + dict(iter(df.groupby("A")["C"])) + dict(iter(df.groupby(["A", "B"])["C"])) + + def test_groupby_with_small_elem(self): + # GH 8542 + # length=2 + df = DataFrame( + {"event": ["start", "start"], "change": [1234, 5678]}, + index=pd.DatetimeIndex(["2014-09-10", "2013-10-10"]), + ) + grouped = df.groupby([Grouper(freq="ME"), "event"]) + assert len(grouped.groups) == 2 + assert grouped.ngroups == 2 + assert (Timestamp("2014-09-30"), "start") in grouped.groups + assert (Timestamp("2013-10-31"), "start") in grouped.groups + + res = grouped.get_group((Timestamp("2014-09-30"), "start")) + tm.assert_frame_equal(res, df.iloc[[0], :]) + res = grouped.get_group((Timestamp("2013-10-31"), "start")) + tm.assert_frame_equal(res, df.iloc[[1], :]) + + df = DataFrame( + {"event": ["start", "start", "start"], "change": [1234, 5678, 9123]}, + index=pd.DatetimeIndex(["2014-09-10", "2013-10-10", "2014-09-15"]), + ) + grouped = df.groupby([Grouper(freq="ME"), "event"]) + assert len(grouped.groups) == 2 + assert grouped.ngroups == 2 + assert (Timestamp("2014-09-30"), "start") in grouped.groups + assert (Timestamp("2013-10-31"), "start") in grouped.groups + + res = grouped.get_group((Timestamp("2014-09-30"), "start")) + tm.assert_frame_equal(res, df.iloc[[0, 2], :]) + res = grouped.get_group((Timestamp("2013-10-31"), "start")) + tm.assert_frame_equal(res, df.iloc[[1], :]) + + # length=3 + df = DataFrame( + {"event": ["start", "start", "start"], "change": [1234, 5678, 9123]}, + index=pd.DatetimeIndex(["2014-09-10", "2013-10-10", "2014-08-05"]), + ) + grouped = df.groupby([Grouper(freq="ME"), "event"]) + assert len(grouped.groups) == 3 + assert grouped.ngroups == 3 + assert (Timestamp("2014-09-30"), "start") in grouped.groups + assert (Timestamp("2013-10-31"), "start") in grouped.groups + assert (Timestamp("2014-08-31"), "start") in grouped.groups + + res = grouped.get_group((Timestamp("2014-09-30"), "start")) + tm.assert_frame_equal(res, df.iloc[[0], :]) + res = grouped.get_group((Timestamp("2013-10-31"), "start")) + tm.assert_frame_equal(res, df.iloc[[1], :]) + res = grouped.get_group((Timestamp("2014-08-31"), "start")) + tm.assert_frame_equal(res, df.iloc[[2], :]) + + def test_grouping_string_repr(self): + # GH 13394 + mi = MultiIndex.from_arrays([list("AAB"), list("aba")]) + df = DataFrame([[1, 2, 3]], columns=mi) + gr = df.groupby(df[("A", "a")]) + + result = gr._grouper.groupings[0].__repr__() + expected = "Grouping(('A', 'a'))" + assert result == expected + + +def test_grouping_by_key_is_in_axis(): + # GH#50413 - Groupers specified by key are in-axis + df = DataFrame({"a": [1, 1, 2], "b": [1, 1, 2], "c": [3, 4, 5]}).set_index("a") + gb = df.groupby([Grouper(level="a"), Grouper(key="b")], as_index=False) + assert not gb._grouper.groupings[0].in_axis + assert gb._grouper.groupings[1].in_axis + + # Currently only in-axis groupings are including in the result when as_index=False; + # This is likely to change in the future. + msg = "A grouping .* was excluded from the result" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = gb.sum() + expected = DataFrame({"b": [1, 2], "c": [7, 5]}) + tm.assert_frame_equal(result, expected) + + +def test_grouper_groups(): + # GH#51182 check Grouper.groups does not raise AttributeError + df = DataFrame({"a": [1, 2, 3], "b": 1}) + grper = Grouper(key="a") + gb = df.groupby(grper) + + msg = "Use GroupBy.groups instead" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = grper.groups + assert res is gb.groups + + msg = "Use GroupBy.grouper instead" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = grper.grouper + assert res is gb._grouper + + msg = "Grouper.obj is deprecated and will be removed" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = grper.obj + assert res is gb.obj + + msg = "Use Resampler.ax instead" + with tm.assert_produces_warning(FutureWarning, match=msg): + grper.ax + + msg = "Grouper.indexer is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grper.indexer + + +@pytest.mark.parametrize("attr", ["group_index", "result_index", "group_arraylike"]) +def test_depr_grouping_attrs(attr): + # GH#56148 + df = DataFrame({"a": [1, 1, 2], "b": [3, 4, 5]}) + gb = df.groupby("a") + msg = f"{attr} is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + getattr(gb._grouper.groupings[0], attr) diff --git a/shared/package-files/35/35673b393bc3740378e105f339052dff527731f4453c425ba560007ccd586ebb/kaiser_window_compositeexplicitautograd_dispatch.h b/shared/package-files/35/35673b393bc3740378e105f339052dff527731f4453c425ba560007ccd586ebb/kaiser_window_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..4e0fed016566596b6dfd1845c027137314a03009 --- /dev/null +++ b/shared/package-files/35/35673b393bc3740378e105f339052dff527731f4453c425ba560007ccd586ebb/kaiser_window_compositeexplicitautograd_dispatch.h @@ -0,0 +1,34 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor kaiser_window(int64_t window_length, at::TensorOptions options={}); +TORCH_API at::Tensor kaiser_window(int64_t window_length, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +TORCH_API at::Tensor & kaiser_window_out(at::Tensor & out, int64_t window_length); +TORCH_API at::Tensor & kaiser_window_outf(int64_t window_length, at::Tensor & out); +TORCH_API at::Tensor kaiser_window(int64_t window_length, bool periodic, at::TensorOptions options={}); +TORCH_API at::Tensor kaiser_window(int64_t window_length, bool periodic, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +TORCH_API at::Tensor & kaiser_window_out(at::Tensor & out, int64_t window_length, bool periodic); +TORCH_API at::Tensor & kaiser_window_outf(int64_t window_length, bool periodic, at::Tensor & out); +TORCH_API at::Tensor kaiser_window(int64_t window_length, bool periodic, double beta, at::TensorOptions options={}); +TORCH_API at::Tensor kaiser_window(int64_t window_length, bool periodic, double beta, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +TORCH_API at::Tensor & kaiser_window_out(at::Tensor & out, int64_t window_length, bool periodic, double beta); +TORCH_API at::Tensor & kaiser_window_outf(int64_t window_length, bool periodic, double beta, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/35/35690690d3a3ae79d46c78093d39acff9bac285d0cf0995a1cbde7c881c004c9/prepare.py b/shared/package-files/35/35690690d3a3ae79d46c78093d39acff9bac285d0cf0995a1cbde7c881c004c9/prepare.py new file mode 100644 index 0000000000000000000000000000000000000000..488e76358befd4a97740a7d95e9797a059b286b8 --- /dev/null +++ b/shared/package-files/35/35690690d3a3ae79d46c78093d39acff9bac285d0cf0995a1cbde7c881c004c9/prepare.py @@ -0,0 +1,730 @@ +"""Prepares a distribution for installation +""" + +# The following comment should be removed at some point in the future. +# mypy: strict-optional=False + +import mimetypes +import os +import shutil +from pathlib import Path +from typing import Dict, Iterable, List, Optional + +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.distributions import make_distribution_for_install_requirement +from pip._internal.distributions.installed import InstalledDistribution +from pip._internal.exceptions import ( + DirectoryUrlHashUnsupported, + HashMismatch, + HashUnpinned, + InstallationError, + MetadataInconsistent, + NetworkConnectionError, + VcsHashUnsupported, +) +from pip._internal.index.package_finder import PackageFinder +from pip._internal.metadata import BaseDistribution, get_metadata_distribution +from pip._internal.models.direct_url import ArchiveInfo +from pip._internal.models.link import Link +from pip._internal.models.wheel import Wheel +from pip._internal.network.download import BatchDownloader, Downloader +from pip._internal.network.lazy_wheel import ( + HTTPRangeRequestUnsupported, + dist_from_wheel_url, +) +from pip._internal.network.session import PipSession +from pip._internal.operations.build.build_tracker import BuildTracker +from pip._internal.req.req_install import InstallRequirement +from pip._internal.utils._log import getLogger +from pip._internal.utils.direct_url_helpers import ( + direct_url_for_editable, + direct_url_from_link, +) +from pip._internal.utils.hashes import Hashes, MissingHashes +from pip._internal.utils.logging import indent_log +from pip._internal.utils.misc import ( + display_path, + hash_file, + hide_url, + redact_auth_from_requirement, +) +from pip._internal.utils.temp_dir import TempDirectory +from pip._internal.utils.unpacking import unpack_file +from pip._internal.vcs import vcs + +logger = getLogger(__name__) + + +def _get_prepared_distribution( + req: InstallRequirement, + build_tracker: BuildTracker, + finder: PackageFinder, + build_isolation: bool, + check_build_deps: bool, +) -> BaseDistribution: + """Prepare a distribution for installation.""" + abstract_dist = make_distribution_for_install_requirement(req) + tracker_id = abstract_dist.build_tracker_id + if tracker_id is not None: + with build_tracker.track(req, tracker_id): + abstract_dist.prepare_distribution_metadata( + finder, build_isolation, check_build_deps + ) + return abstract_dist.get_metadata_distribution() + + +def unpack_vcs_link(link: Link, location: str, verbosity: int) -> None: + vcs_backend = vcs.get_backend_for_scheme(link.scheme) + assert vcs_backend is not None + vcs_backend.unpack(location, url=hide_url(link.url), verbosity=verbosity) + + +class File: + def __init__(self, path: str, content_type: Optional[str]) -> None: + self.path = path + if content_type is None: + self.content_type = mimetypes.guess_type(path)[0] + else: + self.content_type = content_type + + +def get_http_url( + link: Link, + download: Downloader, + download_dir: Optional[str] = None, + hashes: Optional[Hashes] = None, +) -> File: + temp_dir = TempDirectory(kind="unpack", globally_managed=True) + # If a download dir is specified, is the file already downloaded there? + already_downloaded_path = None + if download_dir: + already_downloaded_path = _check_download_dir(link, download_dir, hashes) + + if already_downloaded_path: + from_path = already_downloaded_path + content_type = None + else: + # let's download to a tmp dir + from_path, content_type = download(link, temp_dir.path) + if hashes: + hashes.check_against_path(from_path) + + return File(from_path, content_type) + + +def get_file_url( + link: Link, download_dir: Optional[str] = None, hashes: Optional[Hashes] = None +) -> File: + """Get file and optionally check its hash.""" + # If a download dir is specified, is the file already there and valid? + already_downloaded_path = None + if download_dir: + already_downloaded_path = _check_download_dir(link, download_dir, hashes) + + if already_downloaded_path: + from_path = already_downloaded_path + else: + from_path = link.file_path + + # If --require-hashes is off, `hashes` is either empty, the + # link's embedded hash, or MissingHashes; it is required to + # match. If --require-hashes is on, we are satisfied by any + # hash in `hashes` matching: a URL-based or an option-based + # one; no internet-sourced hash will be in `hashes`. + if hashes: + hashes.check_against_path(from_path) + return File(from_path, None) + + +def unpack_url( + link: Link, + location: str, + download: Downloader, + verbosity: int, + download_dir: Optional[str] = None, + hashes: Optional[Hashes] = None, +) -> Optional[File]: + """Unpack link into location, downloading if required. + + :param hashes: A Hashes object, one of whose embedded hashes must match, + or HashMismatch will be raised. If the Hashes is empty, no matches are + required, and unhashable types of requirements (like VCS ones, which + would ordinarily raise HashUnsupported) are allowed. + """ + # non-editable vcs urls + if link.is_vcs: + unpack_vcs_link(link, location, verbosity=verbosity) + return None + + assert not link.is_existing_dir() + + # file urls + if link.is_file: + file = get_file_url(link, download_dir, hashes=hashes) + + # http urls + else: + file = get_http_url( + link, + download, + download_dir, + hashes=hashes, + ) + + # unpack the archive to the build dir location. even when only downloading + # archives, they have to be unpacked to parse dependencies, except wheels + if not link.is_wheel: + unpack_file(file.path, location, file.content_type) + + return file + + +def _check_download_dir( + link: Link, + download_dir: str, + hashes: Optional[Hashes], + warn_on_hash_mismatch: bool = True, +) -> Optional[str]: + """Check download_dir for previously downloaded file with correct hash + If a correct file is found return its path else None + """ + download_path = os.path.join(download_dir, link.filename) + + if not os.path.exists(download_path): + return None + + # If already downloaded, does its hash match? + logger.info("File was already downloaded %s", download_path) + if hashes: + try: + hashes.check_against_path(download_path) + except HashMismatch: + if warn_on_hash_mismatch: + logger.warning( + "Previously-downloaded file %s has bad hash. Re-downloading.", + download_path, + ) + os.unlink(download_path) + return None + return download_path + + +class RequirementPreparer: + """Prepares a Requirement""" + + def __init__( + self, + build_dir: str, + download_dir: Optional[str], + src_dir: str, + build_isolation: bool, + check_build_deps: bool, + build_tracker: BuildTracker, + session: PipSession, + progress_bar: str, + finder: PackageFinder, + require_hashes: bool, + use_user_site: bool, + lazy_wheel: bool, + verbosity: int, + legacy_resolver: bool, + ) -> None: + super().__init__() + + self.src_dir = src_dir + self.build_dir = build_dir + self.build_tracker = build_tracker + self._session = session + self._download = Downloader(session, progress_bar) + self._batch_download = BatchDownloader(session, progress_bar) + self.finder = finder + + # Where still-packed archives should be written to. If None, they are + # not saved, and are deleted immediately after unpacking. + self.download_dir = download_dir + + # Is build isolation allowed? + self.build_isolation = build_isolation + + # Should check build dependencies? + self.check_build_deps = check_build_deps + + # Should hash-checking be required? + self.require_hashes = require_hashes + + # Should install in user site-packages? + self.use_user_site = use_user_site + + # Should wheels be downloaded lazily? + self.use_lazy_wheel = lazy_wheel + + # How verbose should underlying tooling be? + self.verbosity = verbosity + + # Are we using the legacy resolver? + self.legacy_resolver = legacy_resolver + + # Memoized downloaded files, as mapping of url: path. + self._downloaded: Dict[str, str] = {} + + # Previous "header" printed for a link-based InstallRequirement + self._previous_requirement_header = ("", "") + + def _log_preparing_link(self, req: InstallRequirement) -> None: + """Provide context for the requirement being prepared.""" + if req.link.is_file and not req.is_wheel_from_cache: + message = "Processing %s" + information = str(display_path(req.link.file_path)) + else: + message = "Collecting %s" + information = redact_auth_from_requirement(req.req) if req.req else str(req) + + # If we used req.req, inject requirement source if available (this + # would already be included if we used req directly) + if req.req and req.comes_from: + if isinstance(req.comes_from, str): + comes_from: Optional[str] = req.comes_from + else: + comes_from = req.comes_from.from_path() + if comes_from: + information += f" (from {comes_from})" + + if (message, information) != self._previous_requirement_header: + self._previous_requirement_header = (message, information) + logger.info(message, information) + + if req.is_wheel_from_cache: + with indent_log(): + logger.info("Using cached %s", req.link.filename) + + def _ensure_link_req_src_dir( + self, req: InstallRequirement, parallel_builds: bool + ) -> None: + """Ensure source_dir of a linked InstallRequirement.""" + # Since source_dir is only set for editable requirements. + if req.link.is_wheel: + # We don't need to unpack wheels, so no need for a source + # directory. + return + assert req.source_dir is None + if req.link.is_existing_dir(): + # build local directories in-tree + req.source_dir = req.link.file_path + return + + # We always delete unpacked sdists after pip runs. + req.ensure_has_source_dir( + self.build_dir, + autodelete=True, + parallel_builds=parallel_builds, + ) + req.ensure_pristine_source_checkout() + + def _get_linked_req_hashes(self, req: InstallRequirement) -> Hashes: + # By the time this is called, the requirement's link should have + # been checked so we can tell what kind of requirements req is + # and raise some more informative errors than otherwise. + # (For example, we can raise VcsHashUnsupported for a VCS URL + # rather than HashMissing.) + if not self.require_hashes: + return req.hashes(trust_internet=True) + + # We could check these first 2 conditions inside unpack_url + # and save repetition of conditions, but then we would + # report less-useful error messages for unhashable + # requirements, complaining that there's no hash provided. + if req.link.is_vcs: + raise VcsHashUnsupported() + if req.link.is_existing_dir(): + raise DirectoryUrlHashUnsupported() + + # Unpinned packages are asking for trouble when a new version + # is uploaded. This isn't a security check, but it saves users + # a surprising hash mismatch in the future. + # file:/// URLs aren't pinnable, so don't complain about them + # not being pinned. + if not req.is_direct and not req.is_pinned: + raise HashUnpinned() + + # If known-good hashes are missing for this requirement, + # shim it with a facade object that will provoke hash + # computation and then raise a HashMissing exception + # showing the user what the hash should be. + return req.hashes(trust_internet=False) or MissingHashes() + + def _fetch_metadata_only( + self, + req: InstallRequirement, + ) -> Optional[BaseDistribution]: + if self.legacy_resolver: + logger.debug( + "Metadata-only fetching is not used in the legacy resolver", + ) + return None + if self.require_hashes: + logger.debug( + "Metadata-only fetching is not used as hash checking is required", + ) + return None + # Try PEP 658 metadata first, then fall back to lazy wheel if unavailable. + return self._fetch_metadata_using_link_data_attr( + req + ) or self._fetch_metadata_using_lazy_wheel(req.link) + + def _fetch_metadata_using_link_data_attr( + self, + req: InstallRequirement, + ) -> Optional[BaseDistribution]: + """Fetch metadata from the data-dist-info-metadata attribute, if possible.""" + # (1) Get the link to the metadata file, if provided by the backend. + metadata_link = req.link.metadata_link() + if metadata_link is None: + return None + assert req.req is not None + logger.verbose( + "Obtaining dependency information for %s from %s", + req.req, + metadata_link, + ) + # (2) Download the contents of the METADATA file, separate from the dist itself. + metadata_file = get_http_url( + metadata_link, + self._download, + hashes=metadata_link.as_hashes(), + ) + with open(metadata_file.path, "rb") as f: + metadata_contents = f.read() + # (3) Generate a dist just from those file contents. + metadata_dist = get_metadata_distribution( + metadata_contents, + req.link.filename, + req.req.name, + ) + # (4) Ensure the Name: field from the METADATA file matches the name from the + # install requirement. + # + # NB: raw_name will fall back to the name from the install requirement if + # the Name: field is not present, but it's noted in the raw_name docstring + # that that should NEVER happen anyway. + if canonicalize_name(metadata_dist.raw_name) != canonicalize_name(req.req.name): + raise MetadataInconsistent( + req, "Name", req.req.name, metadata_dist.raw_name + ) + return metadata_dist + + def _fetch_metadata_using_lazy_wheel( + self, + link: Link, + ) -> Optional[BaseDistribution]: + """Fetch metadata using lazy wheel, if possible.""" + # --use-feature=fast-deps must be provided. + if not self.use_lazy_wheel: + return None + if link.is_file or not link.is_wheel: + logger.debug( + "Lazy wheel is not used as %r does not point to a remote wheel", + link, + ) + return None + + wheel = Wheel(link.filename) + name = canonicalize_name(wheel.name) + logger.info( + "Obtaining dependency information from %s %s", + name, + wheel.version, + ) + url = link.url.split("#", 1)[0] + try: + return dist_from_wheel_url(name, url, self._session) + except HTTPRangeRequestUnsupported: + logger.debug("%s does not support range requests", url) + return None + + def _complete_partial_requirements( + self, + partially_downloaded_reqs: Iterable[InstallRequirement], + parallel_builds: bool = False, + ) -> None: + """Download any requirements which were only fetched by metadata.""" + # Download to a temporary directory. These will be copied over as + # needed for downstream 'download', 'wheel', and 'install' commands. + temp_dir = TempDirectory(kind="unpack", globally_managed=True).path + + # Map each link to the requirement that owns it. This allows us to set + # `req.local_file_path` on the appropriate requirement after passing + # all the links at once into BatchDownloader. + links_to_fully_download: Dict[Link, InstallRequirement] = {} + for req in partially_downloaded_reqs: + assert req.link + links_to_fully_download[req.link] = req + + batch_download = self._batch_download( + links_to_fully_download.keys(), + temp_dir, + ) + for link, (filepath, _) in batch_download: + logger.debug("Downloading link %s to %s", link, filepath) + req = links_to_fully_download[link] + # Record the downloaded file path so wheel reqs can extract a Distribution + # in .get_dist(). + req.local_file_path = filepath + # Record that the file is downloaded so we don't do it again in + # _prepare_linked_requirement(). + self._downloaded[req.link.url] = filepath + + # If this is an sdist, we need to unpack it after downloading, but the + # .source_dir won't be set up until we are in _prepare_linked_requirement(). + # Add the downloaded archive to the install requirement to unpack after + # preparing the source dir. + if not req.is_wheel: + req.needs_unpacked_archive(Path(filepath)) + + # This step is necessary to ensure all lazy wheels are processed + # successfully by the 'download', 'wheel', and 'install' commands. + for req in partially_downloaded_reqs: + self._prepare_linked_requirement(req, parallel_builds) + + def prepare_linked_requirement( + self, req: InstallRequirement, parallel_builds: bool = False + ) -> BaseDistribution: + """Prepare a requirement to be obtained from req.link.""" + assert req.link + self._log_preparing_link(req) + with indent_log(): + # Check if the relevant file is already available + # in the download directory + file_path = None + if self.download_dir is not None and req.link.is_wheel: + hashes = self._get_linked_req_hashes(req) + file_path = _check_download_dir( + req.link, + self.download_dir, + hashes, + # When a locally built wheel has been found in cache, we don't warn + # about re-downloading when the already downloaded wheel hash does + # not match. This is because the hash must be checked against the + # original link, not the cached link. It that case the already + # downloaded file will be removed and re-fetched from cache (which + # implies a hash check against the cache entry's origin.json). + warn_on_hash_mismatch=not req.is_wheel_from_cache, + ) + + if file_path is not None: + # The file is already available, so mark it as downloaded + self._downloaded[req.link.url] = file_path + else: + # The file is not available, attempt to fetch only metadata + metadata_dist = self._fetch_metadata_only(req) + if metadata_dist is not None: + req.needs_more_preparation = True + return metadata_dist + + # None of the optimizations worked, fully prepare the requirement + return self._prepare_linked_requirement(req, parallel_builds) + + def prepare_linked_requirements_more( + self, reqs: Iterable[InstallRequirement], parallel_builds: bool = False + ) -> None: + """Prepare linked requirements more, if needed.""" + reqs = [req for req in reqs if req.needs_more_preparation] + for req in reqs: + # Determine if any of these requirements were already downloaded. + if self.download_dir is not None and req.link.is_wheel: + hashes = self._get_linked_req_hashes(req) + file_path = _check_download_dir(req.link, self.download_dir, hashes) + if file_path is not None: + self._downloaded[req.link.url] = file_path + req.needs_more_preparation = False + + # Prepare requirements we found were already downloaded for some + # reason. The other downloads will be completed separately. + partially_downloaded_reqs: List[InstallRequirement] = [] + for req in reqs: + if req.needs_more_preparation: + partially_downloaded_reqs.append(req) + else: + self._prepare_linked_requirement(req, parallel_builds) + + # TODO: separate this part out from RequirementPreparer when the v1 + # resolver can be removed! + self._complete_partial_requirements( + partially_downloaded_reqs, + parallel_builds=parallel_builds, + ) + + def _prepare_linked_requirement( + self, req: InstallRequirement, parallel_builds: bool + ) -> BaseDistribution: + assert req.link + link = req.link + + hashes = self._get_linked_req_hashes(req) + + if hashes and req.is_wheel_from_cache: + assert req.download_info is not None + assert link.is_wheel + assert link.is_file + # We need to verify hashes, and we have found the requirement in the cache + # of locally built wheels. + if ( + isinstance(req.download_info.info, ArchiveInfo) + and req.download_info.info.hashes + and hashes.has_one_of(req.download_info.info.hashes) + ): + # At this point we know the requirement was built from a hashable source + # artifact, and we verified that the cache entry's hash of the original + # artifact matches one of the hashes we expect. We don't verify hashes + # against the cached wheel, because the wheel is not the original. + hashes = None + else: + logger.warning( + "The hashes of the source archive found in cache entry " + "don't match, ignoring cached built wheel " + "and re-downloading source." + ) + req.link = req.cached_wheel_source_link + link = req.link + + self._ensure_link_req_src_dir(req, parallel_builds) + + if link.is_existing_dir(): + local_file = None + elif link.url not in self._downloaded: + try: + local_file = unpack_url( + link, + req.source_dir, + self._download, + self.verbosity, + self.download_dir, + hashes, + ) + except NetworkConnectionError as exc: + raise InstallationError( + "Could not install requirement {} because of HTTP " + "error {} for URL {}".format(req, exc, link) + ) + else: + file_path = self._downloaded[link.url] + if hashes: + hashes.check_against_path(file_path) + local_file = File(file_path, content_type=None) + + # If download_info is set, we got it from the wheel cache. + if req.download_info is None: + # Editables don't go through this function (see + # prepare_editable_requirement). + assert not req.editable + req.download_info = direct_url_from_link(link, req.source_dir) + # Make sure we have a hash in download_info. If we got it as part of the + # URL, it will have been verified and we can rely on it. Otherwise we + # compute it from the downloaded file. + # FIXME: https://github.com/pypa/pip/issues/11943 + if ( + isinstance(req.download_info.info, ArchiveInfo) + and not req.download_info.info.hashes + and local_file + ): + hash = hash_file(local_file.path)[0].hexdigest() + # We populate info.hash for backward compatibility. + # This will automatically populate info.hashes. + req.download_info.info.hash = f"sha256={hash}" + + # For use in later processing, + # preserve the file path on the requirement. + if local_file: + req.local_file_path = local_file.path + + dist = _get_prepared_distribution( + req, + self.build_tracker, + self.finder, + self.build_isolation, + self.check_build_deps, + ) + return dist + + def save_linked_requirement(self, req: InstallRequirement) -> None: + assert self.download_dir is not None + assert req.link is not None + link = req.link + if link.is_vcs or (link.is_existing_dir() and req.editable): + # Make a .zip of the source_dir we already created. + req.archive(self.download_dir) + return + + if link.is_existing_dir(): + logger.debug( + "Not copying link to destination directory " + "since it is a directory: %s", + link, + ) + return + if req.local_file_path is None: + # No distribution was downloaded for this requirement. + return + + download_location = os.path.join(self.download_dir, link.filename) + if not os.path.exists(download_location): + shutil.copy(req.local_file_path, download_location) + download_path = display_path(download_location) + logger.info("Saved %s", download_path) + + def prepare_editable_requirement( + self, + req: InstallRequirement, + ) -> BaseDistribution: + """Prepare an editable requirement.""" + assert req.editable, "cannot prepare a non-editable req as editable" + + logger.info("Obtaining %s", req) + + with indent_log(): + if self.require_hashes: + raise InstallationError( + "The editable requirement {} cannot be installed when " + "requiring hashes, because there is no single file to " + "hash.".format(req) + ) + req.ensure_has_source_dir(self.src_dir) + req.update_editable() + assert req.source_dir + req.download_info = direct_url_for_editable(req.unpacked_source_directory) + + dist = _get_prepared_distribution( + req, + self.build_tracker, + self.finder, + self.build_isolation, + self.check_build_deps, + ) + + req.check_if_exists(self.use_user_site) + + return dist + + def prepare_installed_requirement( + self, + req: InstallRequirement, + skip_reason: str, + ) -> BaseDistribution: + """Prepare an already-installed requirement.""" + assert req.satisfied_by, "req should have been satisfied but isn't" + assert skip_reason is not None, ( + "did not get skip reason skipped but req.satisfied_by " + "is set to {}".format(req.satisfied_by) + ) + logger.info( + "Requirement %s: %s (%s)", skip_reason, req, req.satisfied_by.version + ) + with indent_log(): + if self.require_hashes: + logger.debug( + "Since it is already installed, we are trusting this " + "package without checking its hash. To ensure a " + "completely repeatable environment, install into an " + "empty virtualenv." + ) + return InstalledDistribution(req).get_metadata_distribution() diff --git a/shared/package-files/35/3569a111272264f1b5f61006db8380a8c5212f4c39143a1fca1a3363c91d7ab0/_embedding.py b/shared/package-files/35/3569a111272264f1b5f61006db8380a8c5212f4c39143a1fca1a3363c91d7ab0/_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..017e5b547c975068e6b2be3511ee100674d2625e --- /dev/null +++ b/shared/package-files/35/3569a111272264f1b5f61006db8380a8c5212f4c39143a1fca1a3363c91d7ab0/_embedding.py @@ -0,0 +1,69 @@ +import matplotlib.pyplot as plt +import sklearn + +from ..utils import convert_name +from . import colors +from ._labels import labels + + +def embedding(ind, shap_values, feature_names=None, method="pca", alpha=1.0, show=True): + """Use the SHAP values as an embedding which we project to 2D for visualization. + + Parameters + ---------- + ind : int or string + If this is an int it is the index of the feature to use to color the embedding. + If this is a string it is either the name of the feature, or it can have the + form "rank(int)" to specify the feature with that rank (ordered by mean absolute + SHAP value over all the samples), or "sum()" to mean the sum of all the SHAP values, + which is the model's output (minus it's expected value). + + shap_values : numpy.array + Matrix of SHAP values (# samples x # features). + + feature_names : None or list + The names of the features in the shap_values array. + + method : "pca" or numpy.array + How to reduce the dimensions of the shap_values to 2D. If "pca" then the 2D + PCA projection of shap_values is used. If a numpy array then is should be + (# samples x 2) and represent the embedding of that values. + + alpha : float + The transparency of the data points (between 0 and 1). This can be useful to the + show density of the data points when using a large dataset. + + """ + if feature_names is None: + feature_names = [labels["FEATURE"] % str(i) for i in range(shap_values.shape[1])] + + ind = convert_name(ind, shap_values, feature_names) + if ind == "sum()": + cvals = shap_values.sum(1) + fname = "sum(SHAP values)" + else: + cvals = shap_values[:, ind] + fname = feature_names[ind] + + # see if we need to compute the embedding + if isinstance(method, str) and method == "pca": + pca = sklearn.decomposition.PCA(2) + embedding_values = pca.fit_transform(shap_values) + elif hasattr(method, "shape") and method.shape[1] == 2: + embedding_values = method + else: + print("Unsupported embedding method:", method) + + plt.scatter(embedding_values[:, 0], embedding_values[:, 1], c=cvals, cmap=colors.red_blue, alpha=alpha, linewidth=0) + plt.axis("off") + # plt.title(feature_names[ind]) + cb = plt.colorbar() + cb.set_label("SHAP value for\n" + fname, size=13) + cb.outline.set_visible(False) # type: ignore + + plt.gcf().set_size_inches(7.5, 5) + bbox = cb.ax.get_window_extent().transformed(plt.gcf().dpi_scale_trans.inverted()) + cb.ax.set_aspect((bbox.height - 0.7) * 10) + cb.set_alpha(1) + if show: + plt.show() diff --git a/shared/package-files/35/356be1e124685366c8d17ee075cd0673914dbb7cb9d602244720cd7d4f77a332/abbr.pyi b/shared/package-files/35/356be1e124685366c8d17ee075cd0673914dbb7cb9d602244720cd7d4f77a332/abbr.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9316c65f8f2dc3ed090d466749a29b571570ef91 --- /dev/null +++ b/shared/package-files/35/356be1e124685366c8d17ee075cd0673914dbb7cb9d602244720cd7d4f77a332/abbr.pyi @@ -0,0 +1,16 @@ +from typing import Any, Pattern + +from markdown.blockprocessors import BlockProcessor +from markdown.extensions import Extension +from markdown.inlinepatterns import InlineProcessor + +ABBR_REF_RE: Pattern + +class AbbrExtension(Extension): ... +class AbbrPreprocessor(BlockProcessor): ... + +class AbbrInlineProcessor(InlineProcessor): + title: Any + def __init__(self, pattern, title) -> None: ... + +def makeExtension(**kwargs): ... diff --git a/shared/package-files/35/356cdc17afe0fc84f41d0446f444d5de48a60002959a816886e1b29aab032cf2/test_nanops.py b/shared/package-files/35/356cdc17afe0fc84f41d0446f444d5de48a60002959a816886e1b29aab032cf2/test_nanops.py new file mode 100644 index 0000000000000000000000000000000000000000..a50054f33f382ed913261e0cafd944c2fd86aaa3 --- /dev/null +++ b/shared/package-files/35/356cdc17afe0fc84f41d0446f444d5de48a60002959a816886e1b29aab032cf2/test_nanops.py @@ -0,0 +1,1274 @@ +from functools import partial + +import numpy as np +import pytest + +import pandas.util._test_decorators as td + +from pandas.core.dtypes.common import is_integer_dtype + +import pandas as pd +from pandas import ( + Series, + isna, +) +import pandas._testing as tm +from pandas.core import nanops + +use_bn = nanops._USE_BOTTLENECK + + +@pytest.fixture +def disable_bottleneck(monkeypatch): + with monkeypatch.context() as m: + m.setattr(nanops, "_USE_BOTTLENECK", False) + yield + + +@pytest.fixture +def arr_shape(): + return 11, 7 + + +@pytest.fixture +def arr_float(arr_shape): + return np.random.default_rng(2).standard_normal(arr_shape) + + +@pytest.fixture +def arr_complex(arr_float): + return arr_float + arr_float * 1j + + +@pytest.fixture +def arr_int(arr_shape): + return np.random.default_rng(2).integers(-10, 10, arr_shape) + + +@pytest.fixture +def arr_bool(arr_shape): + return np.random.default_rng(2).integers(0, 2, arr_shape) == 0 + + +@pytest.fixture +def arr_str(arr_float): + return np.abs(arr_float).astype("S") + + +@pytest.fixture +def arr_utf(arr_float): + return np.abs(arr_float).astype("U") + + +@pytest.fixture +def arr_date(arr_shape): + return np.random.default_rng(2).integers(0, 20000, arr_shape).astype("M8[ns]") + + +@pytest.fixture +def arr_tdelta(arr_shape): + return np.random.default_rng(2).integers(0, 20000, arr_shape).astype("m8[ns]") + + +@pytest.fixture +def arr_nan(arr_shape): + return np.tile(np.nan, arr_shape) + + +@pytest.fixture +def arr_float_nan(arr_float, arr_nan): + return np.vstack([arr_float, arr_nan]) + + +@pytest.fixture +def arr_nan_float1(arr_nan, arr_float): + return np.vstack([arr_nan, arr_float]) + + +@pytest.fixture +def arr_nan_nan(arr_nan): + return np.vstack([arr_nan, arr_nan]) + + +@pytest.fixture +def arr_inf(arr_float): + return arr_float * np.inf + + +@pytest.fixture +def arr_float_inf(arr_float, arr_inf): + return np.vstack([arr_float, arr_inf]) + + +@pytest.fixture +def arr_nan_inf(arr_nan, arr_inf): + return np.vstack([arr_nan, arr_inf]) + + +@pytest.fixture +def arr_float_nan_inf(arr_float, arr_nan, arr_inf): + return np.vstack([arr_float, arr_nan, arr_inf]) + + +@pytest.fixture +def arr_nan_nan_inf(arr_nan, arr_inf): + return np.vstack([arr_nan, arr_nan, arr_inf]) + + +@pytest.fixture +def arr_obj( + arr_float, arr_int, arr_bool, arr_complex, arr_str, arr_utf, arr_date, arr_tdelta +): + return np.vstack( + [ + arr_float.astype("O"), + arr_int.astype("O"), + arr_bool.astype("O"), + arr_complex.astype("O"), + arr_str.astype("O"), + arr_utf.astype("O"), + arr_date.astype("O"), + arr_tdelta.astype("O"), + ] + ) + + +@pytest.fixture +def arr_nan_nanj(arr_nan): + with np.errstate(invalid="ignore"): + return arr_nan + arr_nan * 1j + + +@pytest.fixture +def arr_complex_nan(arr_complex, arr_nan_nanj): + with np.errstate(invalid="ignore"): + return np.vstack([arr_complex, arr_nan_nanj]) + + +@pytest.fixture +def arr_nan_infj(arr_inf): + with np.errstate(invalid="ignore"): + return arr_inf * 1j + + +@pytest.fixture +def arr_complex_nan_infj(arr_complex, arr_nan_infj): + with np.errstate(invalid="ignore"): + return np.vstack([arr_complex, arr_nan_infj]) + + +@pytest.fixture +def arr_float_1d(arr_float): + return arr_float[:, 0] + + +@pytest.fixture +def arr_nan_1d(arr_nan): + return arr_nan[:, 0] + + +@pytest.fixture +def arr_float_nan_1d(arr_float_nan): + return arr_float_nan[:, 0] + + +@pytest.fixture +def arr_float1_nan_1d(arr_float1_nan): + return arr_float1_nan[:, 0] + + +@pytest.fixture +def arr_nan_float1_1d(arr_nan_float1): + return arr_nan_float1[:, 0] + + +class TestnanopsDataFrame: + def setup_method(self): + nanops._USE_BOTTLENECK = False + + arr_shape = (11, 7) + + self.arr_float = np.random.default_rng(2).standard_normal(arr_shape) + self.arr_float1 = np.random.default_rng(2).standard_normal(arr_shape) + self.arr_complex = self.arr_float + self.arr_float1 * 1j + self.arr_int = np.random.default_rng(2).integers(-10, 10, arr_shape) + self.arr_bool = np.random.default_rng(2).integers(0, 2, arr_shape) == 0 + self.arr_str = np.abs(self.arr_float).astype("S") + self.arr_utf = np.abs(self.arr_float).astype("U") + self.arr_date = ( + np.random.default_rng(2).integers(0, 20000, arr_shape).astype("M8[ns]") + ) + self.arr_tdelta = ( + np.random.default_rng(2).integers(0, 20000, arr_shape).astype("m8[ns]") + ) + + self.arr_nan = np.tile(np.nan, arr_shape) + self.arr_float_nan = np.vstack([self.arr_float, self.arr_nan]) + self.arr_float1_nan = np.vstack([self.arr_float1, self.arr_nan]) + self.arr_nan_float1 = np.vstack([self.arr_nan, self.arr_float1]) + self.arr_nan_nan = np.vstack([self.arr_nan, self.arr_nan]) + + self.arr_inf = self.arr_float * np.inf + self.arr_float_inf = np.vstack([self.arr_float, self.arr_inf]) + + self.arr_nan_inf = np.vstack([self.arr_nan, self.arr_inf]) + self.arr_float_nan_inf = np.vstack([self.arr_float, self.arr_nan, self.arr_inf]) + self.arr_nan_nan_inf = np.vstack([self.arr_nan, self.arr_nan, self.arr_inf]) + self.arr_obj = np.vstack( + [ + self.arr_float.astype("O"), + self.arr_int.astype("O"), + self.arr_bool.astype("O"), + self.arr_complex.astype("O"), + self.arr_str.astype("O"), + self.arr_utf.astype("O"), + self.arr_date.astype("O"), + self.arr_tdelta.astype("O"), + ] + ) + + with np.errstate(invalid="ignore"): + self.arr_nan_nanj = self.arr_nan + self.arr_nan * 1j + self.arr_complex_nan = np.vstack([self.arr_complex, self.arr_nan_nanj]) + + self.arr_nan_infj = self.arr_inf * 1j + self.arr_complex_nan_infj = np.vstack([self.arr_complex, self.arr_nan_infj]) + + self.arr_float_2d = self.arr_float + self.arr_float1_2d = self.arr_float1 + + self.arr_nan_2d = self.arr_nan + self.arr_float_nan_2d = self.arr_float_nan + self.arr_float1_nan_2d = self.arr_float1_nan + self.arr_nan_float1_2d = self.arr_nan_float1 + + self.arr_float_1d = self.arr_float[:, 0] + self.arr_float1_1d = self.arr_float1[:, 0] + + self.arr_nan_1d = self.arr_nan[:, 0] + self.arr_float_nan_1d = self.arr_float_nan[:, 0] + self.arr_float1_nan_1d = self.arr_float1_nan[:, 0] + self.arr_nan_float1_1d = self.arr_nan_float1[:, 0] + + def teardown_method(self): + nanops._USE_BOTTLENECK = use_bn + + def check_results(self, targ, res, axis, check_dtype=True): + res = getattr(res, "asm8", res) + + if ( + axis != 0 + and hasattr(targ, "shape") + and targ.ndim + and targ.shape != res.shape + ): + res = np.split(res, [targ.shape[0]], axis=0)[0] + + try: + tm.assert_almost_equal(targ, res, check_dtype=check_dtype) + except AssertionError: + # handle timedelta dtypes + if hasattr(targ, "dtype") and targ.dtype == "m8[ns]": + raise + + # There are sometimes rounding errors with + # complex and object dtypes. + # If it isn't one of those, re-raise the error. + if not hasattr(res, "dtype") or res.dtype.kind not in ["c", "O"]: + raise + # convert object dtypes to something that can be split into + # real and imaginary parts + if res.dtype.kind == "O": + if targ.dtype.kind != "O": + res = res.astype(targ.dtype) + else: + cast_dtype = "c16" if hasattr(np, "complex128") else "f8" + res = res.astype(cast_dtype) + targ = targ.astype(cast_dtype) + # there should never be a case where numpy returns an object + # but nanops doesn't, so make that an exception + elif targ.dtype.kind == "O": + raise + tm.assert_almost_equal(np.real(targ), np.real(res), check_dtype=check_dtype) + tm.assert_almost_equal(np.imag(targ), np.imag(res), check_dtype=check_dtype) + + def check_fun_data( + self, + testfunc, + targfunc, + testarval, + targarval, + skipna, + check_dtype=True, + empty_targfunc=None, + **kwargs, + ): + for axis in list(range(targarval.ndim)) + [None]: + targartempval = targarval if skipna else testarval + if skipna and empty_targfunc and isna(targartempval).all(): + targ = empty_targfunc(targartempval, axis=axis, **kwargs) + else: + targ = targfunc(targartempval, axis=axis, **kwargs) + + if targartempval.dtype == object and ( + targfunc is np.any or targfunc is np.all + ): + # GH#12863 the numpy functions will retain e.g. floatiness + if isinstance(targ, np.ndarray): + targ = targ.astype(bool) + else: + targ = bool(targ) + + res = testfunc(testarval, axis=axis, skipna=skipna, **kwargs) + + if ( + isinstance(targ, np.complex128) + and isinstance(res, float) + and np.isnan(targ) + and np.isnan(res) + ): + # GH#18463 + targ = res + + self.check_results(targ, res, axis, check_dtype=check_dtype) + if skipna: + res = testfunc(testarval, axis=axis, **kwargs) + self.check_results(targ, res, axis, check_dtype=check_dtype) + if axis is None: + res = testfunc(testarval, skipna=skipna, **kwargs) + self.check_results(targ, res, axis, check_dtype=check_dtype) + if skipna and axis is None: + res = testfunc(testarval, **kwargs) + self.check_results(targ, res, axis, check_dtype=check_dtype) + + if testarval.ndim <= 1: + return + + # Recurse on lower-dimension + testarval2 = np.take(testarval, 0, axis=-1) + targarval2 = np.take(targarval, 0, axis=-1) + self.check_fun_data( + testfunc, + targfunc, + testarval2, + targarval2, + skipna=skipna, + check_dtype=check_dtype, + empty_targfunc=empty_targfunc, + **kwargs, + ) + + def check_fun( + self, testfunc, targfunc, testar, skipna, empty_targfunc=None, **kwargs + ): + targar = testar + if testar.endswith("_nan") and hasattr(self, testar[:-4]): + targar = testar[:-4] + + testarval = getattr(self, testar) + targarval = getattr(self, targar) + self.check_fun_data( + testfunc, + targfunc, + testarval, + targarval, + skipna=skipna, + empty_targfunc=empty_targfunc, + **kwargs, + ) + + def check_funs( + self, + testfunc, + targfunc, + skipna, + allow_complex=True, + allow_all_nan=True, + allow_date=True, + allow_tdelta=True, + allow_obj=True, + **kwargs, + ): + self.check_fun(testfunc, targfunc, "arr_float", skipna, **kwargs) + self.check_fun(testfunc, targfunc, "arr_float_nan", skipna, **kwargs) + self.check_fun(testfunc, targfunc, "arr_int", skipna, **kwargs) + self.check_fun(testfunc, targfunc, "arr_bool", skipna, **kwargs) + objs = [ + self.arr_float.astype("O"), + self.arr_int.astype("O"), + self.arr_bool.astype("O"), + ] + + if allow_all_nan: + self.check_fun(testfunc, targfunc, "arr_nan", skipna, **kwargs) + + if allow_complex: + self.check_fun(testfunc, targfunc, "arr_complex", skipna, **kwargs) + self.check_fun(testfunc, targfunc, "arr_complex_nan", skipna, **kwargs) + if allow_all_nan: + self.check_fun(testfunc, targfunc, "arr_nan_nanj", skipna, **kwargs) + objs += [self.arr_complex.astype("O")] + + if allow_date: + targfunc(self.arr_date) + self.check_fun(testfunc, targfunc, "arr_date", skipna, **kwargs) + objs += [self.arr_date.astype("O")] + + if allow_tdelta: + try: + targfunc(self.arr_tdelta) + except TypeError: + pass + else: + self.check_fun(testfunc, targfunc, "arr_tdelta", skipna, **kwargs) + objs += [self.arr_tdelta.astype("O")] + + if allow_obj: + self.arr_obj = np.vstack(objs) + # some nanops handle object dtypes better than their numpy + # counterparts, so the numpy functions need to be given something + # else + if allow_obj == "convert": + targfunc = partial( + self._badobj_wrap, func=targfunc, allow_complex=allow_complex + ) + self.check_fun(testfunc, targfunc, "arr_obj", skipna, **kwargs) + + def _badobj_wrap(self, value, func, allow_complex=True, **kwargs): + if value.dtype.kind == "O": + if allow_complex: + value = value.astype("c16") + else: + value = value.astype("f8") + return func(value, **kwargs) + + @pytest.mark.parametrize( + "nan_op,np_op", [(nanops.nanany, np.any), (nanops.nanall, np.all)] + ) + def test_nan_funcs(self, nan_op, np_op, skipna): + self.check_funs(nan_op, np_op, skipna, allow_all_nan=False, allow_date=False) + + def test_nansum(self, skipna): + self.check_funs( + nanops.nansum, + np.sum, + skipna, + allow_date=False, + check_dtype=False, + empty_targfunc=np.nansum, + ) + + def test_nanmean(self, skipna): + self.check_funs( + nanops.nanmean, np.mean, skipna, allow_obj=False, allow_date=False + ) + + @pytest.mark.filterwarnings("ignore::RuntimeWarning") + def test_nanmedian(self, skipna): + self.check_funs( + nanops.nanmedian, + np.median, + skipna, + allow_complex=False, + allow_date=False, + allow_obj="convert", + ) + + @pytest.mark.parametrize("ddof", range(3)) + def test_nanvar(self, ddof, skipna): + self.check_funs( + nanops.nanvar, + np.var, + skipna, + allow_complex=False, + allow_date=False, + allow_obj="convert", + ddof=ddof, + ) + + @pytest.mark.parametrize("ddof", range(3)) + def test_nanstd(self, ddof, skipna): + self.check_funs( + nanops.nanstd, + np.std, + skipna, + allow_complex=False, + allow_date=False, + allow_obj="convert", + ddof=ddof, + ) + + @pytest.mark.parametrize("ddof", range(3)) + def test_nansem(self, ddof, skipna): + sp_stats = pytest.importorskip("scipy.stats") + + with np.errstate(invalid="ignore"): + self.check_funs( + nanops.nansem, + sp_stats.sem, + skipna, + allow_complex=False, + allow_date=False, + allow_tdelta=False, + allow_obj="convert", + ddof=ddof, + ) + + @pytest.mark.filterwarnings("ignore::RuntimeWarning") + @pytest.mark.parametrize( + "nan_op,np_op", [(nanops.nanmin, np.min), (nanops.nanmax, np.max)] + ) + def test_nanops_with_warnings(self, nan_op, np_op, skipna): + self.check_funs(nan_op, np_op, skipna, allow_obj=False) + + def _argminmax_wrap(self, value, axis=None, func=None): + res = func(value, axis) + nans = np.min(value, axis) + nullnan = isna(nans) + if res.ndim: + res[nullnan] = -1 + elif ( + hasattr(nullnan, "all") + and nullnan.all() + or not hasattr(nullnan, "all") + and nullnan + ): + res = -1 + return res + + @pytest.mark.filterwarnings("ignore::RuntimeWarning") + def test_nanargmax(self, skipna): + func = partial(self._argminmax_wrap, func=np.argmax) + self.check_funs(nanops.nanargmax, func, skipna, allow_obj=False) + + @pytest.mark.filterwarnings("ignore::RuntimeWarning") + def test_nanargmin(self, skipna): + func = partial(self._argminmax_wrap, func=np.argmin) + self.check_funs(nanops.nanargmin, func, skipna, allow_obj=False) + + def _skew_kurt_wrap(self, values, axis=None, func=None): + if not isinstance(values.dtype.type, np.floating): + values = values.astype("f8") + result = func(values, axis=axis, bias=False) + # fix for handling cases where all elements in an axis are the same + if isinstance(result, np.ndarray): + result[np.max(values, axis=axis) == np.min(values, axis=axis)] = 0 + return result + elif np.max(values) == np.min(values): + return 0.0 + return result + + def test_nanskew(self, skipna): + sp_stats = pytest.importorskip("scipy.stats") + + func = partial(self._skew_kurt_wrap, func=sp_stats.skew) + with np.errstate(invalid="ignore"): + self.check_funs( + nanops.nanskew, + func, + skipna, + allow_complex=False, + allow_date=False, + allow_tdelta=False, + ) + + def test_nankurt(self, skipna): + sp_stats = pytest.importorskip("scipy.stats") + + func1 = partial(sp_stats.kurtosis, fisher=True) + func = partial(self._skew_kurt_wrap, func=func1) + with np.errstate(invalid="ignore"): + self.check_funs( + nanops.nankurt, + func, + skipna, + allow_complex=False, + allow_date=False, + allow_tdelta=False, + ) + + def test_nanprod(self, skipna): + self.check_funs( + nanops.nanprod, + np.prod, + skipna, + allow_date=False, + allow_tdelta=False, + empty_targfunc=np.nanprod, + ) + + def check_nancorr_nancov_2d(self, checkfun, targ0, targ1, **kwargs): + res00 = checkfun(self.arr_float_2d, self.arr_float1_2d, **kwargs) + res01 = checkfun( + self.arr_float_2d, + self.arr_float1_2d, + min_periods=len(self.arr_float_2d) - 1, + **kwargs, + ) + tm.assert_almost_equal(targ0, res00) + tm.assert_almost_equal(targ0, res01) + + res10 = checkfun(self.arr_float_nan_2d, self.arr_float1_nan_2d, **kwargs) + res11 = checkfun( + self.arr_float_nan_2d, + self.arr_float1_nan_2d, + min_periods=len(self.arr_float_2d) - 1, + **kwargs, + ) + tm.assert_almost_equal(targ1, res10) + tm.assert_almost_equal(targ1, res11) + + targ2 = np.nan + res20 = checkfun(self.arr_nan_2d, self.arr_float1_2d, **kwargs) + res21 = checkfun(self.arr_float_2d, self.arr_nan_2d, **kwargs) + res22 = checkfun(self.arr_nan_2d, self.arr_nan_2d, **kwargs) + res23 = checkfun(self.arr_float_nan_2d, self.arr_nan_float1_2d, **kwargs) + res24 = checkfun( + self.arr_float_nan_2d, + self.arr_nan_float1_2d, + min_periods=len(self.arr_float_2d) - 1, + **kwargs, + ) + res25 = checkfun( + self.arr_float_2d, + self.arr_float1_2d, + min_periods=len(self.arr_float_2d) + 1, + **kwargs, + ) + tm.assert_almost_equal(targ2, res20) + tm.assert_almost_equal(targ2, res21) + tm.assert_almost_equal(targ2, res22) + tm.assert_almost_equal(targ2, res23) + tm.assert_almost_equal(targ2, res24) + tm.assert_almost_equal(targ2, res25) + + def check_nancorr_nancov_1d(self, checkfun, targ0, targ1, **kwargs): + res00 = checkfun(self.arr_float_1d, self.arr_float1_1d, **kwargs) + res01 = checkfun( + self.arr_float_1d, + self.arr_float1_1d, + min_periods=len(self.arr_float_1d) - 1, + **kwargs, + ) + tm.assert_almost_equal(targ0, res00) + tm.assert_almost_equal(targ0, res01) + + res10 = checkfun(self.arr_float_nan_1d, self.arr_float1_nan_1d, **kwargs) + res11 = checkfun( + self.arr_float_nan_1d, + self.arr_float1_nan_1d, + min_periods=len(self.arr_float_1d) - 1, + **kwargs, + ) + tm.assert_almost_equal(targ1, res10) + tm.assert_almost_equal(targ1, res11) + + targ2 = np.nan + res20 = checkfun(self.arr_nan_1d, self.arr_float1_1d, **kwargs) + res21 = checkfun(self.arr_float_1d, self.arr_nan_1d, **kwargs) + res22 = checkfun(self.arr_nan_1d, self.arr_nan_1d, **kwargs) + res23 = checkfun(self.arr_float_nan_1d, self.arr_nan_float1_1d, **kwargs) + res24 = checkfun( + self.arr_float_nan_1d, + self.arr_nan_float1_1d, + min_periods=len(self.arr_float_1d) - 1, + **kwargs, + ) + res25 = checkfun( + self.arr_float_1d, + self.arr_float1_1d, + min_periods=len(self.arr_float_1d) + 1, + **kwargs, + ) + tm.assert_almost_equal(targ2, res20) + tm.assert_almost_equal(targ2, res21) + tm.assert_almost_equal(targ2, res22) + tm.assert_almost_equal(targ2, res23) + tm.assert_almost_equal(targ2, res24) + tm.assert_almost_equal(targ2, res25) + + def test_nancorr(self): + targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1] + targ1 = np.corrcoef(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1] + self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1) + targ0 = np.corrcoef(self.arr_float_1d, self.arr_float1_1d)[0, 1] + targ1 = np.corrcoef(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0, 1] + self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="pearson") + + def test_nancorr_pearson(self): + targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1] + targ1 = np.corrcoef(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1] + self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1, method="pearson") + targ0 = np.corrcoef(self.arr_float_1d, self.arr_float1_1d)[0, 1] + targ1 = np.corrcoef(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0, 1] + self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="pearson") + + def test_nancorr_kendall(self): + sp_stats = pytest.importorskip("scipy.stats") + + targ0 = sp_stats.kendalltau(self.arr_float_2d, self.arr_float1_2d)[0] + targ1 = sp_stats.kendalltau(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0] + self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1, method="kendall") + targ0 = sp_stats.kendalltau(self.arr_float_1d, self.arr_float1_1d)[0] + targ1 = sp_stats.kendalltau(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0] + self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="kendall") + + def test_nancorr_spearman(self): + sp_stats = pytest.importorskip("scipy.stats") + + targ0 = sp_stats.spearmanr(self.arr_float_2d, self.arr_float1_2d)[0] + targ1 = sp_stats.spearmanr(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0] + self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1, method="spearman") + targ0 = sp_stats.spearmanr(self.arr_float_1d, self.arr_float1_1d)[0] + targ1 = sp_stats.spearmanr(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0] + self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="spearman") + + def test_invalid_method(self): + pytest.importorskip("scipy") + targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1] + targ1 = np.corrcoef(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1] + msg = "Unknown method 'foo', expected one of 'kendall', 'spearman'" + with pytest.raises(ValueError, match=msg): + self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="foo") + + def test_nancov(self): + targ0 = np.cov(self.arr_float_2d, self.arr_float1_2d)[0, 1] + targ1 = np.cov(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1] + self.check_nancorr_nancov_2d(nanops.nancov, targ0, targ1) + targ0 = np.cov(self.arr_float_1d, self.arr_float1_1d)[0, 1] + targ1 = np.cov(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0, 1] + self.check_nancorr_nancov_1d(nanops.nancov, targ0, targ1) + + +@pytest.mark.parametrize( + "arr, correct", + [ + ("arr_complex", False), + ("arr_int", False), + ("arr_bool", False), + ("arr_str", False), + ("arr_utf", False), + ("arr_complex", False), + ("arr_complex_nan", False), + ("arr_nan_nanj", False), + ("arr_nan_infj", True), + ("arr_complex_nan_infj", True), + ], +) +def test_has_infs_non_float(request, arr, correct, disable_bottleneck): + val = request.getfixturevalue(arr) + while getattr(val, "ndim", True): + res0 = nanops._has_infs(val) + if correct: + assert res0 + else: + assert not res0 + + if not hasattr(val, "ndim"): + break + + # Reduce dimension for next step in the loop + val = np.take(val, 0, axis=-1) + + +@pytest.mark.parametrize( + "arr, correct", + [ + ("arr_float", False), + ("arr_nan", False), + ("arr_float_nan", False), + ("arr_nan_nan", False), + ("arr_float_inf", True), + ("arr_inf", True), + ("arr_nan_inf", True), + ("arr_float_nan_inf", True), + ("arr_nan_nan_inf", True), + ], +) +@pytest.mark.parametrize("astype", [None, "f4", "f2"]) +def test_has_infs_floats(request, arr, correct, astype, disable_bottleneck): + val = request.getfixturevalue(arr) + if astype is not None: + val = val.astype(astype) + while getattr(val, "ndim", True): + res0 = nanops._has_infs(val) + if correct: + assert res0 + else: + assert not res0 + + if not hasattr(val, "ndim"): + break + + # Reduce dimension for next step in the loop + val = np.take(val, 0, axis=-1) + + +@pytest.mark.parametrize( + "fixture", ["arr_float", "arr_complex", "arr_int", "arr_bool", "arr_str", "arr_utf"] +) +def test_bn_ok_dtype(fixture, request, disable_bottleneck): + obj = request.getfixturevalue(fixture) + assert nanops._bn_ok_dtype(obj.dtype, "test") + + +@pytest.mark.parametrize( + "fixture", + [ + "arr_date", + "arr_tdelta", + "arr_obj", + ], +) +def test_bn_not_ok_dtype(fixture, request, disable_bottleneck): + obj = request.getfixturevalue(fixture) + assert not nanops._bn_ok_dtype(obj.dtype, "test") + + +class TestEnsureNumeric: + def test_numeric_values(self): + # Test integer + assert nanops._ensure_numeric(1) == 1 + + # Test float + assert nanops._ensure_numeric(1.1) == 1.1 + + # Test complex + assert nanops._ensure_numeric(1 + 2j) == 1 + 2j + + def test_ndarray(self): + # Test numeric ndarray + values = np.array([1, 2, 3]) + assert np.allclose(nanops._ensure_numeric(values), values) + + # Test object ndarray + o_values = values.astype(object) + assert np.allclose(nanops._ensure_numeric(o_values), values) + + # Test convertible string ndarray + s_values = np.array(["1", "2", "3"], dtype=object) + msg = r"Could not convert \['1' '2' '3'\] to numeric" + with pytest.raises(TypeError, match=msg): + nanops._ensure_numeric(s_values) + + # Test non-convertible string ndarray + s_values = np.array(["foo", "bar", "baz"], dtype=object) + msg = r"Could not convert .* to numeric" + with pytest.raises(TypeError, match=msg): + nanops._ensure_numeric(s_values) + + def test_convertable_values(self): + with pytest.raises(TypeError, match="Could not convert string '1' to numeric"): + nanops._ensure_numeric("1") + with pytest.raises( + TypeError, match="Could not convert string '1.1' to numeric" + ): + nanops._ensure_numeric("1.1") + with pytest.raises( + TypeError, match=r"Could not convert string '1\+1j' to numeric" + ): + nanops._ensure_numeric("1+1j") + + def test_non_convertable_values(self): + msg = "Could not convert string 'foo' to numeric" + with pytest.raises(TypeError, match=msg): + nanops._ensure_numeric("foo") + + # with the wrong type, python raises TypeError for us + msg = "argument must be a string or a number" + with pytest.raises(TypeError, match=msg): + nanops._ensure_numeric({}) + with pytest.raises(TypeError, match=msg): + nanops._ensure_numeric([]) + + +class TestNanvarFixedValues: + # xref GH10242 + # Samples from a normal distribution. + @pytest.fixture + def variance(self): + return 3.0 + + @pytest.fixture + def samples(self, variance): + return self.prng.normal(scale=variance**0.5, size=100000) + + def test_nanvar_all_finite(self, samples, variance): + actual_variance = nanops.nanvar(samples) + tm.assert_almost_equal(actual_variance, variance, rtol=1e-2) + + def test_nanvar_nans(self, samples, variance): + samples_test = np.nan * np.ones(2 * samples.shape[0]) + samples_test[::2] = samples + + actual_variance = nanops.nanvar(samples_test, skipna=True) + tm.assert_almost_equal(actual_variance, variance, rtol=1e-2) + + actual_variance = nanops.nanvar(samples_test, skipna=False) + tm.assert_almost_equal(actual_variance, np.nan, rtol=1e-2) + + def test_nanstd_nans(self, samples, variance): + samples_test = np.nan * np.ones(2 * samples.shape[0]) + samples_test[::2] = samples + + actual_std = nanops.nanstd(samples_test, skipna=True) + tm.assert_almost_equal(actual_std, variance**0.5, rtol=1e-2) + + actual_std = nanops.nanvar(samples_test, skipna=False) + tm.assert_almost_equal(actual_std, np.nan, rtol=1e-2) + + def test_nanvar_axis(self, samples, variance): + # Generate some sample data. + samples_unif = self.prng.uniform(size=samples.shape[0]) + samples = np.vstack([samples, samples_unif]) + + actual_variance = nanops.nanvar(samples, axis=1) + tm.assert_almost_equal( + actual_variance, np.array([variance, 1.0 / 12]), rtol=1e-2 + ) + + def test_nanvar_ddof(self): + n = 5 + samples = self.prng.uniform(size=(10000, n + 1)) + samples[:, -1] = np.nan # Force use of our own algorithm. + + variance_0 = nanops.nanvar(samples, axis=1, skipna=True, ddof=0).mean() + variance_1 = nanops.nanvar(samples, axis=1, skipna=True, ddof=1).mean() + variance_2 = nanops.nanvar(samples, axis=1, skipna=True, ddof=2).mean() + + # The unbiased estimate. + var = 1.0 / 12 + tm.assert_almost_equal(variance_1, var, rtol=1e-2) + + # The underestimated variance. + tm.assert_almost_equal(variance_0, (n - 1.0) / n * var, rtol=1e-2) + + # The overestimated variance. + tm.assert_almost_equal(variance_2, (n - 1.0) / (n - 2.0) * var, rtol=1e-2) + + @pytest.mark.parametrize("axis", range(2)) + @pytest.mark.parametrize("ddof", range(3)) + def test_ground_truth(self, axis, ddof): + # Test against values that were precomputed with Numpy. + samples = np.empty((4, 4)) + samples[:3, :3] = np.array( + [ + [0.97303362, 0.21869576, 0.55560287], + [0.72980153, 0.03109364, 0.99155171], + [0.09317602, 0.60078248, 0.15871292], + ] + ) + samples[3] = samples[:, 3] = np.nan + + # Actual variances along axis=0, 1 for ddof=0, 1, 2 + variance = np.array( + [ + [ + [0.13762259, 0.05619224, 0.11568816], + [0.20643388, 0.08428837, 0.17353224], + [0.41286776, 0.16857673, 0.34706449], + ], + [ + [0.09519783, 0.16435395, 0.05082054], + [0.14279674, 0.24653093, 0.07623082], + [0.28559348, 0.49306186, 0.15246163], + ], + ] + ) + + # Test nanvar. + var = nanops.nanvar(samples, skipna=True, axis=axis, ddof=ddof) + tm.assert_almost_equal(var[:3], variance[axis, ddof]) + assert np.isnan(var[3]) + + # Test nanstd. + std = nanops.nanstd(samples, skipna=True, axis=axis, ddof=ddof) + tm.assert_almost_equal(std[:3], variance[axis, ddof] ** 0.5) + assert np.isnan(std[3]) + + @pytest.mark.parametrize("ddof", range(3)) + def test_nanstd_roundoff(self, ddof): + # Regression test for GH 10242 (test data taken from GH 10489). Ensure + # that variance is stable. + data = Series(766897346 * np.ones(10)) + result = data.std(ddof=ddof) + assert result == 0.0 + + @property + def prng(self): + return np.random.default_rng(2) + + +class TestNanskewFixedValues: + # xref GH 11974 + # Test data + skewness value (computed with scipy.stats.skew) + @pytest.fixture + def samples(self): + return np.sin(np.linspace(0, 1, 200)) + + @pytest.fixture + def actual_skew(self): + return -0.1875895205961754 + + @pytest.mark.parametrize("val", [3075.2, 3075.3, 3075.5]) + def test_constant_series(self, val): + # xref GH 11974 + data = val * np.ones(300) + skew = nanops.nanskew(data) + assert skew == 0.0 + + def test_all_finite(self): + alpha, beta = 0.3, 0.1 + left_tailed = self.prng.beta(alpha, beta, size=100) + assert nanops.nanskew(left_tailed) < 0 + + alpha, beta = 0.1, 0.3 + right_tailed = self.prng.beta(alpha, beta, size=100) + assert nanops.nanskew(right_tailed) > 0 + + def test_ground_truth(self, samples, actual_skew): + skew = nanops.nanskew(samples) + tm.assert_almost_equal(skew, actual_skew) + + def test_axis(self, samples, actual_skew): + samples = np.vstack([samples, np.nan * np.ones(len(samples))]) + skew = nanops.nanskew(samples, axis=1) + tm.assert_almost_equal(skew, np.array([actual_skew, np.nan])) + + def test_nans(self, samples): + samples = np.hstack([samples, np.nan]) + skew = nanops.nanskew(samples, skipna=False) + assert np.isnan(skew) + + def test_nans_skipna(self, samples, actual_skew): + samples = np.hstack([samples, np.nan]) + skew = nanops.nanskew(samples, skipna=True) + tm.assert_almost_equal(skew, actual_skew) + + @property + def prng(self): + return np.random.default_rng(2) + + +class TestNankurtFixedValues: + # xref GH 11974 + # Test data + kurtosis value (computed with scipy.stats.kurtosis) + @pytest.fixture + def samples(self): + return np.sin(np.linspace(0, 1, 200)) + + @pytest.fixture + def actual_kurt(self): + return -1.2058303433799713 + + @pytest.mark.parametrize("val", [3075.2, 3075.3, 3075.5]) + def test_constant_series(self, val): + # xref GH 11974 + data = val * np.ones(300) + kurt = nanops.nankurt(data) + assert kurt == 0.0 + + def test_all_finite(self): + alpha, beta = 0.3, 0.1 + left_tailed = self.prng.beta(alpha, beta, size=100) + assert nanops.nankurt(left_tailed) < 2 + + alpha, beta = 0.1, 0.3 + right_tailed = self.prng.beta(alpha, beta, size=100) + assert nanops.nankurt(right_tailed) < 0 + + def test_ground_truth(self, samples, actual_kurt): + kurt = nanops.nankurt(samples) + tm.assert_almost_equal(kurt, actual_kurt) + + def test_axis(self, samples, actual_kurt): + samples = np.vstack([samples, np.nan * np.ones(len(samples))]) + kurt = nanops.nankurt(samples, axis=1) + tm.assert_almost_equal(kurt, np.array([actual_kurt, np.nan])) + + def test_nans(self, samples): + samples = np.hstack([samples, np.nan]) + kurt = nanops.nankurt(samples, skipna=False) + assert np.isnan(kurt) + + def test_nans_skipna(self, samples, actual_kurt): + samples = np.hstack([samples, np.nan]) + kurt = nanops.nankurt(samples, skipna=True) + tm.assert_almost_equal(kurt, actual_kurt) + + @property + def prng(self): + return np.random.default_rng(2) + + +class TestDatetime64NaNOps: + @pytest.fixture(params=["s", "ms", "us", "ns"]) + def unit(self, request): + return request.param + + # Enabling mean changes the behavior of DataFrame.mean + # See https://github.com/pandas-dev/pandas/issues/24752 + def test_nanmean(self, unit): + dti = pd.date_range("2016-01-01", periods=3).as_unit(unit) + expected = dti[1] + + for obj in [dti, dti._data]: + result = nanops.nanmean(obj) + assert result == expected + + dti2 = dti.insert(1, pd.NaT) + + for obj in [dti2, dti2._data]: + result = nanops.nanmean(obj) + assert result == expected + + @pytest.mark.parametrize("constructor", ["M8", "m8"]) + def test_nanmean_skipna_false(self, constructor, unit): + dtype = f"{constructor}[{unit}]" + arr = np.arange(12).astype(np.int64).view(dtype).reshape(4, 3) + + arr[-1, -1] = "NaT" + + result = nanops.nanmean(arr, skipna=False) + assert np.isnat(result) + assert result.dtype == dtype + + result = nanops.nanmean(arr, axis=0, skipna=False) + expected = np.array([4, 5, "NaT"], dtype=arr.dtype) + tm.assert_numpy_array_equal(result, expected) + + result = nanops.nanmean(arr, axis=1, skipna=False) + expected = np.array([arr[0, 1], arr[1, 1], arr[2, 1], arr[-1, -1]]) + tm.assert_numpy_array_equal(result, expected) + + +def test_use_bottleneck(): + if nanops._BOTTLENECK_INSTALLED: + with pd.option_context("use_bottleneck", True): + assert pd.get_option("use_bottleneck") + + with pd.option_context("use_bottleneck", False): + assert not pd.get_option("use_bottleneck") + + +@pytest.mark.parametrize( + "numpy_op, expected", + [ + (np.sum, 10), + (np.nansum, 10), + (np.mean, 2.5), + (np.nanmean, 2.5), + (np.median, 2.5), + (np.nanmedian, 2.5), + (np.min, 1), + (np.max, 4), + (np.nanmin, 1), + (np.nanmax, 4), + ], +) +def test_numpy_ops(numpy_op, expected): + # GH8383 + result = numpy_op(Series([1, 2, 3, 4])) + assert result == expected + + +@pytest.mark.parametrize( + "operation", + [ + nanops.nanany, + nanops.nanall, + nanops.nansum, + nanops.nanmean, + nanops.nanmedian, + nanops.nanstd, + nanops.nanvar, + nanops.nansem, + nanops.nanargmax, + nanops.nanargmin, + nanops.nanmax, + nanops.nanmin, + nanops.nanskew, + nanops.nankurt, + nanops.nanprod, + ], +) +def test_nanops_independent_of_mask_param(operation): + # GH22764 + ser = Series([1, 2, np.nan, 3, np.nan, 4]) + mask = ser.isna() + median_expected = operation(ser._values) + median_result = operation(ser._values, mask=mask) + assert median_expected == median_result + + +@pytest.mark.parametrize("min_count", [-1, 0]) +def test_check_below_min_count_negative_or_zero_min_count(min_count): + # GH35227 + result = nanops.check_below_min_count((21, 37), None, min_count) + expected_result = False + assert result == expected_result + + +@pytest.mark.parametrize( + "mask", [None, np.array([False, False, True]), np.array([True] + 9 * [False])] +) +@pytest.mark.parametrize("min_count, expected_result", [(1, False), (101, True)]) +def test_check_below_min_count_positive_min_count(mask, min_count, expected_result): + # GH35227 + shape = (10, 10) + result = nanops.check_below_min_count(shape, mask, min_count) + assert result == expected_result + + +@td.skip_if_windows +@td.skip_if_32bit +@pytest.mark.parametrize("min_count, expected_result", [(1, False), (2812191852, True)]) +def test_check_below_min_count_large_shape(min_count, expected_result): + # GH35227 large shape used to show that the issue is fixed + shape = (2244367, 1253) + result = nanops.check_below_min_count(shape, mask=None, min_count=min_count) + assert result == expected_result + + +@pytest.mark.parametrize("func", ["nanmean", "nansum"]) +def test_check_bottleneck_disallow(any_real_numpy_dtype, func): + # GH 42878 bottleneck sometimes produces unreliable results for mean and sum + assert not nanops._bn_ok_dtype(np.dtype(any_real_numpy_dtype).type, func) + + +@pytest.mark.parametrize("val", [2**55, -(2**55), 20150515061816532]) +def test_nanmean_overflow(disable_bottleneck, val): + # GH 10155 + # In the previous implementation mean can overflow for int dtypes, it + # is now consistent with numpy + + ser = Series(val, index=range(500), dtype=np.int64) + result = ser.mean() + np_result = ser.values.mean() + assert result == val + assert result == np_result + assert result.dtype == np.float64 + + +@pytest.mark.parametrize( + "dtype", + [ + np.int16, + np.int32, + np.int64, + np.float32, + np.float64, + getattr(np, "float128", None), + ], +) +@pytest.mark.parametrize("method", ["mean", "std", "var", "skew", "kurt", "min", "max"]) +def test_returned_dtype(disable_bottleneck, dtype, method): + if dtype is None: + pytest.skip("np.float128 not available") + + ser = Series(range(10), dtype=dtype) + result = getattr(ser, method)() + if is_integer_dtype(dtype) and method not in ["min", "max"]: + assert result.dtype == np.float64 + else: + assert result.dtype == dtype diff --git a/shared/package-files/35/356db4610889804a1f674c6be06828722c787c0b019a7c9a9e499bc4f7f9e059/test_autowrap.py b/shared/package-files/35/356db4610889804a1f674c6be06828722c787c0b019a7c9a9e499bc4f7f9e059/test_autowrap.py new file mode 100644 index 0000000000000000000000000000000000000000..2d6d1796d5a7e6f2b3cf793f31d34f465949a211 --- /dev/null +++ b/shared/package-files/35/356db4610889804a1f674c6be06828722c787c0b019a7c9a9e499bc4f7f9e059/test_autowrap.py @@ -0,0 +1,461 @@ +# Tests that require installed backends go into +# sympy/test_external/test_autowrap + +import os +import tempfile +import shutil +from io import StringIO + +from sympy.core import symbols, Eq +from sympy.utilities.autowrap import (autowrap, binary_function, + CythonCodeWrapper, UfuncifyCodeWrapper, CodeWrapper) +from sympy.utilities.codegen import ( + CCodeGen, C99CodeGen, CodeGenArgumentListError, make_routine +) +from sympy.testing.pytest import raises +from sympy.testing.tmpfiles import TmpFileManager + + +def get_string(dump_fn, routines, prefix="file", **kwargs): + """Wrapper for dump_fn. dump_fn writes its results to a stream object and + this wrapper returns the contents of that stream as a string. This + auxiliary function is used by many tests below. + + The header and the empty lines are not generator to facilitate the + testing of the output. + """ + output = StringIO() + dump_fn(routines, output, prefix, **kwargs) + source = output.getvalue() + output.close() + return source + + +def test_cython_wrapper_scalar_function(): + x, y, z = symbols('x,y,z') + expr = (x + y)*z + routine = make_routine("test", expr) + code_gen = CythonCodeWrapper(CCodeGen()) + source = get_string(code_gen.dump_pyx, [routine]) + + expected = ( + "cdef extern from 'file.h':\n" + " double test(double x, double y, double z)\n" + "\n" + "def test_c(double x, double y, double z):\n" + "\n" + " return test(x, y, z)") + assert source == expected + + +def test_cython_wrapper_outarg(): + from sympy.core.relational import Equality + x, y, z = symbols('x,y,z') + code_gen = CythonCodeWrapper(C99CodeGen()) + + routine = make_routine("test", Equality(z, x + y)) + source = get_string(code_gen.dump_pyx, [routine]) + expected = ( + "cdef extern from 'file.h':\n" + " void test(double x, double y, double *z)\n" + "\n" + "def test_c(double x, double y):\n" + "\n" + " cdef double z = 0\n" + " test(x, y, &z)\n" + " return z") + assert source == expected + + +def test_cython_wrapper_inoutarg(): + from sympy.core.relational import Equality + x, y, z = symbols('x,y,z') + code_gen = CythonCodeWrapper(C99CodeGen()) + routine = make_routine("test", Equality(z, x + y + z)) + source = get_string(code_gen.dump_pyx, [routine]) + expected = ( + "cdef extern from 'file.h':\n" + " void test(double x, double y, double *z)\n" + "\n" + "def test_c(double x, double y, double z):\n" + "\n" + " test(x, y, &z)\n" + " return z") + assert source == expected + + +def test_cython_wrapper_compile_flags(): + from sympy.core.relational import Equality + x, y, z = symbols('x,y,z') + routine = make_routine("test", Equality(z, x + y)) + + code_gen = CythonCodeWrapper(CCodeGen()) + + expected = """\ +from setuptools import setup +from setuptools import Extension +from Cython.Build import cythonize +cy_opts = {'compiler_directives': {'language_level': '3'}} + +ext_mods = [Extension( + 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], + include_dirs=[], + library_dirs=[], + libraries=[], + extra_compile_args=['-std=c99'], + extra_link_args=[] +)] +setup(ext_modules=cythonize(ext_mods, **cy_opts)) +""" % {'num': CodeWrapper._module_counter} + + temp_dir = tempfile.mkdtemp() + TmpFileManager.tmp_folder(temp_dir) + setup_file_path = os.path.join(temp_dir, 'setup.py') + + code_gen._prepare_files(routine, build_dir=temp_dir) + with open(setup_file_path) as f: + setup_text = f.read() + assert setup_text == expected + + code_gen = CythonCodeWrapper(CCodeGen(), + include_dirs=['/usr/local/include', '/opt/booger/include'], + library_dirs=['/user/local/lib'], + libraries=['thelib', 'nilib'], + extra_compile_args=['-slow-math'], + extra_link_args=['-lswamp', '-ltrident'], + cythonize_options={'compiler_directives': {'boundscheck': False}} + ) + expected = """\ +from setuptools import setup +from setuptools import Extension +from Cython.Build import cythonize +cy_opts = {'compiler_directives': {'boundscheck': False}} + +ext_mods = [Extension( + 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], + include_dirs=['/usr/local/include', '/opt/booger/include'], + library_dirs=['/user/local/lib'], + libraries=['thelib', 'nilib'], + extra_compile_args=['-slow-math', '-std=c99'], + extra_link_args=['-lswamp', '-ltrident'] +)] +setup(ext_modules=cythonize(ext_mods, **cy_opts)) +""" % {'num': CodeWrapper._module_counter} + + code_gen._prepare_files(routine, build_dir=temp_dir) + with open(setup_file_path) as f: + setup_text = f.read() + assert setup_text == expected + + expected = """\ +from setuptools import setup +from setuptools import Extension +from Cython.Build import cythonize +cy_opts = {'compiler_directives': {'boundscheck': False}} +import numpy as np + +ext_mods = [Extension( + 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], + include_dirs=['/usr/local/include', '/opt/booger/include', np.get_include()], + library_dirs=['/user/local/lib'], + libraries=['thelib', 'nilib'], + extra_compile_args=['-slow-math', '-std=c99'], + extra_link_args=['-lswamp', '-ltrident'] +)] +setup(ext_modules=cythonize(ext_mods, **cy_opts)) +""" % {'num': CodeWrapper._module_counter} + + code_gen._need_numpy = True + code_gen._prepare_files(routine, build_dir=temp_dir) + with open(setup_file_path) as f: + setup_text = f.read() + assert setup_text == expected + + TmpFileManager.cleanup() + +def test_cython_wrapper_unique_dummyvars(): + from sympy.core.relational import Equality + from sympy.core.symbol import Dummy + x, y, z = Dummy('x'), Dummy('y'), Dummy('z') + x_id, y_id, z_id = [str(d.dummy_index) for d in [x, y, z]] + expr = Equality(z, x + y) + routine = make_routine("test", expr) + code_gen = CythonCodeWrapper(CCodeGen()) + source = get_string(code_gen.dump_pyx, [routine]) + expected_template = ( + "cdef extern from 'file.h':\n" + " void test(double x_{x_id}, double y_{y_id}, double *z_{z_id})\n" + "\n" + "def test_c(double x_{x_id}, double y_{y_id}):\n" + "\n" + " cdef double z_{z_id} = 0\n" + " test(x_{x_id}, y_{y_id}, &z_{z_id})\n" + " return z_{z_id}") + expected = expected_template.format(x_id=x_id, y_id=y_id, z_id=z_id) + assert source == expected + +def test_autowrap_dummy(): + x, y, z = symbols('x y z') + + # Uses DummyWrapper to test that codegen works as expected + + f = autowrap(x + y, backend='dummy') + assert f() == str(x + y) + assert f.args == "x, y" + assert f.returns == "nameless" + f = autowrap(Eq(z, x + y), backend='dummy') + assert f() == str(x + y) + assert f.args == "x, y" + assert f.returns == "z" + f = autowrap(Eq(z, x + y + z), backend='dummy') + assert f() == str(x + y + z) + assert f.args == "x, y, z" + assert f.returns == "z" + + +def test_autowrap_args(): + x, y, z = symbols('x y z') + + raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y), + backend='dummy', args=[x])) + f = autowrap(Eq(z, x + y), backend='dummy', args=[y, x]) + assert f() == str(x + y) + assert f.args == "y, x" + assert f.returns == "z" + + raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y + z), + backend='dummy', args=[x, y])) + f = autowrap(Eq(z, x + y + z), backend='dummy', args=[y, x, z]) + assert f() == str(x + y + z) + assert f.args == "y, x, z" + assert f.returns == "z" + + f = autowrap(Eq(z, x + y + z), backend='dummy', args=(y, x, z)) + assert f() == str(x + y + z) + assert f.args == "y, x, z" + assert f.returns == "z" + +def test_autowrap_store_files(): + x, y = symbols('x y') + tmp = tempfile.mkdtemp() + TmpFileManager.tmp_folder(tmp) + + f = autowrap(x + y, backend='dummy', tempdir=tmp) + assert f() == str(x + y) + assert os.access(tmp, os.F_OK) + + TmpFileManager.cleanup() + +def test_autowrap_store_files_issue_gh12939(): + x, y = symbols('x y') + tmp = './tmp' + saved_cwd = os.getcwd() + temp_cwd = tempfile.mkdtemp() + try: + os.chdir(temp_cwd) + f = autowrap(x + y, backend='dummy', tempdir=tmp) + assert f() == str(x + y) + assert os.access(tmp, os.F_OK) + finally: + os.chdir(saved_cwd) + shutil.rmtree(temp_cwd) + + +def test_binary_function(): + x, y = symbols('x y') + f = binary_function('f', x + y, backend='dummy') + assert f._imp_() == str(x + y) + + +def test_ufuncify_source(): + x, y, z = symbols('x,y,z') + code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify")) + routine = make_routine("test", x + y + z) + source = get_string(code_wrapper.dump_c, [routine]) + expected = """\ +#include "Python.h" +#include "math.h" +#include "numpy/ndarraytypes.h" +#include "numpy/ufuncobject.h" +#include "numpy/halffloat.h" +#include "file.h" + +static PyMethodDef wrapper_module_%(num)sMethods[] = { + {NULL, NULL, 0, NULL} +}; + +static void test_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) +{ + npy_intp i; + npy_intp n = dimensions[0]; + char *in0 = args[0]; + char *in1 = args[1]; + char *in2 = args[2]; + char *out0 = args[3]; + npy_intp in0_step = steps[0]; + npy_intp in1_step = steps[1]; + npy_intp in2_step = steps[2]; + npy_intp out0_step = steps[3]; + for (i = 0; i < n; i++) { + *((double *)out0) = test(*(double *)in0, *(double *)in1, *(double *)in2); + in0 += in0_step; + in1 += in1_step; + in2 += in2_step; + out0 += out0_step; + } +} +PyUFuncGenericFunction test_funcs[1] = {&test_ufunc}; +static char test_types[4] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE}; +static void *test_data[1] = {NULL}; + +#if PY_VERSION_HEX >= 0x03000000 +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "wrapper_module_%(num)s", + NULL, + -1, + wrapper_module_%(num)sMethods, + NULL, + NULL, + NULL, + NULL +}; + +PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void) +{ + PyObject *m, *d; + PyObject *ufunc0; + m = PyModule_Create(&moduledef); + if (!m) { + return NULL; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1, + PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); + PyDict_SetItemString(d, "test", ufunc0); + Py_DECREF(ufunc0); + return m; +} +#else +PyMODINIT_FUNC initwrapper_module_%(num)s(void) +{ + PyObject *m, *d; + PyObject *ufunc0; + m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods); + if (m == NULL) { + return; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1, + PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); + PyDict_SetItemString(d, "test", ufunc0); + Py_DECREF(ufunc0); +} +#endif""" % {'num': CodeWrapper._module_counter} + assert source == expected + + +def test_ufuncify_source_multioutput(): + x, y, z = symbols('x,y,z') + var_symbols = (x, y, z) + expr = x + y**3 + 10*z**2 + code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify")) + routines = [make_routine("func{}".format(i), expr.diff(var_symbols[i]), var_symbols) for i in range(len(var_symbols))] + source = get_string(code_wrapper.dump_c, routines, funcname='multitest') + expected = """\ +#include "Python.h" +#include "math.h" +#include "numpy/ndarraytypes.h" +#include "numpy/ufuncobject.h" +#include "numpy/halffloat.h" +#include "file.h" + +static PyMethodDef wrapper_module_%(num)sMethods[] = { + {NULL, NULL, 0, NULL} +}; + +static void multitest_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) +{ + npy_intp i; + npy_intp n = dimensions[0]; + char *in0 = args[0]; + char *in1 = args[1]; + char *in2 = args[2]; + char *out0 = args[3]; + char *out1 = args[4]; + char *out2 = args[5]; + npy_intp in0_step = steps[0]; + npy_intp in1_step = steps[1]; + npy_intp in2_step = steps[2]; + npy_intp out0_step = steps[3]; + npy_intp out1_step = steps[4]; + npy_intp out2_step = steps[5]; + for (i = 0; i < n; i++) { + *((double *)out0) = func0(*(double *)in0, *(double *)in1, *(double *)in2); + *((double *)out1) = func1(*(double *)in0, *(double *)in1, *(double *)in2); + *((double *)out2) = func2(*(double *)in0, *(double *)in1, *(double *)in2); + in0 += in0_step; + in1 += in1_step; + in2 += in2_step; + out0 += out0_step; + out1 += out1_step; + out2 += out2_step; + } +} +PyUFuncGenericFunction multitest_funcs[1] = {&multitest_ufunc}; +static char multitest_types[6] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE}; +static void *multitest_data[1] = {NULL}; + +#if PY_VERSION_HEX >= 0x03000000 +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "wrapper_module_%(num)s", + NULL, + -1, + wrapper_module_%(num)sMethods, + NULL, + NULL, + NULL, + NULL +}; + +PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void) +{ + PyObject *m, *d; + PyObject *ufunc0; + m = PyModule_Create(&moduledef); + if (!m) { + return NULL; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3, + PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); + PyDict_SetItemString(d, "multitest", ufunc0); + Py_DECREF(ufunc0); + return m; +} +#else +PyMODINIT_FUNC initwrapper_module_%(num)s(void) +{ + PyObject *m, *d; + PyObject *ufunc0; + m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods); + if (m == NULL) { + return; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3, + PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); + PyDict_SetItemString(d, "multitest", ufunc0); + Py_DECREF(ufunc0); +} +#endif""" % {'num': CodeWrapper._module_counter} + assert source == expected diff --git a/shared/package-files/35/356fa6dd8729270c29438502f658faf1e8a8501d4d6dd9a069a4080fabfd79c5/_dbapi_type_object.py b/shared/package-files/35/356fa6dd8729270c29438502f658faf1e8a8501d4d6dd9a069a4080fabfd79c5/_dbapi_type_object.py new file mode 100644 index 0000000000000000000000000000000000000000..ed73760dd489b93492e14140ddc7ce7921f97c97 --- /dev/null +++ b/shared/package-files/35/356fa6dd8729270c29438502f658faf1e8a8501d4d6dd9a069a4080fabfd79c5/_dbapi_type_object.py @@ -0,0 +1,231 @@ +"""DuckDB DB API 2.0 Type Objects Module. + +This module provides DB API 2.0 compliant type objects for DuckDB, allowing applications +to check column types returned by queries against standard database API categories. + +Example: + >>> import duckdb + >>> + >>> conn = duckdb.connect() + >>> cursor = conn.cursor() + >>> cursor.execute("SELECT 'hello' as text_col, 42 as num_col, CURRENT_DATE as date_col") + >>> + >>> # Check column types using DB API type objects + >>> for i, desc in enumerate(cursor.description): + >>> col_name, col_type = desc[0], desc[1] + >>> if col_type == duckdb.STRING: + >>> print(f"{col_name} is a string type") + >>> elif col_type == duckdb.NUMBER: + >>> print(f"{col_name} is a numeric type") + >>> elif col_type == duckdb.DATETIME: + >>> print(f"{col_name} is a date/time type") + +See Also: + - PEP 249: https://peps.python.org/pep-0249/ + - DuckDB Type System: https://duckdb.org/docs/sql/data_types/overview +""" + +from duckdb import sqltypes + + +class DBAPITypeObject: + """DB API 2.0 type object for categorizing database column types. + + This class implements the type objects defined in PEP 249 (DB API 2.0). + It allows checking whether a specific DuckDB type belongs to a broader + category like STRING, NUMBER, DATETIME, etc. + + The type object supports equality comparison with DuckDBPyType instances, + returning True if the type belongs to this category. + + Args: + types: A list of DuckDBPyType instances that belong to this type category. + + Example: + >>> string_types = DBAPITypeObject([sqltypes.VARCHAR, sqltypes.CHAR]) + >>> result = sqltypes.VARCHAR == string_types # True + >>> result = sqltypes.INTEGER == string_types # False + + Note: + This follows the DB API 2.0 specification where type objects are compared + using equality operators rather than isinstance() checks. + """ + + def __init__(self, types: list[sqltypes.DuckDBPyType]) -> None: + """Initialize a DB API type object. + + Args: + types: List of DuckDB types that belong to this category. + """ + self.types = types + + def __eq__(self, other: object) -> bool: + """Check if a DuckDB type belongs to this type category. + + This method implements the DB API 2.0 type checking mechanism. + It returns True if the other object is a DuckDBPyType that + is contained in this type category. + + Args: + other: The object to compare, typically a DuckDBPyType instance. + + Returns: + True if other is a DuckDBPyType in this category, False otherwise. + + Example: + >>> NUMBER == sqltypes.INTEGER # True + >>> NUMBER == sqltypes.VARCHAR # False + """ + if isinstance(other, sqltypes.DuckDBPyType): + return other in self.types + return False + + def __repr__(self) -> str: + """Return a string representation of this type object. + + Returns: + A string showing the type object and its contained DuckDB types. + + Example: + >>> repr(STRING) + '' + """ + return f"" + + +# Define the standard DB API 2.0 type objects for DuckDB + +STRING = DBAPITypeObject([sqltypes.VARCHAR]) +""" +STRING type object for text-based database columns. + +This type object represents all string/text types in DuckDB. Currently includes: +- VARCHAR: Variable-length character strings + +Use this to check if a column contains textual data that should be handled +as Python strings. + +DB API 2.0 Reference: + https://peps.python.org/pep-0249/#string + +Example: + >>> cursor.description[0][1] == STRING # Check if first column is text +""" + +NUMBER = DBAPITypeObject( + [ + sqltypes.TINYINT, + sqltypes.UTINYINT, + sqltypes.SMALLINT, + sqltypes.USMALLINT, + sqltypes.INTEGER, + sqltypes.UINTEGER, + sqltypes.BIGINT, + sqltypes.UBIGINT, + sqltypes.HUGEINT, + sqltypes.UHUGEINT, + sqltypes.DuckDBPyType("BIGNUM"), + sqltypes.DuckDBPyType("DECIMAL"), + sqltypes.FLOAT, + sqltypes.DOUBLE, + ] +) +""" +NUMBER type object for numeric database columns. + +This type object represents all numeric types in DuckDB, including: + +Integer Types: +- TINYINT, UTINYINT: 8-bit signed/unsigned integers +- SMALLINT, USMALLINT: 16-bit signed/unsigned integers +- INTEGER, UINTEGER: 32-bit signed/unsigned integers +- BIGINT, UBIGINT: 64-bit signed/unsigned integers +- HUGEINT, UHUGEINT: 128-bit signed/unsigned integers + +Decimal Types: +- BIGNUM: Arbitrary precision integers +- DECIMAL: Fixed-point decimal numbers + +Floating Point Types: +- FLOAT: 32-bit floating point +- DOUBLE: 64-bit floating point + +Use this to check if a column contains numeric data that should be handled +as Python int, float, or Decimal objects. + +DB API 2.0 Reference: + https://peps.python.org/pep-0249/#number + +Example: + >>> cursor.description[1][1] == NUMBER # Check if second column is numeric +""" + +DATETIME = DBAPITypeObject( + [ + sqltypes.DATE, + sqltypes.TIME, + sqltypes.TIME_TZ, + sqltypes.TIMESTAMP, + sqltypes.TIMESTAMP_TZ, + sqltypes.TIMESTAMP_NS, + sqltypes.TIMESTAMP_MS, + sqltypes.TIMESTAMP_S, + ] +) +""" +DATETIME type object for date and time database columns. + +This type object represents all date/time types in DuckDB, including: + +Date Types: +- DATE: Calendar dates (year, month, day) + +Time Types: +- TIME: Time of day without timezone +- TIME_TZ: Time of day with timezone + +Timestamp Types: +- TIMESTAMP: Date and time without timezone (microsecond precision) +- TIMESTAMP_TZ: Date and time with timezone +- TIMESTAMP_NS: Nanosecond precision timestamps +- TIMESTAMP_MS: Millisecond precision timestamps +- TIMESTAMP_S: Second precision timestamps + +Use this to check if a column contains temporal data that should be handled +as Python datetime, date, or time objects. + +DB API 2.0 Reference: + https://peps.python.org/pep-0249/#datetime + +Example: + >>> cursor.description[2][1] == DATETIME # Check if third column is date/time +""" + +BINARY = DBAPITypeObject([sqltypes.BLOB]) +""" +BINARY type object for binary data database columns. + +This type object represents binary data types in DuckDB: +- BLOB: Binary Large Objects for storing arbitrary binary data + +Use this to check if a column contains binary data that should be handled +as Python bytes objects. + +DB API 2.0 Reference: + https://peps.python.org/pep-0249/#binary + +Example: + >>> cursor.description[3][1] == BINARY # Check if fourth column is binary +""" + +ROWID = None +""" +ROWID type object for row identifier columns. + +DB API 2.0 Reference: + https://peps.python.org/pep-0249/#rowid + +Note: + This will always be None for DuckDB connections. Applications should not + rely on ROWID functionality when using DuckDB. +""" diff --git a/shared/package-files/35/356fcbda617b66b47616f5ed0c4ee235fc3404cfb04f253305afc2d41e5167b0/python_sparse_functions.cpp b/shared/package-files/35/356fcbda617b66b47616f5ed0c4ee235fc3404cfb04f253305afc2d41e5167b0/python_sparse_functions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..648d91442102e9b950cb2ddb8db545c4b4e1100e --- /dev/null +++ b/shared/package-files/35/356fcbda617b66b47616f5ed0c4ee235fc3404cfb04f253305afc2d41e5167b0/python_sparse_functions.cpp @@ -0,0 +1,67 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +// ${generated_comment} + +#include "torch/csrc/Device.h" +#include "torch/csrc/DynamicTypes.h" +#include "torch/csrc/Exceptions.h" +#include "torch/csrc/autograd/python_sparse_functions.h" +#include "torch/csrc/autograd/python_variable.h" +#include "torch/csrc/autograd/utils/wrap_outputs.h" +#include "torch/csrc/autograd/utils/python_arg_parsing.h" +#include "torch/csrc/utils/pycfunction_helpers.h" +#include "torch/csrc/utils/python_arg_parser.h" +#include "torch/csrc/utils/structseq.h" + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +$ops_headers +#endif + +using at::Tensor; +using at::Scalar; +using at::ScalarType; +using at::MemoryFormat; +using at::Generator; +using at::IntArrayRef; +using at::TensorList; + +using namespace torch::autograd::utils; + +namespace torch::autograd { + +// generated forward declarations start here + +${py_forwards} + +static PyMethodDef sparse_functions[] = { + ${py_method_defs} + {NULL} +}; + +static PyObject* THPSparseVariableFunctionsModule = NULL; + +void initSparseFunctions(PyObject* module) { + static struct PyModuleDef def = { + PyModuleDef_HEAD_INIT, + "torch._C._sparse", + NULL, + -1, + sparse_functions + }; + PyObject* sparse = PyModule_Create(&def); + THPSparseVariableFunctionsModule = sparse; + if (!sparse) { + throw python_error(); + } + // steals a reference to sparse + if (PyModule_AddObject(module, "_sparse", sparse) != 0) { + throw python_error(); + } +} + +// generated methods start here + +${py_methods} + +} // namespace torch::autograd diff --git a/shared/package-files/35/357005c709fcf8499a2ed65b5f603c86f7d1c3f8ca1c31fae364210b38136073/rsub_ops.h b/shared/package-files/35/357005c709fcf8499a2ed65b5f603c86f7d1c3f8ca1c31fae364210b38136073/rsub_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..f901c4ab46aaf01cd2db626c1f645bcd54247b6a --- /dev/null +++ b/shared/package-files/35/357005c709fcf8499a2ed65b5f603c86f7d1c3f8ca1c31fae364210b38136073/rsub_ops.h @@ -0,0 +1,61 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API rsub_Tensor { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::rsub") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "rsub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha); +}; + +struct TORCH_API rsub_Scalar { + using schema = at::Tensor (const at::Tensor &, const at::Scalar &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::rsub") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "rsub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Scalar & other, const at::Scalar & alpha); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, const at::Scalar & alpha); +}; + +struct TORCH_API rsub_Tensor_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Scalar &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::rsub") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "rsub.Tensor_out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha, at::Tensor & out); +}; + +struct TORCH_API rsub_Scalar_out { + using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, const at::Scalar &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::rsub") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "rsub.Scalar_out(Tensor self, Scalar other, Scalar alpha=1, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Scalar & other, const at::Scalar & alpha, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, const at::Scalar & alpha, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/35/35736c6b9d3100cdad825447542bec0c6d2742cc47094ab783f325b471621277/search.py b/shared/package-files/35/35736c6b9d3100cdad825447542bec0c6d2742cc47094ab783f325b471621277/search.py new file mode 100644 index 0000000000000000000000000000000000000000..fd90a04e901341a01ac3754963ccf42793e1eabf --- /dev/null +++ b/shared/package-files/35/35736c6b9d3100cdad825447542bec0c6d2742cc47094ab783f325b471621277/search.py @@ -0,0 +1,230 @@ +""" +Search operations. + +For the key bindings implementation with attached filters, check +`prompt_toolkit.key_binding.bindings.search`. (Use these for new key bindings +instead of calling these function directly.) +""" +from __future__ import annotations + +from enum import Enum +from typing import TYPE_CHECKING + +from .application.current import get_app +from .filters import FilterOrBool, is_searching, to_filter +from .key_binding.vi_state import InputMode + +if TYPE_CHECKING: + from prompt_toolkit.layout.controls import BufferControl, SearchBufferControl + from prompt_toolkit.layout.layout import Layout + +__all__ = [ + "SearchDirection", + "start_search", + "stop_search", +] + + +class SearchDirection(Enum): + FORWARD = "FORWARD" + BACKWARD = "BACKWARD" + + +class SearchState: + """ + A search 'query', associated with a search field (like a SearchToolbar). + + Every searchable `BufferControl` points to a `search_buffer_control` + (another `BufferControls`) which represents the search field. The + `SearchState` attached to that search field is used for storing the current + search query. + + It is possible to have one searchfield for multiple `BufferControls`. In + that case, they'll share the same `SearchState`. + If there are multiple `BufferControls` that display the same `Buffer`, then + they can have a different `SearchState` each (if they have a different + search control). + """ + + __slots__ = ("text", "direction", "ignore_case") + + def __init__( + self, + text: str = "", + direction: SearchDirection = SearchDirection.FORWARD, + ignore_case: FilterOrBool = False, + ) -> None: + self.text = text + self.direction = direction + self.ignore_case = to_filter(ignore_case) + + def __repr__(self) -> str: + return "{}({!r}, direction={!r}, ignore_case={!r})".format( + self.__class__.__name__, + self.text, + self.direction, + self.ignore_case, + ) + + def __invert__(self) -> SearchState: + """ + Create a new SearchState where backwards becomes forwards and the other + way around. + """ + if self.direction == SearchDirection.BACKWARD: + direction = SearchDirection.FORWARD + else: + direction = SearchDirection.BACKWARD + + return SearchState( + text=self.text, direction=direction, ignore_case=self.ignore_case + ) + + +def start_search( + buffer_control: BufferControl | None = None, + direction: SearchDirection = SearchDirection.FORWARD, +) -> None: + """ + Start search through the given `buffer_control` using the + `search_buffer_control`. + + :param buffer_control: Start search for this `BufferControl`. If not given, + search through the current control. + """ + from prompt_toolkit.layout.controls import BufferControl + + assert buffer_control is None or isinstance(buffer_control, BufferControl) + + layout = get_app().layout + + # When no control is given, use the current control if that's a BufferControl. + if buffer_control is None: + if not isinstance(layout.current_control, BufferControl): + return + buffer_control = layout.current_control + + # Only if this control is searchable. + search_buffer_control = buffer_control.search_buffer_control + + if search_buffer_control: + buffer_control.search_state.direction = direction + + # Make sure to focus the search BufferControl + layout.focus(search_buffer_control) + + # Remember search link. + layout.search_links[search_buffer_control] = buffer_control + + # If we're in Vi mode, make sure to go into insert mode. + get_app().vi_state.input_mode = InputMode.INSERT + + +def stop_search(buffer_control: BufferControl | None = None) -> None: + """ + Stop search through the given `buffer_control`. + """ + layout = get_app().layout + + if buffer_control is None: + buffer_control = layout.search_target_buffer_control + if buffer_control is None: + # (Should not happen, but possible when `stop_search` is called + # when we're not searching.) + return + search_buffer_control = buffer_control.search_buffer_control + else: + assert buffer_control in layout.search_links.values() + search_buffer_control = _get_reverse_search_links(layout)[buffer_control] + + # Focus the original buffer again. + layout.focus(buffer_control) + + if search_buffer_control is not None: + # Remove the search link. + del layout.search_links[search_buffer_control] + + # Reset content of search control. + search_buffer_control.buffer.reset() + + # If we're in Vi mode, go back to navigation mode. + get_app().vi_state.input_mode = InputMode.NAVIGATION + + +def do_incremental_search(direction: SearchDirection, count: int = 1) -> None: + """ + Apply search, but keep search buffer focused. + """ + assert is_searching() + + layout = get_app().layout + + # Only search if the current control is a `BufferControl`. + from prompt_toolkit.layout.controls import BufferControl + + search_control = layout.current_control + if not isinstance(search_control, BufferControl): + return + + prev_control = layout.search_target_buffer_control + if prev_control is None: + return + search_state = prev_control.search_state + + # Update search_state. + direction_changed = search_state.direction != direction + + search_state.text = search_control.buffer.text + search_state.direction = direction + + # Apply search to current buffer. + if not direction_changed: + prev_control.buffer.apply_search( + search_state, include_current_position=False, count=count + ) + + +def accept_search() -> None: + """ + Accept current search query. Focus original `BufferControl` again. + """ + layout = get_app().layout + + search_control = layout.current_control + target_buffer_control = layout.search_target_buffer_control + + from prompt_toolkit.layout.controls import BufferControl + + if not isinstance(search_control, BufferControl): + return + if target_buffer_control is None: + return + + search_state = target_buffer_control.search_state + + # Update search state. + if search_control.buffer.text: + search_state.text = search_control.buffer.text + + # Apply search. + target_buffer_control.buffer.apply_search( + search_state, include_current_position=True + ) + + # Add query to history of search line. + search_control.buffer.append_to_history() + + # Stop search and focus previous control again. + stop_search(target_buffer_control) + + +def _get_reverse_search_links( + layout: Layout, +) -> dict[BufferControl, SearchBufferControl]: + """ + Return mapping from BufferControl to SearchBufferControl. + """ + return { + buffer_control: search_buffer_control + for search_buffer_control, buffer_control in layout.search_links.items() + } diff --git a/shared/package-files/35/35742115970e3967365c12fbec2300c50f2f3adc5f7b2b051e63edb41da9f228/_fw_primal_compositeexplicitautograd_dispatch.h b/shared/package-files/35/35742115970e3967365c12fbec2300c50f2f3adc5f7b2b051e63edb41da9f228/_fw_primal_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..aa91848397008a42ce309455a1625c7c52110e89 --- /dev/null +++ b/shared/package-files/35/35742115970e3967365c12fbec2300c50f2f3adc5f7b2b051e63edb41da9f228/_fw_primal_compositeexplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor _fw_primal(const at::Tensor & self, int64_t level); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/35/357599b7f652a263ffde3616f93cb2991413b65174268325731fa27088c35fba/lexer.py b/shared/package-files/35/357599b7f652a263ffde3616f93cb2991413b65174268325731fa27088c35fba/lexer.py new file mode 100644 index 0000000000000000000000000000000000000000..88167207d473312decc890e8b962dd4aefc0734c --- /dev/null +++ b/shared/package-files/35/357599b7f652a263ffde3616f93cb2991413b65174268325731fa27088c35fba/lexer.py @@ -0,0 +1,287 @@ +from fontTools.feaLib.error import FeatureLibError, IncludedFeaNotFound +from fontTools.feaLib.location import FeatureLibLocation +import re +import os + +try: + import cython +except ImportError: + # if cython not installed, use mock module with no-op decorators and types + from fontTools.misc import cython + + +class Lexer(object): + NUMBER = "NUMBER" + HEXADECIMAL = "HEXADECIMAL" + OCTAL = "OCTAL" + NUMBERS = (NUMBER, HEXADECIMAL, OCTAL) + FLOAT = "FLOAT" + STRING = "STRING" + NAME = "NAME" + FILENAME = "FILENAME" + GLYPHCLASS = "GLYPHCLASS" + CID = "CID" + SYMBOL = "SYMBOL" + COMMENT = "COMMENT" + NEWLINE = "NEWLINE" + ANONYMOUS_BLOCK = "ANONYMOUS_BLOCK" + + CHAR_WHITESPACE_ = " \t" + CHAR_NEWLINE_ = "\r\n" + CHAR_SYMBOL_ = ",;:-+'{}[]<>()=" + CHAR_DIGIT_ = "0123456789" + CHAR_HEXDIGIT_ = "0123456789ABCDEFabcdef" + CHAR_LETTER_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + CHAR_NAME_START_ = CHAR_LETTER_ + "_+*:.^~!\\" + CHAR_NAME_CONTINUATION_ = CHAR_LETTER_ + CHAR_DIGIT_ + "_.+*:^~!/-" + + RE_GLYPHCLASS = re.compile(r"^[A-Za-z_0-9.\-]+$") + + MODE_NORMAL_ = "NORMAL" + MODE_FILENAME_ = "FILENAME" + + def __init__(self, text, filename): + self.filename_ = filename + self.line_ = 1 + self.pos_ = 0 + self.line_start_ = 0 + self.text_ = text + self.text_length_ = len(text) + self.mode_ = Lexer.MODE_NORMAL_ + + def __iter__(self): + return self + + def next(self): # Python 2 + return self.__next__() + + def __next__(self): # Python 3 + while True: + token_type, token, location = self.next_() + if token_type != Lexer.NEWLINE: + return (token_type, token, location) + + def location_(self): + column = self.pos_ - self.line_start_ + 1 + return FeatureLibLocation(self.filename_ or "", self.line_, column) + + def next_(self): + self.scan_over_(Lexer.CHAR_WHITESPACE_) + location = self.location_() + start = self.pos_ + text = self.text_ + limit = len(text) + if start >= limit: + raise StopIteration() + cur_char = text[start] + next_char = text[start + 1] if start + 1 < limit else None + + if cur_char == "\n": + self.pos_ += 1 + self.line_ += 1 + self.line_start_ = self.pos_ + return (Lexer.NEWLINE, None, location) + if cur_char == "\r": + self.pos_ += 2 if next_char == "\n" else 1 + self.line_ += 1 + self.line_start_ = self.pos_ + return (Lexer.NEWLINE, None, location) + if cur_char == "#": + self.scan_until_(Lexer.CHAR_NEWLINE_) + return (Lexer.COMMENT, text[start : self.pos_], location) + + if self.mode_ is Lexer.MODE_FILENAME_: + if cur_char != "(": + raise FeatureLibError("Expected '(' before file name", location) + self.scan_until_(")") + cur_char = text[self.pos_] if self.pos_ < limit else None + if cur_char != ")": + raise FeatureLibError("Expected ')' after file name", location) + self.pos_ += 1 + self.mode_ = Lexer.MODE_NORMAL_ + return (Lexer.FILENAME, text[start + 1 : self.pos_ - 1], location) + + if cur_char == "\\" and next_char in Lexer.CHAR_DIGIT_: + self.pos_ += 1 + self.scan_over_(Lexer.CHAR_DIGIT_) + return (Lexer.CID, int(text[start + 1 : self.pos_], 10), location) + if cur_char == "@": + self.pos_ += 1 + self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) + glyphclass = text[start + 1 : self.pos_] + if len(glyphclass) < 1: + raise FeatureLibError("Expected glyph class name", location) + if not Lexer.RE_GLYPHCLASS.match(glyphclass): + raise FeatureLibError( + "Glyph class names must consist of letters, digits, " + "underscore, period or hyphen", + location, + ) + return (Lexer.GLYPHCLASS, glyphclass, location) + if cur_char in Lexer.CHAR_NAME_START_: + self.pos_ += 1 + self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) + token = text[start : self.pos_] + if token == "include": + self.mode_ = Lexer.MODE_FILENAME_ + return (Lexer.NAME, token, location) + if cur_char == "0" and next_char in "xX": + self.pos_ += 2 + self.scan_over_(Lexer.CHAR_HEXDIGIT_) + return (Lexer.HEXADECIMAL, int(text[start : self.pos_], 16), location) + if cur_char == "0" and next_char in Lexer.CHAR_DIGIT_: + self.scan_over_(Lexer.CHAR_DIGIT_) + return (Lexer.OCTAL, int(text[start : self.pos_], 8), location) + if cur_char in Lexer.CHAR_DIGIT_: + self.scan_over_(Lexer.CHAR_DIGIT_) + if self.pos_ >= limit or text[self.pos_] != ".": + return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) + self.scan_over_(".") + self.scan_over_(Lexer.CHAR_DIGIT_) + return (Lexer.FLOAT, float(text[start : self.pos_]), location) + if cur_char == "-" and next_char in Lexer.CHAR_DIGIT_: + self.pos_ += 1 + self.scan_over_(Lexer.CHAR_DIGIT_) + if self.pos_ >= limit or text[self.pos_] != ".": + return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) + self.scan_over_(".") + self.scan_over_(Lexer.CHAR_DIGIT_) + return (Lexer.FLOAT, float(text[start : self.pos_]), location) + if cur_char in Lexer.CHAR_SYMBOL_: + self.pos_ += 1 + return (Lexer.SYMBOL, cur_char, location) + if cur_char == '"': + self.pos_ += 1 + self.scan_until_('"') + if self.pos_ < self.text_length_ and self.text_[self.pos_] == '"': + self.pos_ += 1 + # strip newlines embedded within a string + string = re.sub("[\r\n]", "", text[start + 1 : self.pos_ - 1]) + return (Lexer.STRING, string, location) + else: + raise FeatureLibError("Expected '\"' to terminate string", location) + raise FeatureLibError("Unexpected character: %r" % cur_char, location) + + def scan_over_(self, valid): + p = self.pos_ + while p < self.text_length_ and self.text_[p] in valid: + p += 1 + self.pos_ = p + + def scan_until_(self, stop_at): + p = self.pos_ + while p < self.text_length_ and self.text_[p] not in stop_at: + p += 1 + self.pos_ = p + + def scan_anonymous_block(self, tag): + location = self.location_() + tag = tag.strip() + self.scan_until_(Lexer.CHAR_NEWLINE_) + self.scan_over_(Lexer.CHAR_NEWLINE_) + regexp = r"}\s*" + re.escape(tag) + r"\s*;" + split = re.split(regexp, self.text_[self.pos_ :], maxsplit=1) + if len(split) != 2: + raise FeatureLibError( + "Expected '} %s;' to terminate anonymous block" % tag, location + ) + self.pos_ += len(split[0]) + return (Lexer.ANONYMOUS_BLOCK, split[0], location) + + +class IncludingLexer(object): + """A Lexer that follows include statements. + + The OpenType feature file specification states that due to + historical reasons, relative imports should be resolved in this + order: + + 1. If the source font is UFO format, then relative to the UFO's + font directory + 2. relative to the top-level include file + 3. relative to the parent include file + + We only support 1 (via includeDir) and 2. + """ + + def __init__(self, featurefile, *, includeDir=None): + """Initializes an IncludingLexer. + + Behavior: + If includeDir is passed, it will be used to determine the top-level + include directory to use for all encountered include statements. If it is + not passed, ``os.path.dirname(featurefile)`` will be considered the + include directory. + """ + + self.lexers_ = [self.make_lexer_(featurefile)] + self.featurefilepath = self.lexers_[0].filename_ + self.includeDir = includeDir + + def __iter__(self): + return self + + def next(self): # Python 2 + return self.__next__() + + def __next__(self): # Python 3 + while self.lexers_: + lexer = self.lexers_[-1] + try: + token_type, token, location = next(lexer) + except StopIteration: + self.lexers_.pop() + continue + if token_type is Lexer.NAME and token == "include": + fname_type, fname_token, fname_location = lexer.next() + if fname_type is not Lexer.FILENAME: + raise FeatureLibError("Expected file name", fname_location) + # semi_type, semi_token, semi_location = lexer.next() + # if semi_type is not Lexer.SYMBOL or semi_token != ";": + # raise FeatureLibError("Expected ';'", semi_location) + if os.path.isabs(fname_token): + path = fname_token + else: + if self.includeDir is not None: + curpath = self.includeDir + elif self.featurefilepath is not None: + curpath = os.path.dirname(self.featurefilepath) + else: + # if the IncludingLexer was initialized from an in-memory + # file-like stream, it doesn't have a 'name' pointing to + # its filesystem path, therefore we fall back to using the + # current working directory to resolve relative includes + curpath = os.getcwd() + path = os.path.join(curpath, fname_token) + if len(self.lexers_) >= 5: + raise FeatureLibError("Too many recursive includes", fname_location) + try: + self.lexers_.append(self.make_lexer_(path)) + except FileNotFoundError as err: + raise IncludedFeaNotFound(fname_token, fname_location) from err + else: + return (token_type, token, location) + raise StopIteration() + + @staticmethod + def make_lexer_(file_or_path): + if hasattr(file_or_path, "read"): + fileobj, closing = file_or_path, False + else: + filename, closing = file_or_path, True + fileobj = open(filename, "r", encoding="utf-8-sig") + data = fileobj.read() + filename = getattr(fileobj, "name", None) + if closing: + fileobj.close() + return Lexer(data, filename) + + def scan_anonymous_block(self, tag): + return self.lexers_[-1].scan_anonymous_block(tag) + + +class NonIncludingLexer(IncludingLexer): + """Lexer that does not follow `include` statements, emits them as-is.""" + + def __next__(self): # Python 3 + return next(self.lexers_[0]) diff --git a/shared/package-files/35/3575a0295bac7f6c8726906d9446e04ea24f4033171084c1fad532424c260631/to_native.h b/shared/package-files/35/3575a0295bac7f6c8726906d9446e04ea24f4033171084c1fad532424c260631/to_native.h new file mode 100644 index 0000000000000000000000000000000000000000..e596bbec2f30becb2a0c5e73b9a733a7d3206231 --- /dev/null +++ b/shared/package-files/35/3575a0295bac7f6c8726906d9446e04ea24f4033171084c1fad532424c260631/to_native.h @@ -0,0 +1,24 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor to(const at::Tensor & self, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}, bool non_blocking=false, bool copy=false, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor to(const at::Tensor & self, at::Device device, at::ScalarType dtype, bool non_blocking=false, bool copy=false, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor to(const at::Tensor & self, at::ScalarType dtype, bool non_blocking=false, bool copy=false, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor to(const at::Tensor & self, const at::Tensor & other, bool non_blocking=false, bool copy=false, c10::optional memory_format=c10::nullopt); +} // namespace native +} // namespace at diff --git a/shared/package-files/35/3577a0aef133556a2fb21b5afaa8db50a036b6941c01b8d86dfc247fab4a4fa6/test_axislines.py b/shared/package-files/35/3577a0aef133556a2fb21b5afaa8db50a036b6941c01b8d86dfc247fab4a4fa6/test_axislines.py new file mode 100644 index 0000000000000000000000000000000000000000..8bc3707421b61fed84a5ba7fc3958cac7de8dc85 --- /dev/null +++ b/shared/package-files/35/3577a0aef133556a2fb21b5afaa8db50a036b6941c01b8d86dfc247fab4a4fa6/test_axislines.py @@ -0,0 +1,145 @@ +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.testing.decorators import image_comparison +from matplotlib.transforms import IdentityTransform + +from mpl_toolkits.axisartist.axislines import AxesZero, SubplotZero, Subplot +from mpl_toolkits.axisartist import Axes, SubplotHost + + +@image_comparison(['SubplotZero.png'], style='default') +def test_SubplotZero(): + # Remove this line when this test image is regenerated. + plt.rcParams['text.kerning_factor'] = 6 + + fig = plt.figure() + + ax = SubplotZero(fig, 1, 1, 1) + fig.add_subplot(ax) + + ax.axis["xzero"].set_visible(True) + ax.axis["xzero"].label.set_text("Axis Zero") + + for n in ["top", "right"]: + ax.axis[n].set_visible(False) + + xx = np.arange(0, 2 * np.pi, 0.01) + ax.plot(xx, np.sin(xx)) + ax.set_ylabel("Test") + + +@image_comparison(['Subplot.png'], style='default') +def test_Subplot(): + # Remove this line when this test image is regenerated. + plt.rcParams['text.kerning_factor'] = 6 + + fig = plt.figure() + + ax = Subplot(fig, 1, 1, 1) + fig.add_subplot(ax) + + xx = np.arange(0, 2 * np.pi, 0.01) + ax.plot(xx, np.sin(xx)) + ax.set_ylabel("Test") + + ax.axis["top"].major_ticks.set_tick_out(True) + ax.axis["bottom"].major_ticks.set_tick_out(True) + + ax.axis["bottom"].set_label("Tk0") + + +def test_Axes(): + fig = plt.figure() + ax = Axes(fig, [0.15, 0.1, 0.65, 0.8]) + fig.add_axes(ax) + ax.plot([1, 2, 3], [0, 1, 2]) + ax.set_xscale('log') + fig.canvas.draw() + + +@image_comparison(['ParasiteAxesAuxTrans_meshplot.png'], + remove_text=True, style='default', tol=0.075) +def test_ParasiteAxesAuxTrans(): + data = np.ones((6, 6)) + data[2, 2] = 2 + data[0, :] = 0 + data[-2, :] = 0 + data[:, 0] = 0 + data[:, -2] = 0 + x = np.arange(6) + y = np.arange(6) + xx, yy = np.meshgrid(x, y) + + funcnames = ['pcolor', 'pcolormesh', 'contourf'] + + fig = plt.figure() + for i, name in enumerate(funcnames): + + ax1 = SubplotHost(fig, 1, 3, i+1) + fig.add_subplot(ax1) + + ax2 = ax1.get_aux_axes(IdentityTransform(), viewlim_mode=None) + if name.startswith('pcolor'): + getattr(ax2, name)(xx, yy, data[:-1, :-1]) + else: + getattr(ax2, name)(xx, yy, data) + ax1.set_xlim((0, 5)) + ax1.set_ylim((0, 5)) + + ax2.contour(xx, yy, data, colors='k') + + +@image_comparison(['axisline_style.png'], remove_text=True, style='mpl20') +def test_axisline_style(): + fig = plt.figure(figsize=(2, 2)) + ax = fig.add_subplot(axes_class=AxesZero) + ax.axis["xzero"].set_axisline_style("-|>") + ax.axis["xzero"].set_visible(True) + ax.axis["yzero"].set_axisline_style("->") + ax.axis["yzero"].set_visible(True) + + for direction in ("left", "right", "bottom", "top"): + ax.axis[direction].set_visible(False) + + +@image_comparison(['axisline_style_size_color.png'], remove_text=True, + style='mpl20') +def test_axisline_style_size_color(): + fig = plt.figure(figsize=(2, 2)) + ax = fig.add_subplot(axes_class=AxesZero) + ax.axis["xzero"].set_axisline_style("-|>", size=2.0, facecolor='r') + ax.axis["xzero"].set_visible(True) + ax.axis["yzero"].set_axisline_style("->, size=1.5") + ax.axis["yzero"].set_visible(True) + + for direction in ("left", "right", "bottom", "top"): + ax.axis[direction].set_visible(False) + + +@image_comparison(['axisline_style_tight.png'], remove_text=True, + style='mpl20') +def test_axisline_style_tight(): + fig = plt.figure(figsize=(2, 2), layout='tight') + ax = fig.add_subplot(axes_class=AxesZero) + ax.axis["xzero"].set_axisline_style("-|>", size=5, facecolor='g') + ax.axis["xzero"].set_visible(True) + ax.axis["yzero"].set_axisline_style("->, size=8") + ax.axis["yzero"].set_visible(True) + + for direction in ("left", "right", "bottom", "top"): + ax.axis[direction].set_visible(False) + + +@image_comparison(['subplotzero_ylabel.png'], style='mpl20') +def test_subplotzero_ylabel(): + fig = plt.figure() + ax = fig.add_subplot(111, axes_class=SubplotZero) + + ax.set(xlim=(-3, 7), ylim=(-3, 7), xlabel="x", ylabel="y") + + zero_axis = ax.axis["xzero", "yzero"] + zero_axis.set_visible(True) # they are hidden by default + + ax.axis["left", "right", "bottom", "top"].set_visible(False) + + zero_axis.set_axisline_style("->") diff --git a/shared/package-files/35/35798a919a23b90bee72b802adea267c097fea720bded9d919130d11501e42da/_standard_gamma_grad.h b/shared/package-files/35/35798a919a23b90bee72b802adea267c097fea720bded9d919130d11501e42da/_standard_gamma_grad.h new file mode 100644 index 0000000000000000000000000000000000000000..b10ee2d60b85f10e1de83c5194bb1b7645d41269 --- /dev/null +++ b/shared/package-files/35/35798a919a23b90bee72b802adea267c097fea720bded9d919130d11501e42da/_standard_gamma_grad.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_standard_gamma_grad(Tensor self, Tensor output) -> Tensor +inline at::Tensor _standard_gamma_grad(const at::Tensor & self, const at::Tensor & output) { + return at::_ops::_standard_gamma_grad::call(self, output); +} + +// aten::_standard_gamma_grad.out(Tensor self, Tensor output, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _standard_gamma_grad_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & output) { + return at::_ops::_standard_gamma_grad_out::call(self, output, out); +} +// aten::_standard_gamma_grad.out(Tensor self, Tensor output, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _standard_gamma_grad_outf(const at::Tensor & self, const at::Tensor & output, at::Tensor & out) { + return at::_ops::_standard_gamma_grad_out::call(self, output, out); +} + +} diff --git a/shared/package-files/35/357ad276e086fab501163d4e9a0ae13c2fd0647eb08d2305fbc0ca3813892601/LICENSE.md b/shared/package-files/35/357ad276e086fab501163d4e9a0ae13c2fd0647eb08d2305fbc0ca3813892601/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..86f5ad0986c90f85adb79a7964c3752d5d2d397b --- /dev/null +++ b/shared/package-files/35/357ad276e086fab501163d4e9a0ae13c2fd0647eb08d2305fbc0ca3813892601/LICENSE.md @@ -0,0 +1,27 @@ +Copyright (c) 2012-2023, Michael L. Waskom +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the project nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/shared/package-files/35/357c0549102da685644b26c252a89c4032aa73c48d05eab748e075412f867bce/beta_functions.py b/shared/package-files/35/357c0549102da685644b26c252a89c4032aa73c48d05eab748e075412f867bce/beta_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..88b5143769c0ef456f0c62f5267a96fb38fb5519 --- /dev/null +++ b/shared/package-files/35/357c0549102da685644b26c252a89c4032aa73c48d05eab748e075412f867bce/beta_functions.py @@ -0,0 +1,389 @@ +from sympy.core import S +from sympy.core.function import Function, ArgumentIndexError +from sympy.core.symbol import Dummy +from sympy.functions.special.gamma_functions import gamma, digamma +from sympy.functions.combinatorial.numbers import catalan +from sympy.functions.elementary.complexes import conjugate + +# See mpmath #569 and SymPy #20569 +def betainc_mpmath_fix(a, b, x1, x2, reg=0): + from mpmath import betainc, mpf + if x1 == x2: + return mpf(0) + else: + return betainc(a, b, x1, x2, reg) + +############################################################################### +############################ COMPLETE BETA FUNCTION ########################## +############################################################################### + +class beta(Function): + r""" + The beta integral is called the Eulerian integral of the first kind by + Legendre: + + .. math:: + \mathrm{B}(x,y) \int^{1}_{0} t^{x-1} (1-t)^{y-1} \mathrm{d}t. + + Explanation + =========== + + The Beta function or Euler's first integral is closely associated + with the gamma function. The Beta function is often used in probability + theory and mathematical statistics. It satisfies properties like: + + .. math:: + \mathrm{B}(a,1) = \frac{1}{a} \\ + \mathrm{B}(a,b) = \mathrm{B}(b,a) \\ + \mathrm{B}(a,b) = \frac{\Gamma(a) \Gamma(b)}{\Gamma(a+b)} + + Therefore for integral values of $a$ and $b$: + + .. math:: + \mathrm{B} = \frac{(a-1)! (b-1)!}{(a+b-1)!} + + A special case of the Beta function when `x = y` is the + Central Beta function. It satisfies properties like: + + .. math:: + \mathrm{B}(x) = 2^{1 - 2x}\mathrm{B}(x, \frac{1}{2}) + \mathrm{B}(x) = 2^{1 - 2x} cos(\pi x) \mathrm{B}(\frac{1}{2} - x, x) + \mathrm{B}(x) = \int_{0}^{1} \frac{t^x}{(1 + t)^{2x}} dt + \mathrm{B}(x) = \frac{2}{x} \prod_{n = 1}^{\infty} \frac{n(n + 2x)}{(n + x)^2} + + Examples + ======== + + >>> from sympy import I, pi + >>> from sympy.abc import x, y + + The Beta function obeys the mirror symmetry: + + >>> from sympy import beta, conjugate + >>> conjugate(beta(x, y)) + beta(conjugate(x), conjugate(y)) + + Differentiation with respect to both $x$ and $y$ is supported: + + >>> from sympy import beta, diff + >>> diff(beta(x, y), x) + (polygamma(0, x) - polygamma(0, x + y))*beta(x, y) + + >>> diff(beta(x, y), y) + (polygamma(0, y) - polygamma(0, x + y))*beta(x, y) + + >>> diff(beta(x), x) + 2*(polygamma(0, x) - polygamma(0, 2*x))*beta(x, x) + + We can numerically evaluate the Beta function to + arbitrary precision for any complex numbers x and y: + + >>> from sympy import beta + >>> beta(pi).evalf(40) + 0.02671848900111377452242355235388489324562 + + >>> beta(1 + I).evalf(20) + -0.2112723729365330143 - 0.7655283165378005676*I + + See Also + ======== + + gamma: Gamma function. + uppergamma: Upper incomplete gamma function. + lowergamma: Lower incomplete gamma function. + polygamma: Polygamma function. + loggamma: Log Gamma function. + digamma: Digamma function. + trigamma: Trigamma function. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Beta_function + .. [2] https://mathworld.wolfram.com/BetaFunction.html + .. [3] https://dlmf.nist.gov/5.12 + + """ + unbranched = True + + def fdiff(self, argindex): + x, y = self.args + if argindex == 1: + # Diff wrt x + return beta(x, y)*(digamma(x) - digamma(x + y)) + elif argindex == 2: + # Diff wrt y + return beta(x, y)*(digamma(y) - digamma(x + y)) + else: + raise ArgumentIndexError(self, argindex) + + @classmethod + def eval(cls, x, y=None): + if y is None: + return beta(x, x) + if x.is_Number and y.is_Number: + return beta(x, y, evaluate=False).doit() + + def doit(self, **hints): + x = xold = self.args[0] + # Deal with unevaluated single argument beta + single_argument = len(self.args) == 1 + y = yold = self.args[0] if single_argument else self.args[1] + if hints.get('deep', True): + x = x.doit(**hints) + y = y.doit(**hints) + if y.is_zero or x.is_zero: + return S.ComplexInfinity + if y is S.One: + return 1/x + if x is S.One: + return 1/y + if y == x + 1: + return 1/(x*y*catalan(x)) + s = x + y + if (s.is_integer and s.is_negative and x.is_integer is False and + y.is_integer is False): + return S.Zero + if x == xold and y == yold and not single_argument: + return self + return beta(x, y) + + def _eval_expand_func(self, **hints): + x, y = self.args + return gamma(x)*gamma(y) / gamma(x + y) + + def _eval_is_real(self): + return self.args[0].is_real and self.args[1].is_real + + def _eval_conjugate(self): + return self.func(self.args[0].conjugate(), self.args[1].conjugate()) + + def _eval_rewrite_as_gamma(self, x, y, piecewise=True, **kwargs): + return self._eval_expand_func(**kwargs) + + def _eval_rewrite_as_Integral(self, x, y, **kwargs): + from sympy.integrals.integrals import Integral + t = Dummy('t') + return Integral(t**(x - 1)*(1 - t)**(y - 1), (t, 0, 1)) + +############################################################################### +########################## INCOMPLETE BETA FUNCTION ########################### +############################################################################### + +class betainc(Function): + r""" + The Generalized Incomplete Beta function is defined as + + .. math:: + \mathrm{B}_{(x_1, x_2)}(a, b) = \int_{x_1}^{x_2} t^{a - 1} (1 - t)^{b - 1} dt + + The Incomplete Beta function is a special case + of the Generalized Incomplete Beta function : + + .. math:: \mathrm{B}_z (a, b) = \mathrm{B}_{(0, z)}(a, b) + + The Incomplete Beta function satisfies : + + .. math:: \mathrm{B}_z (a, b) = (-1)^a \mathrm{B}_{\frac{z}{z - 1}} (a, 1 - a - b) + + The Beta function is a special case of the Incomplete Beta function : + + .. math:: \mathrm{B}(a, b) = \mathrm{B}_{1}(a, b) + + Examples + ======== + + >>> from sympy import betainc, symbols, conjugate + >>> a, b, x, x1, x2 = symbols('a b x x1 x2') + + The Generalized Incomplete Beta function is given by: + + >>> betainc(a, b, x1, x2) + betainc(a, b, x1, x2) + + The Incomplete Beta function can be obtained as follows: + + >>> betainc(a, b, 0, x) + betainc(a, b, 0, x) + + The Incomplete Beta function obeys the mirror symmetry: + + >>> conjugate(betainc(a, b, x1, x2)) + betainc(conjugate(a), conjugate(b), conjugate(x1), conjugate(x2)) + + We can numerically evaluate the Incomplete Beta function to + arbitrary precision for any complex numbers a, b, x1 and x2: + + >>> from sympy import betainc, I + >>> betainc(2, 3, 4, 5).evalf(10) + 56.08333333 + >>> betainc(0.75, 1 - 4*I, 0, 2 + 3*I).evalf(25) + 0.2241657956955709603655887 + 0.3619619242700451992411724*I + + The Generalized Incomplete Beta function can be expressed + in terms of the Generalized Hypergeometric function. + + >>> from sympy import hyper + >>> betainc(a, b, x1, x2).rewrite(hyper) + (-x1**a*hyper((a, 1 - b), (a + 1,), x1) + x2**a*hyper((a, 1 - b), (a + 1,), x2))/a + + See Also + ======== + + beta: Beta function + hyper: Generalized Hypergeometric function + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Beta_function#Incomplete_beta_function + .. [2] https://dlmf.nist.gov/8.17 + .. [3] https://functions.wolfram.com/GammaBetaErf/Beta4/ + .. [4] https://functions.wolfram.com/GammaBetaErf/BetaRegularized4/02/ + + """ + nargs = 4 + unbranched = True + + def fdiff(self, argindex): + a, b, x1, x2 = self.args + if argindex == 3: + # Diff wrt x1 + return -(1 - x1)**(b - 1)*x1**(a - 1) + elif argindex == 4: + # Diff wrt x2 + return (1 - x2)**(b - 1)*x2**(a - 1) + else: + raise ArgumentIndexError(self, argindex) + + def _eval_mpmath(self): + return betainc_mpmath_fix, self.args + + def _eval_is_real(self): + if all(arg.is_real for arg in self.args): + return True + + def _eval_conjugate(self): + return self.func(*map(conjugate, self.args)) + + def _eval_rewrite_as_Integral(self, a, b, x1, x2, **kwargs): + from sympy.integrals.integrals import Integral + t = Dummy('t') + return Integral(t**(a - 1)*(1 - t)**(b - 1), (t, x1, x2)) + + def _eval_rewrite_as_hyper(self, a, b, x1, x2, **kwargs): + from sympy.functions.special.hyper import hyper + return (x2**a * hyper((a, 1 - b), (a + 1,), x2) - x1**a * hyper((a, 1 - b), (a + 1,), x1)) / a + +############################################################################### +#################### REGULARIZED INCOMPLETE BETA FUNCTION ##################### +############################################################################### + +class betainc_regularized(Function): + r""" + The Generalized Regularized Incomplete Beta function is given by + + .. math:: + \mathrm{I}_{(x_1, x_2)}(a, b) = \frac{\mathrm{B}_{(x_1, x_2)}(a, b)}{\mathrm{B}(a, b)} + + The Regularized Incomplete Beta function is a special case + of the Generalized Regularized Incomplete Beta function : + + .. math:: \mathrm{I}_z (a, b) = \mathrm{I}_{(0, z)}(a, b) + + The Regularized Incomplete Beta function is the cumulative distribution + function of the beta distribution. + + Examples + ======== + + >>> from sympy import betainc_regularized, symbols, conjugate + >>> a, b, x, x1, x2 = symbols('a b x x1 x2') + + The Generalized Regularized Incomplete Beta + function is given by: + + >>> betainc_regularized(a, b, x1, x2) + betainc_regularized(a, b, x1, x2) + + The Regularized Incomplete Beta function + can be obtained as follows: + + >>> betainc_regularized(a, b, 0, x) + betainc_regularized(a, b, 0, x) + + The Regularized Incomplete Beta function + obeys the mirror symmetry: + + >>> conjugate(betainc_regularized(a, b, x1, x2)) + betainc_regularized(conjugate(a), conjugate(b), conjugate(x1), conjugate(x2)) + + We can numerically evaluate the Regularized Incomplete Beta function + to arbitrary precision for any complex numbers a, b, x1 and x2: + + >>> from sympy import betainc_regularized, pi, E + >>> betainc_regularized(1, 2, 0, 0.25).evalf(10) + 0.4375000000 + >>> betainc_regularized(pi, E, 0, 1).evalf(5) + 1.00000 + + The Generalized Regularized Incomplete Beta function can be + expressed in terms of the Generalized Hypergeometric function. + + >>> from sympy import hyper + >>> betainc_regularized(a, b, x1, x2).rewrite(hyper) + (-x1**a*hyper((a, 1 - b), (a + 1,), x1) + x2**a*hyper((a, 1 - b), (a + 1,), x2))/(a*beta(a, b)) + + See Also + ======== + + beta: Beta function + hyper: Generalized Hypergeometric function + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Beta_function#Incomplete_beta_function + .. [2] https://dlmf.nist.gov/8.17 + .. [3] https://functions.wolfram.com/GammaBetaErf/Beta4/ + .. [4] https://functions.wolfram.com/GammaBetaErf/BetaRegularized4/02/ + + """ + nargs = 4 + unbranched = True + + def __new__(cls, a, b, x1, x2): + return Function.__new__(cls, a, b, x1, x2) + + def _eval_mpmath(self): + return betainc_mpmath_fix, (*self.args, S(1)) + + def fdiff(self, argindex): + a, b, x1, x2 = self.args + if argindex == 3: + # Diff wrt x1 + return -(1 - x1)**(b - 1)*x1**(a - 1) / beta(a, b) + elif argindex == 4: + # Diff wrt x2 + return (1 - x2)**(b - 1)*x2**(a - 1) / beta(a, b) + else: + raise ArgumentIndexError(self, argindex) + + def _eval_is_real(self): + if all(arg.is_real for arg in self.args): + return True + + def _eval_conjugate(self): + return self.func(*map(conjugate, self.args)) + + def _eval_rewrite_as_Integral(self, a, b, x1, x2, **kwargs): + from sympy.integrals.integrals import Integral + t = Dummy('t') + integrand = t**(a - 1)*(1 - t)**(b - 1) + expr = Integral(integrand, (t, x1, x2)) + return expr / Integral(integrand, (t, 0, 1)) + + def _eval_rewrite_as_hyper(self, a, b, x1, x2, **kwargs): + from sympy.functions.special.hyper import hyper + expr = (x2**a * hyper((a, 1 - b), (a + 1,), x2) - x1**a * hyper((a, 1 - b), (a + 1,), x1)) / a + return expr / beta(a, b) diff --git a/shared/package-files/35/357d0fd31ea13271b3e38692ff87c60e4f3b1e08d73dd014c4bf0b1415e4e039/hardsigmoid_backward_meta.h b/shared/package-files/35/357d0fd31ea13271b3e38692ff87c60e4f3b1e08d73dd014c4bf0b1415e4e039/hardsigmoid_backward_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..7a19c1c135832962a8368c3975e0e93b6332d6ba --- /dev/null +++ b/shared/package-files/35/357d0fd31ea13271b3e38692ff87c60e4f3b1e08d73dd014c4bf0b1415e4e039/hardsigmoid_backward_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_hardsigmoid_backward : public TensorIteratorBase { + + + void meta(const at::Tensor & grad_output, const at::Tensor & self); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/35/357dc98e29417f806cd5a6e3206f3e64a1afd1016ce71738def3bc1a8907c571/specifiers.py b/shared/package-files/35/357dc98e29417f806cd5a6e3206f3e64a1afd1016ce71738def3bc1a8907c571/specifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..bd7903de35e685e4d5868136f2aa8863caf682fb --- /dev/null +++ b/shared/package-files/35/357dc98e29417f806cd5a6e3206f3e64a1afd1016ce71738def3bc1a8907c571/specifiers.py @@ -0,0 +1,1006 @@ +# This file is dual licensed under the terms of the Apache License, Version + +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +""" +.. testsetup:: + + from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier + from packaging.version import Version +""" + +import abc +import itertools +import re +from typing import ( + Callable, + Iterable, + Iterator, + List, + Optional, + Set, + Tuple, + TypeVar, + Union, +) + +from .utils import canonicalize_version +from .version import Version + +UnparsedVersion = Union[Version, str] +UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion) +CallableOperator = Callable[[Version, str], bool] + + +def _coerce_version(version: UnparsedVersion) -> Version: + if not isinstance(version, Version): + version = Version(version) + return version + + +class InvalidSpecifier(ValueError): + """ + Raised when attempting to create a :class:`Specifier` with a specifier + string that is invalid. + + >>> Specifier("lolwat") + Traceback (most recent call last): + ... + packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat' + """ + + +class BaseSpecifier(metaclass=abc.ABCMeta): + @abc.abstractmethod + def __str__(self) -> str: + """ + Returns the str representation of this Specifier-like object. This + should be representative of the Specifier itself. + """ + + @abc.abstractmethod + def __hash__(self) -> int: + """ + Returns a hash value for this Specifier-like object. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Returns a boolean representing whether or not the two Specifier-like + objects are equal. + + :param other: The other object to check against. + """ + + @property + @abc.abstractmethod + def prereleases(self) -> Optional[bool]: + """Whether or not pre-releases as a whole are allowed. + + This can be set to either ``True`` or ``False`` to explicitly enable or disable + prereleases or it can be set to ``None`` (the default) to use default semantics. + """ + + @prereleases.setter + def prereleases(self, value: bool) -> None: + """Setter for :attr:`prereleases`. + + :param value: The value to set. + """ + + @abc.abstractmethod + def contains(self, item: str, prereleases: Optional[bool] = None) -> bool: + """ + Determines if the given item is contained within this specifier. + """ + + @abc.abstractmethod + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None + ) -> Iterator[UnparsedVersionVar]: + """ + Takes an iterable of items and filters them so that only items which + are contained within this specifier are allowed in it. + """ + + +class Specifier(BaseSpecifier): + """This class abstracts handling of version specifiers. + + .. tip:: + + It is generally not required to instantiate this manually. You should instead + prefer to work with :class:`SpecifierSet` instead, which can parse + comma-separated version specifiers (which is what package metadata contains). + """ + + _operator_regex_str = r""" + (?P(~=|==|!=|<=|>=|<|>|===)) + """ + _version_regex_str = r""" + (?P + (?: + # The identity operators allow for an escape hatch that will + # do an exact string match of the version you wish to install. + # This will not be parsed by PEP 440 and we cannot determine + # any semantic meaning from it. This operator is discouraged + # but included entirely as an escape hatch. + (?<====) # Only match for the identity operator + \s* + [^\s;)]* # The arbitrary version can be just about anything, + # we match everything except for whitespace, a + # semi-colon for marker support, and a closing paren + # since versions can be enclosed in them. + ) + | + (?: + # The (non)equality operators allow for wild card and local + # versions to be specified so we have to define these two + # operators separately to enable that. + (?<===|!=) # Only match for equals and not equals + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)* # release + + # You cannot use a wild card and a pre-release, post-release, a dev or + # local version together so group them with a | and make them optional. + (?: + \.\* # Wild card syntax of .* + | + (?: # pre release + [-_\.]? + (alpha|beta|preview|pre|a|b|c|rc) + [-_\.]? + [0-9]* + )? + (?: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local + )? + ) + | + (?: + # The compatible operator requires at least two digits in the + # release segment. + (?<=~=) # Only match for the compatible operator + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *) + (?: # pre release + [-_\.]? + (alpha|beta|preview|pre|a|b|c|rc) + [-_\.]? + [0-9]* + )? + (?: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + ) + | + (?: + # All other operators only allow a sub set of what the + # (non)equality operators do. Specifically they do not allow + # local versions to be specified nor do they allow the prefix + # matching wild cards. + (?=": "greater_than_equal", + "<": "less_than", + ">": "greater_than", + "===": "arbitrary", + } + + def __init__(self, spec: str = "", prereleases: Optional[bool] = None) -> None: + """Initialize a Specifier instance. + + :param spec: + The string representation of a specifier which will be parsed and + normalized before use. + :param prereleases: + This tells the specifier if it should accept prerelease versions if + applicable or not. The default of ``None`` will autodetect it from the + given specifiers. + :raises InvalidSpecifier: + If the given specifier is invalid (i.e. bad syntax). + """ + match = self._regex.search(spec) + if not match: + raise InvalidSpecifier(f"Invalid specifier: '{spec}'") + + self._spec: Tuple[str, str] = ( + match.group("operator").strip(), + match.group("version").strip(), + ) + + # Store whether or not this Specifier should accept prereleases + self._prereleases = prereleases + + @property + def prereleases(self) -> bool: + # If there is an explicit prereleases set for this, then we'll just + # blindly use that. + if self._prereleases is not None: + return self._prereleases + + # Look at all of our specifiers and determine if they are inclusive + # operators, and if they are if they are including an explicit + # prerelease. + operator, version = self._spec + if operator in ["==", ">=", "<=", "~=", "==="]: + # The == specifier can include a trailing .*, if it does we + # want to remove before parsing. + if operator == "==" and version.endswith(".*"): + version = version[:-2] + + # Parse the version, and if it is a pre-release than this + # specifier allows pre-releases. + if Version(version).is_prerelease: + return True + + return False + + @prereleases.setter + def prereleases(self, value: bool) -> None: + self._prereleases = value + + @property + def operator(self) -> str: + """The operator of this specifier. + + >>> Specifier("==1.2.3").operator + '==' + """ + return self._spec[0] + + @property + def version(self) -> str: + """The version of this specifier. + + >>> Specifier("==1.2.3").version + '1.2.3' + """ + return self._spec[1] + + def __repr__(self) -> str: + """A representation of the Specifier that shows all internal state. + + >>> Specifier('>=1.0.0') + =1.0.0')> + >>> Specifier('>=1.0.0', prereleases=False) + =1.0.0', prereleases=False)> + >>> Specifier('>=1.0.0', prereleases=True) + =1.0.0', prereleases=True)> + """ + pre = ( + f", prereleases={self.prereleases!r}" + if self._prereleases is not None + else "" + ) + + return f"<{self.__class__.__name__}({str(self)!r}{pre})>" + + def __str__(self) -> str: + """A string representation of the Specifier that can be round-tripped. + + >>> str(Specifier('>=1.0.0')) + '>=1.0.0' + >>> str(Specifier('>=1.0.0', prereleases=False)) + '>=1.0.0' + """ + return "{}{}".format(*self._spec) + + @property + def _canonical_spec(self) -> Tuple[str, str]: + canonical_version = canonicalize_version( + self._spec[1], + strip_trailing_zero=(self._spec[0] != "~="), + ) + return self._spec[0], canonical_version + + def __hash__(self) -> int: + return hash(self._canonical_spec) + + def __eq__(self, other: object) -> bool: + """Whether or not the two Specifier-like objects are equal. + + :param other: The other object to check against. + + The value of :attr:`prereleases` is ignored. + + >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0") + True + >>> (Specifier("==1.2.3", prereleases=False) == + ... Specifier("==1.2.3", prereleases=True)) + True + >>> Specifier("==1.2.3") == "==1.2.3" + True + >>> Specifier("==1.2.3") == Specifier("==1.2.4") + False + >>> Specifier("==1.2.3") == Specifier("~=1.2.3") + False + """ + if isinstance(other, str): + try: + other = self.__class__(str(other)) + except InvalidSpecifier: + return NotImplemented + elif not isinstance(other, self.__class__): + return NotImplemented + + return self._canonical_spec == other._canonical_spec + + def _get_operator(self, op: str) -> CallableOperator: + operator_callable: CallableOperator = getattr( + self, f"_compare_{self._operators[op]}" + ) + return operator_callable + + def _compare_compatible(self, prospective: Version, spec: str) -> bool: + + # Compatible releases have an equivalent combination of >= and ==. That + # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to + # implement this in terms of the other specifiers instead of + # implementing it ourselves. The only thing we need to do is construct + # the other specifiers. + + # We want everything but the last item in the version, but we want to + # ignore suffix segments. + prefix = ".".join( + list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1] + ) + + # Add the prefix notation to the end of our string + prefix += ".*" + + return self._get_operator(">=")(prospective, spec) and self._get_operator("==")( + prospective, prefix + ) + + def _compare_equal(self, prospective: Version, spec: str) -> bool: + + # We need special logic to handle prefix matching + if spec.endswith(".*"): + # In the case of prefix matching we want to ignore local segment. + normalized_prospective = canonicalize_version(prospective.public) + # Get the normalized version string ignoring the trailing .* + normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False) + # Split the spec out by dots, and pretend that there is an implicit + # dot in between a release segment and a pre-release segment. + split_spec = _version_split(normalized_spec) + + # Split the prospective version out by dots, and pretend that there + # is an implicit dot in between a release segment and a pre-release + # segment. + split_prospective = _version_split(normalized_prospective) + + # 0-pad the prospective version before shortening it to get the correct + # shortened version. + padded_prospective, _ = _pad_version(split_prospective, split_spec) + + # Shorten the prospective version to be the same length as the spec + # so that we can determine if the specifier is a prefix of the + # prospective version or not. + shortened_prospective = padded_prospective[: len(split_spec)] + + return shortened_prospective == split_spec + else: + # Convert our spec string into a Version + spec_version = Version(spec) + + # If the specifier does not have a local segment, then we want to + # act as if the prospective version also does not have a local + # segment. + if not spec_version.local: + prospective = Version(prospective.public) + + return prospective == spec_version + + def _compare_not_equal(self, prospective: Version, spec: str) -> bool: + return not self._compare_equal(prospective, spec) + + def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool: + + # NB: Local version identifiers are NOT permitted in the version + # specifier, so local version labels can be universally removed from + # the prospective version. + return Version(prospective.public) <= Version(spec) + + def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool: + + # NB: Local version identifiers are NOT permitted in the version + # specifier, so local version labels can be universally removed from + # the prospective version. + return Version(prospective.public) >= Version(spec) + + def _compare_less_than(self, prospective: Version, spec_str: str) -> bool: + + # Convert our spec to a Version instance, since we'll want to work with + # it as a version. + spec = Version(spec_str) + + # Check to see if the prospective version is less than the spec + # version. If it's not we can short circuit and just return False now + # instead of doing extra unneeded work. + if not prospective < spec: + return False + + # This special case is here so that, unless the specifier itself + # includes is a pre-release version, that we do not accept pre-release + # versions for the version mentioned in the specifier (e.g. <3.1 should + # not match 3.1.dev0, but should match 3.0.dev0). + if not spec.is_prerelease and prospective.is_prerelease: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # If we've gotten to here, it means that prospective version is both + # less than the spec version *and* it's not a pre-release of the same + # version in the spec. + return True + + def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool: + + # Convert our spec to a Version instance, since we'll want to work with + # it as a version. + spec = Version(spec_str) + + # Check to see if the prospective version is greater than the spec + # version. If it's not we can short circuit and just return False now + # instead of doing extra unneeded work. + if not prospective > spec: + return False + + # This special case is here so that, unless the specifier itself + # includes is a post-release version, that we do not accept + # post-release versions for the version mentioned in the specifier + # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0). + if not spec.is_postrelease and prospective.is_postrelease: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # Ensure that we do not allow a local version of the version mentioned + # in the specifier, which is technically greater than, to match. + if prospective.local is not None: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # If we've gotten to here, it means that prospective version is both + # greater than the spec version *and* it's not a pre-release of the + # same version in the spec. + return True + + def _compare_arbitrary(self, prospective: Version, spec: str) -> bool: + return str(prospective).lower() == str(spec).lower() + + def __contains__(self, item: Union[str, Version]) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: The item to check for. + + This is used for the ``in`` operator and behaves the same as + :meth:`contains` with no ``prereleases`` argument passed. + + >>> "1.2.3" in Specifier(">=1.2.3") + True + >>> Version("1.2.3") in Specifier(">=1.2.3") + True + >>> "1.0.0" in Specifier(">=1.2.3") + False + >>> "1.3.0a1" in Specifier(">=1.2.3") + False + >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True) + True + """ + return self.contains(item) + + def contains( + self, item: UnparsedVersion, prereleases: Optional[bool] = None + ) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: + The item to check for, which can be a version string or a + :class:`Version` instance. + :param prereleases: + Whether or not to match prereleases with this Specifier. If set to + ``None`` (the default), it uses :attr:`prereleases` to determine + whether or not prereleases are allowed. + + >>> Specifier(">=1.2.3").contains("1.2.3") + True + >>> Specifier(">=1.2.3").contains(Version("1.2.3")) + True + >>> Specifier(">=1.2.3").contains("1.0.0") + False + >>> Specifier(">=1.2.3").contains("1.3.0a1") + False + >>> Specifier(">=1.2.3", prereleases=True).contains("1.3.0a1") + True + >>> Specifier(">=1.2.3").contains("1.3.0a1", prereleases=True) + True + """ + + # Determine if prereleases are to be allowed or not. + if prereleases is None: + prereleases = self.prereleases + + # Normalize item to a Version, this allows us to have a shortcut for + # "2.0" in Specifier(">=2") + normalized_item = _coerce_version(item) + + # Determine if we should be supporting prereleases in this specifier + # or not, if we do not support prereleases than we can short circuit + # logic if this version is a prereleases. + if normalized_item.is_prerelease and not prereleases: + return False + + # Actually do the comparison to determine if this item is contained + # within this Specifier or not. + operator_callable: CallableOperator = self._get_operator(self.operator) + return operator_callable(normalized_item, self.version) + + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None + ) -> Iterator[UnparsedVersionVar]: + """Filter items in the given iterable, that match the specifier. + + :param iterable: + An iterable that can contain version strings and :class:`Version` instances. + The items in the iterable will be filtered according to the specifier. + :param prereleases: + Whether or not to allow prereleases in the returned iterator. If set to + ``None`` (the default), it will be intelligently decide whether to allow + prereleases or not (based on the :attr:`prereleases` attribute, and + whether the only versions matching are prereleases). + + This method is smarter than just ``filter(Specifier().contains, [...])`` + because it implements the rule from :pep:`440` that a prerelease item + SHOULD be accepted if no other versions match the given specifier. + + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) + ['1.3'] + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")])) + ['1.2.3', '1.3', ] + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"])) + ['1.5a1'] + >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + """ + + yielded = False + found_prereleases = [] + + kw = {"prereleases": prereleases if prereleases is not None else True} + + # Attempt to iterate over all the values in the iterable and if any of + # them match, yield them. + for version in iterable: + parsed_version = _coerce_version(version) + + if self.contains(parsed_version, **kw): + # If our version is a prerelease, and we were not set to allow + # prereleases, then we'll store it for later in case nothing + # else matches this specifier. + if parsed_version.is_prerelease and not ( + prereleases or self.prereleases + ): + found_prereleases.append(version) + # Either this is not a prerelease, or we should have been + # accepting prereleases from the beginning. + else: + yielded = True + yield version + + # Now that we've iterated over everything, determine if we've yielded + # any values, and if we have not and we have any prereleases stored up + # then we will go ahead and yield the prereleases. + if not yielded and found_prereleases: + for version in found_prereleases: + yield version + + +_prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$") + + +def _version_split(version: str) -> List[str]: + result: List[str] = [] + for item in version.split("."): + match = _prefix_regex.search(item) + if match: + result.extend(match.groups()) + else: + result.append(item) + return result + + +def _is_not_suffix(segment: str) -> bool: + return not any( + segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post") + ) + + +def _pad_version(left: List[str], right: List[str]) -> Tuple[List[str], List[str]]: + left_split, right_split = [], [] + + # Get the release segment of our versions + left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left))) + right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right))) + + # Get the rest of our versions + left_split.append(left[len(left_split[0]) :]) + right_split.append(right[len(right_split[0]) :]) + + # Insert our padding + left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0]))) + right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0]))) + + return (list(itertools.chain(*left_split)), list(itertools.chain(*right_split))) + + +class SpecifierSet(BaseSpecifier): + """This class abstracts handling of a set of version specifiers. + + It can be passed a single specifier (``>=3.0``), a comma-separated list of + specifiers (``>=3.0,!=3.1``), or no specifier at all. + """ + + def __init__( + self, specifiers: str = "", prereleases: Optional[bool] = None + ) -> None: + """Initialize a SpecifierSet instance. + + :param specifiers: + The string representation of a specifier or a comma-separated list of + specifiers which will be parsed and normalized before use. + :param prereleases: + This tells the SpecifierSet if it should accept prerelease versions if + applicable or not. The default of ``None`` will autodetect it from the + given specifiers. + + :raises InvalidSpecifier: + If the given ``specifiers`` are not parseable than this exception will be + raised. + """ + + # Split on `,` to break each individual specifier into it's own item, and + # strip each item to remove leading/trailing whitespace. + split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()] + + # Parsed each individual specifier, attempting first to make it a + # Specifier. + parsed: Set[Specifier] = set() + for specifier in split_specifiers: + parsed.add(Specifier(specifier)) + + # Turn our parsed specifiers into a frozen set and save them for later. + self._specs = frozenset(parsed) + + # Store our prereleases value so we can use it later to determine if + # we accept prereleases or not. + self._prereleases = prereleases + + @property + def prereleases(self) -> Optional[bool]: + # If we have been given an explicit prerelease modifier, then we'll + # pass that through here. + if self._prereleases is not None: + return self._prereleases + + # If we don't have any specifiers, and we don't have a forced value, + # then we'll just return None since we don't know if this should have + # pre-releases or not. + if not self._specs: + return None + + # Otherwise we'll see if any of the given specifiers accept + # prereleases, if any of them do we'll return True, otherwise False. + return any(s.prereleases for s in self._specs) + + @prereleases.setter + def prereleases(self, value: bool) -> None: + self._prereleases = value + + def __repr__(self) -> str: + """A representation of the specifier set that shows all internal state. + + Note that the ordering of the individual specifiers within the set may not + match the input string. + + >>> SpecifierSet('>=1.0.0,!=2.0.0') + =1.0.0')> + >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False) + =1.0.0', prereleases=False)> + >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True) + =1.0.0', prereleases=True)> + """ + pre = ( + f", prereleases={self.prereleases!r}" + if self._prereleases is not None + else "" + ) + + return f"" + + def __str__(self) -> str: + """A string representation of the specifier set that can be round-tripped. + + Note that the ordering of the individual specifiers within the set may not + match the input string. + + >>> str(SpecifierSet(">=1.0.0,!=1.0.1")) + '!=1.0.1,>=1.0.0' + >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False)) + '!=1.0.1,>=1.0.0' + """ + return ",".join(sorted(str(s) for s in self._specs)) + + def __hash__(self) -> int: + return hash(self._specs) + + def __and__(self, other: Union["SpecifierSet", str]) -> "SpecifierSet": + """Return a SpecifierSet which is a combination of the two sets. + + :param other: The other object to combine with. + + >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1' + =1.0.0')> + >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1') + =1.0.0')> + """ + if isinstance(other, str): + other = SpecifierSet(other) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + specifier = SpecifierSet() + specifier._specs = frozenset(self._specs | other._specs) + + if self._prereleases is None and other._prereleases is not None: + specifier._prereleases = other._prereleases + elif self._prereleases is not None and other._prereleases is None: + specifier._prereleases = self._prereleases + elif self._prereleases == other._prereleases: + specifier._prereleases = self._prereleases + else: + raise ValueError( + "Cannot combine SpecifierSets with True and False prerelease " + "overrides." + ) + + return specifier + + def __eq__(self, other: object) -> bool: + """Whether or not the two SpecifierSet-like objects are equal. + + :param other: The other object to check against. + + The value of :attr:`prereleases` is ignored. + + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) == + ... SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)) + True + >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1" + True + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2") + False + """ + if isinstance(other, (str, Specifier)): + other = SpecifierSet(str(other)) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + return self._specs == other._specs + + def __len__(self) -> int: + """Returns the number of specifiers in this specifier set.""" + return len(self._specs) + + def __iter__(self) -> Iterator[Specifier]: + """ + Returns an iterator over all the underlying :class:`Specifier` instances + in this specifier set. + + >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str) + [, =1.0.0')>] + """ + return iter(self._specs) + + def __contains__(self, item: UnparsedVersion) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: The item to check for. + + This is used for the ``in`` operator and behaves the same as + :meth:`contains` with no ``prereleases`` argument passed. + + >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1") + False + >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1") + False + >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True) + True + """ + return self.contains(item) + + def contains( + self, + item: UnparsedVersion, + prereleases: Optional[bool] = None, + installed: Optional[bool] = None, + ) -> bool: + """Return whether or not the item is contained in this SpecifierSet. + + :param item: + The item to check for, which can be a version string or a + :class:`Version` instance. + :param prereleases: + Whether or not to match prereleases with this SpecifierSet. If set to + ``None`` (the default), it uses :attr:`prereleases` to determine + whether or not prereleases are allowed. + + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3") + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3")) + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True).contains("1.3.0a1") + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True) + True + """ + # Ensure that our item is a Version instance. + if not isinstance(item, Version): + item = Version(item) + + # Determine if we're forcing a prerelease or not, if we're not forcing + # one for this particular filter call, then we'll use whatever the + # SpecifierSet thinks for whether or not we should support prereleases. + if prereleases is None: + prereleases = self.prereleases + + # We can determine if we're going to allow pre-releases by looking to + # see if any of the underlying items supports them. If none of them do + # and this item is a pre-release then we do not allow it and we can + # short circuit that here. + # Note: This means that 1.0.dev1 would not be contained in something + # like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0 + if not prereleases and item.is_prerelease: + return False + + if installed and item.is_prerelease: + item = Version(item.base_version) + + # We simply dispatch to the underlying specs here to make sure that the + # given version is contained within all of them. + # Note: This use of all() here means that an empty set of specifiers + # will always return True, this is an explicit design decision. + return all(s.contains(item, prereleases=prereleases) for s in self._specs) + + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None + ) -> Iterator[UnparsedVersionVar]: + """Filter items in the given iterable, that match the specifiers in this set. + + :param iterable: + An iterable that can contain version strings and :class:`Version` instances. + The items in the iterable will be filtered according to the specifier. + :param prereleases: + Whether or not to allow prereleases in the returned iterator. If set to + ``None`` (the default), it will be intelligently decide whether to allow + prereleases or not (based on the :attr:`prereleases` attribute, and + whether the only versions matching are prereleases). + + This method is smarter than just ``filter(SpecifierSet(...).contains, [...])`` + because it implements the rule from :pep:`440` that a prerelease item + SHOULD be accepted if no other versions match the given specifier. + + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) + ['1.3'] + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")])) + ['1.3', ] + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"])) + [] + >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + + An "empty" SpecifierSet will filter items based on the presence of prerelease + versions in the set. + + >>> list(SpecifierSet("").filter(["1.3", "1.5a1"])) + ['1.3'] + >>> list(SpecifierSet("").filter(["1.5a1"])) + ['1.5a1'] + >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + """ + # Determine if we're forcing a prerelease or not, if we're not forcing + # one for this particular filter call, then we'll use whatever the + # SpecifierSet thinks for whether or not we should support prereleases. + if prereleases is None: + prereleases = self.prereleases + + # If we have any specifiers, then we want to wrap our iterable in the + # filter method for each one, this will act as a logical AND amongst + # each specifier. + if self._specs: + for spec in self._specs: + iterable = spec.filter(iterable, prereleases=bool(prereleases)) + return iter(iterable) + # If we do not have any specifiers, then we need to have a rough filter + # which will filter out any pre-releases, unless there are no final + # releases. + else: + filtered: List[UnparsedVersionVar] = [] + found_prereleases: List[UnparsedVersionVar] = [] + + for item in iterable: + parsed_version = _coerce_version(item) + + # Store any item which is a pre-release for later unless we've + # already found a final version or we are accepting prereleases + if parsed_version.is_prerelease and not prereleases: + if not filtered: + found_prereleases.append(item) + else: + filtered.append(item) + + # If we've found no items except for pre-releases, then we'll go + # ahead and use the pre-releases + if not filtered and found_prereleases and prereleases is None: + return iter(found_prereleases) + + return iter(filtered) diff --git a/shared/package-files/35/35818ccad5de9cb5d27b645971176cdf219f1e5bd0c0a9a97a0903b8a9c31fc8/k1.h b/shared/package-files/35/35818ccad5de9cb5d27b645971176cdf219f1e5bd0c0a9a97a0903b8a9c31fc8/k1.h new file mode 100644 index 0000000000000000000000000000000000000000..96594fd9c345e6fd2ecf02a269601cd2d9592525 --- /dev/null +++ b/shared/package-files/35/35818ccad5de9cb5d27b645971176cdf219f1e5bd0c0a9a97a0903b8a9c31fc8/k1.h @@ -0,0 +1,163 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* k1.c + * + * Modified Bessel function, third kind, order one + * + * + * + * SYNOPSIS: + * + * double x, y, k1(); + * + * y = k1( x ); + * + * + * + * DESCRIPTION: + * + * Computes the modified Bessel function of the third kind + * of order one of the argument. + * + * The range is partitioned into the two intervals [0,2] and + * (2, infinity). Chebyshev polynomial expansions are employed + * in each interval. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 1.2e-15 1.6e-16 + * + * ERROR MESSAGES: + * + * message condition value returned + * k1 domain x <= 0 INFINITY + * + */ +/* k1e.c + * + * Modified Bessel function, third kind, order one, + * exponentially scaled + * + * + * + * SYNOPSIS: + * + * double x, y, k1e(); + * + * y = k1e( x ); + * + * + * + * DESCRIPTION: + * + * Returns exponentially scaled modified Bessel function + * of the third kind of order one of the argument: + * + * k1e(x) = exp(x) * k1(x). + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 7.8e-16 1.2e-16 + * See k1(). + * + */ + +/* + * Cephes Math Library Release 2.8: June, 2000 + * Copyright 1984, 1987, 2000 by Stephen L. Moshier + */ +#pragma once + +#include "../config.h" +#include "../error.h" + +#include "chbevl.h" +#include "const.h" + +namespace xsf { +namespace cephes { + + namespace detail { + /* Chebyshev coefficients for x(K1(x) - log(x/2) I1(x)) + * in the interval [0,2]. + * + * lim(x->0){ x(K1(x) - log(x/2) I1(x)) } = 1. + */ + + constexpr double k1_A[] = { + -7.02386347938628759343E-18, -2.42744985051936593393E-15, -6.66690169419932900609E-13, + -1.41148839263352776110E-10, -2.21338763073472585583E-8, -2.43340614156596823496E-6, + -1.73028895751305206302E-4, -6.97572385963986435018E-3, -1.22611180822657148235E-1, + -3.53155960776544875667E-1, 1.52530022733894777053E0}; + + /* Chebyshev coefficients for exp(x) sqrt(x) K1(x) + * in the interval [2,infinity]. + * + * lim(x->inf){ exp(x) sqrt(x) K1(x) } = sqrt(pi/2). + */ + constexpr double k1_B[] = { + -5.75674448366501715755E-18, 1.79405087314755922667E-17, -5.68946255844285935196E-17, + 1.83809354436663880070E-16, -6.05704724837331885336E-16, 2.03870316562433424052E-15, + -7.01983709041831346144E-15, 2.47715442448130437068E-14, -8.97670518232499435011E-14, + 3.34841966607842919884E-13, -1.28917396095102890680E-12, 5.13963967348173025100E-12, + -2.12996783842756842877E-11, 9.21831518760500529508E-11, -4.19035475934189648750E-10, + 2.01504975519703286596E-9, -1.03457624656780970260E-8, 5.74108412545004946722E-8, + -3.50196060308781257119E-7, 2.40648494783721712015E-6, -1.93619797416608296024E-5, + 1.95215518471351631108E-4, -2.85781685962277938680E-3, 1.03923736576817238437E-1, + 2.72062619048444266945E0}; + + } // namespace detail + + XSF_HOST_DEVICE inline double k1(double x) { + double y, z; + + if (x == 0.0) { + set_error("k1", SF_ERROR_SINGULAR, NULL); + return std::numeric_limits::infinity(); + } else if (x < 0.0) { + set_error("k1", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + z = 0.5 * x; + + if (x <= 2.0) { + y = x * x - 2.0; + y = std::log(z) * i1(x) + chbevl(y, detail::k1_A, 11) / x; + return (y); + } + + return (std::exp(-x) * chbevl(8.0 / x - 2.0, detail::k1_B, 25) / std::sqrt(x)); + } + + XSF_HOST_DEVICE double k1e(double x) { + double y; + + if (x == 0.0) { + set_error("k1e", SF_ERROR_SINGULAR, NULL); + return std::numeric_limits::infinity(); + } else if (x < 0.0) { + set_error("k1e", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + + if (x <= 2.0) { + y = x * x - 2.0; + y = std::log(0.5 * x) * i1(x) + chbevl(y, detail::k1_A, 11) / x; + return (y * exp(x)); + } + + return (chbevl(8.0 / x - 2.0, detail::k1_B, 25) / std::sqrt(x)); + } + +} // namespace cephes +} // namespace xsf diff --git a/shared/package-files/35/3584ea5e1c76b1590ea26cdb2642eb9d8a0ce06df0d52925a5f80e9ec2ed814e/triu_indices_cuda_dispatch.h b/shared/package-files/35/3584ea5e1c76b1590ea26cdb2642eb9d8a0ce06df0d52925a5f80e9ec2ed814e/triu_indices_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..12c2ca49bb344b59345d2f281530afca9350a2e4 --- /dev/null +++ b/shared/package-files/35/3584ea5e1c76b1590ea26cdb2642eb9d8a0ce06df0d52925a5f80e9ec2ed814e/triu_indices_cuda_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor triu_indices(int64_t row, int64_t col, int64_t offset=0, at::TensorOptions options=at::kLong); +TORCH_API at::Tensor triu_indices(int64_t row, int64_t col, int64_t offset, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/35/3588b37c682525f86ab7f18cb524977fb6105c81071c2889fd8fea68b55e88e2/__init__.py b/shared/package-files/35/3588b37c682525f86ab7f18cb524977fb6105c81071c2889fd8fea68b55e88e2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3997f84c3dd9a8a5e2b20d0740dbf9a379cb6967 --- /dev/null +++ b/shared/package-files/35/3588b37c682525f86ab7f18cb524977fb6105c81071c2889fd8fea68b55e88e2/__init__.py @@ -0,0 +1,33 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS rdata type classes""" + +__all__ = [ + "ANY", + "IN", + "CH", + "dnskeybase", + "dsbase", + "euibase", + "mxbase", + "nsbase", + "svcbbase", + "tlsabase", + "txtbase", + "util", +] diff --git a/shared/package-files/35/358a5cb1568e31febc25e1342d00bc1dd194f3207be7a1408f566dc16872e5d3/hardtanh_backward_ops.h b/shared/package-files/35/358a5cb1568e31febc25e1342d00bc1dd194f3207be7a1408f566dc16872e5d3/hardtanh_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..56da58886c8c7a4cb9f037f17e1e0df27ba78250 --- /dev/null +++ b/shared/package-files/35/358a5cb1568e31febc25e1342d00bc1dd194f3207be7a1408f566dc16872e5d3/hardtanh_backward_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API hardtanh_backward_grad_input { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::hardtanh_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "grad_input") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "hardtanh_backward.grad_input(Tensor grad_output, Tensor self, Scalar min_val, Scalar max_val, *, Tensor(a!) grad_input) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val, at::Tensor & grad_input); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val, at::Tensor & grad_input); +}; + +struct TORCH_API hardtanh_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::hardtanh_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "hardtanh_backward(Tensor grad_output, Tensor self, Scalar min_val, Scalar max_val) -> Tensor") + static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/35/358efd35cd7b715026b19628c9bcf1a9e38feecebdf4cd40b40b1acb119bcfa8/test_events.py b/shared/package-files/35/358efd35cd7b715026b19628c9bcf1a9e38feecebdf4cd40b40b1acb119bcfa8/test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..61bc01d40e5a6317e7ea96e8d40ad5e6eecbe76b --- /dev/null +++ b/shared/package-files/35/358efd35cd7b715026b19628c9bcf1a9e38feecebdf4cd40b40b1acb119bcfa8/test_events.py @@ -0,0 +1,78 @@ +import unittest +from unittest.mock import Mock + +from IPython.core import events +import IPython.testing.tools as tt + + +@events._define_event +def ping_received(): + pass + + +@events._define_event +def event_with_argument(argument): + pass + + +class CallbackTests(unittest.TestCase): + def setUp(self): + self.em = events.EventManager(get_ipython(), + {'ping_received': ping_received, + 'event_with_argument': event_with_argument}) + + def test_register_unregister(self): + cb = Mock() + + self.em.register('ping_received', cb) + self.em.trigger('ping_received') + self.assertEqual(cb.call_count, 1) + + self.em.unregister('ping_received', cb) + self.em.trigger('ping_received') + self.assertEqual(cb.call_count, 1) + + def test_bare_function_missed_unregister(self): + def cb1(): + ... + + def cb2(): + ... + + self.em.register("ping_received", cb1) + self.assertRaises(ValueError, self.em.unregister, "ping_received", cb2) + self.em.unregister("ping_received", cb1) + + def test_cb_error(self): + cb = Mock(side_effect=ValueError) + self.em.register('ping_received', cb) + with tt.AssertPrints("Error in callback"): + self.em.trigger('ping_received') + + def test_cb_keyboard_interrupt(self): + cb = Mock(side_effect=KeyboardInterrupt) + self.em.register('ping_received', cb) + with tt.AssertPrints("Error in callback"): + self.em.trigger('ping_received') + + def test_unregister_during_callback(self): + invoked = [False] * 3 + + def func1(*_): + invoked[0] = True + self.em.unregister('ping_received', func1) + self.em.register('ping_received', func3) + + def func2(*_): + invoked[1] = True + self.em.unregister('ping_received', func2) + + def func3(*_): + invoked[2] = True + + self.em.register('ping_received', func1) + self.em.register('ping_received', func2) + + self.em.trigger('ping_received') + self.assertEqual([True, True, False], invoked) + self.assertEqual([func3], self.em.callbacks['ping_received']) diff --git a/shared/package-files/35/35908a8c86e5717f7d7e8a99ca9e758b4febf29d2bd55295199166435fff9049/chebyshev.py b/shared/package-files/35/35908a8c86e5717f7d7e8a99ca9e758b4febf29d2bd55295199166435fff9049/chebyshev.py new file mode 100644 index 0000000000000000000000000000000000000000..efbe13e0cadb27e29bea430a858dea5110621a0c --- /dev/null +++ b/shared/package-files/35/35908a8c86e5717f7d7e8a99ca9e758b4febf29d2bd55295199166435fff9049/chebyshev.py @@ -0,0 +1,2082 @@ +""" +==================================================== +Chebyshev Series (:mod:`numpy.polynomial.chebyshev`) +==================================================== + +This module provides a number of objects (mostly functions) useful for +dealing with Chebyshev series, including a `Chebyshev` class that +encapsulates the usual arithmetic operations. (General information +on how this module represents and works with such polynomials is in the +docstring for its "parent" sub-package, `numpy.polynomial`). + +Classes +------- + +.. autosummary:: + :toctree: generated/ + + Chebyshev + + +Constants +--------- + +.. autosummary:: + :toctree: generated/ + + chebdomain + chebzero + chebone + chebx + +Arithmetic +---------- + +.. autosummary:: + :toctree: generated/ + + chebadd + chebsub + chebmulx + chebmul + chebdiv + chebpow + chebval + chebval2d + chebval3d + chebgrid2d + chebgrid3d + +Calculus +-------- + +.. autosummary:: + :toctree: generated/ + + chebder + chebint + +Misc Functions +-------------- + +.. autosummary:: + :toctree: generated/ + + chebfromroots + chebroots + chebvander + chebvander2d + chebvander3d + chebgauss + chebweight + chebcompanion + chebfit + chebpts1 + chebpts2 + chebtrim + chebline + cheb2poly + poly2cheb + chebinterpolate + +See also +-------- +`numpy.polynomial` + +Notes +----- +The implementations of multiplication, division, integration, and +differentiation use the algebraic identities [1]_: + +.. math:: + T_n(x) = \\frac{z^n + z^{-n}}{2} \\\\ + z\\frac{dx}{dz} = \\frac{z - z^{-1}}{2}. + +where + +.. math:: x = \\frac{z + z^{-1}}{2}. + +These identities allow a Chebyshev series to be expressed as a finite, +symmetric Laurent series. In this module, this sort of Laurent series +is referred to as a "z-series." + +References +---------- +.. [1] A. T. Benjamin, et al., "Combinatorial Trigonometry with Chebyshev + Polynomials," *Journal of Statistical Planning and Inference 14*, 2008 + (https://web.archive.org/web/20080221202153/https://www.math.hmc.edu/~benjamin/papers/CombTrig.pdf, pg. 4) + +""" +import numpy as np +import numpy.linalg as la +from numpy.core.multiarray import normalize_axis_index + +from . import polyutils as pu +from ._polybase import ABCPolyBase + +__all__ = [ + 'chebzero', 'chebone', 'chebx', 'chebdomain', 'chebline', 'chebadd', + 'chebsub', 'chebmulx', 'chebmul', 'chebdiv', 'chebpow', 'chebval', + 'chebder', 'chebint', 'cheb2poly', 'poly2cheb', 'chebfromroots', + 'chebvander', 'chebfit', 'chebtrim', 'chebroots', 'chebpts1', + 'chebpts2', 'Chebyshev', 'chebval2d', 'chebval3d', 'chebgrid2d', + 'chebgrid3d', 'chebvander2d', 'chebvander3d', 'chebcompanion', + 'chebgauss', 'chebweight', 'chebinterpolate'] + +chebtrim = pu.trimcoef + +# +# A collection of functions for manipulating z-series. These are private +# functions and do minimal error checking. +# + +def _cseries_to_zseries(c): + """Convert Chebyshev series to z-series. + + Convert a Chebyshev series to the equivalent z-series. The result is + never an empty array. The dtype of the return is the same as that of + the input. No checks are run on the arguments as this routine is for + internal use. + + Parameters + ---------- + c : 1-D ndarray + Chebyshev coefficients, ordered from low to high + + Returns + ------- + zs : 1-D ndarray + Odd length symmetric z-series, ordered from low to high. + + """ + n = c.size + zs = np.zeros(2*n-1, dtype=c.dtype) + zs[n-1:] = c/2 + return zs + zs[::-1] + + +def _zseries_to_cseries(zs): + """Convert z-series to a Chebyshev series. + + Convert a z series to the equivalent Chebyshev series. The result is + never an empty array. The dtype of the return is the same as that of + the input. No checks are run on the arguments as this routine is for + internal use. + + Parameters + ---------- + zs : 1-D ndarray + Odd length symmetric z-series, ordered from low to high. + + Returns + ------- + c : 1-D ndarray + Chebyshev coefficients, ordered from low to high. + + """ + n = (zs.size + 1)//2 + c = zs[n-1:].copy() + c[1:n] *= 2 + return c + + +def _zseries_mul(z1, z2): + """Multiply two z-series. + + Multiply two z-series to produce a z-series. + + Parameters + ---------- + z1, z2 : 1-D ndarray + The arrays must be 1-D but this is not checked. + + Returns + ------- + product : 1-D ndarray + The product z-series. + + Notes + ----- + This is simply convolution. If symmetric/anti-symmetric z-series are + denoted by S/A then the following rules apply: + + S*S, A*A -> S + S*A, A*S -> A + + """ + return np.convolve(z1, z2) + + +def _zseries_div(z1, z2): + """Divide the first z-series by the second. + + Divide `z1` by `z2` and return the quotient and remainder as z-series. + Warning: this implementation only applies when both z1 and z2 have the + same symmetry, which is sufficient for present purposes. + + Parameters + ---------- + z1, z2 : 1-D ndarray + The arrays must be 1-D and have the same symmetry, but this is not + checked. + + Returns + ------- + + (quotient, remainder) : 1-D ndarrays + Quotient and remainder as z-series. + + Notes + ----- + This is not the same as polynomial division on account of the desired form + of the remainder. If symmetric/anti-symmetric z-series are denoted by S/A + then the following rules apply: + + S/S -> S,S + A/A -> S,A + + The restriction to types of the same symmetry could be fixed but seems like + unneeded generality. There is no natural form for the remainder in the case + where there is no symmetry. + + """ + z1 = z1.copy() + z2 = z2.copy() + lc1 = len(z1) + lc2 = len(z2) + if lc2 == 1: + z1 /= z2 + return z1, z1[:1]*0 + elif lc1 < lc2: + return z1[:1]*0, z1 + else: + dlen = lc1 - lc2 + scl = z2[0] + z2 /= scl + quo = np.empty(dlen + 1, dtype=z1.dtype) + i = 0 + j = dlen + while i < j: + r = z1[i] + quo[i] = z1[i] + quo[dlen - i] = r + tmp = r*z2 + z1[i:i+lc2] -= tmp + z1[j:j+lc2] -= tmp + i += 1 + j -= 1 + r = z1[i] + quo[i] = r + tmp = r*z2 + z1[i:i+lc2] -= tmp + quo /= scl + rem = z1[i+1:i-1+lc2].copy() + return quo, rem + + +def _zseries_der(zs): + """Differentiate a z-series. + + The derivative is with respect to x, not z. This is achieved using the + chain rule and the value of dx/dz given in the module notes. + + Parameters + ---------- + zs : z-series + The z-series to differentiate. + + Returns + ------- + derivative : z-series + The derivative + + Notes + ----- + The zseries for x (ns) has been multiplied by two in order to avoid + using floats that are incompatible with Decimal and likely other + specialized scalar types. This scaling has been compensated by + multiplying the value of zs by two also so that the two cancels in the + division. + + """ + n = len(zs)//2 + ns = np.array([-1, 0, 1], dtype=zs.dtype) + zs *= np.arange(-n, n+1)*2 + d, r = _zseries_div(zs, ns) + return d + + +def _zseries_int(zs): + """Integrate a z-series. + + The integral is with respect to x, not z. This is achieved by a change + of variable using dx/dz given in the module notes. + + Parameters + ---------- + zs : z-series + The z-series to integrate + + Returns + ------- + integral : z-series + The indefinite integral + + Notes + ----- + The zseries for x (ns) has been multiplied by two in order to avoid + using floats that are incompatible with Decimal and likely other + specialized scalar types. This scaling has been compensated by + dividing the resulting zs by two. + + """ + n = 1 + len(zs)//2 + ns = np.array([-1, 0, 1], dtype=zs.dtype) + zs = _zseries_mul(zs, ns) + div = np.arange(-n, n+1)*2 + zs[:n] /= div[:n] + zs[n+1:] /= div[n+1:] + zs[n] = 0 + return zs + +# +# Chebyshev series functions +# + + +def poly2cheb(pol): + """ + Convert a polynomial to a Chebyshev series. + + Convert an array representing the coefficients of a polynomial (relative + to the "standard" basis) ordered from lowest degree to highest, to an + array of the coefficients of the equivalent Chebyshev series, ordered + from lowest to highest degree. + + Parameters + ---------- + pol : array_like + 1-D array containing the polynomial coefficients + + Returns + ------- + c : ndarray + 1-D array containing the coefficients of the equivalent Chebyshev + series. + + See Also + -------- + cheb2poly + + Notes + ----- + The easy way to do conversions between polynomial basis sets + is to use the convert method of a class instance. + + Examples + -------- + >>> from numpy import polynomial as P + >>> p = P.Polynomial(range(4)) + >>> p + Polynomial([0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1]) + >>> c = p.convert(kind=P.Chebyshev) + >>> c + Chebyshev([1. , 3.25, 1. , 0.75], domain=[-1., 1.], window=[-1., 1.]) + >>> P.chebyshev.poly2cheb(range(4)) + array([1. , 3.25, 1. , 0.75]) + + """ + [pol] = pu.as_series([pol]) + deg = len(pol) - 1 + res = 0 + for i in range(deg, -1, -1): + res = chebadd(chebmulx(res), pol[i]) + return res + + +def cheb2poly(c): + """ + Convert a Chebyshev series to a polynomial. + + Convert an array representing the coefficients of a Chebyshev series, + ordered from lowest degree to highest, to an array of the coefficients + of the equivalent polynomial (relative to the "standard" basis) ordered + from lowest to highest degree. + + Parameters + ---------- + c : array_like + 1-D array containing the Chebyshev series coefficients, ordered + from lowest order term to highest. + + Returns + ------- + pol : ndarray + 1-D array containing the coefficients of the equivalent polynomial + (relative to the "standard" basis) ordered from lowest order term + to highest. + + See Also + -------- + poly2cheb + + Notes + ----- + The easy way to do conversions between polynomial basis sets + is to use the convert method of a class instance. + + Examples + -------- + >>> from numpy import polynomial as P + >>> c = P.Chebyshev(range(4)) + >>> c + Chebyshev([0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1]) + >>> p = c.convert(kind=P.Polynomial) + >>> p + Polynomial([-2., -8., 4., 12.], domain=[-1., 1.], window=[-1., 1.]) + >>> P.chebyshev.cheb2poly(range(4)) + array([-2., -8., 4., 12.]) + + """ + from .polynomial import polyadd, polysub, polymulx + + [c] = pu.as_series([c]) + n = len(c) + if n < 3: + return c + else: + c0 = c[-2] + c1 = c[-1] + # i is the current degree of c1 + for i in range(n - 1, 1, -1): + tmp = c0 + c0 = polysub(c[i - 2], c1) + c1 = polyadd(tmp, polymulx(c1)*2) + return polyadd(c0, polymulx(c1)) + + +# +# These are constant arrays are of integer type so as to be compatible +# with the widest range of other types, such as Decimal. +# + +# Chebyshev default domain. +chebdomain = np.array([-1, 1]) + +# Chebyshev coefficients representing zero. +chebzero = np.array([0]) + +# Chebyshev coefficients representing one. +chebone = np.array([1]) + +# Chebyshev coefficients representing the identity x. +chebx = np.array([0, 1]) + + +def chebline(off, scl): + """ + Chebyshev series whose graph is a straight line. + + Parameters + ---------- + off, scl : scalars + The specified line is given by ``off + scl*x``. + + Returns + ------- + y : ndarray + This module's representation of the Chebyshev series for + ``off + scl*x``. + + See Also + -------- + numpy.polynomial.polynomial.polyline + numpy.polynomial.legendre.legline + numpy.polynomial.laguerre.lagline + numpy.polynomial.hermite.hermline + numpy.polynomial.hermite_e.hermeline + + Examples + -------- + >>> import numpy.polynomial.chebyshev as C + >>> C.chebline(3,2) + array([3, 2]) + >>> C.chebval(-3, C.chebline(3,2)) # should be -3 + -3.0 + + """ + if scl != 0: + return np.array([off, scl]) + else: + return np.array([off]) + + +def chebfromroots(roots): + """ + Generate a Chebyshev series with given roots. + + The function returns the coefficients of the polynomial + + .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n), + + in Chebyshev form, where the `r_n` are the roots specified in `roots`. + If a zero has multiplicity n, then it must appear in `roots` n times. + For instance, if 2 is a root of multiplicity three and 3 is a root of + multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The + roots can appear in any order. + + If the returned coefficients are `c`, then + + .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x) + + The coefficient of the last term is not generally 1 for monic + polynomials in Chebyshev form. + + Parameters + ---------- + roots : array_like + Sequence containing the roots. + + Returns + ------- + out : ndarray + 1-D array of coefficients. If all roots are real then `out` is a + real array, if some of the roots are complex, then `out` is complex + even if all the coefficients in the result are real (see Examples + below). + + See Also + -------- + numpy.polynomial.polynomial.polyfromroots + numpy.polynomial.legendre.legfromroots + numpy.polynomial.laguerre.lagfromroots + numpy.polynomial.hermite.hermfromroots + numpy.polynomial.hermite_e.hermefromroots + + Examples + -------- + >>> import numpy.polynomial.chebyshev as C + >>> C.chebfromroots((-1,0,1)) # x^3 - x relative to the standard basis + array([ 0. , -0.25, 0. , 0.25]) + >>> j = complex(0,1) + >>> C.chebfromroots((-j,j)) # x^2 + 1 relative to the standard basis + array([1.5+0.j, 0. +0.j, 0.5+0.j]) + + """ + return pu._fromroots(chebline, chebmul, roots) + + +def chebadd(c1, c2): + """ + Add one Chebyshev series to another. + + Returns the sum of two Chebyshev series `c1` + `c2`. The arguments + are sequences of coefficients ordered from lowest order term to + highest, i.e., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. + + Parameters + ---------- + c1, c2 : array_like + 1-D arrays of Chebyshev series coefficients ordered from low to + high. + + Returns + ------- + out : ndarray + Array representing the Chebyshev series of their sum. + + See Also + -------- + chebsub, chebmulx, chebmul, chebdiv, chebpow + + Notes + ----- + Unlike multiplication, division, etc., the sum of two Chebyshev series + is a Chebyshev series (without having to "reproject" the result onto + the basis set) so addition, just like that of "standard" polynomials, + is simply "component-wise." + + Examples + -------- + >>> from numpy.polynomial import chebyshev as C + >>> c1 = (1,2,3) + >>> c2 = (3,2,1) + >>> C.chebadd(c1,c2) + array([4., 4., 4.]) + + """ + return pu._add(c1, c2) + + +def chebsub(c1, c2): + """ + Subtract one Chebyshev series from another. + + Returns the difference of two Chebyshev series `c1` - `c2`. The + sequences of coefficients are from lowest order term to highest, i.e., + [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. + + Parameters + ---------- + c1, c2 : array_like + 1-D arrays of Chebyshev series coefficients ordered from low to + high. + + Returns + ------- + out : ndarray + Of Chebyshev series coefficients representing their difference. + + See Also + -------- + chebadd, chebmulx, chebmul, chebdiv, chebpow + + Notes + ----- + Unlike multiplication, division, etc., the difference of two Chebyshev + series is a Chebyshev series (without having to "reproject" the result + onto the basis set) so subtraction, just like that of "standard" + polynomials, is simply "component-wise." + + Examples + -------- + >>> from numpy.polynomial import chebyshev as C + >>> c1 = (1,2,3) + >>> c2 = (3,2,1) + >>> C.chebsub(c1,c2) + array([-2., 0., 2.]) + >>> C.chebsub(c2,c1) # -C.chebsub(c1,c2) + array([ 2., 0., -2.]) + + """ + return pu._sub(c1, c2) + + +def chebmulx(c): + """Multiply a Chebyshev series by x. + + Multiply the polynomial `c` by x, where x is the independent + variable. + + + Parameters + ---------- + c : array_like + 1-D array of Chebyshev series coefficients ordered from low to + high. + + Returns + ------- + out : ndarray + Array representing the result of the multiplication. + + Notes + ----- + + .. versionadded:: 1.5.0 + + Examples + -------- + >>> from numpy.polynomial import chebyshev as C + >>> C.chebmulx([1,2,3]) + array([1. , 2.5, 1. , 1.5]) + + """ + # c is a trimmed copy + [c] = pu.as_series([c]) + # The zero series needs special treatment + if len(c) == 1 and c[0] == 0: + return c + + prd = np.empty(len(c) + 1, dtype=c.dtype) + prd[0] = c[0]*0 + prd[1] = c[0] + if len(c) > 1: + tmp = c[1:]/2 + prd[2:] = tmp + prd[0:-2] += tmp + return prd + + +def chebmul(c1, c2): + """ + Multiply one Chebyshev series by another. + + Returns the product of two Chebyshev series `c1` * `c2`. The arguments + are sequences of coefficients, from lowest order "term" to highest, + e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. + + Parameters + ---------- + c1, c2 : array_like + 1-D arrays of Chebyshev series coefficients ordered from low to + high. + + Returns + ------- + out : ndarray + Of Chebyshev series coefficients representing their product. + + See Also + -------- + chebadd, chebsub, chebmulx, chebdiv, chebpow + + Notes + ----- + In general, the (polynomial) product of two C-series results in terms + that are not in the Chebyshev polynomial basis set. Thus, to express + the product as a C-series, it is typically necessary to "reproject" + the product onto said basis set, which typically produces + "unintuitive live" (but correct) results; see Examples section below. + + Examples + -------- + >>> from numpy.polynomial import chebyshev as C + >>> c1 = (1,2,3) + >>> c2 = (3,2,1) + >>> C.chebmul(c1,c2) # multiplication requires "reprojection" + array([ 6.5, 12. , 12. , 4. , 1.5]) + + """ + # c1, c2 are trimmed copies + [c1, c2] = pu.as_series([c1, c2]) + z1 = _cseries_to_zseries(c1) + z2 = _cseries_to_zseries(c2) + prd = _zseries_mul(z1, z2) + ret = _zseries_to_cseries(prd) + return pu.trimseq(ret) + + +def chebdiv(c1, c2): + """ + Divide one Chebyshev series by another. + + Returns the quotient-with-remainder of two Chebyshev series + `c1` / `c2`. The arguments are sequences of coefficients from lowest + order "term" to highest, e.g., [1,2,3] represents the series + ``T_0 + 2*T_1 + 3*T_2``. + + Parameters + ---------- + c1, c2 : array_like + 1-D arrays of Chebyshev series coefficients ordered from low to + high. + + Returns + ------- + [quo, rem] : ndarrays + Of Chebyshev series coefficients representing the quotient and + remainder. + + See Also + -------- + chebadd, chebsub, chebmulx, chebmul, chebpow + + Notes + ----- + In general, the (polynomial) division of one C-series by another + results in quotient and remainder terms that are not in the Chebyshev + polynomial basis set. Thus, to express these results as C-series, it + is typically necessary to "reproject" the results onto said basis + set, which typically produces "unintuitive" (but correct) results; + see Examples section below. + + Examples + -------- + >>> from numpy.polynomial import chebyshev as C + >>> c1 = (1,2,3) + >>> c2 = (3,2,1) + >>> C.chebdiv(c1,c2) # quotient "intuitive," remainder not + (array([3.]), array([-8., -4.])) + >>> c2 = (0,1,2,3) + >>> C.chebdiv(c2,c1) # neither "intuitive" + (array([0., 2.]), array([-2., -4.])) + + """ + # c1, c2 are trimmed copies + [c1, c2] = pu.as_series([c1, c2]) + if c2[-1] == 0: + raise ZeroDivisionError() + + # note: this is more efficient than `pu._div(chebmul, c1, c2)` + lc1 = len(c1) + lc2 = len(c2) + if lc1 < lc2: + return c1[:1]*0, c1 + elif lc2 == 1: + return c1/c2[-1], c1[:1]*0 + else: + z1 = _cseries_to_zseries(c1) + z2 = _cseries_to_zseries(c2) + quo, rem = _zseries_div(z1, z2) + quo = pu.trimseq(_zseries_to_cseries(quo)) + rem = pu.trimseq(_zseries_to_cseries(rem)) + return quo, rem + + +def chebpow(c, pow, maxpower=16): + """Raise a Chebyshev series to a power. + + Returns the Chebyshev series `c` raised to the power `pow`. The + argument `c` is a sequence of coefficients ordered from low to high. + i.e., [1,2,3] is the series ``T_0 + 2*T_1 + 3*T_2.`` + + Parameters + ---------- + c : array_like + 1-D array of Chebyshev series coefficients ordered from low to + high. + pow : integer + Power to which the series will be raised + maxpower : integer, optional + Maximum power allowed. This is mainly to limit growth of the series + to unmanageable size. Default is 16 + + Returns + ------- + coef : ndarray + Chebyshev series of power. + + See Also + -------- + chebadd, chebsub, chebmulx, chebmul, chebdiv + + Examples + -------- + >>> from numpy.polynomial import chebyshev as C + >>> C.chebpow([1, 2, 3, 4], 2) + array([15.5, 22. , 16. , ..., 12.5, 12. , 8. ]) + + """ + # note: this is more efficient than `pu._pow(chebmul, c1, c2)`, as it + # avoids converting between z and c series repeatedly + + # c is a trimmed copy + [c] = pu.as_series([c]) + power = int(pow) + if power != pow or power < 0: + raise ValueError("Power must be a non-negative integer.") + elif maxpower is not None and power > maxpower: + raise ValueError("Power is too large") + elif power == 0: + return np.array([1], dtype=c.dtype) + elif power == 1: + return c + else: + # This can be made more efficient by using powers of two + # in the usual way. + zs = _cseries_to_zseries(c) + prd = zs + for i in range(2, power + 1): + prd = np.convolve(prd, zs) + return _zseries_to_cseries(prd) + + +def chebder(c, m=1, scl=1, axis=0): + """ + Differentiate a Chebyshev series. + + Returns the Chebyshev series coefficients `c` differentiated `m` times + along `axis`. At each iteration the result is multiplied by `scl` (the + scaling factor is for use in a linear change of variable). The argument + `c` is an array of coefficients from low to high degree along each + axis, e.g., [1,2,3] represents the series ``1*T_0 + 2*T_1 + 3*T_2`` + while [[1,2],[1,2]] represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + + 2*T_0(x)*T_1(y) + 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is + ``y``. + + Parameters + ---------- + c : array_like + Array of Chebyshev series coefficients. If c is multidimensional + the different axis correspond to different variables with the + degree in each axis given by the corresponding index. + m : int, optional + Number of derivatives taken, must be non-negative. (Default: 1) + scl : scalar, optional + Each differentiation is multiplied by `scl`. The end result is + multiplication by ``scl**m``. This is for use in a linear change of + variable. (Default: 1) + axis : int, optional + Axis over which the derivative is taken. (Default: 0). + + .. versionadded:: 1.7.0 + + Returns + ------- + der : ndarray + Chebyshev series of the derivative. + + See Also + -------- + chebint + + Notes + ----- + In general, the result of differentiating a C-series needs to be + "reprojected" onto the C-series basis set. Thus, typically, the + result of this function is "unintuitive," albeit correct; see Examples + section below. + + Examples + -------- + >>> from numpy.polynomial import chebyshev as C + >>> c = (1,2,3,4) + >>> C.chebder(c) + array([14., 12., 24.]) + >>> C.chebder(c,3) + array([96.]) + >>> C.chebder(c,scl=-1) + array([-14., -12., -24.]) + >>> C.chebder(c,2,-1) + array([12., 96.]) + + """ + c = np.array(c, ndmin=1, copy=True) + if c.dtype.char in '?bBhHiIlLqQpP': + c = c.astype(np.double) + cnt = pu._deprecate_as_int(m, "the order of derivation") + iaxis = pu._deprecate_as_int(axis, "the axis") + if cnt < 0: + raise ValueError("The order of derivation must be non-negative") + iaxis = normalize_axis_index(iaxis, c.ndim) + + if cnt == 0: + return c + + c = np.moveaxis(c, iaxis, 0) + n = len(c) + if cnt >= n: + c = c[:1]*0 + else: + for i in range(cnt): + n = n - 1 + c *= scl + der = np.empty((n,) + c.shape[1:], dtype=c.dtype) + for j in range(n, 2, -1): + der[j - 1] = (2*j)*c[j] + c[j - 2] += (j*c[j])/(j - 2) + if n > 1: + der[1] = 4*c[2] + der[0] = c[1] + c = der + c = np.moveaxis(c, 0, iaxis) + return c + + +def chebint(c, m=1, k=[], lbnd=0, scl=1, axis=0): + """ + Integrate a Chebyshev series. + + Returns the Chebyshev series coefficients `c` integrated `m` times from + `lbnd` along `axis`. At each iteration the resulting series is + **multiplied** by `scl` and an integration constant, `k`, is added. + The scaling factor is for use in a linear change of variable. ("Buyer + beware": note that, depending on what one is doing, one may want `scl` + to be the reciprocal of what one might expect; for more information, + see the Notes section below.) The argument `c` is an array of + coefficients from low to high degree along each axis, e.g., [1,2,3] + represents the series ``T_0 + 2*T_1 + 3*T_2`` while [[1,2],[1,2]] + represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + 2*T_0(x)*T_1(y) + + 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. + + Parameters + ---------- + c : array_like + Array of Chebyshev series coefficients. If c is multidimensional + the different axis correspond to different variables with the + degree in each axis given by the corresponding index. + m : int, optional + Order of integration, must be positive. (Default: 1) + k : {[], list, scalar}, optional + Integration constant(s). The value of the first integral at zero + is the first value in the list, the value of the second integral + at zero is the second value, etc. If ``k == []`` (the default), + all constants are set to zero. If ``m == 1``, a single scalar can + be given instead of a list. + lbnd : scalar, optional + The lower bound of the integral. (Default: 0) + scl : scalar, optional + Following each integration the result is *multiplied* by `scl` + before the integration constant is added. (Default: 1) + axis : int, optional + Axis over which the integral is taken. (Default: 0). + + .. versionadded:: 1.7.0 + + Returns + ------- + S : ndarray + C-series coefficients of the integral. + + Raises + ------ + ValueError + If ``m < 1``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or + ``np.ndim(scl) != 0``. + + See Also + -------- + chebder + + Notes + ----- + Note that the result of each integration is *multiplied* by `scl`. + Why is this important to note? Say one is making a linear change of + variable :math:`u = ax + b` in an integral relative to `x`. Then + :math:`dx = du/a`, so one will need to set `scl` equal to + :math:`1/a`- perhaps not what one would have first thought. + + Also note that, in general, the result of integrating a C-series needs + to be "reprojected" onto the C-series basis set. Thus, typically, + the result of this function is "unintuitive," albeit correct; see + Examples section below. + + Examples + -------- + >>> from numpy.polynomial import chebyshev as C + >>> c = (1,2,3) + >>> C.chebint(c) + array([ 0.5, -0.5, 0.5, 0.5]) + >>> C.chebint(c,3) + array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667, # may vary + 0.00625 ]) + >>> C.chebint(c, k=3) + array([ 3.5, -0.5, 0.5, 0.5]) + >>> C.chebint(c,lbnd=-2) + array([ 8.5, -0.5, 0.5, 0.5]) + >>> C.chebint(c,scl=-2) + array([-1., 1., -1., -1.]) + + """ + c = np.array(c, ndmin=1, copy=True) + if c.dtype.char in '?bBhHiIlLqQpP': + c = c.astype(np.double) + if not np.iterable(k): + k = [k] + cnt = pu._deprecate_as_int(m, "the order of integration") + iaxis = pu._deprecate_as_int(axis, "the axis") + if cnt < 0: + raise ValueError("The order of integration must be non-negative") + if len(k) > cnt: + raise ValueError("Too many integration constants") + if np.ndim(lbnd) != 0: + raise ValueError("lbnd must be a scalar.") + if np.ndim(scl) != 0: + raise ValueError("scl must be a scalar.") + iaxis = normalize_axis_index(iaxis, c.ndim) + + if cnt == 0: + return c + + c = np.moveaxis(c, iaxis, 0) + k = list(k) + [0]*(cnt - len(k)) + for i in range(cnt): + n = len(c) + c *= scl + if n == 1 and np.all(c[0] == 0): + c[0] += k[i] + else: + tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype) + tmp[0] = c[0]*0 + tmp[1] = c[0] + if n > 1: + tmp[2] = c[1]/4 + for j in range(2, n): + tmp[j + 1] = c[j]/(2*(j + 1)) + tmp[j - 1] -= c[j]/(2*(j - 1)) + tmp[0] += k[i] - chebval(lbnd, tmp) + c = tmp + c = np.moveaxis(c, 0, iaxis) + return c + + +def chebval(x, c, tensor=True): + """ + Evaluate a Chebyshev series at points x. + + If `c` is of length `n + 1`, this function returns the value: + + .. math:: p(x) = c_0 * T_0(x) + c_1 * T_1(x) + ... + c_n * T_n(x) + + The parameter `x` is converted to an array only if it is a tuple or a + list, otherwise it is treated as a scalar. In either case, either `x` + or its elements must support multiplication and addition both with + themselves and with the elements of `c`. + + If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If + `c` is multidimensional, then the shape of the result depends on the + value of `tensor`. If `tensor` is true the shape will be c.shape[1:] + + x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that + scalars have shape (,). + + Trailing zeros in the coefficients will be used in the evaluation, so + they should be avoided if efficiency is a concern. + + Parameters + ---------- + x : array_like, compatible object + If `x` is a list or tuple, it is converted to an ndarray, otherwise + it is left unchanged and treated as a scalar. In either case, `x` + or its elements must support addition and multiplication with + themselves and with the elements of `c`. + c : array_like + Array of coefficients ordered so that the coefficients for terms of + degree n are contained in c[n]. If `c` is multidimensional the + remaining indices enumerate multiple polynomials. In the two + dimensional case the coefficients may be thought of as stored in + the columns of `c`. + tensor : boolean, optional + If True, the shape of the coefficient array is extended with ones + on the right, one for each dimension of `x`. Scalars have dimension 0 + for this action. The result is that every column of coefficients in + `c` is evaluated for every element of `x`. If False, `x` is broadcast + over the columns of `c` for the evaluation. This keyword is useful + when `c` is multidimensional. The default value is True. + + .. versionadded:: 1.7.0 + + Returns + ------- + values : ndarray, algebra_like + The shape of the return value is described above. + + See Also + -------- + chebval2d, chebgrid2d, chebval3d, chebgrid3d + + Notes + ----- + The evaluation uses Clenshaw recursion, aka synthetic division. + + """ + c = np.array(c, ndmin=1, copy=True) + if c.dtype.char in '?bBhHiIlLqQpP': + c = c.astype(np.double) + if isinstance(x, (tuple, list)): + x = np.asarray(x) + if isinstance(x, np.ndarray) and tensor: + c = c.reshape(c.shape + (1,)*x.ndim) + + if len(c) == 1: + c0 = c[0] + c1 = 0 + elif len(c) == 2: + c0 = c[0] + c1 = c[1] + else: + x2 = 2*x + c0 = c[-2] + c1 = c[-1] + for i in range(3, len(c) + 1): + tmp = c0 + c0 = c[-i] - c1 + c1 = tmp + c1*x2 + return c0 + c1*x + + +def chebval2d(x, y, c): + """ + Evaluate a 2-D Chebyshev series at points (x, y). + + This function returns the values: + + .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * T_i(x) * T_j(y) + + The parameters `x` and `y` are converted to arrays only if they are + tuples or a lists, otherwise they are treated as a scalars and they + must have the same shape after conversion. In either case, either `x` + and `y` or their elements must support multiplication and addition both + with themselves and with the elements of `c`. + + If `c` is a 1-D array a one is implicitly appended to its shape to make + it 2-D. The shape of the result will be c.shape[2:] + x.shape. + + Parameters + ---------- + x, y : array_like, compatible objects + The two dimensional series is evaluated at the points `(x, y)`, + where `x` and `y` must have the same shape. If `x` or `y` is a list + or tuple, it is first converted to an ndarray, otherwise it is left + unchanged and if it isn't an ndarray it is treated as a scalar. + c : array_like + Array of coefficients ordered so that the coefficient of the term + of multi-degree i,j is contained in ``c[i,j]``. If `c` has + dimension greater than 2 the remaining indices enumerate multiple + sets of coefficients. + + Returns + ------- + values : ndarray, compatible object + The values of the two dimensional Chebyshev series at points formed + from pairs of corresponding values from `x` and `y`. + + See Also + -------- + chebval, chebgrid2d, chebval3d, chebgrid3d + + Notes + ----- + + .. versionadded:: 1.7.0 + + """ + return pu._valnd(chebval, c, x, y) + + +def chebgrid2d(x, y, c): + """ + Evaluate a 2-D Chebyshev series on the Cartesian product of x and y. + + This function returns the values: + + .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * T_i(a) * T_j(b), + + where the points `(a, b)` consist of all pairs formed by taking + `a` from `x` and `b` from `y`. The resulting points form a grid with + `x` in the first dimension and `y` in the second. + + The parameters `x` and `y` are converted to arrays only if they are + tuples or a lists, otherwise they are treated as a scalars. In either + case, either `x` and `y` or their elements must support multiplication + and addition both with themselves and with the elements of `c`. + + If `c` has fewer than two dimensions, ones are implicitly appended to + its shape to make it 2-D. The shape of the result will be c.shape[2:] + + x.shape + y.shape. + + Parameters + ---------- + x, y : array_like, compatible objects + The two dimensional series is evaluated at the points in the + Cartesian product of `x` and `y`. If `x` or `y` is a list or + tuple, it is first converted to an ndarray, otherwise it is left + unchanged and, if it isn't an ndarray, it is treated as a scalar. + c : array_like + Array of coefficients ordered so that the coefficient of the term of + multi-degree i,j is contained in `c[i,j]`. If `c` has dimension + greater than two the remaining indices enumerate multiple sets of + coefficients. + + Returns + ------- + values : ndarray, compatible object + The values of the two dimensional Chebyshev series at points in the + Cartesian product of `x` and `y`. + + See Also + -------- + chebval, chebval2d, chebval3d, chebgrid3d + + Notes + ----- + + .. versionadded:: 1.7.0 + + """ + return pu._gridnd(chebval, c, x, y) + + +def chebval3d(x, y, z, c): + """ + Evaluate a 3-D Chebyshev series at points (x, y, z). + + This function returns the values: + + .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * T_i(x) * T_j(y) * T_k(z) + + The parameters `x`, `y`, and `z` are converted to arrays only if + they are tuples or a lists, otherwise they are treated as a scalars and + they must have the same shape after conversion. In either case, either + `x`, `y`, and `z` or their elements must support multiplication and + addition both with themselves and with the elements of `c`. + + If `c` has fewer than 3 dimensions, ones are implicitly appended to its + shape to make it 3-D. The shape of the result will be c.shape[3:] + + x.shape. + + Parameters + ---------- + x, y, z : array_like, compatible object + The three dimensional series is evaluated at the points + `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If + any of `x`, `y`, or `z` is a list or tuple, it is first converted + to an ndarray, otherwise it is left unchanged and if it isn't an + ndarray it is treated as a scalar. + c : array_like + Array of coefficients ordered so that the coefficient of the term of + multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension + greater than 3 the remaining indices enumerate multiple sets of + coefficients. + + Returns + ------- + values : ndarray, compatible object + The values of the multidimensional polynomial on points formed with + triples of corresponding values from `x`, `y`, and `z`. + + See Also + -------- + chebval, chebval2d, chebgrid2d, chebgrid3d + + Notes + ----- + + .. versionadded:: 1.7.0 + + """ + return pu._valnd(chebval, c, x, y, z) + + +def chebgrid3d(x, y, z, c): + """ + Evaluate a 3-D Chebyshev series on the Cartesian product of x, y, and z. + + This function returns the values: + + .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * T_i(a) * T_j(b) * T_k(c) + + where the points `(a, b, c)` consist of all triples formed by taking + `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form + a grid with `x` in the first dimension, `y` in the second, and `z` in + the third. + + The parameters `x`, `y`, and `z` are converted to arrays only if they + are tuples or a lists, otherwise they are treated as a scalars. In + either case, either `x`, `y`, and `z` or their elements must support + multiplication and addition both with themselves and with the elements + of `c`. + + If `c` has fewer than three dimensions, ones are implicitly appended to + its shape to make it 3-D. The shape of the result will be c.shape[3:] + + x.shape + y.shape + z.shape. + + Parameters + ---------- + x, y, z : array_like, compatible objects + The three dimensional series is evaluated at the points in the + Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a + list or tuple, it is first converted to an ndarray, otherwise it is + left unchanged and, if it isn't an ndarray, it is treated as a + scalar. + c : array_like + Array of coefficients ordered so that the coefficients for terms of + degree i,j are contained in ``c[i,j]``. If `c` has dimension + greater than two the remaining indices enumerate multiple sets of + coefficients. + + Returns + ------- + values : ndarray, compatible object + The values of the two dimensional polynomial at points in the Cartesian + product of `x` and `y`. + + See Also + -------- + chebval, chebval2d, chebgrid2d, chebval3d + + Notes + ----- + + .. versionadded:: 1.7.0 + + """ + return pu._gridnd(chebval, c, x, y, z) + + +def chebvander(x, deg): + """Pseudo-Vandermonde matrix of given degree. + + Returns the pseudo-Vandermonde matrix of degree `deg` and sample points + `x`. The pseudo-Vandermonde matrix is defined by + + .. math:: V[..., i] = T_i(x), + + where `0 <= i <= deg`. The leading indices of `V` index the elements of + `x` and the last index is the degree of the Chebyshev polynomial. + + If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the + matrix ``V = chebvander(x, n)``, then ``np.dot(V, c)`` and + ``chebval(x, c)`` are the same up to roundoff. This equivalence is + useful both for least squares fitting and for the evaluation of a large + number of Chebyshev series of the same degree and sample points. + + Parameters + ---------- + x : array_like + Array of points. The dtype is converted to float64 or complex128 + depending on whether any of the elements are complex. If `x` is + scalar it is converted to a 1-D array. + deg : int + Degree of the resulting matrix. + + Returns + ------- + vander : ndarray + The pseudo Vandermonde matrix. The shape of the returned matrix is + ``x.shape + (deg + 1,)``, where The last index is the degree of the + corresponding Chebyshev polynomial. The dtype will be the same as + the converted `x`. + + """ + ideg = pu._deprecate_as_int(deg, "deg") + if ideg < 0: + raise ValueError("deg must be non-negative") + + x = np.array(x, copy=False, ndmin=1) + 0.0 + dims = (ideg + 1,) + x.shape + dtyp = x.dtype + v = np.empty(dims, dtype=dtyp) + # Use forward recursion to generate the entries. + v[0] = x*0 + 1 + if ideg > 0: + x2 = 2*x + v[1] = x + for i in range(2, ideg + 1): + v[i] = v[i-1]*x2 - v[i-2] + return np.moveaxis(v, 0, -1) + + +def chebvander2d(x, y, deg): + """Pseudo-Vandermonde matrix of given degrees. + + Returns the pseudo-Vandermonde matrix of degrees `deg` and sample + points `(x, y)`. The pseudo-Vandermonde matrix is defined by + + .. math:: V[..., (deg[1] + 1)*i + j] = T_i(x) * T_j(y), + + where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of + `V` index the points `(x, y)` and the last index encodes the degrees of + the Chebyshev polynomials. + + If ``V = chebvander2d(x, y, [xdeg, ydeg])``, then the columns of `V` + correspond to the elements of a 2-D coefficient array `c` of shape + (xdeg + 1, ydeg + 1) in the order + + .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ... + + and ``np.dot(V, c.flat)`` and ``chebval2d(x, y, c)`` will be the same + up to roundoff. This equivalence is useful both for least squares + fitting and for the evaluation of a large number of 2-D Chebyshev + series of the same degrees and sample points. + + Parameters + ---------- + x, y : array_like + Arrays of point coordinates, all of the same shape. The dtypes + will be converted to either float64 or complex128 depending on + whether any of the elements are complex. Scalars are converted to + 1-D arrays. + deg : list of ints + List of maximum degrees of the form [x_deg, y_deg]. + + Returns + ------- + vander2d : ndarray + The shape of the returned matrix is ``x.shape + (order,)``, where + :math:`order = (deg[0]+1)*(deg[1]+1)`. The dtype will be the same + as the converted `x` and `y`. + + See Also + -------- + chebvander, chebvander3d, chebval2d, chebval3d + + Notes + ----- + + .. versionadded:: 1.7.0 + + """ + return pu._vander_nd_flat((chebvander, chebvander), (x, y), deg) + + +def chebvander3d(x, y, z, deg): + """Pseudo-Vandermonde matrix of given degrees. + + Returns the pseudo-Vandermonde matrix of degrees `deg` and sample + points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`, + then The pseudo-Vandermonde matrix is defined by + + .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = T_i(x)*T_j(y)*T_k(z), + + where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading + indices of `V` index the points `(x, y, z)` and the last index encodes + the degrees of the Chebyshev polynomials. + + If ``V = chebvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns + of `V` correspond to the elements of a 3-D coefficient array `c` of + shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order + + .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},... + + and ``np.dot(V, c.flat)`` and ``chebval3d(x, y, z, c)`` will be the + same up to roundoff. This equivalence is useful both for least squares + fitting and for the evaluation of a large number of 3-D Chebyshev + series of the same degrees and sample points. + + Parameters + ---------- + x, y, z : array_like + Arrays of point coordinates, all of the same shape. The dtypes will + be converted to either float64 or complex128 depending on whether + any of the elements are complex. Scalars are converted to 1-D + arrays. + deg : list of ints + List of maximum degrees of the form [x_deg, y_deg, z_deg]. + + Returns + ------- + vander3d : ndarray + The shape of the returned matrix is ``x.shape + (order,)``, where + :math:`order = (deg[0]+1)*(deg[1]+1)*(deg[2]+1)`. The dtype will + be the same as the converted `x`, `y`, and `z`. + + See Also + -------- + chebvander, chebvander3d, chebval2d, chebval3d + + Notes + ----- + + .. versionadded:: 1.7.0 + + """ + return pu._vander_nd_flat((chebvander, chebvander, chebvander), (x, y, z), deg) + + +def chebfit(x, y, deg, rcond=None, full=False, w=None): + """ + Least squares fit of Chebyshev series to data. + + Return the coefficients of a Chebyshev series of degree `deg` that is the + least squares fit to the data values `y` given at points `x`. If `y` is + 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple + fits are done, one for each column of `y`, and the resulting + coefficients are stored in the corresponding columns of a 2-D return. + The fitted polynomial(s) are in the form + + .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x), + + where `n` is `deg`. + + Parameters + ---------- + x : array_like, shape (M,) + x-coordinates of the M sample points ``(x[i], y[i])``. + y : array_like, shape (M,) or (M, K) + y-coordinates of the sample points. Several data sets of sample + points sharing the same x-coordinates can be fitted at once by + passing in a 2D-array that contains one dataset per column. + deg : int or 1-D array_like + Degree(s) of the fitting polynomials. If `deg` is a single integer, + all terms up to and including the `deg`'th term are included in the + fit. For NumPy versions >= 1.11.0 a list of integers specifying the + degrees of the terms to include may be used instead. + rcond : float, optional + Relative condition number of the fit. Singular values smaller than + this relative to the largest singular value will be ignored. The + default value is len(x)*eps, where eps is the relative precision of + the float type, about 2e-16 in most cases. + full : bool, optional + Switch determining nature of return value. When it is False (the + default) just the coefficients are returned, when True diagnostic + information from the singular value decomposition is also returned. + w : array_like, shape (`M`,), optional + Weights. If not None, the weight ``w[i]`` applies to the unsquared + residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are + chosen so that the errors of the products ``w[i]*y[i]`` all have the + same variance. When using inverse-variance weighting, use + ``w[i] = 1/sigma(y[i])``. The default value is None. + + .. versionadded:: 1.5.0 + + Returns + ------- + coef : ndarray, shape (M,) or (M, K) + Chebyshev coefficients ordered from low to high. If `y` was 2-D, + the coefficients for the data in column k of `y` are in column + `k`. + + [residuals, rank, singular_values, rcond] : list + These values are only returned if ``full == True`` + + - residuals -- sum of squared residuals of the least squares fit + - rank -- the numerical rank of the scaled Vandermonde matrix + - singular_values -- singular values of the scaled Vandermonde matrix + - rcond -- value of `rcond`. + + For more details, see `numpy.linalg.lstsq`. + + Warns + ----- + RankWarning + The rank of the coefficient matrix in the least-squares fit is + deficient. The warning is only raised if ``full == False``. The + warnings can be turned off by + + >>> import warnings + >>> warnings.simplefilter('ignore', np.RankWarning) + + See Also + -------- + numpy.polynomial.polynomial.polyfit + numpy.polynomial.legendre.legfit + numpy.polynomial.laguerre.lagfit + numpy.polynomial.hermite.hermfit + numpy.polynomial.hermite_e.hermefit + chebval : Evaluates a Chebyshev series. + chebvander : Vandermonde matrix of Chebyshev series. + chebweight : Chebyshev weight function. + numpy.linalg.lstsq : Computes a least-squares fit from the matrix. + scipy.interpolate.UnivariateSpline : Computes spline fits. + + Notes + ----- + The solution is the coefficients of the Chebyshev series `p` that + minimizes the sum of the weighted squared errors + + .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2, + + where :math:`w_j` are the weights. This problem is solved by setting up + as the (typically) overdetermined matrix equation + + .. math:: V(x) * c = w * y, + + where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the + coefficients to be solved for, `w` are the weights, and `y` are the + observed values. This equation is then solved using the singular value + decomposition of `V`. + + If some of the singular values of `V` are so small that they are + neglected, then a `RankWarning` will be issued. This means that the + coefficient values may be poorly determined. Using a lower order fit + will usually get rid of the warning. The `rcond` parameter can also be + set to a value smaller than its default, but the resulting fit may be + spurious and have large contributions from roundoff error. + + Fits using Chebyshev series are usually better conditioned than fits + using power series, but much can depend on the distribution of the + sample points and the smoothness of the data. If the quality of the fit + is inadequate splines may be a good alternative. + + References + ---------- + .. [1] Wikipedia, "Curve fitting", + https://en.wikipedia.org/wiki/Curve_fitting + + Examples + -------- + + """ + return pu._fit(chebvander, x, y, deg, rcond, full, w) + + +def chebcompanion(c): + """Return the scaled companion matrix of c. + + The basis polynomials are scaled so that the companion matrix is + symmetric when `c` is a Chebyshev basis polynomial. This provides + better eigenvalue estimates than the unscaled case and for basis + polynomials the eigenvalues are guaranteed to be real if + `numpy.linalg.eigvalsh` is used to obtain them. + + Parameters + ---------- + c : array_like + 1-D array of Chebyshev series coefficients ordered from low to high + degree. + + Returns + ------- + mat : ndarray + Scaled companion matrix of dimensions (deg, deg). + + Notes + ----- + + .. versionadded:: 1.7.0 + + """ + # c is a trimmed copy + [c] = pu.as_series([c]) + if len(c) < 2: + raise ValueError('Series must have maximum degree of at least 1.') + if len(c) == 2: + return np.array([[-c[0]/c[1]]]) + + n = len(c) - 1 + mat = np.zeros((n, n), dtype=c.dtype) + scl = np.array([1.] + [np.sqrt(.5)]*(n-1)) + top = mat.reshape(-1)[1::n+1] + bot = mat.reshape(-1)[n::n+1] + top[0] = np.sqrt(.5) + top[1:] = 1/2 + bot[...] = top + mat[:, -1] -= (c[:-1]/c[-1])*(scl/scl[-1])*.5 + return mat + + +def chebroots(c): + """ + Compute the roots of a Chebyshev series. + + Return the roots (a.k.a. "zeros") of the polynomial + + .. math:: p(x) = \\sum_i c[i] * T_i(x). + + Parameters + ---------- + c : 1-D array_like + 1-D array of coefficients. + + Returns + ------- + out : ndarray + Array of the roots of the series. If all the roots are real, + then `out` is also real, otherwise it is complex. + + See Also + -------- + numpy.polynomial.polynomial.polyroots + numpy.polynomial.legendre.legroots + numpy.polynomial.laguerre.lagroots + numpy.polynomial.hermite.hermroots + numpy.polynomial.hermite_e.hermeroots + + Notes + ----- + The root estimates are obtained as the eigenvalues of the companion + matrix, Roots far from the origin of the complex plane may have large + errors due to the numerical instability of the series for such + values. Roots with multiplicity greater than 1 will also show larger + errors as the value of the series near such points is relatively + insensitive to errors in the roots. Isolated roots near the origin can + be improved by a few iterations of Newton's method. + + The Chebyshev series basis polynomials aren't powers of `x` so the + results of this function may seem unintuitive. + + Examples + -------- + >>> import numpy.polynomial.chebyshev as cheb + >>> cheb.chebroots((-1, 1,-1, 1)) # T3 - T2 + T1 - T0 has real roots + array([ -5.00000000e-01, 2.60860684e-17, 1.00000000e+00]) # may vary + + """ + # c is a trimmed copy + [c] = pu.as_series([c]) + if len(c) < 2: + return np.array([], dtype=c.dtype) + if len(c) == 2: + return np.array([-c[0]/c[1]]) + + # rotated companion matrix reduces error + m = chebcompanion(c)[::-1,::-1] + r = la.eigvals(m) + r.sort() + return r + + +def chebinterpolate(func, deg, args=()): + """Interpolate a function at the Chebyshev points of the first kind. + + Returns the Chebyshev series that interpolates `func` at the Chebyshev + points of the first kind in the interval [-1, 1]. The interpolating + series tends to a minmax approximation to `func` with increasing `deg` + if the function is continuous in the interval. + + .. versionadded:: 1.14.0 + + Parameters + ---------- + func : function + The function to be approximated. It must be a function of a single + variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are + extra arguments passed in the `args` parameter. + deg : int + Degree of the interpolating polynomial + args : tuple, optional + Extra arguments to be used in the function call. Default is no extra + arguments. + + Returns + ------- + coef : ndarray, shape (deg + 1,) + Chebyshev coefficients of the interpolating series ordered from low to + high. + + Examples + -------- + >>> import numpy.polynomial.chebyshev as C + >>> C.chebfromfunction(lambda x: np.tanh(x) + 0.5, 8) + array([ 5.00000000e-01, 8.11675684e-01, -9.86864911e-17, + -5.42457905e-02, -2.71387850e-16, 4.51658839e-03, + 2.46716228e-17, -3.79694221e-04, -3.26899002e-16]) + + Notes + ----- + + The Chebyshev polynomials used in the interpolation are orthogonal when + sampled at the Chebyshev points of the first kind. If it is desired to + constrain some of the coefficients they can simply be set to the desired + value after the interpolation, no new interpolation or fit is needed. This + is especially useful if it is known apriori that some of coefficients are + zero. For instance, if the function is even then the coefficients of the + terms of odd degree in the result can be set to zero. + + """ + deg = np.asarray(deg) + + # check arguments. + if deg.ndim > 0 or deg.dtype.kind not in 'iu' or deg.size == 0: + raise TypeError("deg must be an int") + if deg < 0: + raise ValueError("expected deg >= 0") + + order = deg + 1 + xcheb = chebpts1(order) + yfunc = func(xcheb, *args) + m = chebvander(xcheb, deg) + c = np.dot(m.T, yfunc) + c[0] /= order + c[1:] /= 0.5*order + + return c + + +def chebgauss(deg): + """ + Gauss-Chebyshev quadrature. + + Computes the sample points and weights for Gauss-Chebyshev quadrature. + These sample points and weights will correctly integrate polynomials of + degree :math:`2*deg - 1` or less over the interval :math:`[-1, 1]` with + the weight function :math:`f(x) = 1/\\sqrt{1 - x^2}`. + + Parameters + ---------- + deg : int + Number of sample points and weights. It must be >= 1. + + Returns + ------- + x : ndarray + 1-D ndarray containing the sample points. + y : ndarray + 1-D ndarray containing the weights. + + Notes + ----- + + .. versionadded:: 1.7.0 + + The results have only been tested up to degree 100, higher degrees may + be problematic. For Gauss-Chebyshev there are closed form solutions for + the sample points and weights. If n = `deg`, then + + .. math:: x_i = \\cos(\\pi (2 i - 1) / (2 n)) + + .. math:: w_i = \\pi / n + + """ + ideg = pu._deprecate_as_int(deg, "deg") + if ideg <= 0: + raise ValueError("deg must be a positive integer") + + x = np.cos(np.pi * np.arange(1, 2*ideg, 2) / (2.0*ideg)) + w = np.ones(ideg)*(np.pi/ideg) + + return x, w + + +def chebweight(x): + """ + The weight function of the Chebyshev polynomials. + + The weight function is :math:`1/\\sqrt{1 - x^2}` and the interval of + integration is :math:`[-1, 1]`. The Chebyshev polynomials are + orthogonal, but not normalized, with respect to this weight function. + + Parameters + ---------- + x : array_like + Values at which the weight function will be computed. + + Returns + ------- + w : ndarray + The weight function at `x`. + + Notes + ----- + + .. versionadded:: 1.7.0 + + """ + w = 1./(np.sqrt(1. + x) * np.sqrt(1. - x)) + return w + + +def chebpts1(npts): + """ + Chebyshev points of the first kind. + + The Chebyshev points of the first kind are the points ``cos(x)``, + where ``x = [pi*(k + .5)/npts for k in range(npts)]``. + + Parameters + ---------- + npts : int + Number of sample points desired. + + Returns + ------- + pts : ndarray + The Chebyshev points of the first kind. + + See Also + -------- + chebpts2 + + Notes + ----- + + .. versionadded:: 1.5.0 + + """ + _npts = int(npts) + if _npts != npts: + raise ValueError("npts must be integer") + if _npts < 1: + raise ValueError("npts must be >= 1") + + x = 0.5 * np.pi / _npts * np.arange(-_npts+1, _npts+1, 2) + return np.sin(x) + + +def chebpts2(npts): + """ + Chebyshev points of the second kind. + + The Chebyshev points of the second kind are the points ``cos(x)``, + where ``x = [pi*k/(npts - 1) for k in range(npts)]`` sorted in ascending + order. + + Parameters + ---------- + npts : int + Number of sample points desired. + + Returns + ------- + pts : ndarray + The Chebyshev points of the second kind. + + Notes + ----- + + .. versionadded:: 1.5.0 + + """ + _npts = int(npts) + if _npts != npts: + raise ValueError("npts must be integer") + if _npts < 2: + raise ValueError("npts must be >= 2") + + x = np.linspace(-np.pi, 0, _npts) + return np.cos(x) + + +# +# Chebyshev series class +# + +class Chebyshev(ABCPolyBase): + """A Chebyshev series class. + + The Chebyshev class provides the standard Python numerical methods + '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the + methods listed below. + + Parameters + ---------- + coef : array_like + Chebyshev coefficients in order of increasing degree, i.e., + ``(1, 2, 3)`` gives ``1*T_0(x) + 2*T_1(x) + 3*T_2(x)``. + domain : (2,) array_like, optional + Domain to use. The interval ``[domain[0], domain[1]]`` is mapped + to the interval ``[window[0], window[1]]`` by shifting and scaling. + The default value is [-1, 1]. + window : (2,) array_like, optional + Window, see `domain` for its use. The default value is [-1, 1]. + + .. versionadded:: 1.6.0 + symbol : str, optional + Symbol used to represent the independent variable in string + representations of the polynomial expression, e.g. for printing. + The symbol must be a valid Python identifier. Default value is 'x'. + + .. versionadded:: 1.24 + + """ + # Virtual Functions + _add = staticmethod(chebadd) + _sub = staticmethod(chebsub) + _mul = staticmethod(chebmul) + _div = staticmethod(chebdiv) + _pow = staticmethod(chebpow) + _val = staticmethod(chebval) + _int = staticmethod(chebint) + _der = staticmethod(chebder) + _fit = staticmethod(chebfit) + _line = staticmethod(chebline) + _roots = staticmethod(chebroots) + _fromroots = staticmethod(chebfromroots) + + @classmethod + def interpolate(cls, func, deg, domain=None, args=()): + """Interpolate a function at the Chebyshev points of the first kind. + + Returns the series that interpolates `func` at the Chebyshev points of + the first kind scaled and shifted to the `domain`. The resulting series + tends to a minmax approximation of `func` when the function is + continuous in the domain. + + .. versionadded:: 1.14.0 + + Parameters + ---------- + func : function + The function to be interpolated. It must be a function of a single + variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are + extra arguments passed in the `args` parameter. + deg : int + Degree of the interpolating polynomial. + domain : {None, [beg, end]}, optional + Domain over which `func` is interpolated. The default is None, in + which case the domain is [-1, 1]. + args : tuple, optional + Extra arguments to be used in the function call. Default is no + extra arguments. + + Returns + ------- + polynomial : Chebyshev instance + Interpolating Chebyshev instance. + + Notes + ----- + See `numpy.polynomial.chebfromfunction` for more details. + + """ + if domain is None: + domain = cls.domain + xfunc = lambda x: func(pu.mapdomain(x, cls.window, domain), *args) + coef = chebinterpolate(xfunc, deg) + return cls(coef, domain=domain) + + # Virtual properties + domain = np.array(chebdomain) + window = np.array(chebdomain) + basis_name = 'T' diff --git a/shared/package-files/35/35966bfd260ee713dd4085d15779f9f3bee4c7129dcad674a0a7dd6dccdd8e98/RECORD b/shared/package-files/35/35966bfd260ee713dd4085d15779f9f3bee4c7129dcad674a0a7dd6dccdd8e98/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..de18f6a34532eb4abdb84442c2d9a371f9b07fa7 --- /dev/null +++ b/shared/package-files/35/35966bfd260ee713dd4085d15779f9f3bee4c7129dcad674a0a7dd6dccdd8e98/RECORD @@ -0,0 +1,12 @@ +rpds/__init__.py,sha256=w3MgXW7lpTCICw0KXbw20QX573_kbsEnWIeMsCAugvM,99 +rpds/__init__.pyi,sha256=t5pX7chyrwZ6SXE5gQ8UMSGG2Fw3fQfgw0_0yp6Zol8,1646 +rpds/__pycache__/__init__.cpython-310.pyc,, +rpds/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +rpds/rpds.cpython-310-x86_64-linux-gnu.so,sha256=pylX0u0GPg0kwALuiPb4ujfiGSNeYgJyqC-N8u1Lz0U,4765320 +rpds_py-0.10.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +rpds_py-0.10.6.dist-info/METADATA,sha256=B1WN0GwNfVMDLc44E9NvtfIpqWUkazKv1Lv9MNSi9l0,3747 +rpds_py-0.10.6.dist-info/RECORD,, +rpds_py-0.10.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +rpds_py-0.10.6.dist-info/WHEEL,sha256=POOdWHfB1kGRzyfjvAGidHvMZrERqSoUtoRB0BEm4jo,99 +rpds_py-0.10.6.dist-info/direct_url.json,sha256=PTTX-2aumOILis0bKaU7N4EDGwGGmO_s7h_w5v1Nhjs,67 +rpds_py-0.10.6.dist-info/license_files/LICENSE,sha256=MU5Okb47qpPA-0vMyeTpfNZD64ObBlr5IXgsIXX-mQk,1057 diff --git a/shared/package-files/35/35984f86404e9fd20d61993c1baf6b0deb916a6ced81708c2e1d74cfd71f4fa8/_typing.py b/shared/package-files/35/35984f86404e9fd20d61993c1baf6b0deb916a6ced81708c2e1d74cfd71f4fa8/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..d283dc48d10489baf7516182bfb1b111faf12ba0 --- /dev/null +++ b/shared/package-files/35/35984f86404e9fd20d61993c1baf6b0deb916a6ced81708c2e1d74cfd71f4fa8/_typing.py @@ -0,0 +1,28 @@ +""" +Some (initially private) typing helpers for jsonschema's types. +""" +from typing import Any, Callable, Iterable, Protocol, Tuple, Union + +import referencing.jsonschema + +from jsonschema.protocols import Validator + + +class SchemaKeywordValidator(Protocol): + def __call__( + self, + validator: Validator, + value: Any, + instance: Any, + schema: referencing.jsonschema.Schema, + ) -> None: + ... + + +id_of = Callable[[referencing.jsonschema.Schema], Union[str, None]] + + +ApplicableValidators = Callable[ + [referencing.jsonschema.Schema], + Iterable[Tuple[str, Any]], +] diff --git a/shared/package-files/35/359e1164ed0c83e7d0e7e8a7c2a48f076ae78e550a0589fd261f98863b14714a/hp2621-a b/shared/package-files/35/359e1164ed0c83e7d0e7e8a7c2a48f076ae78e550a0589fd261f98863b14714a/hp2621-a new file mode 100644 index 0000000000000000000000000000000000000000..6baa75ccef8bbddd1d6a1fbeb305353e87517e61 Binary files /dev/null and b/shared/package-files/35/359e1164ed0c83e7d0e7e8a7c2a48f076ae78e550a0589fd261f98863b14714a/hp2621-a differ diff --git a/shared/package-files/35/359e1164ed0c83e7d0e7e8a7c2a48f076ae78e550a0589fd261f98863b14714a/hp2621a-a b/shared/package-files/35/359e1164ed0c83e7d0e7e8a7c2a48f076ae78e550a0589fd261f98863b14714a/hp2621a-a new file mode 100644 index 0000000000000000000000000000000000000000..6baa75ccef8bbddd1d6a1fbeb305353e87517e61 Binary files /dev/null and b/shared/package-files/35/359e1164ed0c83e7d0e7e8a7c2a48f076ae78e550a0589fd261f98863b14714a/hp2621a-a differ diff --git a/shared/package-files/35/359e5c5b7feff4c130f671ad1296ee129c219823e93622028028683c70f06127/st-0.7 b/shared/package-files/35/359e5c5b7feff4c130f671ad1296ee129c219823e93622028028683c70f06127/st-0.7 new file mode 100644 index 0000000000000000000000000000000000000000..0052581cd1dccbe062dda26bb76fb085cbf31968 Binary files /dev/null and b/shared/package-files/35/359e5c5b7feff4c130f671ad1296ee129c219823e93622028028683c70f06127/st-0.7 differ diff --git a/shared/package-files/35/35a0d1fb7e47f6c2711e914d7d7febce14e5dfd939dd5930e6a15b4a02baf408/special_bessel_y0_meta.h b/shared/package-files/35/35a0d1fb7e47f6c2711e914d7d7febce14e5dfd939dd5930e6a15b4a02baf408/special_bessel_y0_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..d8251bbcbf0726feb4272a2b91cab267a6a0e75f --- /dev/null +++ b/shared/package-files/35/35a0d1fb7e47f6c2711e914d7d7febce14e5dfd939dd5930e6a15b4a02baf408/special_bessel_y0_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_special_bessel_y0 : public TensorIteratorBase { + + + void meta(const at::Tensor & self); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/35/35a14a7a3bbba7b70cfd0aee78712b3cac4bcb1a831cb10a04076807e4715925/quantize_per_channel_cpu_dispatch.h b/shared/package-files/35/35a14a7a3bbba7b70cfd0aee78712b3cac4bcb1a831cb10a04076807e4715925/quantize_per_channel_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..382ce43161562695db7a43e6e9f023e94df95c72 --- /dev/null +++ b/shared/package-files/35/35a14a7a3bbba7b70cfd0aee78712b3cac4bcb1a831cb10a04076807e4715925/quantize_per_channel_cpu_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor quantize_per_channel(const at::Tensor & self, const at::Tensor & scales, const at::Tensor & zero_points, int64_t axis, at::ScalarType dtype); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/35/35a1a775fa732635183125243f7d21d3c6d4b91662a1006eca640bdd28e96639/GPUTrace.h b/shared/package-files/35/35a1a775fa732635183125243f7d21d3c6d4b91662a1006eca640bdd28e96639/GPUTrace.h new file mode 100644 index 0000000000000000000000000000000000000000..3acb875b54a32c7032d5945afac7e1137fc489e8 --- /dev/null +++ b/shared/package-files/35/35a1a775fa732635183125243f7d21d3c6d4b91662a1006eca640bdd28e96639/GPUTrace.h @@ -0,0 +1,28 @@ +#pragma once + +#include + +namespace c10::impl { + +struct C10_API GPUTrace { + // On the x86 architecture the atomic operations are lock-less. + static std::atomic gpuTraceState; + + // When PyTorch migrates to C++20, this should be changed to an atomic flag. + // Currently, the access to this variable is not synchronized, on the basis + // that it will only be flipped once and by the first interpreter that + // accesses it. + static bool haveState; + + // This function will only register the first interpreter that tries to invoke + // it. For all of the next ones it will be a no-op. + static void set_trace(const PyInterpreter*); + + static const PyInterpreter* get_trace() { + if (!haveState) + return nullptr; + return gpuTraceState.load(std::memory_order_acquire); + } +}; + +} // namespace c10::impl diff --git a/shared/package-files/35/35a21e081f70ee233f3ed6a6c782282cc470206f5e510c6c4c9a54d9c041e72d/test_readlines.py b/shared/package-files/35/35a21e081f70ee233f3ed6a6c782282cc470206f5e510c6c4c9a54d9c041e72d/test_readlines.py new file mode 100644 index 0000000000000000000000000000000000000000..d96ccb4b94cc2c567c8d7e59cad3227017f9200d --- /dev/null +++ b/shared/package-files/35/35a21e081f70ee233f3ed6a6c782282cc470206f5e510c6c4c9a54d9c041e72d/test_readlines.py @@ -0,0 +1,543 @@ +from collections.abc import Iterator +from io import StringIO +from pathlib import Path + +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + DataFrame, + read_json, +) +import pandas._testing as tm + +from pandas.io.json._json import JsonReader + +pytestmark = pytest.mark.filterwarnings( + "ignore:Passing a BlockManager to DataFrame:DeprecationWarning" +) + + +@pytest.fixture +def lines_json_df(): + df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) + return df.to_json(lines=True, orient="records") + + +@pytest.fixture(params=["ujson", "pyarrow"]) +def engine(request): + if request.param == "pyarrow": + pytest.importorskip("pyarrow.json") + return request.param + + +def test_read_jsonl(): + # GH9180 + result = read_json(StringIO('{"a": 1, "b": 2}\n{"b":2, "a" :1}\n'), lines=True) + expected = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) + tm.assert_frame_equal(result, expected) + + +def test_read_jsonl_engine_pyarrow(datapath, engine): + result = read_json( + datapath("io", "json", "data", "line_delimited.json"), + lines=True, + engine=engine, + ) + expected = DataFrame({"a": [1, 3, 5], "b": [2, 4, 6]}) + tm.assert_frame_equal(result, expected) + + +def test_read_datetime(request, engine): + # GH33787 + if engine == "pyarrow": + # GH 48893 + reason = "Pyarrow only supports a file path as an input and line delimited json" + request.applymarker(pytest.mark.xfail(reason=reason, raises=ValueError)) + + df = DataFrame( + [([1, 2], ["2020-03-05", "2020-04-08T09:58:49+00:00"], "hector")], + columns=["accounts", "date", "name"], + ) + json_line = df.to_json(lines=True, orient="records") + + if engine == "pyarrow": + result = read_json(StringIO(json_line), engine=engine) + else: + result = read_json(StringIO(json_line), engine=engine) + expected = DataFrame( + [[1, "2020-03-05", "hector"], [2, "2020-04-08T09:58:49+00:00", "hector"]], + columns=["accounts", "date", "name"], + ) + tm.assert_frame_equal(result, expected) + + +def test_read_jsonl_unicode_chars(): + # GH15132: non-ascii unicode characters + # \u201d == RIGHT DOUBLE QUOTATION MARK + + # simulate file handle + json = '{"a": "foo”", "b": "bar"}\n{"a": "foo", "b": "bar"}\n' + json = StringIO(json) + result = read_json(json, lines=True) + expected = DataFrame([["foo\u201d", "bar"], ["foo", "bar"]], columns=["a", "b"]) + tm.assert_frame_equal(result, expected) + + # simulate string + json = '{"a": "foo”", "b": "bar"}\n{"a": "foo", "b": "bar"}\n' + result = read_json(StringIO(json), lines=True) + expected = DataFrame([["foo\u201d", "bar"], ["foo", "bar"]], columns=["a", "b"]) + tm.assert_frame_equal(result, expected) + + +def test_to_jsonl(): + # GH9180 + df = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) + result = df.to_json(orient="records", lines=True) + expected = '{"a":1,"b":2}\n{"a":1,"b":2}\n' + assert result == expected + + df = DataFrame([["foo}", "bar"], ['foo"', "bar"]], columns=["a", "b"]) + result = df.to_json(orient="records", lines=True) + expected = '{"a":"foo}","b":"bar"}\n{"a":"foo\\"","b":"bar"}\n' + assert result == expected + tm.assert_frame_equal(read_json(StringIO(result), lines=True), df) + + # GH15096: escaped characters in columns and data + df = DataFrame([["foo\\", "bar"], ['foo"', "bar"]], columns=["a\\", "b"]) + result = df.to_json(orient="records", lines=True) + expected = '{"a\\\\":"foo\\\\","b":"bar"}\n{"a\\\\":"foo\\"","b":"bar"}\n' + assert result == expected + tm.assert_frame_equal(read_json(StringIO(result), lines=True), df) + + +def test_to_jsonl_count_new_lines(): + # GH36888 + df = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) + actual_new_lines_count = df.to_json(orient="records", lines=True).count("\n") + expected_new_lines_count = 2 + assert actual_new_lines_count == expected_new_lines_count + + +@pytest.mark.parametrize("chunksize", [1, 1.0]) +def test_readjson_chunks(request, lines_json_df, chunksize, engine): + # Basic test that read_json(chunks=True) gives the same result as + # read_json(chunks=False) + # GH17048: memory usage when lines=True + + if engine == "pyarrow": + # GH 48893 + reason = ( + "Pyarrow only supports a file path as an input and line delimited json" + "and doesn't support chunksize parameter." + ) + request.applymarker(pytest.mark.xfail(reason=reason, raises=ValueError)) + + unchunked = read_json(StringIO(lines_json_df), lines=True) + with read_json( + StringIO(lines_json_df), lines=True, chunksize=chunksize, engine=engine + ) as reader: + chunked = pd.concat(reader) + + tm.assert_frame_equal(chunked, unchunked) + + +def test_readjson_chunksize_requires_lines(lines_json_df, engine): + msg = "chunksize can only be passed if lines=True" + with pytest.raises(ValueError, match=msg): + with read_json( + StringIO(lines_json_df), lines=False, chunksize=2, engine=engine + ) as _: + pass + + +def test_readjson_chunks_series(request, engine): + if engine == "pyarrow": + # GH 48893 + reason = ( + "Pyarrow only supports a file path as an input and line delimited json" + "and doesn't support chunksize parameter." + ) + request.applymarker(pytest.mark.xfail(reason=reason)) + + # Test reading line-format JSON to Series with chunksize param + s = pd.Series({"A": 1, "B": 2}) + + strio = StringIO(s.to_json(lines=True, orient="records")) + unchunked = read_json(strio, lines=True, typ="Series", engine=engine) + + strio = StringIO(s.to_json(lines=True, orient="records")) + with read_json( + strio, lines=True, typ="Series", chunksize=1, engine=engine + ) as reader: + chunked = pd.concat(reader) + + tm.assert_series_equal(chunked, unchunked) + + +def test_readjson_each_chunk(request, lines_json_df, engine): + if engine == "pyarrow": + # GH 48893 + reason = ( + "Pyarrow only supports a file path as an input and line delimited json" + "and doesn't support chunksize parameter." + ) + request.applymarker(pytest.mark.xfail(reason=reason, raises=ValueError)) + + # Other tests check that the final result of read_json(chunksize=True) + # is correct. This checks the intermediate chunks. + with read_json( + StringIO(lines_json_df), lines=True, chunksize=2, engine=engine + ) as reader: + chunks = list(reader) + assert chunks[0].shape == (2, 2) + assert chunks[1].shape == (1, 2) + + +def test_readjson_chunks_from_file(request, engine): + if engine == "pyarrow": + # GH 48893 + reason = ( + "Pyarrow only supports a file path as an input and line delimited json" + "and doesn't support chunksize parameter." + ) + request.applymarker(pytest.mark.xfail(reason=reason, raises=ValueError)) + + with tm.ensure_clean("test.json") as path: + df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) + df.to_json(path, lines=True, orient="records") + with read_json(path, lines=True, chunksize=1, engine=engine) as reader: + chunked = pd.concat(reader) + unchunked = read_json(path, lines=True, engine=engine) + tm.assert_frame_equal(unchunked, chunked) + + +@pytest.mark.parametrize("chunksize", [None, 1]) +def test_readjson_chunks_closes(chunksize): + with tm.ensure_clean("test.json") as path: + df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) + df.to_json(path, lines=True, orient="records") + reader = JsonReader( + path, + orient=None, + typ="frame", + dtype=True, + convert_axes=True, + convert_dates=True, + keep_default_dates=True, + precise_float=False, + date_unit=None, + encoding=None, + lines=True, + chunksize=chunksize, + compression=None, + nrows=None, + ) + with reader: + reader.read() + assert ( + reader.handles.handle.closed + ), f"didn't close stream with chunksize = {chunksize}" + + +@pytest.mark.parametrize("chunksize", [0, -1, 2.2, "foo"]) +def test_readjson_invalid_chunksize(lines_json_df, chunksize, engine): + msg = r"'chunksize' must be an integer >=1" + + with pytest.raises(ValueError, match=msg): + with read_json( + StringIO(lines_json_df), lines=True, chunksize=chunksize, engine=engine + ) as _: + pass + + +@pytest.mark.parametrize("chunksize", [None, 1, 2]) +def test_readjson_chunks_multiple_empty_lines(chunksize): + j = """ + + {"A":1,"B":4} + + + + {"A":2,"B":5} + + + + + + + + {"A":3,"B":6} + """ + orig = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) + test = read_json(StringIO(j), lines=True, chunksize=chunksize) + if chunksize is not None: + with test: + test = pd.concat(test) + tm.assert_frame_equal(orig, test, obj=f"chunksize: {chunksize}") + + +def test_readjson_unicode(request, monkeypatch, engine): + if engine == "pyarrow": + # GH 48893 + reason = ( + "Pyarrow only supports a file path as an input and line delimited json" + "and doesn't support chunksize parameter." + ) + request.applymarker(pytest.mark.xfail(reason=reason, raises=ValueError)) + + with tm.ensure_clean("test.json") as path: + monkeypatch.setattr("locale.getpreferredencoding", lambda do_setlocale: "cp949") + with open(path, "w", encoding="utf-8") as f: + f.write('{"£©µÀÆÖÞßéöÿ":["АБВГДабвгд가"]}') + + result = read_json(path, engine=engine) + expected = DataFrame({"£©µÀÆÖÞßéöÿ": ["АБВГДабвгд가"]}) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("nrows", [1, 2]) +def test_readjson_nrows(nrows, engine): + # GH 33916 + # Test reading line-format JSON to Series with nrows param + jsonl = """{"a": 1, "b": 2} + {"a": 3, "b": 4} + {"a": 5, "b": 6} + {"a": 7, "b": 8}""" + result = read_json(StringIO(jsonl), lines=True, nrows=nrows) + expected = DataFrame({"a": [1, 3, 5, 7], "b": [2, 4, 6, 8]}).iloc[:nrows] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("nrows,chunksize", [(2, 2), (4, 2)]) +def test_readjson_nrows_chunks(request, nrows, chunksize, engine): + # GH 33916 + # Test reading line-format JSON to Series with nrows and chunksize param + if engine == "pyarrow": + # GH 48893 + reason = ( + "Pyarrow only supports a file path as an input and line delimited json" + "and doesn't support chunksize parameter." + ) + request.applymarker(pytest.mark.xfail(reason=reason, raises=ValueError)) + + jsonl = """{"a": 1, "b": 2} + {"a": 3, "b": 4} + {"a": 5, "b": 6} + {"a": 7, "b": 8}""" + + if engine != "pyarrow": + with read_json( + StringIO(jsonl), lines=True, nrows=nrows, chunksize=chunksize, engine=engine + ) as reader: + chunked = pd.concat(reader) + else: + with read_json( + jsonl, lines=True, nrows=nrows, chunksize=chunksize, engine=engine + ) as reader: + chunked = pd.concat(reader) + expected = DataFrame({"a": [1, 3, 5, 7], "b": [2, 4, 6, 8]}).iloc[:nrows] + tm.assert_frame_equal(chunked, expected) + + +def test_readjson_nrows_requires_lines(engine): + # GH 33916 + # Test ValueError raised if nrows is set without setting lines in read_json + jsonl = """{"a": 1, "b": 2} + {"a": 3, "b": 4} + {"a": 5, "b": 6} + {"a": 7, "b": 8}""" + msg = "nrows can only be passed if lines=True" + with pytest.raises(ValueError, match=msg): + read_json(jsonl, lines=False, nrows=2, engine=engine) + + +def test_readjson_lines_chunks_fileurl(request, datapath, engine): + # GH 27135 + # Test reading line-format JSON from file url + if engine == "pyarrow": + # GH 48893 + reason = ( + "Pyarrow only supports a file path as an input and line delimited json" + "and doesn't support chunksize parameter." + ) + request.applymarker(pytest.mark.xfail(reason=reason, raises=ValueError)) + + df_list_expected = [ + DataFrame([[1, 2]], columns=["a", "b"], index=[0]), + DataFrame([[3, 4]], columns=["a", "b"], index=[1]), + DataFrame([[5, 6]], columns=["a", "b"], index=[2]), + ] + os_path = datapath("io", "json", "data", "line_delimited.json") + file_url = Path(os_path).as_uri() + with read_json(file_url, lines=True, chunksize=1, engine=engine) as url_reader: + for index, chuck in enumerate(url_reader): + tm.assert_frame_equal(chuck, df_list_expected[index]) + + +def test_chunksize_is_incremental(): + # See https://github.com/pandas-dev/pandas/issues/34548 + jsonl = ( + """{"a": 1, "b": 2} + {"a": 3, "b": 4} + {"a": 5, "b": 6} + {"a": 7, "b": 8}\n""" + * 1000 + ) + + class MyReader: + def __init__(self, contents) -> None: + self.read_count = 0 + self.stringio = StringIO(contents) + + def read(self, *args): + self.read_count += 1 + return self.stringio.read(*args) + + def __iter__(self) -> Iterator: + self.read_count += 1 + return iter(self.stringio) + + reader = MyReader(jsonl) + assert len(list(read_json(reader, lines=True, chunksize=100))) > 1 + assert reader.read_count > 10 + + +@pytest.mark.parametrize("orient_", ["split", "index", "table"]) +def test_to_json_append_orient(orient_): + # GH 35849 + # Test ValueError when orient is not 'records' + df = DataFrame({"col1": [1, 2], "col2": ["a", "b"]}) + msg = ( + r"mode='a' \(append\) is only supported when " + "lines is True and orient is 'records'" + ) + with pytest.raises(ValueError, match=msg): + df.to_json(mode="a", orient=orient_) + + +def test_to_json_append_lines(): + # GH 35849 + # Test ValueError when lines is not True + df = DataFrame({"col1": [1, 2], "col2": ["a", "b"]}) + msg = ( + r"mode='a' \(append\) is only supported when " + "lines is True and orient is 'records'" + ) + with pytest.raises(ValueError, match=msg): + df.to_json(mode="a", lines=False, orient="records") + + +@pytest.mark.parametrize("mode_", ["r", "x"]) +def test_to_json_append_mode(mode_): + # GH 35849 + # Test ValueError when mode is not supported option + df = DataFrame({"col1": [1, 2], "col2": ["a", "b"]}) + msg = ( + f"mode={mode_} is not a valid option." + "Only 'w' and 'a' are currently supported." + ) + with pytest.raises(ValueError, match=msg): + df.to_json(mode=mode_, lines=False, orient="records") + + +def test_to_json_append_output_consistent_columns(): + # GH 35849 + # Testing that resulting output reads in as expected. + # Testing same columns, new rows + df1 = DataFrame({"col1": [1, 2], "col2": ["a", "b"]}) + df2 = DataFrame({"col1": [3, 4], "col2": ["c", "d"]}) + + expected = DataFrame({"col1": [1, 2, 3, 4], "col2": ["a", "b", "c", "d"]}) + with tm.ensure_clean("test.json") as path: + # Save dataframes to the same file + df1.to_json(path, lines=True, orient="records") + df2.to_json(path, mode="a", lines=True, orient="records") + + # Read path file + result = read_json(path, lines=True) + tm.assert_frame_equal(result, expected) + + +def test_to_json_append_output_inconsistent_columns(): + # GH 35849 + # Testing that resulting output reads in as expected. + # Testing one new column, one old column, new rows + df1 = DataFrame({"col1": [1, 2], "col2": ["a", "b"]}) + df3 = DataFrame({"col2": ["e", "f"], "col3": ["!", "#"]}) + + expected = DataFrame( + { + "col1": [1, 2, None, None], + "col2": ["a", "b", "e", "f"], + "col3": [np.nan, np.nan, "!", "#"], + } + ) + with tm.ensure_clean("test.json") as path: + # Save dataframes to the same file + df1.to_json(path, mode="a", lines=True, orient="records") + df3.to_json(path, mode="a", lines=True, orient="records") + + # Read path file + result = read_json(path, lines=True) + tm.assert_frame_equal(result, expected) + + +def test_to_json_append_output_different_columns(): + # GH 35849 + # Testing that resulting output reads in as expected. + # Testing same, differing and new columns + df1 = DataFrame({"col1": [1, 2], "col2": ["a", "b"]}) + df2 = DataFrame({"col1": [3, 4], "col2": ["c", "d"]}) + df3 = DataFrame({"col2": ["e", "f"], "col3": ["!", "#"]}) + df4 = DataFrame({"col4": [True, False]}) + + expected = DataFrame( + { + "col1": [1, 2, 3, 4, None, None, None, None], + "col2": ["a", "b", "c", "d", "e", "f", np.nan, np.nan], + "col3": [np.nan, np.nan, np.nan, np.nan, "!", "#", np.nan, np.nan], + "col4": [None, None, None, None, None, None, True, False], + } + ).astype({"col4": "float"}) + with tm.ensure_clean("test.json") as path: + # Save dataframes to the same file + df1.to_json(path, mode="a", lines=True, orient="records") + df2.to_json(path, mode="a", lines=True, orient="records") + df3.to_json(path, mode="a", lines=True, orient="records") + df4.to_json(path, mode="a", lines=True, orient="records") + + # Read path file + result = read_json(path, lines=True) + tm.assert_frame_equal(result, expected) + + +def test_to_json_append_output_different_columns_reordered(): + # GH 35849 + # Testing that resulting output reads in as expected. + # Testing specific result column order. + df1 = DataFrame({"col1": [1, 2], "col2": ["a", "b"]}) + df2 = DataFrame({"col1": [3, 4], "col2": ["c", "d"]}) + df3 = DataFrame({"col2": ["e", "f"], "col3": ["!", "#"]}) + df4 = DataFrame({"col4": [True, False]}) + + # df4, df3, df2, df1 (in that order) + expected = DataFrame( + { + "col4": [True, False, None, None, None, None, None, None], + "col2": [np.nan, np.nan, "e", "f", "c", "d", "a", "b"], + "col3": [np.nan, np.nan, "!", "#", np.nan, np.nan, np.nan, np.nan], + "col1": [None, None, None, None, 3, 4, 1, 2], + } + ).astype({"col4": "float"}) + with tm.ensure_clean("test.json") as path: + # Save dataframes to the same file + df4.to_json(path, mode="a", lines=True, orient="records") + df3.to_json(path, mode="a", lines=True, orient="records") + df2.to_json(path, mode="a", lines=True, orient="records") + df1.to_json(path, mode="a", lines=True, orient="records") + + # Read path file + result = read_json(path, lines=True) + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/35/35a29aff27377e8deb9f8f67c529939b4fd9606ce7d172bd023226cfbf0fdb0b/_classification_threshold.py b/shared/package-files/35/35a29aff27377e8deb9f8f67c529939b4fd9606ce7d172bd023226cfbf0fdb0b/_classification_threshold.py new file mode 100644 index 0000000000000000000000000000000000000000..c68ed38b8819d989d0ec838840b5b5406eec7e57 --- /dev/null +++ b/shared/package-files/35/35a29aff27377e8deb9f8f67c529939b4fd9606ce7d172bd023226cfbf0fdb0b/_classification_threshold.py @@ -0,0 +1,889 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from collections.abc import MutableMapping +from numbers import Integral, Real + +import numpy as np + +from ..base import ( + BaseEstimator, + ClassifierMixin, + MetaEstimatorMixin, + _fit_context, + clone, +) +from ..exceptions import NotFittedError +from ..metrics import ( + check_scoring, + get_scorer_names, +) +from ..metrics._scorer import ( + _CurveScorer, + _threshold_scores_to_class_labels, +) +from ..utils import _safe_indexing, get_tags +from ..utils._param_validation import HasMethods, Interval, RealNotInt, StrOptions +from ..utils._response import _get_response_values_binary +from ..utils.metadata_routing import ( + MetadataRouter, + MethodMapping, + _raise_for_params, + process_routing, +) +from ..utils.metaestimators import available_if +from ..utils.multiclass import type_of_target +from ..utils.parallel import Parallel, delayed +from ..utils.validation import ( + _check_method_params, + _estimator_has, + _num_samples, + check_is_fitted, + indexable, +) +from ._split import StratifiedShuffleSplit, check_cv + + +def _check_is_fitted(estimator): + try: + check_is_fitted(estimator.estimator) + except NotFittedError: + check_is_fitted(estimator, "estimator_") + + +class BaseThresholdClassifier(ClassifierMixin, MetaEstimatorMixin, BaseEstimator): + """Base class for binary classifiers that set a non-default decision threshold. + + In this base class, we define the following interface: + + - the validation of common parameters in `fit`; + - the different prediction methods that can be used with the classifier. + + .. versionadded:: 1.5 + + Parameters + ---------- + estimator : estimator instance + The binary classifier, fitted or not, for which we want to optimize + the decision threshold used during `predict`. + + response_method : {"auto", "decision_function", "predict_proba"}, default="auto" + Methods by the classifier `estimator` corresponding to the + decision function for which we want to find a threshold. It can be: + + * if `"auto"`, it will try to invoke, for each classifier, + `"predict_proba"` or `"decision_function"` in that order. + * otherwise, one of `"predict_proba"` or `"decision_function"`. + If the method is not implemented by the classifier, it will raise an + error. + """ + + _parameter_constraints: dict = { + "estimator": [ + HasMethods(["fit", "predict_proba"]), + HasMethods(["fit", "decision_function"]), + ], + "response_method": [StrOptions({"auto", "predict_proba", "decision_function"})], + } + + def __init__(self, estimator, *, response_method="auto"): + self.estimator = estimator + self.response_method = response_method + + def _get_response_method(self): + """Define the response method.""" + if self.response_method == "auto": + response_method = ["predict_proba", "decision_function"] + else: + response_method = self.response_method + return response_method + + @_fit_context( + # *ThresholdClassifier*.estimator is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y, **params): + """Fit the classifier. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) + Target values. + + **params : dict + Parameters to pass to the `fit` method of the underlying + classifier. + + Returns + ------- + self : object + Returns an instance of self. + """ + _raise_for_params(params, self, None) + + X, y = indexable(X, y) + + y_type = type_of_target(y, input_name="y") + if y_type != "binary": + raise ValueError( + f"Only binary classification is supported. Unknown label type: {y_type}" + ) + + self._fit(X, y, **params) + + if hasattr(self.estimator_, "n_features_in_"): + self.n_features_in_ = self.estimator_.n_features_in_ + if hasattr(self.estimator_, "feature_names_in_"): + self.feature_names_in_ = self.estimator_.feature_names_in_ + + return self + + @property + def classes_(self): + """Classes labels.""" + return self.estimator_.classes_ + + @available_if(_estimator_has("predict_proba")) + def predict_proba(self, X): + """Predict class probabilities for `X` using the fitted estimator. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vectors, where `n_samples` is the number of samples and + `n_features` is the number of features. + + Returns + ------- + probabilities : ndarray of shape (n_samples, n_classes) + The class probabilities of the input samples. + """ + _check_is_fitted(self) + estimator = getattr(self, "estimator_", self.estimator) + return estimator.predict_proba(X) + + @available_if(_estimator_has("predict_log_proba")) + def predict_log_proba(self, X): + """Predict logarithm class probabilities for `X` using the fitted estimator. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vectors, where `n_samples` is the number of samples and + `n_features` is the number of features. + + Returns + ------- + log_probabilities : ndarray of shape (n_samples, n_classes) + The logarithm class probabilities of the input samples. + """ + _check_is_fitted(self) + estimator = getattr(self, "estimator_", self.estimator) + return estimator.predict_log_proba(X) + + @available_if(_estimator_has("decision_function")) + def decision_function(self, X): + """Decision function for samples in `X` using the fitted estimator. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vectors, where `n_samples` is the number of samples and + `n_features` is the number of features. + + Returns + ------- + decisions : ndarray of shape (n_samples,) + The decision function computed the fitted estimator. + """ + _check_is_fitted(self) + estimator = getattr(self, "estimator_", self.estimator) + return estimator.decision_function(X) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.classifier_tags.multi_class = False + tags.input_tags.sparse = get_tags(self.estimator).input_tags.sparse + return tags + + +class FixedThresholdClassifier(BaseThresholdClassifier): + """Binary classifier that manually sets the decision threshold. + + This classifier allows to change the default decision threshold used for + converting posterior probability estimates (i.e. output of `predict_proba`) or + decision scores (i.e. output of `decision_function`) into a class label. + + Here, the threshold is not optimized and is set to a constant value. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.5 + + Parameters + ---------- + estimator : estimator instance + The binary classifier, fitted or not, for which we want to optimize + the decision threshold used during `predict`. + + threshold : {"auto"} or float, default="auto" + The decision threshold to use when converting posterior probability estimates + (i.e. output of `predict_proba`) or decision scores (i.e. output of + `decision_function`) into a class label. When `"auto"`, the threshold is set + to 0.5 if `predict_proba` is used as `response_method`, otherwise it is set to + 0 (i.e. the default threshold for `decision_function`). + + pos_label : int, float, bool or str, default=None + The label of the positive class. Used to process the output of the + `response_method` method. When `pos_label=None`, if `y_true` is in `{-1, 1}` or + `{0, 1}`, `pos_label` is set to 1, otherwise an error will be raised. + + response_method : {"auto", "decision_function", "predict_proba"}, default="auto" + Methods by the classifier `estimator` corresponding to the + decision function for which we want to find a threshold. It can be: + + * if `"auto"`, it will try to invoke `"predict_proba"` or `"decision_function"` + in that order. + * otherwise, one of `"predict_proba"` or `"decision_function"`. + If the method is not implemented by the classifier, it will raise an + error. + + Attributes + ---------- + estimator_ : estimator instance + The fitted classifier used when predicting. + + classes_ : ndarray of shape (n_classes,) + The class labels. + + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if the + underlying estimator exposes such an attribute when fit. + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Only defined if the + underlying estimator exposes such an attribute when fit. + + See Also + -------- + sklearn.model_selection.TunedThresholdClassifierCV : Classifier that post-tunes + the decision threshold based on some metrics and using cross-validation. + sklearn.calibration.CalibratedClassifierCV : Estimator that calibrates + probabilities. + + Examples + -------- + >>> from sklearn.datasets import make_classification + >>> from sklearn.linear_model import LogisticRegression + >>> from sklearn.metrics import confusion_matrix + >>> from sklearn.model_selection import FixedThresholdClassifier, train_test_split + >>> X, y = make_classification( + ... n_samples=1_000, weights=[0.9, 0.1], class_sep=0.8, random_state=42 + ... ) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, stratify=y, random_state=42 + ... ) + >>> classifier = LogisticRegression(random_state=0).fit(X_train, y_train) + >>> print(confusion_matrix(y_test, classifier.predict(X_test))) + [[217 7] + [ 19 7]] + >>> classifier_other_threshold = FixedThresholdClassifier( + ... classifier, threshold=0.1, response_method="predict_proba" + ... ).fit(X_train, y_train) + >>> print(confusion_matrix(y_test, classifier_other_threshold.predict(X_test))) + [[184 40] + [ 6 20]] + """ + + _parameter_constraints: dict = { + **BaseThresholdClassifier._parameter_constraints, + "threshold": [StrOptions({"auto"}), Real], + "pos_label": [Real, str, "boolean", None], + } + + def __init__( + self, + estimator, + *, + threshold="auto", + pos_label=None, + response_method="auto", + ): + super().__init__(estimator=estimator, response_method=response_method) + self.pos_label = pos_label + self.threshold = threshold + + @property + def classes_(self): + if estimator := getattr(self, "estimator_", None): + return estimator.classes_ + try: + check_is_fitted(self.estimator) + return self.estimator.classes_ + except NotFittedError: + raise AttributeError( + "The underlying estimator is not fitted yet." + ) from NotFittedError + + def _fit(self, X, y, **params): + """Fit the classifier. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) + Target values. + + **params : dict + Parameters to pass to the `fit` method of the underlying + classifier. + + Returns + ------- + self : object + Returns an instance of self. + """ + routed_params = process_routing(self, "fit", **params) + self.estimator_ = clone(self.estimator).fit(X, y, **routed_params.estimator.fit) + return self + + def predict(self, X): + """Predict the target of new samples. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The samples, as accepted by `estimator.predict`. + + Returns + ------- + class_labels : ndarray of shape (n_samples,) + The predicted class. + """ + _check_is_fitted(self) + + estimator = getattr(self, "estimator_", self.estimator) + + y_score, _, response_method_used = _get_response_values_binary( + estimator, + X, + self._get_response_method(), + pos_label=self.pos_label, + return_response_method_used=True, + ) + + if self.threshold == "auto": + decision_threshold = 0.5 if response_method_used == "predict_proba" else 0.0 + else: + decision_threshold = self.threshold + + return _threshold_scores_to_class_labels( + y_score, decision_threshold, self.classes_, self.pos_label + ) + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + Returns + ------- + routing : MetadataRouter + A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + router = MetadataRouter(owner=self.__class__.__name__).add( + estimator=self.estimator, + method_mapping=MethodMapping().add(callee="fit", caller="fit"), + ) + return router + + +def _fit_and_score_over_thresholds( + classifier, + X, + y, + *, + fit_params, + train_idx, + val_idx, + curve_scorer, + score_params, +): + """Fit a classifier and compute the scores for different decision thresholds. + + Parameters + ---------- + classifier : estimator instance + The classifier to fit and use for scoring. If `classifier` is already fitted, + it will be used as is. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The entire dataset. + + y : array-like of shape (n_samples,) + The entire target vector. + + fit_params : dict + Parameters to pass to the `fit` method of the underlying classifier. + + train_idx : ndarray of shape (n_train_samples,) or None + The indices of the training set. If `None`, `classifier` is expected to be + already fitted. + + val_idx : ndarray of shape (n_val_samples,) + The indices of the validation set used to score `classifier`. If `train_idx`, + the entire set will be used. + + curve_scorer : scorer instance + The scorer taking `classifier` and the validation set as input and outputting + decision thresholds and scores as a curve. Note that this is different from + the usual scorer that outputs a single score value as `curve_scorer` + outputs a single score value for each threshold. + + score_params : dict + Parameters to pass to the `score` method of the underlying scorer. + + Returns + ------- + scores : ndarray of shape (thresholds,) or tuple of such arrays + The scores computed for each decision threshold. When TPR/TNR or precision/ + recall are computed, `scores` is a tuple of two arrays. + + potential_thresholds : ndarray of shape (thresholds,) + The decision thresholds used to compute the scores. They are returned in + ascending order. + """ + + if train_idx is not None: + X_train, X_val = _safe_indexing(X, train_idx), _safe_indexing(X, val_idx) + y_train, y_val = _safe_indexing(y, train_idx), _safe_indexing(y, val_idx) + fit_params_train = _check_method_params(X, fit_params, indices=train_idx) + score_params_val = _check_method_params(X, score_params, indices=val_idx) + classifier.fit(X_train, y_train, **fit_params_train) + else: # prefit estimator, only a validation set is provided + X_val, y_val, score_params_val = X, y, score_params + + return curve_scorer(classifier, X_val, y_val, **score_params_val) + + +def _mean_interpolated_score(target_thresholds, cv_thresholds, cv_scores): + """Compute the mean interpolated score across folds by defining common thresholds. + + Parameters + ---------- + target_thresholds : ndarray of shape (thresholds,) + The thresholds to use to compute the mean score. + + cv_thresholds : ndarray of shape (n_folds, thresholds_fold) + The thresholds used to compute the scores for each fold. + + cv_scores : ndarray of shape (n_folds, thresholds_fold) + The scores computed for each threshold for each fold. + + Returns + ------- + mean_score : ndarray of shape (thresholds,) + The mean score across all folds for each target threshold. + """ + return np.mean( + [ + np.interp(target_thresholds, split_thresholds, split_score) + for split_thresholds, split_score in zip(cv_thresholds, cv_scores) + ], + axis=0, + ) + + +class TunedThresholdClassifierCV(BaseThresholdClassifier): + """Classifier that post-tunes the decision threshold using cross-validation. + + This estimator post-tunes the decision threshold (cut-off point) that is + used for converting posterior probability estimates (i.e. output of + `predict_proba`) or decision scores (i.e. output of `decision_function`) + into a class label. The tuning is done by optimizing a binary metric, + potentially constrained by a another metric. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.5 + + Parameters + ---------- + estimator : estimator instance + The classifier, fitted or not, for which we want to optimize + the decision threshold used during `predict`. + + scoring : str or callable, default="balanced_accuracy" + The objective metric to be optimized. Can be one of: + + - str: string associated to a scoring function for binary classification, + see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. + + response_method : {"auto", "decision_function", "predict_proba"}, default="auto" + Methods by the classifier `estimator` corresponding to the + decision function for which we want to find a threshold. It can be: + + * if `"auto"`, it will try to invoke, for each classifier, + `"predict_proba"` or `"decision_function"` in that order. + * otherwise, one of `"predict_proba"` or `"decision_function"`. + If the method is not implemented by the classifier, it will raise an + error. + + thresholds : int or array-like, default=100 + The number of decision threshold to use when discretizing the output of the + classifier `method`. Pass an array-like to manually specify the thresholds + to use. + + cv : int, float, cross-validation generator, iterable or "prefit", default=None + Determines the cross-validation splitting strategy to train classifier. + Possible inputs for cv are: + + * `None`, to use the default 5-fold stratified K-fold cross validation; + * An integer number, to specify the number of folds in a stratified k-fold; + * A float number, to specify a single shuffle split. The floating number should + be in (0, 1) and represent the size of the validation set; + * An object to be used as a cross-validation generator; + * An iterable yielding train, test splits; + * `"prefit"`, to bypass the cross-validation. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. warning:: + Using `cv="prefit"` and passing the same dataset for fitting `estimator` + and tuning the cut-off point is subject to undesired overfitting. You can + refer to :ref:`TunedThresholdClassifierCV_no_cv` for an example. + + This option should only be used when the set used to fit `estimator` is + different from the one used to tune the cut-off point (by calling + :meth:`TunedThresholdClassifierCV.fit`). + + refit : bool, default=True + Whether or not to refit the classifier on the entire training set once + the decision threshold has been found. + Note that forcing `refit=False` on cross-validation having more + than a single split will raise an error. Similarly, `refit=True` in + conjunction with `cv="prefit"` will raise an error. + + n_jobs : int, default=None + The number of jobs to run in parallel. When `cv` represents a + cross-validation strategy, the fitting and scoring on each data split + is done in parallel. ``None`` means 1 unless in a + :obj:`joblib.parallel_backend` context. ``-1`` means using all + processors. See :term:`Glossary ` for more details. + + random_state : int, RandomState instance or None, default=None + Controls the randomness of cross-validation when `cv` is a float. + See :term:`Glossary `. + + store_cv_results : bool, default=False + Whether to store all scores and thresholds computed during the cross-validation + process. + + Attributes + ---------- + estimator_ : estimator instance + The fitted classifier used when predicting. + + best_threshold_ : float + The new decision threshold. + + best_score_ : float or None + The optimal score of the objective metric, evaluated at `best_threshold_`. + + cv_results_ : dict or None + A dictionary containing the scores and thresholds computed during the + cross-validation process. Only exist if `store_cv_results=True`. The + keys are `"thresholds"` and `"scores"`. + + classes_ : ndarray of shape (n_classes,) + The class labels. + + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if the + underlying estimator exposes such an attribute when fit. + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Only defined if the + underlying estimator exposes such an attribute when fit. + + See Also + -------- + sklearn.model_selection.FixedThresholdClassifier : Classifier that uses a + constant threshold. + sklearn.calibration.CalibratedClassifierCV : Estimator that calibrates + probabilities. + + Examples + -------- + >>> from sklearn.datasets import make_classification + >>> from sklearn.ensemble import RandomForestClassifier + >>> from sklearn.metrics import classification_report + >>> from sklearn.model_selection import TunedThresholdClassifierCV, train_test_split + >>> X, y = make_classification( + ... n_samples=1_000, weights=[0.9, 0.1], class_sep=0.8, random_state=42 + ... ) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, stratify=y, random_state=42 + ... ) + >>> classifier = RandomForestClassifier(random_state=0).fit(X_train, y_train) + >>> print(classification_report(y_test, classifier.predict(X_test))) + precision recall f1-score support + + 0 0.94 0.99 0.96 224 + 1 0.80 0.46 0.59 26 + + accuracy 0.93 250 + macro avg 0.87 0.72 0.77 250 + weighted avg 0.93 0.93 0.92 250 + + >>> classifier_tuned = TunedThresholdClassifierCV( + ... classifier, scoring="balanced_accuracy" + ... ).fit(X_train, y_train) + >>> print( + ... f"Cut-off point found at {classifier_tuned.best_threshold_:.3f}" + ... ) + Cut-off point found at 0.342 + >>> print(classification_report(y_test, classifier_tuned.predict(X_test))) + precision recall f1-score support + + 0 0.96 0.95 0.96 224 + 1 0.61 0.65 0.63 26 + + accuracy 0.92 250 + macro avg 0.78 0.80 0.79 250 + weighted avg 0.92 0.92 0.92 250 + + """ + + _parameter_constraints: dict = { + **BaseThresholdClassifier._parameter_constraints, + "scoring": [ + StrOptions(set(get_scorer_names())), + callable, + MutableMapping, + ], + "thresholds": [Interval(Integral, 1, None, closed="left"), "array-like"], + "cv": [ + "cv_object", + StrOptions({"prefit"}), + Interval(RealNotInt, 0.0, 1.0, closed="neither"), + ], + "refit": ["boolean"], + "n_jobs": [Integral, None], + "random_state": ["random_state"], + "store_cv_results": ["boolean"], + } + + def __init__( + self, + estimator, + *, + scoring="balanced_accuracy", + response_method="auto", + thresholds=100, + cv=None, + refit=True, + n_jobs=None, + random_state=None, + store_cv_results=False, + ): + super().__init__(estimator=estimator, response_method=response_method) + self.scoring = scoring + self.thresholds = thresholds + self.cv = cv + self.refit = refit + self.n_jobs = n_jobs + self.random_state = random_state + self.store_cv_results = store_cv_results + + def _fit(self, X, y, **params): + """Fit the classifier and post-tune the decision threshold. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) + Target values. + + **params : dict + Parameters to pass to the `fit` method of the underlying + classifier and to the `scoring` scorer. + + Returns + ------- + self : object + Returns an instance of self. + """ + if isinstance(self.cv, Real) and 0 < self.cv < 1: + cv = StratifiedShuffleSplit( + n_splits=1, test_size=self.cv, random_state=self.random_state + ) + elif self.cv == "prefit": + if self.refit is True: + raise ValueError("When cv='prefit', refit cannot be True.") + try: + check_is_fitted(self.estimator, "classes_") + except NotFittedError as exc: + raise NotFittedError( + """When cv='prefit', `estimator` must be fitted.""" + ) from exc + cv = self.cv + else: + cv = check_cv(self.cv, y=y, classifier=True) + if self.refit is False and cv.get_n_splits() > 1: + raise ValueError("When cv has several folds, refit cannot be False.") + + routed_params = process_routing(self, "fit", **params) + self._curve_scorer = self._get_curve_scorer() + + # in the following block, we: + # - define the final classifier `self.estimator_` and train it if necessary + # - define `classifier` to be used to post-tune the decision threshold + # - define `split` to be used to fit/score `classifier` + if cv == "prefit": + self.estimator_ = self.estimator + classifier = self.estimator_ + splits = [(None, range(_num_samples(X)))] + else: + self.estimator_ = clone(self.estimator) + classifier = clone(self.estimator) + splits = cv.split(X, y, **routed_params.splitter.split) + + if self.refit: + # train on the whole dataset + X_train, y_train, fit_params_train = X, y, routed_params.estimator.fit + else: + # single split cross-validation + train_idx, _ = next(cv.split(X, y, **routed_params.splitter.split)) + X_train = _safe_indexing(X, train_idx) + y_train = _safe_indexing(y, train_idx) + fit_params_train = _check_method_params( + X, routed_params.estimator.fit, indices=train_idx + ) + + self.estimator_.fit(X_train, y_train, **fit_params_train) + + cv_scores, cv_thresholds = zip( + *Parallel(n_jobs=self.n_jobs)( + delayed(_fit_and_score_over_thresholds)( + clone(classifier) if cv != "prefit" else classifier, + X, + y, + fit_params=routed_params.estimator.fit, + train_idx=train_idx, + val_idx=val_idx, + curve_scorer=self._curve_scorer, + score_params=routed_params.scorer.score, + ) + for train_idx, val_idx in splits + ) + ) + + if any(np.isclose(th[0], th[-1]) for th in cv_thresholds): + raise ValueError( + "The provided estimator makes constant predictions. Therefore, it is " + "impossible to optimize the decision threshold." + ) + + # find the global min and max thresholds across all folds + min_threshold = min( + split_thresholds.min() for split_thresholds in cv_thresholds + ) + max_threshold = max( + split_thresholds.max() for split_thresholds in cv_thresholds + ) + if isinstance(self.thresholds, Integral): + decision_thresholds = np.linspace( + min_threshold, max_threshold, num=self.thresholds + ) + else: + decision_thresholds = np.asarray(self.thresholds) + + objective_scores = _mean_interpolated_score( + decision_thresholds, cv_thresholds, cv_scores + ) + best_idx = objective_scores.argmax() + self.best_score_ = objective_scores[best_idx] + self.best_threshold_ = decision_thresholds[best_idx] + if self.store_cv_results: + self.cv_results_ = { + "thresholds": decision_thresholds, + "scores": objective_scores, + } + + return self + + def predict(self, X): + """Predict the target of new samples. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The samples, as accepted by `estimator.predict`. + + Returns + ------- + class_labels : ndarray of shape (n_samples,) + The predicted class. + """ + check_is_fitted(self, "estimator_") + pos_label = self._curve_scorer._get_pos_label() + y_score, _ = _get_response_values_binary( + self.estimator_, + X, + self._get_response_method(), + pos_label=pos_label, + ) + + return _threshold_scores_to_class_labels( + y_score, self.best_threshold_, self.classes_, pos_label + ) + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + Returns + ------- + routing : MetadataRouter + A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + router = ( + MetadataRouter(owner=self.__class__.__name__) + .add( + estimator=self.estimator, + method_mapping=MethodMapping().add(callee="fit", caller="fit"), + ) + .add( + splitter=self.cv, + method_mapping=MethodMapping().add(callee="split", caller="fit"), + ) + .add( + scorer=self._get_curve_scorer(), + method_mapping=MethodMapping().add(callee="score", caller="fit"), + ) + ) + return router + + def _get_curve_scorer(self): + """Get the curve scorer based on the objective metric used.""" + scoring = check_scoring(self.estimator, scoring=self.scoring) + curve_scorer = _CurveScorer.from_scorer( + scoring, self._get_response_method(), self.thresholds + ) + return curve_scorer diff --git a/shared/package-files/35/35a2b85a76e183948b10d6f8825bd65d0122bf70228f67fba5f196fbe43b4731/activate.py b/shared/package-files/35/35a2b85a76e183948b10d6f8825bd65d0122bf70228f67fba5f196fbe43b4731/activate.py new file mode 100644 index 0000000000000000000000000000000000000000..2eccc5f1f3f9fb08482127537646307b2ace2232 --- /dev/null +++ b/shared/package-files/35/35a2b85a76e183948b10d6f8825bd65d0122bf70228f67fba5f196fbe43b4731/activate.py @@ -0,0 +1,1257 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from __future__ import annotations + +import abc +import json +import os +import re +import sys +from collections.abc import Callable, Iterable +from os.path import ( + abspath, + basename, + dirname, + exists, + expanduser, + expandvars, + isdir, + join, +) +from pathlib import Path +from textwrap import dedent + +# Since we have to have configuration context here, anything imported by +# conda.base.context is fair game, but nothing more. +from . import CONDA_PACKAGE_ROOT, CONDA_SOURCE_ROOT +from .auxlib.compat import Utf8NamedTemporaryFile +from .base.constants import ( + CONDA_ENV_VARS_UNSET_VAR, + PACKAGE_ENV_VARS_DIR, + PREFIX_STATE_FILE, +) +from .base.context import ROOT_ENV_NAME, context, locate_prefix_by_name +from .common.compat import FILESYSTEM_ENCODING, on_win +from .common.path import paths_equal + + +class _Activator(metaclass=abc.ABCMeta): + # Activate and deactivate have three tasks + # 1. Set and unset environment variables + # 2. Execute/source activate.d/deactivate.d scripts + # 3. Update the command prompt + # + # Shells should also use 'reactivate' following conda's install, update, and + # remove/uninstall commands. + # + # All core logic is in build_activate() or build_deactivate(), and is independent of + # shell type. Each returns a map containing the keys: + # export_vars + # unset_var + # activate_scripts + # deactivate_scripts + # + # The value of the CONDA_PROMPT_MODIFIER environment variable holds conda's contribution + # to the command prompt. + # + # To implement support for a new shell, ideally one would only need to add shell-specific + # information to the __init__ method of this class. + + # The following instance variables must be defined by each implementation. + pathsep_join: str + sep: str + path_conversion: Callable[ + (str | Iterable[str] | None), str | tuple[str, ...] | None + ] + script_extension: str + #: temporary file's extension, None writes to stdout instead + tempfile_extension: str | None + command_join: str + + unset_var_tmpl: str + export_var_tmpl: str + set_var_tmpl: str + run_script_tmpl: str + + hook_source_path: str + + def __init__(self, arguments=None): + self._raw_arguments = arguments + self.environ = os.environ.copy() + + def get_export_unset_vars(self, export_metavars=True, **kwargs): + """ + :param export_metavars: whether to export `conda_exe_vars` meta variables. + :param kwargs: environment variables to export. + .. if you pass and set any other variable to None, then it + emits it to the dict with a value of None. + + :return: A dict of env vars to export ordered the same way as kwargs. + And a list of env vars to unset. + """ + unset_vars = [] + export_vars = {} + + # split provided environment variables into exports vs unsets + for name, value in kwargs.items(): + if value is None: + unset_vars.append(name.upper()) + else: + export_vars[name.upper()] = value + + if export_metavars: + # split meta variables into exports vs unsets + for name, value in context.conda_exe_vars_dict.items(): + if value is None: + unset_vars.append(name.upper()) + elif "/" in value or "\\" in value: + export_vars[name.upper()] = self.path_conversion(value) + else: + export_vars[name.upper()] = value + else: + # unset all meta variables + unset_vars.extend(context.conda_exe_vars_dict) + + return export_vars, unset_vars + + # Used in tests only. + def add_export_unset_vars(self, export_vars, unset_vars, **kwargs): + new_export_vars, new_unset_vars = self.get_export_unset_vars(**kwargs) + if export_vars is not None: + export_vars = {**export_vars, **new_export_vars} + if unset_vars is not None: + unset_vars = [*unset_vars, *new_unset_vars] + return export_vars, unset_vars + + # Used in tests only. + def get_scripts_export_unset_vars(self, **kwargs): + export_vars, unset_vars = self.get_export_unset_vars(**kwargs) + script_export_vars = script_unset_vars = None + if export_vars: + script_export_vars = self.command_join.join( + [self.export_var_tmpl % (k, v) for k, v in export_vars.items()] + ) + if unset_vars: + script_unset_vars = self.command_join.join( + [self.unset_var_tmpl % (k) for k in unset_vars] + ) + return script_export_vars or "", script_unset_vars or "" + + def _finalize(self, commands, ext): + commands = (*commands, "") # add terminating newline + if ext is None: + return self.command_join.join(commands) + elif ext: + with Utf8NamedTemporaryFile("w+", suffix=ext, delete=False) as tf: + # the default mode is 'w+b', and universal new lines don't work in that mode + # command_join should account for that + tf.write(self.command_join.join(commands)) + return tf.name + else: + raise NotImplementedError() + + def activate(self): + if self.stack: + builder_result = self.build_stack(self.env_name_or_prefix) + else: + builder_result = self.build_activate(self.env_name_or_prefix) + return self._finalize( + self._yield_commands(builder_result), self.tempfile_extension + ) + + def deactivate(self): + return self._finalize( + self._yield_commands(self.build_deactivate()), self.tempfile_extension + ) + + def reactivate(self): + return self._finalize( + self._yield_commands(self.build_reactivate()), self.tempfile_extension + ) + + def hook(self, auto_activate_base=None): + builder = [] + builder.append(self._hook_preamble()) + with open(self.hook_source_path) as fsrc: + builder.append(fsrc.read()) + if ( + auto_activate_base is None + and context.auto_activate_base + or auto_activate_base + ): + builder.append("conda activate base\n") + postamble = self._hook_postamble() + if postamble is not None: + builder.append(postamble) + return "\n".join(builder) + + def execute(self): + # return value meant to be written to stdout + self._parse_and_set_args(self._raw_arguments) + return getattr(self, self.command)() + + def commands(self): + """ + Returns a list of possible subcommands that are valid + immediately following `conda` at the command line. + This method is generally only used by tab-completion. + """ + # Import locally to reduce impact on initialization time. + from .cli.conda_argparse import find_builtin_commands, generate_parser + from .cli.find_commands import find_commands + + # return value meant to be written to stdout + # Hidden commands to provide metadata to shells. + return "\n".join( + sorted( + find_builtin_commands(generate_parser()) + tuple(find_commands(True)) + ) + ) + + @abc.abstractmethod + def _hook_preamble(self) -> str | None: + # must be implemented in subclass + raise NotImplementedError + + def _hook_postamble(self) -> str | None: + return None + + def _parse_and_set_args(self, arguments): + def raise_invalid_command_error(actual_command=None): + from .exceptions import ArgumentError + + message = ( + "'activate', 'deactivate', 'hook', 'commands', or 'reactivate' " + "command must be given" + ) + if actual_command: + message += ". Instead got '%s'." % actual_command + raise ArgumentError(message) + + if arguments is None or len(arguments) < 1: + raise_invalid_command_error() + + command, *arguments = arguments + help_flags = ("-h", "--help", "/?") + non_help_args = tuple(arg for arg in arguments if arg not in help_flags) + help_requested = len(arguments) != len(non_help_args) + remainder_args = list(arg for arg in non_help_args if arg and arg != command) + + if not command: + raise_invalid_command_error() + elif help_requested: + from .exceptions import ActivateHelp, DeactivateHelp, GenericHelp + + help_classes = { + "activate": ActivateHelp(), + "deactivate": DeactivateHelp(), + "hook": GenericHelp("hook"), + "commands": GenericHelp("commands"), + "reactivate": GenericHelp("reactivate"), + } + raise help_classes[command] + elif command not in ( + "activate", + "deactivate", + "reactivate", + "hook", + "commands", + ): + raise_invalid_command_error(actual_command=command) + + if command.endswith("activate") or command == "hook": + try: + dev_idx = remainder_args.index("--dev") + except ValueError: + context.dev = False + else: + del remainder_args[dev_idx] + context.dev = True + + if command == "activate": + self.stack = context.auto_stack and context.shlvl <= context.auto_stack + try: + stack_idx = remainder_args.index("--stack") + except ValueError: + stack_idx = -1 + try: + no_stack_idx = remainder_args.index("--no-stack") + except ValueError: + no_stack_idx = -1 + if stack_idx >= 0 and no_stack_idx >= 0: + from .exceptions import ArgumentError + + raise ArgumentError( + "cannot specify both --stack and --no-stack to " + command + ) + if stack_idx >= 0: + self.stack = True + del remainder_args[stack_idx] + if no_stack_idx >= 0: + self.stack = False + del remainder_args[no_stack_idx] + if len(remainder_args) > 1: + from .exceptions import ArgumentError + + raise ArgumentError( + command + + " does not accept more than one argument:\n" + + str(remainder_args) + + "\n" + ) + self.env_name_or_prefix = remainder_args and remainder_args[0] or "base" + + else: + if remainder_args: + from .exceptions import ArgumentError + + raise ArgumentError( + "%s does not accept arguments\nremainder_args: %s\n" + % (command, remainder_args) + ) + + self.command = command + + def _yield_commands(self, cmds_dict): + for key, value in sorted(cmds_dict.get("export_path", {}).items()): + yield self.export_var_tmpl % (key, value) + + for script in cmds_dict.get("deactivate_scripts", ()): + yield self.run_script_tmpl % script + + for key in cmds_dict.get("unset_vars", ()): + yield self.unset_var_tmpl % key + + for key, value in cmds_dict.get("set_vars", {}).items(): + yield self.set_var_tmpl % (key, value) + + for key, value in cmds_dict.get("export_vars", {}).items(): + yield self.export_var_tmpl % (key, value) + + for script in cmds_dict.get("activate_scripts", ()): + yield self.run_script_tmpl % script + + def build_activate(self, env_name_or_prefix): + return self._build_activate_stack(env_name_or_prefix, False) + + def build_stack(self, env_name_or_prefix): + return self._build_activate_stack(env_name_or_prefix, True) + + def _build_activate_stack(self, env_name_or_prefix, stack): + # get environment prefix + if re.search(r"\\|/", env_name_or_prefix): + prefix = expand(env_name_or_prefix) + if not isdir(join(prefix, "conda-meta")): + from .exceptions import EnvironmentLocationNotFound + + raise EnvironmentLocationNotFound(prefix) + elif env_name_or_prefix in (ROOT_ENV_NAME, "root"): + prefix = context.root_prefix + else: + prefix = locate_prefix_by_name(env_name_or_prefix) + + # get prior shlvl and prefix + old_conda_shlvl = int(self.environ.get("CONDA_SHLVL", "").strip() or 0) + old_conda_prefix = self.environ.get("CONDA_PREFIX") + + # if the prior active prefix is this prefix we are actually doing a reactivate + if old_conda_prefix == prefix and old_conda_shlvl > 0: + return self.build_reactivate() + + activate_scripts = self._get_activate_scripts(prefix) + conda_shlvl = old_conda_shlvl + 1 + conda_default_env = self._default_env(prefix) + conda_prompt_modifier = self._prompt_modifier(prefix, conda_default_env) + env_vars = { + name: value + for name, value in self._get_environment_env_vars(prefix).items() + if value != CONDA_ENV_VARS_UNSET_VAR + } + + # get clobbered environment variables + clobber_vars = set(env_vars.keys()).intersection(os.environ.keys()) + clobber_vars = set( + filter(lambda var: env_vars[var] != os.environ[var], clobber_vars) + ) + if clobber_vars: + print( + "WARNING: overwriting environment variables set in the machine", + file=sys.stderr, + ) + print(f"overwriting variable {clobber_vars}", file=sys.stderr) + for name in clobber_vars: + env_vars[f"__CONDA_SHLVL_{old_conda_shlvl}_{name}"] = os.environ.get(name) + + if old_conda_shlvl == 0: + export_vars, unset_vars = self.get_export_unset_vars( + path=self.pathsep_join(self._add_prefix_to_path(prefix)), + conda_prefix=prefix, + conda_shlvl=conda_shlvl, + conda_default_env=conda_default_env, + conda_prompt_modifier=conda_prompt_modifier, + **env_vars, + ) + deactivate_scripts = () + elif stack: + export_vars, unset_vars = self.get_export_unset_vars( + path=self.pathsep_join(self._add_prefix_to_path(prefix)), + conda_prefix=prefix, + conda_shlvl=conda_shlvl, + conda_default_env=conda_default_env, + conda_prompt_modifier=conda_prompt_modifier, + **env_vars, + **{ + f"CONDA_PREFIX_{old_conda_shlvl}": old_conda_prefix, + f"CONDA_STACKED_{conda_shlvl}": "true", + }, + ) + deactivate_scripts = () + else: + export_vars, unset_vars = self.get_export_unset_vars( + path=self.pathsep_join( + self._replace_prefix_in_path(old_conda_prefix, prefix) + ), + conda_prefix=prefix, + conda_shlvl=conda_shlvl, + conda_default_env=conda_default_env, + conda_prompt_modifier=conda_prompt_modifier, + **env_vars, + **{ + f"CONDA_PREFIX_{old_conda_shlvl}": old_conda_prefix, + }, + ) + deactivate_scripts = self._get_deactivate_scripts(old_conda_prefix) + + set_vars = {} + if context.changeps1: + self._update_prompt(set_vars, conda_prompt_modifier) + + return { + "unset_vars": unset_vars, + "set_vars": set_vars, + "export_vars": export_vars, + "deactivate_scripts": deactivate_scripts, + "activate_scripts": activate_scripts, + } + + def build_deactivate(self): + self._deactivate = True + # query environment + old_conda_prefix = self.environ.get("CONDA_PREFIX") + old_conda_shlvl = int(self.environ.get("CONDA_SHLVL", "").strip() or 0) + if not old_conda_prefix or old_conda_shlvl < 1: + # no active environment, so cannot deactivate; do nothing + return { + "unset_vars": (), + "set_vars": {}, + "export_vars": {}, + "deactivate_scripts": (), + "activate_scripts": (), + } + deactivate_scripts = self._get_deactivate_scripts(old_conda_prefix) + old_conda_environment_env_vars = self._get_environment_env_vars( + old_conda_prefix + ) + + new_conda_shlvl = old_conda_shlvl - 1 + set_vars = {} + if old_conda_shlvl == 1: + new_path = self.pathsep_join( + self._remove_prefix_from_path(old_conda_prefix) + ) + # You might think that you can remove the CONDA_EXE vars with export_metavars=False + # here so that "deactivate means deactivate" but you cannot since the conda shell + # scripts still refer to them and they only set them once at the top. We could change + # that though, the conda() shell function could set them instead of doing it at the + # top. This would be *much* cleaner. I personally cannot abide that I have + # deactivated conda and anything at all in my env still references it (apart from the + # shell script, we need something I suppose!) + export_vars, unset_vars = self.get_export_unset_vars( + conda_prefix=None, + conda_shlvl=new_conda_shlvl, + conda_default_env=None, + conda_prompt_modifier=None, + ) + conda_prompt_modifier = "" + activate_scripts = () + export_path = { + "PATH": new_path, + } + else: + assert old_conda_shlvl > 1 + new_prefix = self.environ.get("CONDA_PREFIX_%d" % new_conda_shlvl) + conda_default_env = self._default_env(new_prefix) + conda_prompt_modifier = self._prompt_modifier(new_prefix, conda_default_env) + new_conda_environment_env_vars = self._get_environment_env_vars(new_prefix) + + old_prefix_stacked = "CONDA_STACKED_%d" % old_conda_shlvl in self.environ + new_path = "" + + unset_vars = ["CONDA_PREFIX_%d" % new_conda_shlvl] + if old_prefix_stacked: + new_path = self.pathsep_join( + self._remove_prefix_from_path(old_conda_prefix) + ) + unset_vars.append("CONDA_STACKED_%d" % old_conda_shlvl) + else: + new_path = self.pathsep_join( + self._replace_prefix_in_path(old_conda_prefix, new_prefix) + ) + + export_vars, unset_vars2 = self.get_export_unset_vars( + conda_prefix=new_prefix, + conda_shlvl=new_conda_shlvl, + conda_default_env=conda_default_env, + conda_prompt_modifier=conda_prompt_modifier, + **new_conda_environment_env_vars, + ) + unset_vars += unset_vars2 + export_path = { + "PATH": new_path, + } + activate_scripts = self._get_activate_scripts(new_prefix) + + if context.changeps1: + self._update_prompt(set_vars, conda_prompt_modifier) + + for env_var in old_conda_environment_env_vars.keys(): + unset_vars.append(env_var) + save_var = f"__CONDA_SHLVL_{new_conda_shlvl}_{env_var}" + if save_var in os.environ.keys(): + export_vars[env_var] = os.environ[save_var] + return { + "unset_vars": unset_vars, + "set_vars": set_vars, + "export_vars": export_vars, + "export_path": export_path, + "deactivate_scripts": deactivate_scripts, + "activate_scripts": activate_scripts, + } + + def build_reactivate(self): + self._reactivate = True + conda_prefix = self.environ.get("CONDA_PREFIX") + conda_shlvl = int(self.environ.get("CONDA_SHLVL", "").strip() or 0) + if not conda_prefix or conda_shlvl < 1: + # no active environment, so cannot reactivate; do nothing + return { + "unset_vars": (), + "set_vars": {}, + "export_vars": {}, + "deactivate_scripts": (), + "activate_scripts": (), + } + conda_default_env = self.environ.get( + "CONDA_DEFAULT_ENV", self._default_env(conda_prefix) + ) + new_path = self.pathsep_join( + self._replace_prefix_in_path(conda_prefix, conda_prefix) + ) + set_vars = {} + conda_prompt_modifier = self._prompt_modifier(conda_prefix, conda_default_env) + if context.changeps1: + self._update_prompt(set_vars, conda_prompt_modifier) + + env_vars_to_unset = () + env_vars_to_export = { + "PATH": new_path, + "CONDA_SHLVL": conda_shlvl, + "CONDA_PROMPT_MODIFIER": self._prompt_modifier( + conda_prefix, conda_default_env + ), + } + conda_environment_env_vars = self._get_environment_env_vars(conda_prefix) + for k, v in conda_environment_env_vars.items(): + if v == CONDA_ENV_VARS_UNSET_VAR: + env_vars_to_unset = env_vars_to_unset + (k,) + else: + env_vars_to_export[k] = v + # environment variables are set only to aid transition from conda 4.3 to conda 4.4 + return { + "unset_vars": env_vars_to_unset, + "set_vars": set_vars, + "export_vars": env_vars_to_export, + "deactivate_scripts": self._get_deactivate_scripts(conda_prefix), + "activate_scripts": self._get_activate_scripts(conda_prefix), + } + + def _get_starting_path_list(self): + # For isolation, running the conda test suite *without* env. var. inheritance + # every so often is a good idea. We should probably make this a pytest fixture + # along with one that tests both hardlink-only and copy-only, but before that + # conda's testsuite needs to be a lot faster! + clean_paths = { + "darwin": "/usr/bin:/bin:/usr/sbin:/sbin", + # You may think 'let us do something more clever here and interpolate + # `%windir%`' but the point here is the the whole env. is cleaned out + "win32": "C:\\Windows\\system32;" + "C:\\Windows;" + "C:\\Windows\\System32\\Wbem;" + "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\", + } + path = self.environ.get( + "PATH", + clean_paths[sys.platform] if sys.platform in clean_paths else "/usr/bin", + ) + path_split = path.split(os.pathsep) + return path_split + + def _get_path_dirs(self, prefix, extra_library_bin=False): + if on_win: # pragma: unix no cover + yield prefix.rstrip("\\") + yield self.sep.join((prefix, "Library", "mingw-w64", "bin")) + yield self.sep.join((prefix, "Library", "usr", "bin")) + yield self.sep.join((prefix, "Library", "bin")) + yield self.sep.join((prefix, "Scripts")) + yield self.sep.join((prefix, "bin")) + else: + yield self.sep.join((prefix, "bin")) + + def _add_prefix_to_path(self, prefix, starting_path_dirs=None): + prefix = self.path_conversion(prefix) + if starting_path_dirs is None: + path_list = list(self.path_conversion(self._get_starting_path_list())) + else: + path_list = list(self.path_conversion(starting_path_dirs)) + + # If this is the first time we're activating an environment, we need to ensure that + # the condabin directory is included in the path list. + # Under normal conditions, if the shell hook is working correctly, this should + # never trigger. + old_conda_shlvl = int(self.environ.get("CONDA_SHLVL", "").strip() or 0) + if not old_conda_shlvl and not any(p.endswith("condabin") for p in path_list): + condabin_dir = self.path_conversion(join(context.conda_prefix, "condabin")) + path_list.insert(0, condabin_dir) + + path_list[0:0] = list(self.path_conversion(self._get_path_dirs(prefix))) + return tuple(path_list) + + def _remove_prefix_from_path(self, prefix, starting_path_dirs=None): + return self._replace_prefix_in_path(prefix, None, starting_path_dirs) + + def _replace_prefix_in_path(self, old_prefix, new_prefix, starting_path_dirs=None): + old_prefix = self.path_conversion(old_prefix) + new_prefix = self.path_conversion(new_prefix) + if starting_path_dirs is None: + path_list = list(self.path_conversion(self._get_starting_path_list())) + else: + path_list = list(self.path_conversion(starting_path_dirs)) + + def index_of_path(paths, test_path): + for q, path in enumerate(paths): + if paths_equal(path, test_path): + return q + return None + + if old_prefix is not None: + prefix_dirs = tuple(self._get_path_dirs(old_prefix)) + first_idx = index_of_path(path_list, prefix_dirs[0]) + if first_idx is None: + first_idx = 0 + else: + prefix_dirs_idx = len(prefix_dirs) - 1 + last_idx = None + while last_idx is None and prefix_dirs_idx > -1: + last_idx = index_of_path(path_list, prefix_dirs[prefix_dirs_idx]) + if last_idx is None: + print( + f"Did not find path entry {prefix_dirs[prefix_dirs_idx]}", + file=sys.stderr, + ) + prefix_dirs_idx = prefix_dirs_idx - 1 + # this compensates for an extra Library/bin dir entry from the interpreter on + # windows. If that entry isn't being added, it should have no effect. + library_bin_dir = self.path_conversion( + self.sep.join((sys.prefix, "Library", "bin")) + ) + if path_list[last_idx + 1] == library_bin_dir: + last_idx += 1 + del path_list[first_idx : last_idx + 1] + else: + first_idx = 0 + + if new_prefix is not None: + path_list[first_idx:first_idx] = list(self._get_path_dirs(new_prefix)) + + return tuple(path_list) + + def _update_prompt(self, set_vars, conda_prompt_modifier): + pass + + def _default_env(self, prefix): + if paths_equal(prefix, context.root_prefix): + return "base" + return basename(prefix) if basename(dirname(prefix)) == "envs" else prefix + + def _prompt_modifier(self, prefix, conda_default_env): + if context.changeps1: + # Get current environment and prompt stack + env_stack = [] + prompt_stack = [] + old_shlvl = int(self.environ.get("CONDA_SHLVL", "0").rstrip()) + for i in range(1, old_shlvl + 1): + if i == old_shlvl: + env_i = self._default_env(self.environ.get("CONDA_PREFIX", "")) + else: + env_i = self._default_env( + self.environ.get(f"CONDA_PREFIX_{i}", "").rstrip() + ) + stacked_i = bool(self.environ.get(f"CONDA_STACKED_{i}", "").rstrip()) + env_stack.append(env_i) + if not stacked_i: + prompt_stack = prompt_stack[0:-1] + prompt_stack.append(env_i) + + # Modify prompt stack according to pending operation + deactivate = getattr(self, "_deactivate", False) + reactivate = getattr(self, "_reactivate", False) + if deactivate: + prompt_stack = prompt_stack[0:-1] + env_stack = env_stack[0:-1] + stacked = bool( + self.environ.get(f"CONDA_STACKED_{old_shlvl}", "").rstrip() + ) + if not stacked and env_stack: + prompt_stack.append(env_stack[-1]) + elif reactivate: + pass + else: + stack = getattr(self, "stack", False) + if not stack: + prompt_stack = prompt_stack[0:-1] + prompt_stack.append(conda_default_env) + + conda_stacked_env = ",".join(prompt_stack[::-1]) + + return context.env_prompt.format( + default_env=conda_default_env, + stacked_env=conda_stacked_env, + prefix=prefix, + name=basename(prefix), + ) + else: + return "" + + def _get_activate_scripts(self, prefix): + _script_extension = self.script_extension + se_len = -len(_script_extension) + try: + paths = ( + entry.path + for entry in os.scandir(join(prefix, "etc", "conda", "activate.d")) + ) + except OSError: + return () + return self.path_conversion( + sorted(p for p in paths if p[se_len:] == _script_extension) + ) + + def _get_deactivate_scripts(self, prefix): + _script_extension = self.script_extension + se_len = -len(_script_extension) + try: + paths = ( + entry.path + for entry in os.scandir(join(prefix, "etc", "conda", "deactivate.d")) + ) + except OSError: + return () + return self.path_conversion( + sorted((p for p in paths if p[se_len:] == _script_extension), reverse=True) + ) + + def _get_environment_env_vars(self, prefix): + env_vars_file = join(prefix, PREFIX_STATE_FILE) + pkg_env_var_dir = join(prefix, PACKAGE_ENV_VARS_DIR) + env_vars = {} + + # First get env vars from packages + if exists(pkg_env_var_dir): + for pkg_env_var_path in sorted( + entry.path for entry in os.scandir(pkg_env_var_dir) + ): + with open(pkg_env_var_path) as f: + env_vars.update(json.loads(f.read())) + + # Then get env vars from environment specification + if exists(env_vars_file): + with open(env_vars_file) as f: + prefix_state = json.loads(f.read()) + prefix_state_env_vars = prefix_state.get("env_vars", {}) + dup_vars = [ + ev for ev in env_vars.keys() if ev in prefix_state_env_vars.keys() + ] + for dup in dup_vars: + print( + "WARNING: duplicate env vars detected. Vars from the environment " + "will overwrite those from packages", + file=sys.stderr, + ) + print("variable %s duplicated" % dup, file=sys.stderr) + env_vars.update(prefix_state_env_vars) + + return env_vars + + +def expand(path): + return abspath(expanduser(expandvars(path))) + + +def ensure_binary(value): + try: + return value.encode("utf-8") + except AttributeError: # pragma: no cover + # AttributeError: '<>' object has no attribute 'encode' + # In this case assume already binary type and do nothing + return value + + +def ensure_fs_path_encoding(value): + try: + return value.decode(FILESYSTEM_ENCODING) + except AttributeError: + return value + + +def native_path_to_unix( + paths: str | Iterable[str] | None, +) -> str | tuple[str, ...] | None: + if paths is None: + return None + elif not on_win: + return path_identity(paths) + + # short-circuit if we don't get any paths + paths = paths if isinstance(paths, str) else tuple(paths) + if not paths: + return "." if isinstance(paths, str) else () + + # on windows, uses cygpath to convert windows native paths to posix paths + from shutil import which + from subprocess import run + + # It is very easy to end up with a bash in one place and a cygpath in another due to e.g. + # using upstream MSYS2 bash, but with a conda env that does not have bash but does have + # cygpath. When this happens, we have two different virtual POSIX machines, rooted at + # different points in the Windows filesystem. We do our path conversions with one and + # expect the results to work with the other. It does not. + + bash = which("bash") + cygpath = (Path(bash).parent / "cygpath") if bash else "cygpath" + joined = paths if isinstance(paths, str) else os.pathsep.join(paths) + + try: + # if present, use cygpath to convert paths since its more reliable + unix_path = run( + [cygpath, "--path", joined], + text=True, + capture_output=True, + check=True, + ).stdout.strip() + except FileNotFoundError: + # fallback logic when cygpath is not available + # i.e. conda without anything else installed + def _translation(found_path): + found = ( + found_path.group(1) + .replace("\\", "/") + .replace(":", "") + .replace("//", "/") + ) + return "/" + found.rstrip("/") + + unix_path = ( + re.sub( + r"([a-zA-Z]:[\/\\\\]+(?:[^:*?\"<>|;]+[\/\\\\]*)*)", + _translation, + joined, + ) + .replace(";/", ":/") + .rstrip(";") + ) + + unix_path = unix_path.split(":") if unix_path else () + + return unix_path[0] if isinstance(paths, str) else tuple(unix_path) + + +def path_identity(paths: str | Iterable[str] | None) -> str | tuple[str, ...] | None: + if paths is None: + return None + elif isinstance(paths, str): + return os.path.normpath(paths) + else: + return tuple(os.path.normpath(path) for path in paths) + + +def backslash_to_forwardslash( + paths: str | Iterable[str] | None, +) -> str | tuple[str, ...] | None: + if paths is None: + return None + elif isinstance(paths, str): + return paths.replace("\\", "/") + else: + return tuple([path.replace("\\", "/") for path in paths]) + + +class PosixActivator(_Activator): + pathsep_join = ":".join + sep = "/" + path_conversion = staticmethod(native_path_to_unix) + script_extension = ".sh" + tempfile_extension = None # output to stdout + command_join = "\n" + + unset_var_tmpl = "unset %s" + export_var_tmpl = "export %s='%s'" + set_var_tmpl = "%s='%s'" + run_script_tmpl = '. "%s"' + + hook_source_path = join( + CONDA_PACKAGE_ROOT, + "shell", + "etc", + "profile.d", + "conda.sh", + ) + + def _update_prompt(self, set_vars, conda_prompt_modifier): + ps1 = self.environ.get("PS1", "") + if "POWERLINE_COMMAND" in ps1: + # Defer to powerline (https://github.com/powerline/powerline) if it's in use. + return + current_prompt_modifier = self.environ.get("CONDA_PROMPT_MODIFIER") + if current_prompt_modifier: + ps1 = re.sub(re.escape(current_prompt_modifier), r"", ps1) + # Because we're using single-quotes to set shell variables, we need to handle the + # proper escaping of single quotes that are already part of the string. + # Best solution appears to be https://stackoverflow.com/a/1250279 + ps1 = ps1.replace("'", "'\"'\"'") + set_vars.update( + { + "PS1": conda_prompt_modifier + ps1, + } + ) + + def _hook_preamble(self) -> str: + result = [] + for key, value in context.conda_exe_vars_dict.items(): + if value is None: + # Using `unset_var_tmpl` would cause issues for people running + # with shell flag -u set (error on unset). + result.append(self.export_var_tmpl % (key, "")) + elif on_win and ("/" in value or "\\" in value): + result.append(f'''export {key}="$(cygpath '{value}')"''') + else: + result.append(self.export_var_tmpl % (key, value)) + return "\n".join(result) + "\n" + + +class CshActivator(_Activator): + pathsep_join = ":".join + sep = "/" + path_conversion = staticmethod(native_path_to_unix) + script_extension = ".csh" + tempfile_extension = None # output to stdout + command_join = ";\n" + + unset_var_tmpl = "unsetenv %s" + export_var_tmpl = 'setenv %s "%s"' + set_var_tmpl = "set %s='%s'" + run_script_tmpl = 'source "%s"' + + hook_source_path = join( + CONDA_PACKAGE_ROOT, + "shell", + "etc", + "profile.d", + "conda.csh", + ) + + def _update_prompt(self, set_vars, conda_prompt_modifier): + prompt = self.environ.get("prompt", "") + current_prompt_modifier = self.environ.get("CONDA_PROMPT_MODIFIER") + if current_prompt_modifier: + prompt = re.sub(re.escape(current_prompt_modifier), r"", prompt) + set_vars.update( + { + "prompt": conda_prompt_modifier + prompt, + } + ) + + def _hook_preamble(self) -> str: + if on_win: + return dedent( + f""" + setenv CONDA_EXE `cygpath {context.conda_exe}` + setenv _CONDA_ROOT `cygpath {context.conda_prefix}` + setenv _CONDA_EXE `cygpath {context.conda_exe}` + setenv CONDA_PYTHON_EXE `cygpath {sys.executable}` + """ + ).strip() + else: + return dedent( + f""" + setenv CONDA_EXE "{context.conda_exe}" + setenv _CONDA_ROOT "{context.conda_prefix}" + setenv _CONDA_EXE "{context.conda_exe}" + setenv CONDA_PYTHON_EXE "{sys.executable}" + """ + ).strip() + + +class XonshActivator(_Activator): + pathsep_join = ";".join if on_win else ":".join + sep = "/" + path_conversion = staticmethod( + backslash_to_forwardslash if on_win else path_identity + ) + # 'scripts' really refer to de/activation scripts, not scripts in the language per se + # xonsh can piggy-back activation scripts from other languages depending on the platform + script_extension = ".bat" if on_win else ".sh" + tempfile_extension = None # output to stdout + command_join = "\n" + + unset_var_tmpl = "del $%s" + export_var_tmpl = "$%s = '%s'" + # TODO: determine if different than export_var_tmpl + set_var_tmpl = "$%s = '%s'" + run_script_tmpl = ( + 'source-cmd --suppress-skip-message "%s"' + if on_win + else 'source-bash --suppress-skip-message "%s"' + ) + + hook_source_path = join(CONDA_PACKAGE_ROOT, "shell", "conda.xsh") + + def _hook_preamble(self) -> str: + return '$CONDA_EXE = "%s"' % self.path_conversion(context.conda_exe) + + +class CmdExeActivator(_Activator): + pathsep_join = ";".join + sep = "\\" + path_conversion = staticmethod(path_identity) + script_extension = ".bat" + tempfile_extension = ".bat" + command_join = "\n" + + unset_var_tmpl = "@SET %s=" + export_var_tmpl = '@SET "%s=%s"' + # TODO: determine if different than export_var_tmpl + set_var_tmpl = '@SET "%s=%s"' + run_script_tmpl = '@CALL "%s"' + + hook_source_path = None + + def _hook_preamble(self) -> None: + # TODO: cmd.exe doesn't get a hook function? Or do we need to do something different? + # Like, for cmd.exe only, put a special directory containing only conda.bat on PATH? + pass + + +class FishActivator(_Activator): + pathsep_join = '" "'.join + sep = "/" + path_conversion = staticmethod(native_path_to_unix) + script_extension = ".fish" + tempfile_extension = None # output to stdout + command_join = ";\n" + + unset_var_tmpl = "set -e %s" + export_var_tmpl = 'set -gx %s "%s"' + set_var_tmpl = 'set -g %s "%s"' + run_script_tmpl = 'source "%s"' + + hook_source_path = join( + CONDA_PACKAGE_ROOT, + "shell", + "etc", + "fish", + "conf.d", + "conda.fish", + ) + + def _hook_preamble(self) -> str: + if on_win: + return dedent( + f""" + set -gx CONDA_EXE (cygpath "{context.conda_exe}") + set _CONDA_ROOT (cygpath "{context.conda_prefix}") + set _CONDA_EXE (cygpath "{context.conda_exe}") + set -gx CONDA_PYTHON_EXE (cygpath "{sys.executable}") + """ + ).strip() + else: + return dedent( + f""" + set -gx CONDA_EXE "{context.conda_exe}" + set _CONDA_ROOT "{context.conda_prefix}" + set _CONDA_EXE "{context.conda_exe}" + set -gx CONDA_PYTHON_EXE "{sys.executable}" + """ + ).strip() + + +class PowerShellActivator(_Activator): + pathsep_join = ";".join if on_win else ":".join + sep = "\\" if on_win else "/" + path_conversion = staticmethod(path_identity) + script_extension = ".ps1" + tempfile_extension = None # output to stdout + command_join = "\n" + + unset_var_tmpl = '$Env:%s = ""' + export_var_tmpl = '$Env:%s = "%s"' + set_var_tmpl = '$Env:%s = "%s"' + run_script_tmpl = '. "%s"' + + hook_source_path = join( + CONDA_PACKAGE_ROOT, + "shell", + "condabin", + "conda-hook.ps1", + ) + + def _hook_preamble(self) -> str: + if context.dev: + return dedent( + f""" + $Env:PYTHONPATH = "{CONDA_SOURCE_ROOT}" + $Env:CONDA_EXE = "{sys.executable}" + $Env:_CE_M = "-m" + $Env:_CE_CONDA = "conda" + $Env:_CONDA_ROOT = "{CONDA_PACKAGE_ROOT}" + $Env:_CONDA_EXE = "{context.conda_exe}" + $CondaModuleArgs = @{{ChangePs1 = ${context.changeps1}}} + """ + ).strip() + else: + return dedent( + f""" + $Env:CONDA_EXE = "{context.conda_exe}" + $Env:_CE_M = "" + $Env:_CE_CONDA = "" + $Env:_CONDA_ROOT = "{context.conda_prefix}" + $Env:_CONDA_EXE = "{context.conda_exe}" + $CondaModuleArgs = @{{ChangePs1 = ${context.changeps1}}} + """ + ).strip() + + def _hook_postamble(self) -> str: + return "Remove-Variable CondaModuleArgs" + + +class JSONFormatMixin(_Activator): + """Returns the necessary values for activation as JSON, so that tools can use them.""" + + pathsep_join = list + tempfile_extension = None # output to stdout + command_join = list + + def _hook_preamble(self): + if context.dev: + return { + "PYTHONPATH": CONDA_SOURCE_ROOT, + "CONDA_EXE": sys.executable, + "_CE_M": "-m", + "_CE_CONDA": "conda", + "_CONDA_ROOT": CONDA_PACKAGE_ROOT, + "_CONDA_EXE": context.conda_exe, + } + else: + return { + "CONDA_EXE": context.conda_exe, + "_CE_M": "", + "_CE_CONDA": "", + "_CONDA_ROOT": context.conda_prefix, + "_CONDA_EXE": context.conda_exe, + } + + def get_scripts_export_unset_vars(self, **kwargs): + export_vars, unset_vars = self.get_export_unset_vars(**kwargs) + script_export_vars = script_unset_vars = None + if export_vars: + script_export_vars = dict(export_vars.items()) + if unset_vars: + script_unset_vars = unset_vars + return script_export_vars or {}, script_unset_vars or [] + + def _finalize(self, commands, ext): + merged = {} + for _cmds in commands: + merged.update(_cmds) + + commands = merged + if ext is None: + return json.dumps(commands, indent=2) + elif ext: + with Utf8NamedTemporaryFile("w+", suffix=ext, delete=False) as tf: + # the default mode is 'w+b', and universal new lines don't work in that mode + # command_join should account for that + json.dump(commands, tf, indent=2) + return tf.name + else: + raise NotImplementedError() + + def _yield_commands(self, cmds_dict): + # TODO: _Is_ defining our own object shape here any better than + # just dumping the `cmds_dict`? + path = cmds_dict.get("export_path", {}) + export_vars = cmds_dict.get("export_vars", {}) + # treat PATH specially + if "PATH" in export_vars: + new_path = path.get("PATH", []) + new_path.extend(export_vars.pop("PATH")) + path["PATH"] = new_path + + yield { + "path": path, + "vars": { + "export": export_vars, + "unset": cmds_dict.get("unset_vars", ()), + "set": cmds_dict.get("set_vars", {}), + }, + "scripts": { + "activate": cmds_dict.get("activate_scripts", ()), + "deactivate": cmds_dict.get("deactivate_scripts", ()), + }, + } + + +activator_map: dict[str, type[_Activator]] = { + "posix": PosixActivator, + "ash": PosixActivator, + "bash": PosixActivator, + "dash": PosixActivator, + "zsh": PosixActivator, + "csh": CshActivator, + "tcsh": CshActivator, + "xonsh": XonshActivator, + "cmd.exe": CmdExeActivator, + "fish": FishActivator, + "powershell": PowerShellActivator, +} + +formatter_map = { + "json": JSONFormatMixin, +} + + +def _build_activator_cls(shell): + """Dynamically construct the activator class. + + Detect the base activator and any number of formatters (appended using '+' to the base name). + For example, `posix+json` (as in `conda shell.posix+json activate`) would use the + `PosixActivator` base class and add the `JSONFormatMixin`. + """ + shell_etc = shell.split("+") + activator, formatters = shell_etc[0], shell_etc[1:] + + bases = [activator_map[activator]] + for f in formatters: + bases.append(formatter_map[f]) + + cls = type("Activator", tuple(reversed(bases)), {}) + return cls diff --git a/shared/package-files/35/35a605432f542714276c04c939e3e1da1d6b7f53d0b31c2540874b434c3821ae/_slow_conv2d_backward.h b/shared/package-files/35/35a605432f542714276c04c939e3e1da1d6b7f53d0b31c2540874b434c3821ae/_slow_conv2d_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..670cda82f6902cb5d6fb30d4802693cc8d70d663 --- /dev/null +++ b/shared/package-files/35/35a605432f542714276c04c939e3e1da1d6b7f53d0b31c2540874b434c3821ae/_slow_conv2d_backward.h @@ -0,0 +1,135 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_slow_conv2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, *, Tensor(a!) grad_input, Tensor(b!) grad_weight, Tensor(c!) grad_bias) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple _slow_conv2d_backward_out(at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding) { + return at::_ops::_slow_conv2d_backward_grad_input::call(grad_output, self, weight, c10::fromIntArrayRefSlow(kernel_size), c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), grad_input, grad_weight, grad_bias); +} +namespace symint { + template ::value>> + ::std::tuple _slow_conv2d_backward_out(at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding) { + return at::_ops::_slow_conv2d_backward_grad_input::call(grad_output, self, weight, c10::fromIntArrayRefSlow(kernel_size), c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), grad_input, grad_weight, grad_bias); + } +} + +// aten::_slow_conv2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, *, Tensor(a!) grad_input, Tensor(b!) grad_weight, Tensor(c!) grad_bias) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple _slow_conv2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias) { + return at::_ops::_slow_conv2d_backward_grad_input::call(grad_output, self, weight, c10::fromIntArrayRefSlow(kernel_size), c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), grad_input, grad_weight, grad_bias); +} +namespace symint { + template ::value>> + ::std::tuple _slow_conv2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias) { + return at::_ops::_slow_conv2d_backward_grad_input::call(grad_output, self, weight, c10::fromIntArrayRefSlow(kernel_size), c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), grad_input, grad_weight, grad_bias); + } +} + +// aten::_slow_conv2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, *, Tensor(a!) grad_input, Tensor(b!) grad_weight, Tensor(c!) grad_bias) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple _slow_conv2d_backward_symint_out(at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding) { + return at::_ops::_slow_conv2d_backward_grad_input::call(grad_output, self, weight, kernel_size, stride, padding, grad_input, grad_weight, grad_bias); +} +namespace symint { + template ::value>> + ::std::tuple _slow_conv2d_backward_out(at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding) { + return at::_ops::_slow_conv2d_backward_grad_input::call(grad_output, self, weight, kernel_size, stride, padding, grad_input, grad_weight, grad_bias); + } +} + +// aten::_slow_conv2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, *, Tensor(a!) grad_input, Tensor(b!) grad_weight, Tensor(c!) grad_bias) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple _slow_conv2d_backward_symint_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias) { + return at::_ops::_slow_conv2d_backward_grad_input::call(grad_output, self, weight, kernel_size, stride, padding, grad_input, grad_weight, grad_bias); +} +namespace symint { + template ::value>> + ::std::tuple _slow_conv2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias) { + return at::_ops::_slow_conv2d_backward_grad_input::call(grad_output, self, weight, kernel_size, stride, padding, grad_input, grad_weight, grad_bias); + } +} + +// aten::_slow_conv2d_backward.output_mask(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias) +inline ::std::tuple _slow_conv2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, ::std::array output_mask) { + return at::_ops::_slow_conv2d_backward_output_mask::call(grad_output, self, weight, c10::fromIntArrayRefSlow(kernel_size), c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), output_mask); +} +namespace symint { + template ::value>> + ::std::tuple _slow_conv2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, ::std::array output_mask) { + return at::_ops::_slow_conv2d_backward_output_mask::call(grad_output, self, weight, c10::fromIntArrayRefSlow(kernel_size), c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), output_mask); + } +} + +// aten::_slow_conv2d_backward.output_mask(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias) +inline ::std::tuple _slow_conv2d_backward_symint(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, ::std::array output_mask) { + return at::_ops::_slow_conv2d_backward_output_mask::call(grad_output, self, weight, kernel_size, stride, padding, output_mask); +} +namespace symint { + template ::value>> + ::std::tuple _slow_conv2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, ::std::array output_mask) { + return at::_ops::_slow_conv2d_backward_output_mask::call(grad_output, self, weight, kernel_size, stride, padding, output_mask); + } +} + +// aten::_slow_conv2d_backward.output_mask_out(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple _slow_conv2d_backward_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, ::std::array output_mask) { + return at::_ops::_slow_conv2d_backward_output_mask_out::call(grad_output, self, weight, c10::fromIntArrayRefSlow(kernel_size), c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), output_mask, out0, out1, out2); +} +namespace symint { + template ::value>> + ::std::tuple _slow_conv2d_backward_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, ::std::array output_mask) { + return at::_ops::_slow_conv2d_backward_output_mask_out::call(grad_output, self, weight, c10::fromIntArrayRefSlow(kernel_size), c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), output_mask, out0, out1, out2); + } +} + +// aten::_slow_conv2d_backward.output_mask_out(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple _slow_conv2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) { + return at::_ops::_slow_conv2d_backward_output_mask_out::call(grad_output, self, weight, c10::fromIntArrayRefSlow(kernel_size), c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), output_mask, out0, out1, out2); +} +namespace symint { + template ::value>> + ::std::tuple _slow_conv2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) { + return at::_ops::_slow_conv2d_backward_output_mask_out::call(grad_output, self, weight, c10::fromIntArrayRefSlow(kernel_size), c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), output_mask, out0, out1, out2); + } +} + +// aten::_slow_conv2d_backward.output_mask_out(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple _slow_conv2d_backward_symint_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, ::std::array output_mask) { + return at::_ops::_slow_conv2d_backward_output_mask_out::call(grad_output, self, weight, kernel_size, stride, padding, output_mask, out0, out1, out2); +} +namespace symint { + template ::value>> + ::std::tuple _slow_conv2d_backward_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, ::std::array output_mask) { + return at::_ops::_slow_conv2d_backward_output_mask_out::call(grad_output, self, weight, kernel_size, stride, padding, output_mask, out0, out1, out2); + } +} + +// aten::_slow_conv2d_backward.output_mask_out(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple _slow_conv2d_backward_symint_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) { + return at::_ops::_slow_conv2d_backward_output_mask_out::call(grad_output, self, weight, kernel_size, stride, padding, output_mask, out0, out1, out2); +} +namespace symint { + template ::value>> + ::std::tuple _slow_conv2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) { + return at::_ops::_slow_conv2d_backward_output_mask_out::call(grad_output, self, weight, kernel_size, stride, padding, output_mask, out0, out1, out2); + } +} + +} diff --git a/shared/package-files/35/35a65af399429a86aa612630c32a4a2ac71249e00801280fcb55785cd39c4d62/peephole_dict_idioms.h b/shared/package-files/35/35a65af399429a86aa612630c32a4a2ac71249e00801280fcb55785cd39c4d62/peephole_dict_idioms.h new file mode 100644 index 0000000000000000000000000000000000000000..283c313d9ee2ae8024ba286d1a5bd0ea5cf1fdd3 --- /dev/null +++ b/shared/package-files/35/35a65af399429a86aa612630c32a4a2ac71249e00801280fcb55785cd39c4d62/peephole_dict_idioms.h @@ -0,0 +1,38 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Peephole Optimizes Dict Ops such as len() and __getitem__ +// 1. getitem optimizations +// Given a function like this: +// def foo(): +// d = {0 : 1} +// x = d[0] +// return x +// This pass produces (after dead code elimination): +// def foo(a, b): +// return 1 +// +// This optimization can only happen if the dict is not modified +// and the dict has constant, non overlapping keys. +// +// 2. len optimizations +// Given a function like this: +// def foo(): +// d = {0 : 1} +// return len(d) +// This pass produces (after dead code elimination): +// def foo(): +// return 1 +// +// This has the same requirements as the getitem optimizations. +// +// Currently this is invoked as part of PeepholeOptimize +// return true if graph is modified. +TORCH_API bool PeepholeOptimizeDictIdioms(const std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/shared/package-files/35/35a9f593ca7aabd007edd71555ce468eb3e5e57f52033bb7192d58ea370b6da9/special_spherical_bessel_j0_native.h b/shared/package-files/35/35a9f593ca7aabd007edd71555ce468eb3e5e57f52033bb7192d58ea370b6da9/special_spherical_bessel_j0_native.h new file mode 100644 index 0000000000000000000000000000000000000000..e110305b370bfd9566080c7d41bb26a2a30ae0bf --- /dev/null +++ b/shared/package-files/35/35a9f593ca7aabd007edd71555ce468eb3e5e57f52033bb7192d58ea370b6da9/special_spherical_bessel_j0_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_special_spherical_bessel_j0_out : public at::meta::structured_special_spherical_bessel_j0 { +void impl(const at::Tensor & x, const at::Tensor & out); +}; +} // namespace native +} // namespace at diff --git a/shared/package-files/35/35b11d3417d57e72560342531ce8b1a0e427e1a5cf2b163e04879805bbe658ce/backend_interface.h b/shared/package-files/35/35b11d3417d57e72560342531ce8b1a0e427e1a5cf2b163e04879805bbe658ce/backend_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..f94d3b602e52c889c96162143f8d6eb8b8d0237b --- /dev/null +++ b/shared/package-files/35/35b11d3417d57e72560342531ce8b1a0e427e1a5cf2b163e04879805bbe658ce/backend_interface.h @@ -0,0 +1,158 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch { +namespace lazy { + +struct IrBuilder; + +/** + * Work in progress- don't treat this as a stable interface yet! + */ +class TORCH_API BackendImplInterface { + public: + virtual ~BackendImplInterface() = default; + + /** + * Initialization/Teardown + * */ + // No-op by default. Allows custom functionality to be exposed through + // extension bindings. + virtual void InitializeAtenBindings() const {} + + virtual void PrepareToExit() const = 0; + + /** + * Configuration + * */ + + virtual void SetRngSeed(size_t seed) const = 0; + + /** + * IR Tracing + * */ + + virtual const IrBuilder* GetIrBuilder() const = 0; + + /** + * Data Transfer + * */ + + virtual BackendDataPtr MakeComputationDataFromTensor( + const at::Tensor& tensor, + const Shape& shape, + const BackendDevice& device) const = 0; + virtual BackendDataPtr MakeComputationDataFromScalar( + const at::Scalar& scalar, + const torch::lazy::BackendDevice& device) const = 0; + virtual BackendDataPtr CreateDataPlaceholder( + const BackendDevice& device, + const Shape& shape) const = 0; + + // Gets backend data if the node is a device data node. Otherwise returns + // nullptr + virtual BackendDataPtr GetComputationDataFromNode(const Node*) const = 0; + + virtual at::Tensor MakeTensorFromComputationData( + const BackendDataPtr data, + c10::optional logical_scalar_type) const = 0; + + /** + * Lowering, Compilation, Execution + * */ + + virtual std::unique_ptr CreateLoweringContext( + const std::string& name, + BackendDevice device, + c10::ArrayRef post_order, + Util::EmissionMap emit_status) const = 0; + + virtual std::unique_ptr CreateLoweringContext( + const std::string& name, + BackendDevice device) const = 0; + + // TODO(whc) need to keep this? + virtual std::vector GetCompilationDevices( + const std::string& device, + c10::ArrayRef devices) const = 0; + + virtual std::vector Compile( + std::vector instances) const = 0; + + virtual std::vector ExecuteComputation( + torch::lazy::ComputationPtr computation, + c10::ArrayRef arguments, + const BackendDevice& device) const = 0; + + /** + * Device Configuration + * */ + + // Set or get the default device type. + // For backends used with virtual c10::Devices, this configures what real + // device type the backend should use, and matters if the backend supports + // more than one type of real device. + virtual std::shared_ptr GetDefaultDeviceType() const = 0; + virtual void SetDefaultDeviceType(int8_t type) = 0; + + // Set or get the default device ordinal. + // For backends that supports multi-device, this configures what the + // default device the backend should use. + virtual int64_t GetDefaultDeviceOrdinal() const = 0; + virtual void SetDefaultDeviceOrdinal(int64_t) = 0; + + // Specify which aten device should be used for eager fallback + // may change depending on current 'Default' DeviceType + virtual at::DeviceType EagerFallbackDeviceType() const = 0; + + // Query all available backend devices + virtual std::vector GetBackendDevices() const = 0; + + virtual std::string CreateMetricReport() const { + return ""; + } + + // Map a particular c10:: device to a concrete backend device + // Note:: c10:: devices may be virtual or concrete. xla:: and lazy:: are + // virtual devices, meaning they may map to a gpu, tpu, etc. behind the + // scenes. In the future, non-virtual c10:: devices may also use lazy tensors + // through a mode, in which case these APIs should still work, but should be + // identity mappings. + virtual BackendDevice GetBackendDevice(c10::Device device) const = 0; + + // TODO(whc) + // Additional APIs expected for supporting distributed training, to be + // designed + + /** + * Debug/Metrics + * */ + + // virtual std::map GetMetrics() const = 0; + + // virtual MemoryInfo GetMemoryInfo(const std::string& device) = 0; + + virtual std::string GetComputationBackendText( + const ComputationPtr computation) const = 0; +}; + +class TORCH_API BackendRegistrar { + public: + BackendRegistrar(const BackendImplInterface* backend_impl_interface); +}; + +TORCH_API bool hasBackend(); +TORCH_API const BackendImplInterface* getBackend(); + +TORCH_API const IrBuilder* getIrBuilder(); + +} // namespace lazy +} // namespace torch diff --git a/shared/package-files/35/35b37da39d7721477aecb5379e447b68665eeab7651643aa6907daacb3cae9a2/cli.py b/shared/package-files/35/35b37da39d7721477aecb5379e447b68665eeab7651643aa6907daacb3cae9a2/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..2e5ea5265eb26a213cbffa3aa3ba9ddc272ce45b --- /dev/null +++ b/shared/package-files/35/35b37da39d7721477aecb5379e447b68665eeab7651643aa6907daacb3cae9a2/cli.py @@ -0,0 +1,345 @@ +# This file is part of Hypothesis, which may be found at +# https://github.com/HypothesisWorks/hypothesis/ +# +# Copyright the Hypothesis Authors. +# Individual contributors are listed in AUTHORS.rst and the git log. +# +# This Source Code Form is subject to the terms of the Mozilla Public License, +# v. 2.0. If a copy of the MPL was not distributed with this file, You can +# obtain one at https://mozilla.org/MPL/2.0/. + +""" +.. _hypothesis-cli: + +---------------- +hypothesis[cli] +---------------- + +:: + + $ hypothesis --help + Usage: hypothesis [OPTIONS] COMMAND [ARGS]... + + Options: + --version Show the version and exit. + -h, --help Show this message and exit. + + Commands: + codemod `hypothesis codemod` refactors deprecated or inefficient code. + fuzz [hypofuzz] runs tests with an adaptive coverage-guided fuzzer. + write `hypothesis write` writes property-based tests for you! + +This module requires the :pypi:`click` package, and provides Hypothesis' command-line +interface, for e.g. :doc:`'ghostwriting' tests ` via the terminal. +It's also where `HypoFuzz `__ adds the :command:`hypothesis fuzz` +command (`learn more about that here `__). +""" + +import builtins +import importlib +import inspect +import sys +import types +from difflib import get_close_matches +from functools import partial +from multiprocessing import Pool +from pathlib import Path + +try: + import pytest +except ImportError: + pytest = None # type: ignore + +MESSAGE = """ +The Hypothesis command-line interface requires the `{}` package, +which you do not have installed. Run: + + python -m pip install --upgrade 'hypothesis[cli]' + +and try again. +""" + +try: + import click +except ImportError: + + def main(): + """If `click` is not installed, tell the user to install it then exit.""" + sys.stderr.write(MESSAGE.format("click")) + sys.exit(1) + +else: + # Ensure that Python scripts in the current working directory are importable, + # on the principle that Ghostwriter should 'just work' for novice users. Note + # that we append rather than prepend to the module search path, so this will + # never shadow the stdlib or installed packages. + sys.path.append(".") + + @click.group(context_settings={"help_option_names": ("-h", "--help")}) + @click.version_option() + def main(): + pass + + def obj_name(s: str) -> object: + """This "type" imports whatever object is named by a dotted string.""" + s = s.strip() + if "/" in s or "\\" in s: + raise click.UsageError( + "Remember that the ghostwriter should be passed the name of a module, not a path." + ) from None + try: + return importlib.import_module(s) + except ImportError: + pass + classname = None + if "." not in s: + modulename, module, funcname = "builtins", builtins, s + else: + modulename, funcname = s.rsplit(".", 1) + try: + module = importlib.import_module(modulename) + except ImportError as err: + try: + modulename, classname = modulename.rsplit(".", 1) + module = importlib.import_module(modulename) + except (ImportError, ValueError): + if s.endswith(".py"): + raise click.UsageError( + "Remember that the ghostwriter should be passed the name of a module, not a file." + ) from None + raise click.UsageError( + f"Failed to import the {modulename} module for introspection. " + "Check spelling and your Python import path, or use the Python API?" + ) from err + + def describe_close_matches( + module_or_class: types.ModuleType, objname: str + ) -> str: + public_names = [ + name for name in vars(module_or_class) if not name.startswith("_") + ] + matches = get_close_matches(objname, public_names) + if matches: + return f" Closest matches: {matches!r}" + else: + return "" + + if classname is None: + try: + return getattr(module, funcname) + except AttributeError as err: + if funcname == "py": + # Likely attempted to pass a local file (Eg., "myscript.py") instead of a module name + raise click.UsageError( + "Remember that the ghostwriter should be passed the name of a module, not a file." + f"\n\tTry: hypothesis write {s[:-3]}" + ) from None + raise click.UsageError( + f"Found the {modulename!r} module, but it doesn't have a " + f"{funcname!r} attribute." + + describe_close_matches(module, funcname) + ) from err + else: + try: + func_class = getattr(module, classname) + except AttributeError as err: + raise click.UsageError( + f"Found the {modulename!r} module, but it doesn't have a " + f"{classname!r} class." + describe_close_matches(module, classname) + ) from err + try: + return getattr(func_class, funcname) + except AttributeError as err: + if inspect.isclass(func_class): + func_class_is = "class" + else: + func_class_is = "attribute" + raise click.UsageError( + f"Found the {modulename!r} module and {classname!r} {func_class_is}, " + f"but it doesn't have a {funcname!r} attribute." + + describe_close_matches(func_class, funcname) + ) from err + + def _refactor(func, fname): + try: + oldcode = Path(fname).read_text(encoding="utf-8") + except (OSError, UnicodeError) as err: + # Permissions or encoding issue, or file deleted, etc. + return f"skipping {fname!r} due to {err}" + + if "hypothesis" not in oldcode: + return # This is a fast way to avoid running slow no-op codemods + + try: + newcode = func(oldcode) + except Exception as err: + from libcst import ParserSyntaxError + + if isinstance(err, ParserSyntaxError): + from hypothesis.extra._patching import indent + + msg = indent(str(err).replace("\n\n", "\n"), " ").strip() + return f"skipping {fname!r} due to {msg}" + raise + + if newcode != oldcode: + Path(fname).write_text(newcode, encoding="utf-8") + + @main.command() # type: ignore # Click adds the .command attribute + @click.argument("path", type=str, required=True, nargs=-1) + def codemod(path): + """`hypothesis codemod` refactors deprecated or inefficient code. + + It adapts `python -m libcst.tool`, removing many features and config options + which are rarely relevant for this purpose. If you need more control, we + encourage you to use the libcst CLI directly; if not this one is easier. + + PATH is the file(s) or directories of files to format in place, or + "-" to read from stdin and write to stdout. + """ + try: + from libcst.codemod import gather_files + + from hypothesis.extra import codemods + except ImportError: + sys.stderr.write( + "You are missing required dependencies for this option. Run:\n\n" + " python -m pip install --upgrade hypothesis[codemods]\n\n" + "and try again." + ) + sys.exit(1) + + # Special case for stdin/stdout usage + if "-" in path: + if len(path) > 1: + raise Exception( + "Cannot specify multiple paths when reading from stdin!" + ) + print("Codemodding from stdin", file=sys.stderr) + print(codemods.refactor(sys.stdin.read())) + return 0 + + # Find all the files to refactor, and then codemod them + files = gather_files(path) + errors = set() + if len(files) <= 1: + errors.add(_refactor(codemods.refactor, *files)) + else: + with Pool() as pool: + for msg in pool.imap_unordered( + partial(_refactor, codemods.refactor), files + ): + errors.add(msg) + errors.discard(None) + for msg in errors: + print(msg, file=sys.stderr) + return 1 if errors else 0 + + @main.command() # type: ignore # Click adds the .command attribute + @click.argument("func", type=obj_name, required=True, nargs=-1) + @click.option( + "--roundtrip", + "writer", + flag_value="roundtrip", + help="start by testing write/read or encode/decode!", + ) + @click.option( + "--equivalent", + "writer", + flag_value="equivalent", + help="very useful when optimising or refactoring code", + ) + @click.option( + "--errors-equivalent", + "writer", + flag_value="errors-equivalent", + help="--equivalent, but also allows consistent errors", + ) + @click.option( + "--idempotent", + "writer", + flag_value="idempotent", + help="check that f(x) == f(f(x))", + ) + @click.option( + "--binary-op", + "writer", + flag_value="binary_operation", + help="associativity, commutativity, identity element", + ) + # Note: we deliberately omit a --ufunc flag, because the magic() + # detection of ufuncs is both precise and complete. + @click.option( + "--style", + type=click.Choice(["pytest", "unittest"]), + default="pytest" if pytest else "unittest", + help="pytest-style function, or unittest-style method?", + ) + @click.option( + "-e", + "--except", + "except_", + type=obj_name, + multiple=True, + help="dotted name of exception(s) to ignore", + ) + @click.option( + "--annotate/--no-annotate", + default=None, + help="force ghostwritten tests to be type-annotated (or not). " + "By default, match the code to test.", + ) + def write(func, writer, except_, style, annotate): # \b disables autowrap + """`hypothesis write` writes property-based tests for you! + + Type annotations are helpful but not required for our advanced introspection + and templating logic. Try running the examples below to see how it works: + + \b + hypothesis write gzip + hypothesis write numpy.matmul + hypothesis write pandas.from_dummies + hypothesis write re.compile --except re.error + hypothesis write --equivalent ast.literal_eval eval + hypothesis write --roundtrip json.dumps json.loads + hypothesis write --style=unittest --idempotent sorted + hypothesis write --binary-op operator.add + """ + # NOTE: if you want to call this function from Python, look instead at the + # ``hypothesis.extra.ghostwriter`` module. Click-decorated functions have + # a different calling convention, and raise SystemExit instead of returning. + kwargs = {"except_": except_ or (), "style": style, "annotate": annotate} + if writer is None: + writer = "magic" + elif writer == "idempotent" and len(func) > 1: + raise click.UsageError("Test functions for idempotence one at a time.") + elif writer == "roundtrip" and len(func) == 1: + writer = "idempotent" + elif "equivalent" in writer and len(func) == 1: + writer = "fuzz" + if writer == "errors-equivalent": + writer = "equivalent" + kwargs["allow_same_errors"] = True + + try: + from hypothesis.extra import ghostwriter + except ImportError: + sys.stderr.write(MESSAGE.format("black")) + sys.exit(1) + + code = getattr(ghostwriter, writer)(*func, **kwargs) + try: + from rich.console import Console + from rich.syntax import Syntax + + from hypothesis.utils.terminal import guess_background_color + except ImportError: + print(code) + else: + try: + theme = "default" if guess_background_color() == "light" else "monokai" + code = Syntax(code, "python", background_color="default", theme=theme) + Console().print(code, soft_wrap=True) + except Exception: + print("# Error while syntax-highlighting code", file=sys.stderr) + print(code) diff --git a/shared/package-files/35/35b957460a5f93cabd303a04c422acc99a83144d809c70eaf2c203ba575c3afa/index_fill_compositeexplicitautograd_dispatch.h b/shared/package-files/35/35b957460a5f93cabd303a04c422acc99a83144d809c70eaf2c203ba575c3afa/index_fill_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f94f5aa1224f5cc024b55afb159d164432a53856 --- /dev/null +++ b/shared/package-files/35/35b957460a5f93cabd303a04c422acc99a83144d809c70eaf2c203ba575c3afa/index_fill_compositeexplicitautograd_dispatch.h @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor index_fill(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Scalar & value); +TORCH_API at::Tensor & index_fill_out(at::Tensor & out, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Scalar & value); +TORCH_API at::Tensor & index_fill_outf(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Scalar & value, at::Tensor & out); +TORCH_API at::Tensor index_fill(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & value); +TORCH_API at::Tensor & index_fill_out(at::Tensor & out, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & value); +TORCH_API at::Tensor & index_fill_outf(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & value, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/35/35ba9a8e5502bdd57c868bbea5e8a72e3a3a222933f57c37fc85453251f40b5a/atari-old b/shared/package-files/35/35ba9a8e5502bdd57c868bbea5e8a72e3a3a222933f57c37fc85453251f40b5a/atari-old new file mode 100644 index 0000000000000000000000000000000000000000..0539eb37971c5cc92ada2ca2a9a074397fe70cd4 Binary files /dev/null and b/shared/package-files/35/35ba9a8e5502bdd57c868bbea5e8a72e3a3a222933f57c37fc85453251f40b5a/atari-old differ diff --git a/shared/package-files/35/35bac30c18dd6ea5fe0c91390f433986df650ae00448cd3d7f70d378b3b71bcf/log2_ops.h b/shared/package-files/35/35bac30c18dd6ea5fe0c91390f433986df650ae00448cd3d7f70d378b3b71bcf/log2_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..902a17815d49cba9aca582a067a35e8d6e6ab38e --- /dev/null +++ b/shared/package-files/35/35bac30c18dd6ea5fe0c91390f433986df650ae00448cd3d7f70d378b3b71bcf/log2_ops.h @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API log2 { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::log2") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "log2(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API log2_ { + using schema = at::Tensor & (at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::log2_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "log2_(Tensor(a!) self) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self); +}; + +struct TORCH_API log2_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::log2") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "log2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/35/35be7c4505b998f2e0b8665380e191b410ea5ca0ca09b2c47053044fa84cdfa9/IndexKernel.h b/shared/package-files/35/35be7c4505b998f2e0b8665380e191b410ea5ca0ca09b2c47053044fa84cdfa9/IndexKernel.h new file mode 100644 index 0000000000000000000000000000000000000000..edd9190deb0dba12979556a9f1bc12705f5801b4 --- /dev/null +++ b/shared/package-files/35/35be7c4505b998f2e0b8665380e191b410ea5ca0ca09b2c47053044fa84cdfa9/IndexKernel.h @@ -0,0 +1,16 @@ +#pragma once +#include +#include + +namespace at { +struct TensorIteratorBase; +class TensorBase; +} + +namespace at { +namespace native { +/// @param maskPrefixSum[in,out] +void launch_masked_scatter_kernel( + const TensorBase &self, const TensorBase &mask, + const TensorBase &maskPrefixSum, const TensorBase &source); +}} diff --git a/shared/package-files/35/35c05df1f0f5a414dc8d3f59f1ae693f88ec755907f75da88129c8be41835d17/results_theil_textile.py b/shared/package-files/35/35c05df1f0f5a414dc8d3f59f1ae693f88ec755907f75da88129c8be41835d17/results_theil_textile.py new file mode 100644 index 0000000000000000000000000000000000000000..a09c6b41a0e04de32d4b48ef1782f394b2baac83 --- /dev/null +++ b/shared/package-files/35/35c05df1f0f5a414dc8d3f59f1ae693f88ec755907f75da88129c8be41835d17/results_theil_textile.py @@ -0,0 +1,69 @@ +"""Reference results for Theil textile regression tests.""" + +import numpy as np + +from statsmodels.tools.testing import ParamsTableTestBunch + +est = dict( + rmse=.0136097497582343, + r2=.9741055881598619, + N=17, + df_r=14, + compat=.860625753607033, + vrank=2, + pvalue=.6503055973535645, + frac_sample=.7935370014985163, + frac_prior=.2064629985014838, + cmd="tgmixed", + predict="regres_p", + depvar="lconsump", + marginsok="XB default", + cmdline="tgmixed lconsump lincome lprice, prior(lprice -0.7 0.15 lincome 1 0.15) cov(lprice lincome -0.01)", + prior="lprice -0.7 0.15 lincome 1 0.15", + properties="b V", +) + +params_table = np.array([ + 1.0893571039001, .10338923727975, 10.53646523141, 4.871483239e-08, + .86760924410848, 1.3111049636916, 14, 2.1447866879178, + 0, -.82054628653043, .03496499383295, -23.467651401591, + 1.218701708e-12, -.89553873984647, -.74555383321439, 14, + 2.1447866879178, 0, 1.4666439879147, .20347802665937, + 7.2078740490733, 4.509300573e-06, 1.0302270250519, 1.9030609507775, + 14, 2.1447866879178, 0]).reshape(3, 9) + +params_table_colnames = "b se t pvalue ll ul df crit eform".split() + +params_table_rownames = "lincome lprice _cons".split() + +cov = np.array([ + .01068933438529, -.00081953185523, -.0199747086722, -.00081953185523, + .00122255079374, -.00064024357954, -.0199747086722, -.00064024357954, + .04140330733319]).reshape(3, 3) + +cov_colnames = "lincome lprice _cons".split() + +cov_rownames = "lincome lprice _cons".split() + +cov_prior = np.array([ + .0225, -.01, 0, -.01, + .0225, 0, 0, 0, + 0]).reshape(3, 3) + +cov_prior_colnames = "lincome lprice _cons".split() + +cov_prior_rownames = "lincome lprice _cons".split() + + +results_theil_textile = ParamsTableTestBunch( + params_table=params_table, + params_table_colnames=params_table_colnames, + params_table_rownames=params_table_rownames, + cov=cov, + cov_colnames=cov_colnames, + cov_rownames=cov_rownames, + cov_prior=cov_prior, + cov_prior_colnames=cov_prior_colnames, + cov_prior_rownames=cov_prior_rownames, + **est +) diff --git a/shared/package-files/35/35c0684fc1c0c6dce8475cd906ed15dcc169196b5d15a0db950f28dce4ceeb33/test_compare_images.py b/shared/package-files/35/35c0684fc1c0c6dce8475cd906ed15dcc169196b5d15a0db950f28dce4ceeb33/test_compare_images.py new file mode 100644 index 0000000000000000000000000000000000000000..6023f3d054682568c52256464c7ff7f4e525d7ba --- /dev/null +++ b/shared/package-files/35/35c0684fc1c0c6dce8475cd906ed15dcc169196b5d15a0db950f28dce4ceeb33/test_compare_images.py @@ -0,0 +1,73 @@ +from pathlib import Path +import shutil + +import pytest +from pytest import approx + +from matplotlib.testing.compare import compare_images +from matplotlib.testing.decorators import _image_directories + + +# Tests of the image comparison algorithm. +@pytest.mark.parametrize( + 'im1, im2, tol, expect_rms', + [ + # Comparison of an image and the same image with minor differences. + # This expects the images to compare equal under normal tolerance, and + # have a small RMS. + ('basn3p02.png', 'basn3p02-minorchange.png', 10, None), + # Now test with no tolerance. + ('basn3p02.png', 'basn3p02-minorchange.png', 0, 6.50646), + # Comparison with an image that is shifted by 1px in the X axis. + ('basn3p02.png', 'basn3p02-1px-offset.png', 0, 90.15611), + # Comparison with an image with half the pixels shifted by 1px in the X + # axis. + ('basn3p02.png', 'basn3p02-half-1px-offset.png', 0, 63.75), + # Comparison of an image and the same image scrambled. + # This expects the images to compare completely different, with a very + # large RMS. + # Note: The image has been scrambled in a specific way, by having + # each color component of each pixel randomly placed somewhere in the + # image. It contains exactly the same number of pixels of each color + # value of R, G and B, but in a totally different position. + # Test with no tolerance to make sure that we pick up even a very small + # RMS error. + ('basn3p02.png', 'basn3p02-scrambled.png', 0, 172.63582), + # Comparison of an image and a slightly brighter image. + # The two images are solid color, with the second image being exactly 1 + # color value brighter. + # This expects the images to compare equal under normal tolerance, and + # have an RMS of exactly 1. + ('all127.png', 'all128.png', 0, 1), + # Now test the reverse comparison. + ('all128.png', 'all127.png', 0, 1), + ]) +def test_image_comparison_expect_rms(im1, im2, tol, expect_rms, tmp_path, + monkeypatch): + """ + Compare two images, expecting a particular RMS error. + + im1 and im2 are filenames relative to the baseline_dir directory. + + tol is the tolerance to pass to compare_images. + + expect_rms is the expected RMS value, or None. If None, the test will + succeed if compare_images succeeds. Otherwise, the test will succeed if + compare_images fails and returns an RMS error almost equal to this value. + """ + # Change the working directory using monkeypatch to use a temporary + # test specific directory + monkeypatch.chdir(tmp_path) + baseline_dir, result_dir = map(Path, _image_directories(lambda: "dummy")) + # Copy "test" image to result_dir, so that compare_images writes + # the diff to result_dir, rather than to the source tree + result_im2 = result_dir / im1 + shutil.copyfile(baseline_dir / im2, result_im2) + results = compare_images( + baseline_dir / im1, result_im2, tol=tol, in_decorator=True) + + if expect_rms is None: + assert results is None + else: + assert results is not None + assert results['rms'] == approx(expect_rms, abs=1e-4) diff --git a/shared/package-files/35/35c2dc2b2e8cd1f42aab3b0e9f16f27c6ef35c647154a8d3a0136cc44040d0fd/adm2 b/shared/package-files/35/35c2dc2b2e8cd1f42aab3b0e9f16f27c6ef35c647154a8d3a0136cc44040d0fd/adm2 new file mode 100644 index 0000000000000000000000000000000000000000..0a17e87d6551bbb8580aad3583a00a995bc4579a Binary files /dev/null and b/shared/package-files/35/35c2dc2b2e8cd1f42aab3b0e9f16f27c6ef35c647154a8d3a0136cc44040d0fd/adm2 differ diff --git a/shared/package-files/35/35c49e3c02edcb62a82d87d3bf43315782935dea3841434ef37eaf30e1fed58e/debug_info.h b/shared/package-files/35/35c49e3c02edcb62a82d87d3bf43315782935dea3841434ef37eaf30e1fed58e/debug_info.h new file mode 100644 index 0000000000000000000000000000000000000000..7044aa644d67e83ba6f7eb28bd0d6cacf1ebb182 --- /dev/null +++ b/shared/package-files/35/35c49e3c02edcb62a82d87d3bf43315782935dea3841434ef37eaf30e1fed58e/debug_info.h @@ -0,0 +1,57 @@ +#pragma once +#include +#include +#include +#include +#include + +namespace torch { +namespace jit { +/* + * MobileDebugTable: + * Deserializes debug_pkl and callstack_map records from PT model's zip archive + * and stores them in a map of debug handles to DebugInfoPair. Debug handles are + * unique per model and runtime, be in lite interpreter or delegate, an + * exception of BackendRuntimeException should raised using debug handles. + * getSourceDebugString method is responsible for translating debug + * handles to correspond debug information. + * This debug informatin includes stack trace of model level source code and + * module hierarchy where the exception occurred. + */ +class MobileDebugTable { + public: + MobileDebugTable() = default; + MobileDebugTable( + std::unique_ptr& reader, + const std::shared_ptr& cu); + + template + MobileDebugTable(It begin, It end) : callstack_ptr_map_(begin, end) {} + + std::string getSourceDebugString( + const int64_t debug_handle, + const std::string& top_module_type_name = "ModuleTypeUnknown") const; + std::string getSourceDebugString( + const std::vector& debug_handles, + const std::string& top_module_type_name = "ModuleTypeUnknown") const; + std::string getModuleHierarchyInfo( + const int64_t debug_handle, + const std::string& top_module_type_name = "ModuleTypeUnknown") const; + std::string getModuleHierarchyInfo( + const std::vector& debug_handles, + const std::string& top_module_type_name = "ModuleTypeUnknown") const; + + const ska::flat_hash_map& getCallStackPtrMap() + const { + return callstack_ptr_map_; + } + + private: + std::pair getSourceDebugModuleHierarchyInfo( + const std::vector& debug_handles, + const std::string& top_module_type_name = "ModuleTypeUnknown") const; + ska::flat_hash_map callstack_ptr_map_; +}; + +} // namespace jit +} // namespace torch diff --git a/shared/package-files/35/35c53c7b3f0d16f9ee21ea7dc35477264ffb5d9fabeebeaf183e87469d3738a7/results_arima_forecasts_all_css_diff.csv b/shared/package-files/35/35c53c7b3f0d16f9ee21ea7dc35477264ffb5d9fabeebeaf183e87469d3738a7/results_arima_forecasts_all_css_diff.csv new file mode 100644 index 0000000000000000000000000000000000000000..fbf9f39185ee5485ba1140ce49b875fc2a5d985b --- /dev/null +++ b/shared/package-files/35/35c53c7b3f0d16f9ee21ea7dc35477264ffb5d9fabeebeaf183e87469d3738a7/results_arima_forecasts_all_css_diff.csv @@ -0,0 +1,229 @@ +fc,fcdyn,fcdyn2,fcdyn3,fcdyn4,orig_index,year,quarter +NA,NA,NA,NA,NA,0,1959,1 +NA,NA,NA,NA,NA,1,1959,2 +NA,NA,NA,NA,NA,2,1959,3 +NA,NA,NA,NA,NA,3,1959,4 +NA,NA,NA,NA,NA,4,1960,1 +0.770379010745,0.770379010745,NA,NA,NA,5,1960,2 +0.159960553047,0.453990324197,NA,NA,NA,6,1960,3 +0.763902636357,0.835731904216,NA,NA,NA,7,1960,4 +0.200611089248,0.705191313109,NA,NA,NA,8,1961,1 +0.670090201275,0.878649341133,NA,NA,NA,9,1961,2 +0.245168528115,0.810852023674,NA,NA,NA,10,1961,3 +0.618223678922,0.909437206879,NA,NA,NA,11,1961,4 +0.282923463794,0.866788837448,NA,NA,NA,12,1962,1 +0.635883564254,0.922010172534,NA,NA,NA,13,1962,2 +0.279170332796,0.897571310587,NA,NA,NA,14,1962,3 +0.643061831375,0.927716334514,NA,NA,NA,15,1962,4 +0.287355845649,0.913766102843,NA,NA,NA,16,1963,1 +0.597148109291,0.93039301962,NA,NA,NA,17,1963,2 +0.361195118636,0.922366013779,NA,NA,NA,18,1963,3 +0.558818431023,0.931556196153,NA,NA,NA,19,1963,4 +0.421807086713,0.926960893399,NA,NA,NA,20,1964,1 +0.498754378826,0.93203785154,NA,NA,NA,21,1964,2 +0.411493694656,0.929414312482,NA,NA,NA,22,1964,3 +0.489155194512,0.932222349489,NA,NA,NA,23,1964,4 +0.446951599675,0.930726591642,0.446951599675,NA,NA,24,1965,1 +0.496243085307,0.932281263054,0.630405257081,NA,NA,25,1965,2 +0.489368402982,0.931429947097,0.643761598303,NA,NA,26,1965,3 +0.4681674419,0.932291342811,0.777776477505,NA,NA,27,1965,4 +0.52772975703,0.93180755357,0.789968560438,NA,NA,28,1966,1 +0.566505362972,0.932285198199,0.849816173977,NA,NA,29,1966,2 +0.524692473871,0.932010627185,0.858628330853,NA,NA,30,1966,3 +0.640394605109,0.93227567702,0.890822320917,NA,NA,31,1966,4 +0.430064342168,0.932120030939,0.893594141216,NA,NA,32,1967,1 +0.60512160276,0.932267209981,0.911236513022,NA,NA,33,1967,2 +0.463290054836,0.932179073129,0.912165678359,NA,NA,34,1967,3 +0.627745226416,0.932260852206,0.921540199879,NA,NA,35,1967,4 +0.557677999745,0.932210991288,0.921794627945,NA,NA,36,1968,1 +0.626379486361,0.932256458527,0.926817814232,NA,NA,37,1968,2 +0.63479357732,0.932228275536,0.926795159452,NA,NA,38,1968,3 +0.636990972422,0.932253568383,0.929498781138,NA,NA,39,1968,4 +0.644872375458,0.932237650911,0.929402909137,NA,NA,40,1969,1 +0.710134532495,0.932251728339,0.930858156063,NA,NA,41,1969,2 +0.664847766932,0.932242744672,0.93076242395,NA,NA,42,1969,3 +0.727209717161,0.932250583661,0.93154715447,NA,NA,43,1969,4 +0.703673706075,0.932245516618,0.931471664527,NA,NA,44,1970,1 +0.74665149928,0.932249883719,0.931895643642,NA,NA,45,1970,2 +0.656169792059,0.932247027427,0.931842084649,NA,NA,46,1970,3 +0.724661886465,0.932249461364,0.93207152956,NA,NA,47,1970,4 +0.640947957999,0.932247852124,0.932035726827,NA,NA,48,1971,1 +0.606792931728,0.932249209172,0.932160103317,NA,NA,49,1971,2 +0.668684332178,0.932248302959,0.932137056951,NA,NA,50,1971,3 +0.551525721652,0.93224905986,0.932204590693,NA,NA,51,1971,4 +0.641943695427,0.932248549766,0.932190139193,NA,NA,52,1972,1 +0.53831115973,0.932248972074,0.932226867829,NA,NA,53,1972,2 +0.612089176946,0.932248685065,0.932217978042,NA,NA,54,1972,3 +0.582872466048,0.932248920763,0.932237984669,NA,NA,55,1972,4 +0.680534925403,0.932248759333,0.932232595379,NA,NA,56,1973,1 +0.842528352287,0.932248890919,0.932243510039,NA,NA,57,1973,2 +0.697870627846,0.932248800152,0.932240280052,NA,NA,58,1973,3 +1.16123771239,0.932248873633,0.932246243448,NA,NA,59,1973,4 +0.868472110564,0.932248822613,0.932244325314,NA,NA,60,1974,1 +1.295970462021,0.932248863657,0.932247588207,NA,NA,61,1974,2 +0.940353780865,0.932248834987,0.932246457649,NA,NA,62,1974,3 +1.433625706241,0.932248857918,0.932248245434,NA,NA,63,1974,4 +0.970014205625,0.932248841811,0.932247583225,NA,NA,64,1975,1 +1.157361101681,0.932248854626,0.932248564087,NA,NA,65,1975,2 +0.856660585072,0.932248845579,0.932248178238,NA,NA,66,1975,3 +0.989444399201,0.932248852741,0.932248717075,NA,NA,67,1975,4 +0.849626106286,0.932248847661,0.932248493253,NA,NA,68,1976,1 +0.752229636283,0.932248851665,0.932248789627,NA,NA,69,1976,2 +0.870409319371,0.932248848813,0.932248660289,NA,NA,70,1976,3 +0.795923084138,0.932248851051,0.932248823493,NA,NA,71,1976,4 +0.919465973242,0.93224884945,0.932248749,NA,NA,72,1977,1 +1.031756943989,0.932248850702,0.932248838972,NA,NA,73,1977,2 +0.869240748572,0.932248849803,0.932248796191,NA,NA,74,1977,3 +0.979442748794,0.932248850504,0.932248845843,NA,NA,75,1977,4 +0.915986730044,0.932248849999,0.932248821336,NA,NA,76,1978,1 +1.055430500674,0.932248850391,0.932248848765,NA,NA,77,1978,2 +1.193113232312,0.932248850108,0.932248834757,NA,NA,78,1978,3 +1.253636070397,0.932248850327,0.932248849924,NA,NA,79,1978,4 +1.237003161064,0.932248850168,0.932248841933,NA,NA,80,1979,1 +1.50192411252,0.932248850291,0.932248850326,NA,NA,81,1979,2 +1.546138346398,0.932248850202,0.932248845776,NA,NA,82,1979,3 +1.687679883907,0.932248850271,0.932248850425,NA,NA,83,1979,4 +1.879960751704,0.932248850221,0.932248847838,NA,NA,84,1980,1 +1.913931910998,0.932248850259,0.932248850415,NA,NA,85,1980,2 +1.587588013175,0.932248850231,0.932248848946,NA,NA,86,1980,3 +1.74835279899,0.932248850252,0.932248850376,NA,NA,87,1980,4 +1.577518609117,0.932248850237,0.932248849543,NA,NA,88,1981,1 +1.607276198134,0.932248850249,0.932248850336,NA,NA,89,1981,2 +1.729337563595,0.93224885024,0.932248849864,NA,NA,90,1981,3 +1.468980381219,0.932248850247,0.932248850305,NA,NA,91,1981,4 +1.267245335864,0.932248850242,0.932248850038,NA,NA,92,1982,1 +0.931137515728,0.932248850246,0.932248850283,NA,NA,93,1982,2 +1.555112467159,0.932248850243,0.932248850132,NA,NA,94,1982,3 +0.653657375856,0.932248850245,0.932248850269,NA,NA,95,1982,4 +1.022136154907,0.932248850243,0.932248850183,NA,NA,96,1983,1 +0.554925174321,0.932248850245,0.932248850259,NA,NA,97,1983,2 +0.960506447796,0.932248850244,0.932248850211,NA,NA,98,1983,3 +0.823531392412,0.932248850244,0.932248850253,NA,NA,99,1983,4 +1.210651458454,0.932248850244,0.932248850226,NA,NA,100,1984,1 +0.922900777171,0.932248850244,0.932248850249,NA,NA,101,1984,2 +1.080087538278,0.932248850244,0.932248850234,NA,NA,102,1984,3 +0.890316325546,0.932248850244,0.932248850247,NA,NA,103,1984,4 +0.858082546678,0.932248850244,0.932248850239,NA,NA,104,1985,1 +1.039629514659,0.932248850244,0.932248850246,NA,NA,105,1985,2 +0.781314429462,0.932248850244,0.932248850241,NA,NA,106,1985,3 +1.006658595835,0.932248850244,0.932248850245,NA,NA,107,1985,4 +0.980549828263,0.932248850244,0.932248850242,NA,NA,108,1986,1 +0.153513926076,0.932248850244,0.932248850245,NA,NA,109,1986,2 +1.022200152993,0.932248850244,0.932248850243,NA,NA,110,1986,3 +0.204732775526,0.932248850244,0.932248850244,NA,NA,111,1986,4 +1.365660419996,0.932248850244,0.932248850244,NA,NA,112,1987,1 +0.686049071399,0.932248850244,0.932248850244,NA,NA,113,1987,2 +1.387371677459,0.932248850244,0.932248850244,NA,NA,114,1987,3 +0.796855404679,0.932248850244,0.932248850244,NA,NA,115,1987,4 +1.252967659219,0.932248850244,0.932248850244,NA,NA,116,1988,1 +0.851224474584,0.932248850244,0.932248850244,NA,NA,117,1988,2 +1.281757367744,0.932248850244,0.932248850244,NA,NA,118,1988,3 +0.987614096066,0.932248850244,0.932248850244,NA,NA,119,1988,4 +1.299685315792,0.932248850244,0.932248850244,NA,NA,120,1989,1 +1.249631195825,0.932248850244,0.932248850244,NA,NA,121,1989,2 +1.279393196417,0.932248850244,0.932248850244,NA,NA,122,1989,3 +1.045730799045,0.932248850244,0.932248850244,NA,NA,123,1989,4 +1.496932175978,0.932248850244,0.932248850244,NA,NA,124,1990,1 +1.01045926974,0.932248850244,0.932248850244,NA,NA,125,1990,2 +1.573514752605,0.932248850244,0.932248850244,NA,NA,126,1990,3 +1.567001969786,0.932248850244,0.932248850244,NA,NA,127,1990,4 +1.349008606055,0.932248850244,0.932248850244,NA,NA,128,1991,1 +1.052599747774,0.932248850244,0.932248850244,NA,NA,129,1991,2 +1.02485856054,0.932248850244,0.932248850244,NA,NA,130,1991,3 +0.826255442224,0.932248850244,0.932248850244,NA,NA,131,1991,4 +1.103264402043,0.932248850244,0.932248850244,NA,NA,132,1992,1 +0.929610346126,0.932248850244,0.932248850244,NA,NA,133,1992,2 +1.105007514812,0.932248850244,0.932248850244,NA,NA,134,1992,3 +0.993076541355,0.932248850244,0.932248850244,NA,NA,135,1992,4 +1.089509398065,0.932248850244,0.932248850244,NA,NA,136,1993,1 +0.956400421858,0.932248850244,0.932248850244,NA,NA,137,1993,2 +0.915149001744,0.932248850244,0.932248850244,NA,NA,138,1993,3 +0.974259971098,0.932248850244,0.932248850244,NA,NA,139,1993,4 +0.803643581793,0.932248850244,0.932248850244,NA,NA,140,1994,1 +0.982767992868,0.932248850244,0.932248850244,NA,NA,141,1994,2 +0.935727379917,0.932248850244,0.932248850244,NA,NA,142,1994,3 +1.007651588714,0.932248850244,0.932248850244,NA,NA,143,1994,4 +1.016701279278,0.932248850244,0.932248850244,NA,NA,144,1995,1 +1.09738640548,0.932248850244,0.932248850244,NA,NA,145,1995,2 +0.898845509928,0.932248850244,0.932248850244,NA,NA,146,1995,3 +1.023237765215,0.932248850244,0.932248850244,NA,NA,147,1995,4 +0.946468723079,0.932248850244,0.932248850244,NA,NA,148,1996,1 +1.163232329785,0.932248850244,0.932248850244,NA,NA,149,1996,2 +0.924650165645,0.932248850244,0.932248850244,NA,NA,150,1996,3 +1.184801033993,0.932248850244,0.932248850244,NA,NA,151,1996,4 +0.931330281248,0.932248850244,0.932248850244,NA,NA,152,1997,1 +0.919134674162,0.932248850244,0.932248850244,NA,NA,153,1997,2 +0.737950142031,0.932248850244,0.932248850244,NA,NA,154,1997,3 +0.951868264252,0.932248850244,0.932248850244,NA,NA,155,1997,4 +0.640162611467,0.932248850244,0.932248850244,NA,NA,156,1998,1 +0.776711858234,0.932248850244,0.932248850244,NA,NA,157,1998,2 +0.770413570866,0.932248850244,0.932248850244,NA,NA,158,1998,3 +0.773148559181,0.932248850244,0.932248850244,NA,NA,159,1998,4 +0.891813237097,0.932248850244,0.932248850244,NA,NA,160,1999,1 +0.976518615776,0.932248850244,0.932248850244,NA,NA,161,1999,2 +0.866379311426,0.932248850244,0.932248850244,NA,NA,162,1999,3 +1.187687466079,0.932248850244,0.932248850244,NA,NA,163,1999,4 +0.944916221783,0.932248850244,0.932248850244,NA,NA,164,2000,1 +1.374004755733,0.932248850244,0.932248850244,NA,NA,165,2000,2 +1.196896057424,0.932248850244,0.932248850244,NA,NA,166,2000,3 +1.276094544431,0.932248850244,0.932248850244,NA,NA,167,2000,4 +1.299861238063,0.932248850244,0.932248850244,NA,NA,168,2001,1 +0.953695155871,0.932248850244,0.932248850244,NA,NA,169,2001,2 +1.127831475679,0.932248850244,0.932248850244,NA,NA,170,2001,3 +0.538805881288,0.932248850244,0.932248850244,NA,NA,171,2001,4 +0.740938763678,0.932248850244,0.932248850244,NA,NA,172,2002,1 +0.913239687679,0.932248850244,0.932248850244,NA,NA,173,2002,2 +0.775624092729,0.932248850244,0.932248850244,NA,NA,174,2002,3 +1.191829445117,0.932248850244,0.932248850244,NA,NA,175,2002,4 +0.970976057583,0.932248850244,0.932248850244,NA,NA,176,2003,1 +0.963967235811,0.932248850244,0.932248850244,NA,NA,177,2003,2 +0.781611104879,0.932248850244,0.932248850244,NA,NA,178,2003,3 +0.998342132877,0.932248850244,0.932248850244,NA,NA,179,2003,4 +0.988319280658,0.932248850244,0.932248850244,NA,NA,180,2004,1 +1.119775738948,0.932248850244,0.932248850244,NA,NA,181,2004,2 +1.262824600847,0.932248850244,0.932248850244,NA,NA,182,2004,3 +1.266236815215,0.932248850244,0.932248850244,NA,NA,183,2004,4 +1.118456220708,0.932248850244,0.932248850244,NA,NA,184,2005,1 +1.481082761854,0.932248850244,0.932248850244,NA,NA,185,2005,2 +0.858355967219,0.932248850244,0.932248850244,NA,NA,186,2005,3 +2.658702151815,0.932248850244,0.932248850244,NA,NA,187,2005,4 +0.312832597414,0.932248850244,0.932248850244,NA,NA,188,2006,1 +2.347722707187,0.932248850244,0.932248850244,NA,NA,189,2006,2 +0.352394195822,0.932248850244,0.932248850244,NA,NA,190,2006,3 +1.156900058414,0.932248850244,0.932248850244,NA,NA,191,2006,4 +0.777710696447,0.932248850244,0.932248850244,NA,NA,192,2007,1 +1.517167214051,0.932248850244,0.932248850244,NA,NA,193,2007,2 +1.044783734001,0.932248850244,0.932248850244,NA,NA,194,2007,3 +1.771568384475,0.932248850244,0.932248850244,NA,NA,195,2007,4 +1.657324391142,0.932248850244,0.932248850244,NA,NA,196,2008,1 +1.54578539557,0.932248850244,0.932248850244,NA,NA,197,2008,2 +2.708532318705,0.932248850244,0.932248850244,NA,NA,198,2008,3 +-0.133682222205,0.932248850244,0.932248850244,NA,NA,199,2008,4 +-0.089413477292,0.932248850244,0.932248850244,NA,NA,200,2009,1 +-0.412725484186,0.932248850244,0.932248850244,NA,NA,201,2009,2 +0.58762097819,0.932248850244,0.932248850244,0.58762097819,NA,202,2009,3 +1.183570299308,0.932248850244,0.932248850244,0.6699014917,1.183570299308,203,2009,4 +1.295679884183,0.932248850244,0.932248850244,1.14314607419,1.295679884183,204,2010,1 +1.172205899038,0.932248850244,0.932248850244,0.73792459293,1.172205899038,205,2010,2 +1.093431415153,0.932248850244,0.932248850244,0.99718558439,1.093431415153,206,2010,3 +1.046383010753,0.932248850244,0.932248850244,0.8625857921,1.046383010753,207,2010,4 +1.02568256393,0.932248850244,0.932248850244,0.96171093112,1.02568256393,208,2011,1 +0.987498840379,0.932248850244,0.932248850244,0.89034221344,0.987498840379,209,2011,2 +0.980300525866,0.932248850244,0.932248850244,0.95267807706,0.980300525866,210,2011,3 +0.961338343426,0.932248850244,0.932248850244,0.90815715445,0.961338343426,211,2011,4 +0.956827888488,0.932248850244,0.932248850244,0.94377506166,0.956827888488,212,2012,1 +0.947125117184,0.932248850244,0.932248850244,0.91923666474,0.947125117184,213,2012,2 +0.945069813517,0.932248850244,0.932248850244,0.93873479867,0.945069813517,214,2012,3 +0.93981399433,0.932248850244,0.932248850244,0.92505455088,0.93981399433,215,2012,4 +0.938909436829,0.932248850244,0.932248850244,0.93597743253,0.938909436829,216,2013,1 +0.936114863886,0.932248850244,0.932248850244,0.92825825312,0.936114863886,217,2013,2 +0.935705810698,0.932248850244,0.932248850244,0.93437524527,0.935705810698,218,2013,3 +0.934220814397,0.932248850244,0.932248850244,0.93004135366,0.934220814397,219,2013,4 +0.934046235214,0.932248850244,0.932248850244,0.93345792245,0.934046235214,220,2014,1 +0.933253028912,0.932248850244,0.932248850244,0.93102589872,0.933253028912,221,2014,2 +0.933183912552,0.932248850244,0.932248850244,0.93293607052,0.933183912552,222,2014,3 +0.932759776053,0.932248850244,0.932248850244,0.93157060956,0.932759776053,223,2014,4 +0.932735584257,0.932248850244,0.932248850244,0.93263889295,0.932735584257,224,2015,1 +0.932508472206,0.932248850244,0.932248850244,0.93187249128,0.932508472206,225,2015,2 +0.932502421551,0.932248850244,0.932248850244,0.93246993987,0.932502421551,226,2015,3 +0.932380576436,0.932248850244,0.932248850244,0.93203986296,0.932380576436,227,2015,4 diff --git a/shared/package-files/35/35c9631557ab1f6b6f57ea369f4b96334779dd3a7dd56a770565e604f1a02129/misc.py b/shared/package-files/35/35c9631557ab1f6b6f57ea369f4b96334779dd3a7dd56a770565e604f1a02129/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..666b122d18860f88eaaa800dd7a3866f5c520e03 --- /dev/null +++ b/shared/package-files/35/35c9631557ab1f6b6f57ea369f4b96334779dd3a7dd56a770565e604f1a02129/misc.py @@ -0,0 +1,556 @@ +from numba.core.types.abstract import Callable, Literal, Type, Hashable +from numba.core.types.common import (Dummy, IterableType, Opaque, + SimpleIteratorType) +from numba.core.typeconv import Conversion +from numba.core.errors import TypingError, LiteralTypingError +from numba.core.ir import UndefinedType +from numba.core.utils import get_hashable_key + + +class PyObject(Dummy): + """ + A generic CPython object. + """ + + def is_precise(self): + return False + + +class Phantom(Dummy): + """ + A type that cannot be materialized. A Phantom cannot be used as + argument or return type. + """ + + +class Undefined(Dummy): + """ + A type that is left imprecise. This is used as a temporaray placeholder + during type inference in the hope that the type can be later refined. + """ + + def is_precise(self): + return False + + +class UndefVar(Dummy): + """ + A type that is created by Expr.undef to represent an undefined variable. + This type can be promoted to any other type. + This is introduced to handle Python 3.12 LOAD_FAST_AND_CLEAR. + """ + + def can_convert_to(self, typingctx, other): + return Conversion.promote + + +class RawPointer(Opaque): + """ + A raw pointer without any specific meaning. + """ + + +class StringLiteral(Literal, Dummy): + + def can_convert_to(self, typingctx, other): + if isinstance(other, UnicodeType): + return Conversion.safe + + +Literal.ctor_map[str] = StringLiteral + + +def unliteral(lit_type): + """ + Get base type from Literal type. + """ + if hasattr(lit_type, '__unliteral__'): + return lit_type.__unliteral__() + return getattr(lit_type, 'literal_type', lit_type) + + +def literal(value): + """Returns a Literal instance or raise LiteralTypingError + """ + ty = type(value) + if isinstance(value, Literal): + msg = "the function does not accept a Literal type; got {} ({})" + raise ValueError(msg.format(value, ty)) + try: + ctor = Literal.ctor_map[ty] + except KeyError: + raise LiteralTypingError("{} cannot be used as a literal".format(ty)) + else: + return ctor(value) + + +def maybe_literal(value): + """Get a Literal type for the value or None. + """ + try: + return literal(value) + except LiteralTypingError: + return + + +class Omitted(Opaque): + """ + An omitted function argument with a default value. + """ + + def __init__(self, value): + self._value = value + # Use helper function to support both hashable and non-hashable + # values. See discussion in gh #6957. + self._value_key = get_hashable_key(value) + super(Omitted, self).__init__("omitted(default=%r)" % (value,)) + + @property + def key(self): + return type(self._value), self._value_key + + @property + def value(self): + return self._value + + +class VarArg(Type): + """ + Special type representing a variable number of arguments at the + end of a function's signature. Only used for signature matching, + not for actual values. + """ + + def __init__(self, dtype): + self.dtype = dtype + super(VarArg, self).__init__("*%s" % dtype) + + @property + def key(self): + return self.dtype + + +class Module(Dummy): + def __init__(self, pymod): + self.pymod = pymod + super(Module, self).__init__("Module(%s)" % pymod) + + @property + def key(self): + return self.pymod + + +class MemInfoPointer(Type): + """ + Pointer to a Numba "meminfo" (i.e. the information for a managed + piece of memory). + """ + mutable = True + + def __init__(self, dtype): + self.dtype = dtype + name = "memory-managed *%s" % dtype + super(MemInfoPointer, self).__init__(name) + + @property + def key(self): + return self.dtype + + +class CPointer(Type): + """ + Type class for pointers to other types. + + Attributes + ---------- + dtype : The pointee type + addrspace : int + The address space pointee belongs to. + """ + mutable = True + + def __init__(self, dtype, addrspace=None): + self.dtype = dtype + self.addrspace = addrspace + if addrspace is not None: + name = "%s_%s*" % (dtype, addrspace) + else: + name = "%s*" % dtype + super(CPointer, self).__init__(name) + + @property + def key(self): + return self.dtype, self.addrspace + + +class EphemeralPointer(CPointer): + """ + Type class for pointers which aren't guaranteed to last long - e.g. + stack-allocated slots. The data model serializes such pointers + by copying the data pointed to. + """ + + +class EphemeralArray(Type): + """ + Similar to EphemeralPointer, but pointing to an array of elements, + rather than a single one. The array size must be known at compile-time. + """ + + def __init__(self, dtype, count): + self.dtype = dtype + self.count = count + name = "*%s[%d]" % (dtype, count) + super(EphemeralArray, self).__init__(name) + + @property + def key(self): + return self.dtype, self.count + + +class Object(Type): + # XXX unused? + mutable = True + + def __init__(self, clsobj): + self.cls = clsobj + name = "Object(%s)" % clsobj.__name__ + super(Object, self).__init__(name) + + @property + def key(self): + return self.cls + + +class Optional(Type): + """ + Type class for optional types, i.e. union { some type, None } + """ + + def __init__(self, typ): + assert not isinstance(typ, (Optional, NoneType)) + typ = unliteral(typ) + self.type = typ + name = "OptionalType(%s)" % self.type + super(Optional, self).__init__(name) + + @property + def key(self): + return self.type + + def can_convert_to(self, typingctx, other): + if isinstance(other, Optional): + return typingctx.can_convert(self.type, other.type) + else: + conv = typingctx.can_convert(self.type, other) + if conv is not None: + return max(conv, Conversion.safe) + + def can_convert_from(self, typingctx, other): + if isinstance(other, NoneType): + return Conversion.promote + elif isinstance(other, Optional): + return typingctx.can_convert(other.type, self.type) + else: + conv = typingctx.can_convert(other, self.type) + if conv is not None: + return max(conv, Conversion.promote) + + def unify(self, typingctx, other): + if isinstance(other, Optional): + unified = typingctx.unify_pairs(self.type, other.type) + else: + unified = typingctx.unify_pairs(self.type, other) + + if unified is not None: + if isinstance(unified, Optional): + return unified + else: + return Optional(unified) + + +class NoneType(Opaque): + """ + The type for None. + """ + + def unify(self, typingctx, other): + """ + Turn anything to a Optional type; + """ + if isinstance(other, (Optional, NoneType)): + return other + return Optional(other) + + +class EllipsisType(Opaque): + """ + The type for the Ellipsis singleton. + """ + + +class ExceptionClass(Callable, Phantom): + """ + The type of exception classes (not instances). + """ + + def __init__(self, exc_class): + assert issubclass(exc_class, BaseException) + name = "%s" % (exc_class.__name__) + self.exc_class = exc_class + super(ExceptionClass, self).__init__(name) + + def get_call_type(self, context, args, kws): + return self.get_call_signatures()[0][0] + + def get_call_signatures(self): + from numba.core import typing + return_type = ExceptionInstance(self.exc_class) + return [typing.signature(return_type)], False + + def get_impl_key(self, sig): + return type(self) + + @property + def key(self): + return self.exc_class + + +class ExceptionInstance(Phantom): + """ + The type of exception instances. *exc_class* should be the + exception class. + """ + + def __init__(self, exc_class): + assert issubclass(exc_class, BaseException) + name = "%s(...)" % (exc_class.__name__,) + self.exc_class = exc_class + super(ExceptionInstance, self).__init__(name) + + @property + def key(self): + return self.exc_class + + +class SliceType(Type): + + def __init__(self, name, members): + assert members in (2, 3) + self.members = members + self.has_step = members >= 3 + super(SliceType, self).__init__(name) + + @property + def key(self): + return self.members + + +class SliceLiteral(Literal, SliceType): + def __init__(self, value): + self._literal_init(value) + name = 'Literal[slice]({})'.format(value) + members = 2 if value.step is None else 3 + SliceType.__init__(self, name=name, members=members) + + @property + def key(self): + sl = self.literal_value + return sl.start, sl.stop, sl.step + + +Literal.ctor_map[slice] = SliceLiteral + + +class ClassInstanceType(Type): + """ + The type of a jitted class *instance*. It will be the return-type + of the constructor of the class. + """ + mutable = True + name_prefix = "instance" + + def __init__(self, class_type): + self.class_type = class_type + name = "{0}.{1}".format(self.name_prefix, self.class_type.name) + super(ClassInstanceType, self).__init__(name) + + def get_data_type(self): + return ClassDataType(self) + + def get_reference_type(self): + return self + + @property + def key(self): + return self.class_type.key + + @property + def classname(self): + return self.class_type.class_name + + @property + def jit_props(self): + return self.class_type.jit_props + + @property + def jit_static_methods(self): + return self.class_type.jit_static_methods + + @property + def jit_methods(self): + return self.class_type.jit_methods + + @property + def struct(self): + return self.class_type.struct + + @property + def methods(self): + return self.class_type.methods + + @property + def static_methods(self): + return self.class_type.static_methods + + +class ClassType(Callable, Opaque): + """ + The type of the jitted class (not instance). When the type of a class + is called, its constructor is invoked. + """ + mutable = True + name_prefix = "jitclass" + instance_type_class = ClassInstanceType + + def __init__(self, class_def, ctor_template_cls, struct, jit_methods, + jit_props, jit_static_methods): + self.class_name = class_def.__name__ + self.class_doc = class_def.__doc__ + self._ctor_template_class = ctor_template_cls + self.jit_methods = jit_methods + self.jit_props = jit_props + self.jit_static_methods = jit_static_methods + self.struct = struct + fielddesc = ','.join("{0}:{1}".format(k, v) for k, v in struct.items()) + name = "{0}.{1}#{2:x}<{3}>".format(self.name_prefix, self.class_name, + id(self), fielddesc) + super(ClassType, self).__init__(name) + + def get_call_type(self, context, args, kws): + return self.ctor_template(context).apply(args, kws) + + def get_call_signatures(self): + return (), True + + def get_impl_key(self, sig): + return type(self) + + @property + def methods(self): + return {k: v.py_func for k, v in self.jit_methods.items()} + + @property + def static_methods(self): + return {k: v.py_func for k, v in self.jit_static_methods.items()} + + @property + def instance_type(self): + return ClassInstanceType(self) + + @property + def ctor_template(self): + return self._specialize_template(self._ctor_template_class) + + def _specialize_template(self, basecls): + return type(basecls.__name__, (basecls,), dict(key=self)) + + +class DeferredType(Type): + """ + Represents a type that will be defined later. It must be defined + before it is materialized (used in the compiler). Once defined, it + behaves exactly as the type it is defining. + """ + + def __init__(self): + self._define = None + name = "{0}#{1}".format(type(self).__name__, id(self)) + super(DeferredType, self).__init__(name) + + def get(self): + if self._define is None: + raise RuntimeError("deferred type not defined") + return self._define + + def define(self, typ): + if self._define is not None: + raise TypeError("deferred type already defined") + if not isinstance(typ, Type): + raise TypeError("arg is not a Type; got: {0}".format(type(typ))) + self._define = typ + + def unify(self, typingctx, other): + return typingctx.unify_pairs(self.get(), other) + + +class ClassDataType(Type): + """ + Internal only. + Represents the data of the instance. The representation of + ClassInstanceType contains a pointer to a ClassDataType which represents + a C structure that contains all the data fields of the class instance. + """ + + def __init__(self, classtyp): + self.class_type = classtyp + name = "data.{0}".format(self.class_type.name) + super(ClassDataType, self).__init__(name) + + +class ContextManager(Callable, Phantom): + """ + An overly-simple ContextManager type that cannot be materialized. + """ + + def __init__(self, cm): + self.cm = cm + super(ContextManager, self).__init__("ContextManager({})".format(cm)) + + def get_call_signatures(self): + if not self.cm.is_callable: + msg = "contextmanager {} is not callable".format(self.cm) + raise TypingError(msg) + + return (), False + + def get_call_type(self, context, args, kws): + from numba.core import typing + + if not self.cm.is_callable: + msg = "contextmanager {} is not callable".format(self.cm) + raise TypingError(msg) + + posargs = list(args) + [v for k, v in sorted(kws.items())] + return typing.signature(self, *posargs) + + def get_impl_key(self, sig): + return type(self) + + +class UnicodeType(IterableType, Hashable): + + def __init__(self, name): + super(UnicodeType, self).__init__(name) + + @property + def iterator_type(self): + return UnicodeIteratorType(self) + + +class UnicodeIteratorType(SimpleIteratorType): + + def __init__(self, dtype): + name = "iter_unicode" + self.data = dtype + super(UnicodeIteratorType, self).__init__(name, dtype) diff --git a/shared/package-files/35/35cd7b94b78452e23704967e32fca34552ff54318676c3d3858b663e7477ae92/darwin-80x30-m b/shared/package-files/35/35cd7b94b78452e23704967e32fca34552ff54318676c3d3858b663e7477ae92/darwin-80x30-m new file mode 100644 index 0000000000000000000000000000000000000000..60f5b1b14ede060c582e5a3a55e059102927eda6 Binary files /dev/null and b/shared/package-files/35/35cd7b94b78452e23704967e32fca34552ff54318676c3d3858b663e7477ae92/darwin-80x30-m differ diff --git a/shared/package-files/35/35cd7b94b78452e23704967e32fca34552ff54318676c3d3858b663e7477ae92/xnuppc-80x30-m b/shared/package-files/35/35cd7b94b78452e23704967e32fca34552ff54318676c3d3858b663e7477ae92/xnuppc-80x30-m new file mode 100644 index 0000000000000000000000000000000000000000..60f5b1b14ede060c582e5a3a55e059102927eda6 Binary files /dev/null and b/shared/package-files/35/35cd7b94b78452e23704967e32fca34552ff54318676c3d3858b663e7477ae92/xnuppc-80x30-m differ diff --git a/shared/package-files/35/35cef22ccfab6819b9e97f4874027f0b92c3b0a142060c71e2454c3c0f5fcdd1/wy85-vb b/shared/package-files/35/35cef22ccfab6819b9e97f4874027f0b92c3b0a142060c71e2454c3c0f5fcdd1/wy85-vb new file mode 100644 index 0000000000000000000000000000000000000000..5f91df955404139564e35d39e562b8a82c810f16 Binary files /dev/null and b/shared/package-files/35/35cef22ccfab6819b9e97f4874027f0b92c3b0a142060c71e2454c3c0f5fcdd1/wy85-vb differ diff --git a/shared/package-files/35/35cef22ccfab6819b9e97f4874027f0b92c3b0a142060c71e2454c3c0f5fcdd1/wyse85-vb b/shared/package-files/35/35cef22ccfab6819b9e97f4874027f0b92c3b0a142060c71e2454c3c0f5fcdd1/wyse85-vb new file mode 100644 index 0000000000000000000000000000000000000000..5f91df955404139564e35d39e562b8a82c810f16 Binary files /dev/null and b/shared/package-files/35/35cef22ccfab6819b9e97f4874027f0b92c3b0a142060c71e2454c3c0f5fcdd1/wyse85-vb differ diff --git a/shared/package-files/35/35cf4fbb45ed80edca5d0167155d6e177774fe5242fbe332cf0af096c46329bd/cudnn_convolution_add_relu_ops.h b/shared/package-files/35/35cf4fbb45ed80edca5d0167155d6e177774fe5242fbe332cf0af096c46329bd/cudnn_convolution_add_relu_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..4439b6925d54eea3f2ffe9637cffa0b3a35c1baf --- /dev/null +++ b/shared/package-files/35/35cf4fbb45ed80edca5d0167155d6e177774fe5242fbe332cf0af096c46329bd/cudnn_convolution_add_relu_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API cudnn_convolution_add_relu { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const c10::optional &, const c10::optional &, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymInt); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cudnn_convolution_add_relu") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cudnn_convolution_add_relu(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const c10::optional & alpha, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const c10::optional & alpha, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups); +}; + +struct TORCH_API cudnn_convolution_add_relu_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, const c10::optional &, const c10::optional &, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymInt, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cudnn_convolution_add_relu") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cudnn_convolution_add_relu.out(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const c10::optional & alpha, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const c10::optional & alpha, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/35/35d75c544bf5b7e7822c98cfd7bc85c5f4b7949ac652163430d5624e367ca19b/errors.py b/shared/package-files/35/35d75c544bf5b7e7822c98cfd7bc85c5f4b7949ac652163430d5624e367ca19b/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..2ad8bab4122edd6fcd35f09767322c46aa7739bb --- /dev/null +++ b/shared/package-files/35/35d75c544bf5b7e7822c98cfd7bc85c5f4b7949ac652163430d5624e367ca19b/errors.py @@ -0,0 +1,106 @@ +"""ONNX exporter exceptions.""" +from __future__ import annotations + +import textwrap +from typing import Optional + +from torch import _C +from torch.onnx import _constants +from torch.onnx._internal import diagnostics + +__all__ = [ + "OnnxExporterError", + "OnnxExporterWarning", + "CheckerError", + "SymbolicValueError", + "UnsupportedOperatorError", +] + + +class OnnxExporterWarning(UserWarning): + """Base class for all warnings in the ONNX exporter.""" + + pass + + +class OnnxExporterError(RuntimeError): + """Errors raised by the ONNX exporter.""" + + pass + + +class CheckerError(OnnxExporterError): + """Raised when ONNX checker detects an invalid model.""" + + pass + + +class UnsupportedOperatorError(OnnxExporterError): + """Raised when an operator is unsupported by the exporter.""" + + def __init__(self, name: str, version: int, supported_version: Optional[int]): + if supported_version is not None: + diagnostic_rule: diagnostics.infra.Rule = ( + diagnostics.rules.operator_supported_in_newer_opset_version + ) + msg = diagnostic_rule.format_message(name, version, supported_version) + diagnostics.diagnose(diagnostic_rule, diagnostics.levels.ERROR, msg) + else: + if name.startswith(("aten::", "prim::", "quantized::")): + diagnostic_rule = diagnostics.rules.missing_standard_symbolic_function + msg = diagnostic_rule.format_message( + name, version, _constants.PYTORCH_GITHUB_ISSUES_URL + ) + diagnostics.diagnose(diagnostic_rule, diagnostics.levels.ERROR, msg) + else: + diagnostic_rule = diagnostics.rules.missing_custom_symbolic_function + msg = diagnostic_rule.format_message(name) + diagnostics.diagnose(diagnostic_rule, diagnostics.levels.ERROR, msg) + super().__init__(msg) + + +class SymbolicValueError(OnnxExporterError): + """Errors around TorchScript values and nodes.""" + + def __init__(self, msg: str, value: _C.Value): + message = ( + f"{msg} [Caused by the value '{value}' (type '{value.type()}') in the " + f"TorchScript graph. The containing node has kind '{value.node().kind()}'.] " + ) + + code_location = value.node().sourceRange() + if code_location: + message += f"\n (node defined in {code_location})" + + try: + # Add its input and output to the message. + message += "\n\n" + message += textwrap.indent( + ( + "Inputs:\n" + + ( + "\n".join( + f" #{i}: {input_} (type '{input_.type()}')" + for i, input_ in enumerate(value.node().inputs()) + ) + or " Empty" + ) + + "\n" + + "Outputs:\n" + + ( + "\n".join( + f" #{i}: {output} (type '{output.type()}')" + for i, output in enumerate(value.node().outputs()) + ) + or " Empty" + ) + ), + " ", + ) + except AttributeError: + message += ( + " Failed to obtain its input and output for debugging. " + "Please refer to the TorchScript graph for debugging information." + ) + + super().__init__(message) diff --git a/shared/package-files/35/35d882763820f67bb75e701fa4e750ab8e901837bb1fe6c48a7ba95b910d9191/validation.py b/shared/package-files/35/35d882763820f67bb75e701fa4e750ab8e901837bb1fe6c48a7ba95b910d9191/validation.py new file mode 100644 index 0000000000000000000000000000000000000000..127445e86e03807c596e96a4cd06c202656dcd41 --- /dev/null +++ b/shared/package-files/35/35d882763820f67bb75e701fa4e750ab8e901837bb1fe6c48a7ba95b910d9191/validation.py @@ -0,0 +1,195 @@ +""" +Input validation for a `Buffer`. +(Validators will be called before accepting input.) +""" +from __future__ import annotations + +from abc import ABCMeta, abstractmethod +from typing import Callable + +from prompt_toolkit.eventloop import run_in_executor_with_context + +from .document import Document +from .filters import FilterOrBool, to_filter + +__all__ = [ + "ConditionalValidator", + "ValidationError", + "Validator", + "ThreadedValidator", + "DummyValidator", + "DynamicValidator", +] + + +class ValidationError(Exception): + """ + Error raised by :meth:`.Validator.validate`. + + :param cursor_position: The cursor position where the error occurred. + :param message: Text. + """ + + def __init__(self, cursor_position: int = 0, message: str = "") -> None: + super().__init__(message) + self.cursor_position = cursor_position + self.message = message + + def __repr__(self) -> str: + return "{}(cursor_position={!r}, message={!r})".format( + self.__class__.__name__, + self.cursor_position, + self.message, + ) + + +class Validator(metaclass=ABCMeta): + """ + Abstract base class for an input validator. + + A validator is typically created in one of the following two ways: + + - Either by overriding this class and implementing the `validate` method. + - Or by passing a callable to `Validator.from_callable`. + + If the validation takes some time and needs to happen in a background + thread, this can be wrapped in a :class:`.ThreadedValidator`. + """ + + @abstractmethod + def validate(self, document: Document) -> None: + """ + Validate the input. + If invalid, this should raise a :class:`.ValidationError`. + + :param document: :class:`~prompt_toolkit.document.Document` instance. + """ + pass + + async def validate_async(self, document: Document) -> None: + """ + Return a `Future` which is set when the validation is ready. + This function can be overloaded in order to provide an asynchronous + implementation. + """ + try: + self.validate(document) + except ValidationError: + raise + + @classmethod + def from_callable( + cls, + validate_func: Callable[[str], bool], + error_message: str = "Invalid input", + move_cursor_to_end: bool = False, + ) -> Validator: + """ + Create a validator from a simple validate callable. E.g.: + + .. code:: python + + def is_valid(text): + return text in ['hello', 'world'] + Validator.from_callable(is_valid, error_message='Invalid input') + + :param validate_func: Callable that takes the input string, and returns + `True` if the input is valid input. + :param error_message: Message to be displayed if the input is invalid. + :param move_cursor_to_end: Move the cursor to the end of the input, if + the input is invalid. + """ + return _ValidatorFromCallable(validate_func, error_message, move_cursor_to_end) + + +class _ValidatorFromCallable(Validator): + """ + Validate input from a simple callable. + """ + + def __init__( + self, func: Callable[[str], bool], error_message: str, move_cursor_to_end: bool + ) -> None: + self.func = func + self.error_message = error_message + self.move_cursor_to_end = move_cursor_to_end + + def __repr__(self) -> str: + return f"Validator.from_callable({self.func!r})" + + def validate(self, document: Document) -> None: + if not self.func(document.text): + if self.move_cursor_to_end: + index = len(document.text) + else: + index = 0 + + raise ValidationError(cursor_position=index, message=self.error_message) + + +class ThreadedValidator(Validator): + """ + Wrapper that runs input validation in a thread. + (Use this to prevent the user interface from becoming unresponsive if the + input validation takes too much time.) + """ + + def __init__(self, validator: Validator) -> None: + self.validator = validator + + def validate(self, document: Document) -> None: + self.validator.validate(document) + + async def validate_async(self, document: Document) -> None: + """ + Run the `validate` function in a thread. + """ + + def run_validation_thread() -> None: + return self.validate(document) + + await run_in_executor_with_context(run_validation_thread) + + +class DummyValidator(Validator): + """ + Validator class that accepts any input. + """ + + def validate(self, document: Document) -> None: + pass # Don't raise any exception. + + +class ConditionalValidator(Validator): + """ + Validator that can be switched on/off according to + a filter. (This wraps around another validator.) + """ + + def __init__(self, validator: Validator, filter: FilterOrBool) -> None: + self.validator = validator + self.filter = to_filter(filter) + + def validate(self, document: Document) -> None: + # Call the validator only if the filter is active. + if self.filter(): + self.validator.validate(document) + + +class DynamicValidator(Validator): + """ + Validator class that can dynamically returns any Validator. + + :param get_validator: Callable that returns a :class:`.Validator` instance. + """ + + def __init__(self, get_validator: Callable[[], Validator | None]) -> None: + self.get_validator = get_validator + + def validate(self, document: Document) -> None: + validator = self.get_validator() or DummyValidator() + validator.validate(document) + + async def validate_async(self, document: Document) -> None: + validator = self.get_validator() or DummyValidator() + await validator.validate_async(document) diff --git a/shared/package-files/35/35d976a06643efab5ffe5424f6b0d9c2fd938a5f1f632e7b06f09ef42ae63b1e/nested_to_padded_tensor_compositeimplicitautograd_dispatch.h b/shared/package-files/35/35d976a06643efab5ffe5424f6b0d9c2fd938a5f1f632e7b06f09ef42ae63b1e/nested_to_padded_tensor_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..690c0c07ca7e45d7bcf6159b242116fb8170eadc --- /dev/null +++ b/shared/package-files/35/35d976a06643efab5ffe5424f6b0d9c2fd938a5f1f632e7b06f09ef42ae63b1e/nested_to_padded_tensor_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor nested_to_padded_tensor(const at::Tensor & self, double padding, at::OptionalIntArrayRef output_size=c10::nullopt); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/35/35d9a2fc814097ccf6f111ec6136cea2e7fe079147f75c7ff64cbe270b1d5d58/arithmetic.pyi b/shared/package-files/35/35d9a2fc814097ccf6f111ec6136cea2e7fe079147f75c7ff64cbe270b1d5d58/arithmetic.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6291fda6cefceeea0129e4006d1cf77c2e92d609 --- /dev/null +++ b/shared/package-files/35/35d9a2fc814097ccf6f111ec6136cea2e7fe079147f75c7ff64cbe270b1d5d58/arithmetic.pyi @@ -0,0 +1,516 @@ +import sys +from typing import Any + +import numpy as np +import numpy.typing as npt +from numpy._typing import _32Bit,_64Bit, _128Bit + +if sys.version_info >= (3, 11): + from typing import assert_type +else: + from typing_extensions import assert_type + +# Can't directly import `np.float128` as it is not available on all platforms +f16: np.floating[_128Bit] + +c16 = np.complex128() +f8 = np.float64() +i8 = np.int64() +u8 = np.uint64() + +c8 = np.complex64() +f4 = np.float32() +i4 = np.int32() +u4 = np.uint32() + +dt = np.datetime64(0, "D") +td = np.timedelta64(0, "D") + +b_ = np.bool_() + +b = bool() +c = complex() +f = float() +i = int() + +AR_b: npt.NDArray[np.bool_] +AR_u: npt.NDArray[np.uint32] +AR_i: npt.NDArray[np.int64] +AR_f: npt.NDArray[np.float64] +AR_c: npt.NDArray[np.complex128] +AR_m: npt.NDArray[np.timedelta64] +AR_M: npt.NDArray[np.datetime64] +AR_O: npt.NDArray[np.object_] +AR_number: npt.NDArray[np.number[Any]] + +AR_LIKE_b: list[bool] +AR_LIKE_u: list[np.uint32] +AR_LIKE_i: list[int] +AR_LIKE_f: list[float] +AR_LIKE_c: list[complex] +AR_LIKE_m: list[np.timedelta64] +AR_LIKE_M: list[np.datetime64] +AR_LIKE_O: list[np.object_] + +# Array subtraction + +assert_type(AR_number - AR_number, npt.NDArray[np.number[Any]]) + +assert_type(AR_b - AR_LIKE_u, npt.NDArray[np.unsignedinteger[Any]]) +assert_type(AR_b - AR_LIKE_i, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_b - AR_LIKE_f, npt.NDArray[np.floating[Any]]) +assert_type(AR_b - AR_LIKE_c, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_b - AR_LIKE_m, npt.NDArray[np.timedelta64]) +assert_type(AR_b - AR_LIKE_O, Any) + +assert_type(AR_LIKE_u - AR_b, npt.NDArray[np.unsignedinteger[Any]]) +assert_type(AR_LIKE_i - AR_b, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_LIKE_f - AR_b, npt.NDArray[np.floating[Any]]) +assert_type(AR_LIKE_c - AR_b, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_LIKE_m - AR_b, npt.NDArray[np.timedelta64]) +assert_type(AR_LIKE_M - AR_b, npt.NDArray[np.datetime64]) +assert_type(AR_LIKE_O - AR_b, Any) + +assert_type(AR_u - AR_LIKE_b, npt.NDArray[np.unsignedinteger[Any]]) +assert_type(AR_u - AR_LIKE_u, npt.NDArray[np.unsignedinteger[Any]]) +assert_type(AR_u - AR_LIKE_i, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_u - AR_LIKE_f, npt.NDArray[np.floating[Any]]) +assert_type(AR_u - AR_LIKE_c, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_u - AR_LIKE_m, npt.NDArray[np.timedelta64]) +assert_type(AR_u - AR_LIKE_O, Any) + +assert_type(AR_LIKE_b - AR_u, npt.NDArray[np.unsignedinteger[Any]]) +assert_type(AR_LIKE_u - AR_u, npt.NDArray[np.unsignedinteger[Any]]) +assert_type(AR_LIKE_i - AR_u, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_LIKE_f - AR_u, npt.NDArray[np.floating[Any]]) +assert_type(AR_LIKE_c - AR_u, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_LIKE_m - AR_u, npt.NDArray[np.timedelta64]) +assert_type(AR_LIKE_M - AR_u, npt.NDArray[np.datetime64]) +assert_type(AR_LIKE_O - AR_u, Any) + +assert_type(AR_i - AR_LIKE_b, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_i - AR_LIKE_u, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_i - AR_LIKE_i, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_i - AR_LIKE_f, npt.NDArray[np.floating[Any]]) +assert_type(AR_i - AR_LIKE_c, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_i - AR_LIKE_m, npt.NDArray[np.timedelta64]) +assert_type(AR_i - AR_LIKE_O, Any) + +assert_type(AR_LIKE_b - AR_i, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_LIKE_u - AR_i, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_LIKE_i - AR_i, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_LIKE_f - AR_i, npt.NDArray[np.floating[Any]]) +assert_type(AR_LIKE_c - AR_i, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_LIKE_m - AR_i, npt.NDArray[np.timedelta64]) +assert_type(AR_LIKE_M - AR_i, npt.NDArray[np.datetime64]) +assert_type(AR_LIKE_O - AR_i, Any) + +assert_type(AR_f - AR_LIKE_b, npt.NDArray[np.floating[Any]]) +assert_type(AR_f - AR_LIKE_u, npt.NDArray[np.floating[Any]]) +assert_type(AR_f - AR_LIKE_i, npt.NDArray[np.floating[Any]]) +assert_type(AR_f - AR_LIKE_f, npt.NDArray[np.floating[Any]]) +assert_type(AR_f - AR_LIKE_c, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_f - AR_LIKE_O, Any) + +assert_type(AR_LIKE_b - AR_f, npt.NDArray[np.floating[Any]]) +assert_type(AR_LIKE_u - AR_f, npt.NDArray[np.floating[Any]]) +assert_type(AR_LIKE_i - AR_f, npt.NDArray[np.floating[Any]]) +assert_type(AR_LIKE_f - AR_f, npt.NDArray[np.floating[Any]]) +assert_type(AR_LIKE_c - AR_f, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_LIKE_O - AR_f, Any) + +assert_type(AR_c - AR_LIKE_b, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_c - AR_LIKE_u, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_c - AR_LIKE_i, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_c - AR_LIKE_f, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_c - AR_LIKE_c, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_c - AR_LIKE_O, Any) + +assert_type(AR_LIKE_b - AR_c, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_LIKE_u - AR_c, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_LIKE_i - AR_c, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_LIKE_f - AR_c, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_LIKE_c - AR_c, npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(AR_LIKE_O - AR_c, Any) + +assert_type(AR_m - AR_LIKE_b, npt.NDArray[np.timedelta64]) +assert_type(AR_m - AR_LIKE_u, npt.NDArray[np.timedelta64]) +assert_type(AR_m - AR_LIKE_i, npt.NDArray[np.timedelta64]) +assert_type(AR_m - AR_LIKE_m, npt.NDArray[np.timedelta64]) +assert_type(AR_m - AR_LIKE_O, Any) + +assert_type(AR_LIKE_b - AR_m, npt.NDArray[np.timedelta64]) +assert_type(AR_LIKE_u - AR_m, npt.NDArray[np.timedelta64]) +assert_type(AR_LIKE_i - AR_m, npt.NDArray[np.timedelta64]) +assert_type(AR_LIKE_m - AR_m, npt.NDArray[np.timedelta64]) +assert_type(AR_LIKE_M - AR_m, npt.NDArray[np.datetime64]) +assert_type(AR_LIKE_O - AR_m, Any) + +assert_type(AR_M - AR_LIKE_b, npt.NDArray[np.datetime64]) +assert_type(AR_M - AR_LIKE_u, npt.NDArray[np.datetime64]) +assert_type(AR_M - AR_LIKE_i, npt.NDArray[np.datetime64]) +assert_type(AR_M - AR_LIKE_m, npt.NDArray[np.datetime64]) +assert_type(AR_M - AR_LIKE_M, npt.NDArray[np.timedelta64]) +assert_type(AR_M - AR_LIKE_O, Any) + +assert_type(AR_LIKE_M - AR_M, npt.NDArray[np.timedelta64]) +assert_type(AR_LIKE_O - AR_M, Any) + +assert_type(AR_O - AR_LIKE_b, Any) +assert_type(AR_O - AR_LIKE_u, Any) +assert_type(AR_O - AR_LIKE_i, Any) +assert_type(AR_O - AR_LIKE_f, Any) +assert_type(AR_O - AR_LIKE_c, Any) +assert_type(AR_O - AR_LIKE_m, Any) +assert_type(AR_O - AR_LIKE_M, Any) +assert_type(AR_O - AR_LIKE_O, Any) + +assert_type(AR_LIKE_b - AR_O, Any) +assert_type(AR_LIKE_u - AR_O, Any) +assert_type(AR_LIKE_i - AR_O, Any) +assert_type(AR_LIKE_f - AR_O, Any) +assert_type(AR_LIKE_c - AR_O, Any) +assert_type(AR_LIKE_m - AR_O, Any) +assert_type(AR_LIKE_M - AR_O, Any) +assert_type(AR_LIKE_O - AR_O, Any) + +# Array floor division + +assert_type(AR_b // AR_LIKE_b, npt.NDArray[np.int8]) +assert_type(AR_b // AR_LIKE_u, npt.NDArray[np.unsignedinteger[Any]]) +assert_type(AR_b // AR_LIKE_i, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_b // AR_LIKE_f, npt.NDArray[np.floating[Any]]) +assert_type(AR_b // AR_LIKE_O, Any) + +assert_type(AR_LIKE_b // AR_b, npt.NDArray[np.int8]) +assert_type(AR_LIKE_u // AR_b, npt.NDArray[np.unsignedinteger[Any]]) +assert_type(AR_LIKE_i // AR_b, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_LIKE_f // AR_b, npt.NDArray[np.floating[Any]]) +assert_type(AR_LIKE_O // AR_b, Any) + +assert_type(AR_u // AR_LIKE_b, npt.NDArray[np.unsignedinteger[Any]]) +assert_type(AR_u // AR_LIKE_u, npt.NDArray[np.unsignedinteger[Any]]) +assert_type(AR_u // AR_LIKE_i, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_u // AR_LIKE_f, npt.NDArray[np.floating[Any]]) +assert_type(AR_u // AR_LIKE_O, Any) + +assert_type(AR_LIKE_b // AR_u, npt.NDArray[np.unsignedinteger[Any]]) +assert_type(AR_LIKE_u // AR_u, npt.NDArray[np.unsignedinteger[Any]]) +assert_type(AR_LIKE_i // AR_u, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_LIKE_f // AR_u, npt.NDArray[np.floating[Any]]) +assert_type(AR_LIKE_m // AR_u, npt.NDArray[np.timedelta64]) +assert_type(AR_LIKE_O // AR_u, Any) + +assert_type(AR_i // AR_LIKE_b, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_i // AR_LIKE_u, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_i // AR_LIKE_i, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_i // AR_LIKE_f, npt.NDArray[np.floating[Any]]) +assert_type(AR_i // AR_LIKE_O, Any) + +assert_type(AR_LIKE_b // AR_i, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_LIKE_u // AR_i, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_LIKE_i // AR_i, npt.NDArray[np.signedinteger[Any]]) +assert_type(AR_LIKE_f // AR_i, npt.NDArray[np.floating[Any]]) +assert_type(AR_LIKE_m // AR_i, npt.NDArray[np.timedelta64]) +assert_type(AR_LIKE_O // AR_i, Any) + +assert_type(AR_f // AR_LIKE_b, npt.NDArray[np.floating[Any]]) +assert_type(AR_f // AR_LIKE_u, npt.NDArray[np.floating[Any]]) +assert_type(AR_f // AR_LIKE_i, npt.NDArray[np.floating[Any]]) +assert_type(AR_f // AR_LIKE_f, npt.NDArray[np.floating[Any]]) +assert_type(AR_f // AR_LIKE_O, Any) + +assert_type(AR_LIKE_b // AR_f, npt.NDArray[np.floating[Any]]) +assert_type(AR_LIKE_u // AR_f, npt.NDArray[np.floating[Any]]) +assert_type(AR_LIKE_i // AR_f, npt.NDArray[np.floating[Any]]) +assert_type(AR_LIKE_f // AR_f, npt.NDArray[np.floating[Any]]) +assert_type(AR_LIKE_m // AR_f, npt.NDArray[np.timedelta64]) +assert_type(AR_LIKE_O // AR_f, Any) + +assert_type(AR_m // AR_LIKE_u, npt.NDArray[np.timedelta64]) +assert_type(AR_m // AR_LIKE_i, npt.NDArray[np.timedelta64]) +assert_type(AR_m // AR_LIKE_f, npt.NDArray[np.timedelta64]) +assert_type(AR_m // AR_LIKE_m, npt.NDArray[np.int64]) +assert_type(AR_m // AR_LIKE_O, Any) + +assert_type(AR_LIKE_m // AR_m, npt.NDArray[np.int64]) +assert_type(AR_LIKE_O // AR_m, Any) + +assert_type(AR_O // AR_LIKE_b, Any) +assert_type(AR_O // AR_LIKE_u, Any) +assert_type(AR_O // AR_LIKE_i, Any) +assert_type(AR_O // AR_LIKE_f, Any) +assert_type(AR_O // AR_LIKE_m, Any) +assert_type(AR_O // AR_LIKE_M, Any) +assert_type(AR_O // AR_LIKE_O, Any) + +assert_type(AR_LIKE_b // AR_O, Any) +assert_type(AR_LIKE_u // AR_O, Any) +assert_type(AR_LIKE_i // AR_O, Any) +assert_type(AR_LIKE_f // AR_O, Any) +assert_type(AR_LIKE_m // AR_O, Any) +assert_type(AR_LIKE_M // AR_O, Any) +assert_type(AR_LIKE_O // AR_O, Any) + +# unary ops + +assert_type(-f16, np.floating[_128Bit]) +assert_type(-c16, np.complex128) +assert_type(-c8, np.complex64) +assert_type(-f8, np.float64) +assert_type(-f4, np.float32) +assert_type(-i8, np.int64) +assert_type(-i4, np.int32) +assert_type(-u8, np.uint64) +assert_type(-u4, np.uint32) +assert_type(-td, np.timedelta64) +assert_type(-AR_f, npt.NDArray[np.float64]) + +assert_type(+f16, np.floating[_128Bit]) +assert_type(+c16, np.complex128) +assert_type(+c8, np.complex64) +assert_type(+f8, np.float64) +assert_type(+f4, np.float32) +assert_type(+i8, np.int64) +assert_type(+i4, np.int32) +assert_type(+u8, np.uint64) +assert_type(+u4, np.uint32) +assert_type(+td, np.timedelta64) +assert_type(+AR_f, npt.NDArray[np.float64]) + +assert_type(abs(f16), np.floating[_128Bit]) +assert_type(abs(c16), np.float64) +assert_type(abs(c8), np.float32) +assert_type(abs(f8), np.float64) +assert_type(abs(f4), np.float32) +assert_type(abs(i8), np.int64) +assert_type(abs(i4), np.int32) +assert_type(abs(u8), np.uint64) +assert_type(abs(u4), np.uint32) +assert_type(abs(td), np.timedelta64) +assert_type(abs(b_), np.bool_) + +# Time structures + +assert_type(dt + td, np.datetime64) +assert_type(dt + i, np.datetime64) +assert_type(dt + i4, np.datetime64) +assert_type(dt + i8, np.datetime64) +assert_type(dt - dt, np.timedelta64) +assert_type(dt - i, np.datetime64) +assert_type(dt - i4, np.datetime64) +assert_type(dt - i8, np.datetime64) + +assert_type(td + td, np.timedelta64) +assert_type(td + i, np.timedelta64) +assert_type(td + i4, np.timedelta64) +assert_type(td + i8, np.timedelta64) +assert_type(td - td, np.timedelta64) +assert_type(td - i, np.timedelta64) +assert_type(td - i4, np.timedelta64) +assert_type(td - i8, np.timedelta64) +assert_type(td / f, np.timedelta64) +assert_type(td / f4, np.timedelta64) +assert_type(td / f8, np.timedelta64) +assert_type(td / td, np.float64) +assert_type(td // td, np.int64) + +# boolean + +assert_type(b_ / b, np.float64) +assert_type(b_ / b_, np.float64) +assert_type(b_ / i, np.float64) +assert_type(b_ / i8, np.float64) +assert_type(b_ / i4, np.float64) +assert_type(b_ / u8, np.float64) +assert_type(b_ / u4, np.float64) +assert_type(b_ / f, np.float64) +assert_type(b_ / f16, np.floating[_128Bit]) +assert_type(b_ / f8, np.float64) +assert_type(b_ / f4, np.float32) +assert_type(b_ / c, np.complex128) +assert_type(b_ / c16, np.complex128) +assert_type(b_ / c8, np.complex64) + +assert_type(b / b_, np.float64) +assert_type(b_ / b_, np.float64) +assert_type(i / b_, np.float64) +assert_type(i8 / b_, np.float64) +assert_type(i4 / b_, np.float64) +assert_type(u8 / b_, np.float64) +assert_type(u4 / b_, np.float64) +assert_type(f / b_, np.float64) +assert_type(f16 / b_, np.floating[_128Bit]) +assert_type(f8 / b_, np.float64) +assert_type(f4 / b_, np.float32) +assert_type(c / b_, np.complex128) +assert_type(c16 / b_, np.complex128) +assert_type(c8 / b_, np.complex64) + +# Complex + +assert_type(c16 + f16, np.complexfloating[_64Bit | _128Bit, _64Bit | _128Bit]) +assert_type(c16 + c16, np.complex128) +assert_type(c16 + f8, np.complex128) +assert_type(c16 + i8, np.complex128) +assert_type(c16 + c8, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(c16 + f4, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(c16 + i4, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(c16 + b_, np.complex128) +assert_type(c16 + b, np.complex128) +assert_type(c16 + c, np.complex128) +assert_type(c16 + f, np.complex128) +assert_type(c16 + AR_f, npt.NDArray[np.complexfloating[Any, Any]]) + +assert_type(f16 + c16, np.complexfloating[_64Bit | _128Bit, _64Bit | _128Bit]) +assert_type(c16 + c16, np.complex128) +assert_type(f8 + c16, np.complex128) +assert_type(i8 + c16, np.complex128) +assert_type(c8 + c16, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(f4 + c16, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(i4 + c16, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(b_ + c16, np.complex128) +assert_type(b + c16, np.complex128) +assert_type(c + c16, np.complex128) +assert_type(f + c16, np.complex128) +assert_type(AR_f + c16, npt.NDArray[np.complexfloating[Any, Any]]) + +assert_type(c8 + f16, np.complexfloating[_32Bit | _128Bit, _32Bit | _128Bit]) +assert_type(c8 + c16, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(c8 + f8, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(c8 + i8, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(c8 + c8, np.complex64) +assert_type(c8 + f4, np.complex64) +assert_type(c8 + i4, np.complex64) +assert_type(c8 + b_, np.complex64) +assert_type(c8 + b, np.complex64) +assert_type(c8 + c, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(c8 + f, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(c8 + AR_f, npt.NDArray[np.complexfloating[Any, Any]]) + +assert_type(f16 + c8, np.complexfloating[_32Bit | _128Bit, _32Bit | _128Bit]) +assert_type(c16 + c8, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(f8 + c8, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(i8 + c8, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(c8 + c8, np.complex64) +assert_type(f4 + c8, np.complex64) +assert_type(i4 + c8, np.complex64) +assert_type(b_ + c8, np.complex64) +assert_type(b + c8, np.complex64) +assert_type(c + c8, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(f + c8, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(AR_f + c8, npt.NDArray[np.complexfloating[Any, Any]]) + +# Float + +assert_type(f8 + f16, np.floating[_64Bit | _128Bit]) +assert_type(f8 + f8, np.float64) +assert_type(f8 + i8, np.float64) +assert_type(f8 + f4, np.floating[_32Bit | _64Bit]) +assert_type(f8 + i4, np.floating[_32Bit | _64Bit]) +assert_type(f8 + b_, np.float64) +assert_type(f8 + b, np.float64) +assert_type(f8 + c, np.complex128) +assert_type(f8 + f, np.float64) +assert_type(f8 + AR_f, npt.NDArray[np.floating[Any]]) + +assert_type(f16 + f8, np.floating[_64Bit | _128Bit]) +assert_type(f8 + f8, np.float64) +assert_type(i8 + f8, np.float64) +assert_type(f4 + f8, np.floating[_32Bit | _64Bit]) +assert_type(i4 + f8, np.floating[_32Bit | _64Bit]) +assert_type(b_ + f8, np.float64) +assert_type(b + f8, np.float64) +assert_type(c + f8, np.complex128) +assert_type(f + f8, np.float64) +assert_type(AR_f + f8, npt.NDArray[np.floating[Any]]) + +assert_type(f4 + f16, np.floating[_32Bit | _128Bit]) +assert_type(f4 + f8, np.floating[_32Bit | _64Bit]) +assert_type(f4 + i8, np.floating[_32Bit | _64Bit]) +assert_type(f4 + f4, np.float32) +assert_type(f4 + i4, np.float32) +assert_type(f4 + b_, np.float32) +assert_type(f4 + b, np.float32) +assert_type(f4 + c, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(f4 + f, np.floating[_32Bit | _64Bit]) +assert_type(f4 + AR_f, npt.NDArray[np.floating[Any]]) + +assert_type(f16 + f4, np.floating[_32Bit | _128Bit]) +assert_type(f8 + f4, np.floating[_32Bit | _64Bit]) +assert_type(i8 + f4, np.floating[_32Bit | _64Bit]) +assert_type(f4 + f4, np.float32) +assert_type(i4 + f4, np.float32) +assert_type(b_ + f4, np.float32) +assert_type(b + f4, np.float32) +assert_type(c + f4, np.complexfloating[_32Bit | _64Bit, _32Bit | _64Bit]) +assert_type(f + f4, np.floating[_32Bit | _64Bit]) +assert_type(AR_f + f4, npt.NDArray[np.floating[Any]]) + +# Int + +assert_type(i8 + i8, np.int64) +assert_type(i8 + u8, Any) +assert_type(i8 + i4, np.signedinteger[_32Bit | _64Bit]) +assert_type(i8 + u4, Any) +assert_type(i8 + b_, np.int64) +assert_type(i8 + b, np.int64) +assert_type(i8 + c, np.complex128) +assert_type(i8 + f, np.float64) +assert_type(i8 + AR_f, npt.NDArray[np.floating[Any]]) + +assert_type(u8 + u8, np.uint64) +assert_type(u8 + i4, Any) +assert_type(u8 + u4, np.unsignedinteger[_32Bit | _64Bit]) +assert_type(u8 + b_, np.uint64) +assert_type(u8 + b, np.uint64) +assert_type(u8 + c, np.complex128) +assert_type(u8 + f, np.float64) +assert_type(u8 + AR_f, npt.NDArray[np.floating[Any]]) + +assert_type(i8 + i8, np.int64) +assert_type(u8 + i8, Any) +assert_type(i4 + i8, np.signedinteger[_32Bit | _64Bit]) +assert_type(u4 + i8, Any) +assert_type(b_ + i8, np.int64) +assert_type(b + i8, np.int64) +assert_type(c + i8, np.complex128) +assert_type(f + i8, np.float64) +assert_type(AR_f + i8, npt.NDArray[np.floating[Any]]) + +assert_type(u8 + u8, np.uint64) +assert_type(i4 + u8, Any) +assert_type(u4 + u8, np.unsignedinteger[_32Bit | _64Bit]) +assert_type(b_ + u8, np.uint64) +assert_type(b + u8, np.uint64) +assert_type(c + u8, np.complex128) +assert_type(f + u8, np.float64) +assert_type(AR_f + u8, npt.NDArray[np.floating[Any]]) + +assert_type(i4 + i8, np.signedinteger[_32Bit | _64Bit]) +assert_type(i4 + i4, np.int32) +assert_type(i4 + b_, np.int32) +assert_type(i4 + b, np.int32) +assert_type(i4 + AR_f, npt.NDArray[np.floating[Any]]) + +assert_type(u4 + i8, Any) +assert_type(u4 + i4, Any) +assert_type(u4 + u8, np.unsignedinteger[_32Bit | _64Bit]) +assert_type(u4 + u4, np.uint32) +assert_type(u4 + b_, np.uint32) +assert_type(u4 + b, np.uint32) +assert_type(u4 + AR_f, npt.NDArray[np.floating[Any]]) + +assert_type(i8 + i4, np.signedinteger[_32Bit | _64Bit]) +assert_type(i4 + i4, np.int32) +assert_type(b_ + i4, np.int32) +assert_type(b + i4, np.int32) +assert_type(AR_f + i4, npt.NDArray[np.floating[Any]]) + +assert_type(i8 + u4, Any) +assert_type(i4 + u4, Any) +assert_type(u8 + u4, np.unsignedinteger[_32Bit | _64Bit]) +assert_type(u4 + u4, np.uint32) +assert_type(b_ + u4, np.uint32) +assert_type(b + u4, np.uint32) +assert_type(AR_f + u4, npt.NDArray[np.floating[Any]]) diff --git a/shared/package-files/35/35de16000b02c60a3a896fe7c9b4ee5266c0b698016c5dc7de4b288316cd1bac/triu_cpu_dispatch.h b/shared/package-files/35/35de16000b02c60a3a896fe7c9b4ee5266c0b698016c5dc7de4b288316cd1bac/triu_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..51606a56d17333d1fdb437f094b8a46119bca58b --- /dev/null +++ b/shared/package-files/35/35de16000b02c60a3a896fe7c9b4ee5266c0b698016c5dc7de4b288316cd1bac/triu_cpu_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor triu(const at::Tensor & self, int64_t diagonal=0); +TORCH_API at::Tensor & triu_out(at::Tensor & out, const at::Tensor & self, int64_t diagonal=0); +TORCH_API at::Tensor & triu_outf(const at::Tensor & self, int64_t diagonal, at::Tensor & out); +TORCH_API at::Tensor & triu_(at::Tensor & self, int64_t diagonal=0); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/35/35df4665a60f09a9337529b1919de367dac37f9f27fa984f4f6195968d344482/unfold_native.h b/shared/package-files/35/35df4665a60f09a9337529b1919de367dac37f9f27fa984f4f6195968d344482/unfold_native.h new file mode 100644 index 0000000000000000000000000000000000000000..1eea477a5ca8ca84dba9c1fac836444c34a42250 --- /dev/null +++ b/shared/package-files/35/35df4665a60f09a9337529b1919de367dac37f9f27fa984f4f6195968d344482/unfold_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor unfold(const at::Tensor & self, int64_t dimension, int64_t size, int64_t step); +} // namespace native +} // namespace at diff --git a/shared/package-files/35/35e05b7aebcd849e3f0919e76b1cf3c03bda6fb2efe1e81e6c194b04da09c099/_triton_multi_head_attention_cuda_dispatch.h b/shared/package-files/35/35e05b7aebcd849e3f0919e76b1cf3c03bda6fb2efe1e81e6c194b04da09c099/_triton_multi_head_attention_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..d52cab455851bfcaec00b237e895be9920ee60c3 --- /dev/null +++ b/shared/package-files/35/35e05b7aebcd849e3f0919e76b1cf3c03bda6fb2efe1e81e6c194b04da09c099/_triton_multi_head_attention_cuda_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor _triton_multi_head_attention(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const c10::optional & mask={}); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/35/35ea3580543d902df54fe807f1379e09a0c335a0dee5d7883fdecc4591603079/pynodes.py b/shared/package-files/35/35ea3580543d902df54fe807f1379e09a0c335a0dee5d7883fdecc4591603079/pynodes.py new file mode 100644 index 0000000000000000000000000000000000000000..f0a08b4a79d32f63d345947d6be310b44504dbf5 --- /dev/null +++ b/shared/package-files/35/35ea3580543d902df54fe807f1379e09a0c335a0dee5d7883fdecc4591603079/pynodes.py @@ -0,0 +1,11 @@ +from .abstract_nodes import List as AbstractList +from .ast import Token + + +class List(AbstractList): + pass + + +class NumExprEvaluate(Token): + """represents a call to :class:`numexpr`s :func:`evaluate`""" + __slots__ = _fields = ('expr',) diff --git a/shared/package-files/35/35ea39d436956b9390925520a0c1e8a66439b1cc0de4c78f132da9522743997f/_cxx_pytree.py b/shared/package-files/35/35ea39d436956b9390925520a0c1e8a66439b1cc0de4c78f132da9522743997f/_cxx_pytree.py new file mode 100644 index 0000000000000000000000000000000000000000..93605d3b0ba8490b1cf1892839b27a4c95b6713c --- /dev/null +++ b/shared/package-files/35/35ea39d436956b9390925520a0c1e8a66439b1cc0de4c78f132da9522743997f/_cxx_pytree.py @@ -0,0 +1,970 @@ +""" +Contains utility functions for working with nested python data structures. + +A *pytree* is Python nested data structure. It is a tree in the sense that +nodes are Python collections (e.g., list, tuple, dict) and the leaves are +Python values. Furthermore, a pytree should not contain reference cycles. + +pytrees are useful for working with nested collections of Tensors. For example, +one can use `tree_map` to map a function over all Tensors inside some nested +collection of Tensors and `tree_leaves` to get a flat list of all Tensors +inside some nested collection. pytrees are helpful for implementing nested +collection support for PyTorch APIs. +""" + +import functools +import sys +import types +import warnings +from typing import ( + Any, + Callable, + Iterable, + List, + Optional, + overload, + Tuple, + Type, + TypeVar, + Union, +) + +import torch + +if torch._running_with_deploy(): # type: ignore[no-untyped-call] + raise ImportError("C++ pytree utilities do not work with torch::deploy.") + +import optree +from optree import PyTreeSpec # direct import for type annotations + +from torch.utils._pytree import KeyEntry + + +__all__ = [ + "PyTree", + "Context", + "FlattenFunc", + "UnflattenFunc", + "DumpableContext", + "ToDumpableContextFn", + "FromDumpableContextFn", + "TreeSpec", + "LeafSpec", + "keystr", + "key_get", + "register_pytree_node", + "tree_flatten", + "tree_flatten_with_path", + "tree_unflatten", + "tree_leaves", + "tree_leaves_with_path", + "tree_structure", + "tree_map", + "tree_map_with_path", + "tree_map_", + "tree_map_only", + "tree_map_only_", + "tree_all", + "tree_any", + "tree_all_only", + "tree_any_only", + "treespec_dumps", + "treespec_loads", + "treespec_pprint", +] + + +T = TypeVar("T") +S = TypeVar("S") +U = TypeVar("U") +R = TypeVar("R") + + +Context = Any +PyTree = Any +TreeSpec = PyTreeSpec +FlattenFunc = Callable[[PyTree], Tuple[List[Any], Context]] +UnflattenFunc = Callable[[Iterable[Any], Context], PyTree] +OpTreeUnflattenFunc = Callable[[Context, Iterable[Any]], PyTree] +DumpableContext = Any # Any json dumpable text +ToDumpableContextFn = Callable[[Context], DumpableContext] +FromDumpableContextFn = Callable[[DumpableContext], Context] +KeyPath = Tuple[KeyEntry, ...] +FlattenWithKeysFunc = Callable[[PyTree], Tuple[List[Tuple[KeyEntry, Any]], Any]] + + +def _reverse_args(func: UnflattenFunc) -> OpTreeUnflattenFunc: + @functools.wraps(func) + def wrapped(*args: Any, **kwargs: Any) -> Any: + return func(*reversed(args), **kwargs) + + return wrapped + + +def register_pytree_node( + cls: Type[Any], + flatten_fn: FlattenFunc, + unflatten_fn: UnflattenFunc, + *, + serialized_type_name: Optional[str] = None, + to_dumpable_context: Optional[ToDumpableContextFn] = None, + from_dumpable_context: Optional[FromDumpableContextFn] = None, + flatten_with_keys_fn: Optional[FlattenWithKeysFunc] = None, +) -> None: + """Register a container-like type as pytree node. + + Args: + cls (type): A Python type to treat as an internal pytree node. + flatten_fn (callable): A function to be used during flattening, taking an instance of + ``cls`` and returning a pair, with (1) an iterable for the children to be flattened + recursively, and (2) some hashable auxiliary data to be stored in the treespec and to be + passed to the ``unflatten_fn``. + unflatten_fn (callable): A function taking two arguments: the auxiliary data that was + returned by ``flatten_fn`` and stored in the treespec, and the unflattened children. + The function should return an instance of ``cls``. + serialized_type_name (str, optional): A keyword argument used to specify the fully + qualified name used when serializing the tree spec. + to_dumpable_context (callable, optional): An optional keyword argument to custom specify how + to convert the context of the pytree to a custom json dumpable representation. This is + used for json serialization, which is being used in :mod:`torch.export` right now. + from_dumpable_context (callable, optional): An optional keyword argument to custom specify + how to convert the custom json dumpable representation of the context back to the + original context. This is used for json deserialization, which is being used in + :mod:`torch.export` right now. + + Example:: + + >>> # xdoctest: +SKIP + >>> # Registry a Python type with lambda functions + >>> register_pytree_node( + ... set, + ... lambda s: (sorted(s), None, None), + ... lambda children, _: set(children), + ... ) + """ + if flatten_with_keys_fn is not None: + raise NotImplementedError("KeyPaths are not yet supported in cxx_pytree.") + + _private_register_pytree_node( + cls, + flatten_fn, + unflatten_fn, + serialized_type_name=serialized_type_name, + to_dumpable_context=to_dumpable_context, + from_dumpable_context=from_dumpable_context, + ) + + from . import _pytree as python + + python._private_register_pytree_node( + cls, + flatten_fn, + unflatten_fn, + serialized_type_name=serialized_type_name, + to_dumpable_context=to_dumpable_context, + from_dumpable_context=from_dumpable_context, + ) + + +def _register_pytree_node( + cls: Type[Any], + flatten_fn: FlattenFunc, + unflatten_fn: UnflattenFunc, + *, + serialized_type_name: Optional[str] = None, + to_dumpable_context: Optional[ToDumpableContextFn] = None, + from_dumpable_context: Optional[FromDumpableContextFn] = None, +) -> None: + """Register a container-like type as pytree node for the C++ pytree only. + + The ``namespace`` argument is used to avoid collisions that occur when different libraries + register the same Python type with different behaviors. It is recommended to add a unique prefix + to the namespace to avoid conflicts with other libraries. Namespaces can also be used to specify + the same class in different namespaces for different use cases. + + .. warning:: + For safety reasons, a ``namespace`` must be specified while registering a custom type. It is + used to isolate the behavior of flattening and unflattening a pytree node type. This is to + prevent accidental collisions between different libraries that may register the same type. + + Args: + cls (type): A Python type to treat as an internal pytree node. + flatten_fn (callable): A function to be used during flattening, taking an instance of + ``cls`` and returning a pair, with (1) an iterable for the children to be flattened + recursively, and (2) some hashable auxiliary data to be stored in the treespec and to be + passed to the ``unflatten_fn``. + unflatten_fn (callable): A function taking two arguments: the auxiliary data that was + returned by ``flatten_fn`` and stored in the treespec, and the unflattened children. + The function should return an instance of ``cls``. + serialized_type_name (str, optional): A keyword argument used to specify the fully + qualified name used when serializing the tree spec. + to_dumpable_context (callable, optional): An optional keyword argument to custom specify how + to convert the context of the pytree to a custom json dumpable representation. This is + used for json serialization, which is being used in :mod:`torch.export` right now. + from_dumpable_context (callable, optional): An optional keyword argument to custom specify + how to convert the custom json dumpable representation of the context back to the + original context. This is used for json deserialization, which is being used in + :mod:`torch.export` right now. + """ + warnings.warn( + "torch.utils._cxx_pytree._register_pytree_node is deprecated. " + "Please use torch.utils._cxx_pytree.register_pytree_node instead.", + stacklevel=2, + ) + + _private_register_pytree_node( + cls, + flatten_fn, + unflatten_fn, + serialized_type_name=serialized_type_name, + to_dumpable_context=to_dumpable_context, + from_dumpable_context=from_dumpable_context, + ) + + +def _private_register_pytree_node( + cls: Type[Any], + flatten_fn: FlattenFunc, + unflatten_fn: UnflattenFunc, + *, + serialized_type_name: Optional[str] = None, + to_dumpable_context: Optional[ToDumpableContextFn] = None, + from_dumpable_context: Optional[FromDumpableContextFn] = None, +) -> None: + """This is an internal function that is used to register a pytree node type + for the C++ pytree only. End-users should use :func:`register_pytree_node` + instead. + """ + # TODO(XuehaiPan): remove this condition when we make Python pytree out-of-box support + # PyStructSequence types + if not optree.is_structseq_class(cls): + optree.register_pytree_node( + cls, + flatten_fn, + _reverse_args(unflatten_fn), + namespace="torch", + ) + + +def tree_flatten( + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> Tuple[List[Any], TreeSpec]: + """Flatten a pytree. + + See also :func:`tree_unflatten`. + + The flattening order (i.e., the order of elements in the output list) is deterministic, + corresponding to a left-to-right depth-first tree traversal. + + >>> tree = {'b': (2, [3, 4]), 'a': 1, 'c': None, 'd': 5} + >>> tree_flatten(tree) + ([1, 2, 3, 4, None, 5], PyTreeSpec({'a': *, 'b': (*, [*, *]), 'c': *, 'd': *}, NoneIsLeaf)) + >>> tree_flatten(1) + ([1], PyTreeSpec(*, NoneIsLeaf)) + >>> tree_flatten(None) + ([None], PyTreeSpec(*, NoneIsLeaf)) + + For unordered dictionaries, :class:`dict` and :class:`collections.defaultdict`, the order is + dependent on the **sorted** keys in the dictionary. Please use :class:`collections.OrderedDict` + if you want to keep the keys in the insertion order. + + >>> from collections import OrderedDict + >>> tree = OrderedDict([('b', (2, [3, 4])), ('a', 1), ('c', None), ('d', 5)]) + >>> tree_flatten(tree) + ([2, 3, 4, 1, None, 5], PyTreeSpec(OrderedDict([('b', (*, [*, *])), ('a', *), ('c', *), ('d', *)]), NoneIsLeaf)) + + Args: + tree (pytree): A pytree to flatten. + is_leaf (callable, optional): An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns: + A pair ``(leaves, treespec)`` where the first element is a list of leaf values and the + second element is a treespec representing the structure of the pytree. + """ + return optree.tree_flatten( # type: ignore[return-value] + tree, + is_leaf=is_leaf, + none_is_leaf=True, + namespace="torch", + ) + + +def tree_unflatten(leaves: Iterable[Any], treespec: TreeSpec) -> PyTree: + """Reconstruct a pytree from the treespec and the leaves. + + The inverse of :func:`tree_flatten`. + + >>> tree = {'b': (2, [3, 4]), 'a': 1, 'c': None, 'd': 5} + >>> leaves, treespec = tree_flatten(tree) + >>> tree == tree_unflatten(leaves, treespec) + True + + Args: + leaves (iterable): The list of leaves to use for reconstruction. The list must match the + number of leaves of the treespec. + treespec (TreeSpec): The treespec to reconstruct. + + Returns: + The reconstructed pytree, containing the ``leaves`` placed in the structure described by + ``treespec``. + """ + if not isinstance(treespec, TreeSpec): + raise TypeError( + f"tree_unflatten(values, spec): Expected `spec` to be instance of " + f"TreeSpec but got item of type {type(treespec)}." + ) + return optree.tree_unflatten(treespec, leaves) # type: ignore[arg-type] + + +def tree_leaves( + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> List[Any]: + """Get the leaves of a pytree. + + See also :func:`tree_flatten`. + + >>> tree = {'b': (2, [3, 4]), 'a': 1, 'c': None, 'd': 5} + >>> tree_leaves(tree) + [1, 2, 3, 4, None, 5] + >>> tree_leaves(1) + [1] + >>> tree_leaves(None) + [None] + + Args: + tree (pytree): A pytree to flatten. + is_leaf (callable, optional): An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns: + A list of leaf values. + """ + return optree.tree_leaves( + tree, + is_leaf=is_leaf, + none_is_leaf=True, + namespace="torch", + ) + + +def tree_structure( + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> TreeSpec: + """Get the treespec for a pytree. + + See also :func:`tree_flatten`. + + >>> tree = {'b': (2, [3, 4]), 'a': 1, 'c': None, 'd': 5} + >>> tree_structure(tree) + PyTreeSpec({'a': *, 'b': (*, [*, *]), 'c': *, 'd': *}, NoneIsLeaf) + >>> tree_structure(1) + PyTreeSpec(*, NoneIsLeaf) + >>> tree_structure(None) + PyTreeSpec(*, NoneIsLeaf) + + Args: + tree (pytree): A pytree to flatten. + is_leaf (callable, optional): An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns: + A treespec object representing the structure of the pytree. + """ + return optree.tree_structure( # type: ignore[return-value] + tree, + is_leaf=is_leaf, + none_is_leaf=True, + namespace="torch", + ) + + +def tree_map( + func: Callable[..., Any], + tree: PyTree, + *rests: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> PyTree: + """Map a multi-input function over pytree args to produce a new pytree. + + See also :func:`tree_map_`. + + >>> tree_map(lambda x: x + 1, {'x': 7, 'y': (42, 64)}) + {'x': 8, 'y': (43, 65)} + >>> tree_map(lambda x: x is None, {'x': 7, 'y': (42, 64), 'z': None}) + {'x': False, 'y': (False, False), 'z': True} + + If multiple inputs are given, the structure of the tree is taken from the first input; + subsequent inputs need only have ``tree`` as a prefix: + + >>> tree_map(lambda x, y: [x] + y, [5, 6], [[7, 9], [1, 2]]) + [[5, 7, 9], [6, 1, 2]] + + Args: + func (callable): A function that takes ``1 + len(rests)`` arguments, to be applied at the + corresponding leaves of the pytrees. + tree (pytree): A pytree to be mapped over, with each leaf providing the first positional + argument to function ``func``. + rests (tuple of pytree): A tuple of pytrees, each of which has the same structure as + ``tree`` or has ``tree`` as a prefix. + is_leaf (callable, optional): An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns: + A new pytree with the same structure as ``tree`` but with the value at each leaf given by + ``func(x, *xs)`` where ``x`` is the value at the corresponding leaf in ``tree`` and ``xs`` + is the tuple of values at corresponding nodes in ``rests``. + """ + return optree.tree_map( + func, + tree, + *rests, + is_leaf=is_leaf, + none_is_leaf=True, + namespace="torch", + ) + + +def tree_map_( + func: Callable[..., Any], + tree: PyTree, + *rests: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> PyTree: + """Like :func:`tree_map`, but do an inplace call on each leaf and return the original tree. + + See also :func:`tree_map`. + + Args: + func (callable): A function that takes ``1 + len(rests)`` arguments, to be applied at the + corresponding leaves of the pytrees. + tree (pytree): A pytree to be mapped over, with each leaf providing the first positional + argument to function ``func``. + rests (tuple of pytree): A tuple of pytrees, each of which has the same structure as + ``tree`` or has ``tree`` as a prefix. + is_leaf (callable, optional): An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns: + The original ``tree`` with the value at each leaf is given by the side-effect of function + ``func(x, *xs)`` (not the return value) where ``x`` is the value at the corresponding leaf + in ``tree`` and ``xs`` is the tuple of values at values at corresponding nodes in ``rests``. + """ + return optree.tree_map_( + func, + tree, + *rests, + is_leaf=is_leaf, + none_is_leaf=True, + namespace="torch", + ) + + +Type2 = Tuple[Type[T], Type[S]] +Type3 = Tuple[Type[T], Type[S], Type[U]] +if sys.version_info >= (3, 10): + TypeAny = Union[Type[Any], Tuple[Type[Any], ...], types.UnionType] +else: + TypeAny = Union[Type[Any], Tuple[Type[Any], ...]] + +Fn2 = Callable[[Union[T, S]], R] +Fn3 = Callable[[Union[T, S, U]], R] +Fn = Callable[[T], R] +FnAny = Callable[[Any], R] + +MapOnlyFn = Callable[[T], Callable[[Any], Any]] + + +# These specializations help with type inference on the lambda passed to this +# function +@overload +def map_only(__type_or_types_or_pred: Type2[T, S]) -> MapOnlyFn[Fn2[T, S, Any]]: + ... + + +@overload +def map_only(__type_or_types_or_pred: Type3[T, S, U]) -> MapOnlyFn[Fn3[T, S, U, Any]]: + ... + + +@overload +def map_only(__type_or_types_or_pred: Type[T]) -> MapOnlyFn[Fn[T, Any]]: + ... + + +# This specialization is needed for the implementations below that call +@overload +def map_only(__type_or_types_or_pred: TypeAny) -> MapOnlyFn[FnAny[Any]]: + ... + + +@overload +def map_only(__type_or_types_or_pred: Callable[[Any], bool]) -> MapOnlyFn[FnAny[Any]]: + ... + + +def map_only( + __type_or_types_or_pred: Union[TypeAny, Callable[[Any], bool]] +) -> MapOnlyFn[FnAny[Any]]: + """ + Suppose you are writing a tree_map over tensors, leaving everything + else unchanged. Ordinarily you would have to write: + + def go(t): + if isinstance(t, Tensor): + return ... + else: + return t + + With this function, you only need to write: + + @map_only(Tensor) + def go(t): + return ... + + You can also directly use 'tree_map_only' + """ + if isinstance(__type_or_types_or_pred, (type, tuple)) or ( + sys.version_info >= (3, 10) + and isinstance(__type_or_types_or_pred, types.UnionType) + ): + + def pred(x: Any) -> bool: + return isinstance(x, __type_or_types_or_pred) # type: ignore[arg-type] + + elif callable(__type_or_types_or_pred): + pred = __type_or_types_or_pred # type: ignore[assignment] + else: + raise TypeError("Argument must be a type, a tuple of types, or a callable.") + + def wrapper(func: Callable[[T], Any]) -> Callable[[Any], Any]: + @functools.wraps(func) + def wrapped(x: T) -> Any: + if pred(x): + return func(x) + return x + + return wrapped + + return wrapper + + +@overload +def tree_map_only( + __type_or_types_or_pred: Type[T], + func: Fn[T, Any], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> PyTree: + ... + + +@overload +def tree_map_only( + __type_or_types_or_pred: Type2[T, S], + func: Fn2[T, S, Any], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> PyTree: + ... + + +@overload +def tree_map_only( + __type_or_types_or_pred: Type3[T, S, U], + func: Fn3[T, S, U, Any], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> PyTree: + ... + + +@overload +def tree_map_only( + __type_or_types_or_pred: Callable[[Any], bool], + func: FnAny[Any], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> PyTree: + ... + + +def tree_map_only( + __type_or_types_or_pred: Union[TypeAny, Callable[[Any], bool]], + func: FnAny[Any], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> PyTree: + return tree_map(map_only(__type_or_types_or_pred)(func), tree, is_leaf=is_leaf) + + +@overload +def tree_map_only_( + __type_or_types_or_pred: Type[T], + func: Fn[T, Any], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> PyTree: + ... + + +@overload +def tree_map_only_( + __type_or_types_or_pred: Type2[T, S], + func: Fn2[T, S, Any], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> PyTree: + ... + + +@overload +def tree_map_only_( + __type_or_types_or_pred: Type3[T, S, U], + func: Fn3[T, S, U, Any], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> PyTree: + ... + + +@overload +def tree_map_only_( + __type_or_types_or_pred: Callable[[Any], bool], + func: FnAny[Any], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> PyTree: + ... + + +def tree_map_only_( + __type_or_types_or_pred: Union[TypeAny, Callable[[Any], bool]], + func: FnAny[Any], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> PyTree: + return tree_map_(map_only(__type_or_types_or_pred)(func), tree, is_leaf=is_leaf) + + +def tree_all( + pred: Callable[[Any], bool], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> bool: + flat_args = tree_leaves(tree, is_leaf=is_leaf) + return all(map(pred, flat_args)) + + +def tree_any( + pred: Callable[[Any], bool], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> bool: + flat_args = tree_leaves(tree, is_leaf=is_leaf) + return any(map(pred, flat_args)) + + +@overload +def tree_all_only( + __type_or_types: Type[T], + pred: Fn[T, bool], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> bool: + ... + + +@overload +def tree_all_only( + __type_or_types: Type2[T, S], + pred: Fn2[T, S, bool], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> bool: + ... + + +@overload +def tree_all_only( + __type_or_types: Type3[T, S, U], + pred: Fn3[T, S, U, bool], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> bool: + ... + + +def tree_all_only( + __type_or_types: TypeAny, + pred: FnAny[bool], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> bool: + flat_args = tree_leaves(tree, is_leaf=is_leaf) + return all(pred(x) for x in flat_args if isinstance(x, __type_or_types)) + + +@overload +def tree_any_only( + __type_or_types: Type[T], + pred: Fn[T, bool], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> bool: + ... + + +@overload +def tree_any_only( + __type_or_types: Type2[T, S], + pred: Fn2[T, S, bool], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> bool: + ... + + +@overload +def tree_any_only( + __type_or_types: Type3[T, S, U], + pred: Fn3[T, S, U, bool], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> bool: + ... + + +def tree_any_only( + __type_or_types: TypeAny, + pred: FnAny[bool], + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> bool: + flat_args = tree_leaves(tree, is_leaf=is_leaf) + return any(pred(x) for x in flat_args if isinstance(x, __type_or_types)) + + +def broadcast_prefix( + prefix_tree: PyTree, + full_tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> List[Any]: + """Return a list of broadcasted leaves in ``prefix_tree`` to match the number of leaves in ``full_tree``. + + If a ``prefix_tree`` is a prefix of a ``full_tree``, this means the ``full_tree`` can be + constructed by replacing the leaves of ``prefix_tree`` with appropriate **subtrees**. + + This function returns a list of leaves with the same size as ``full_tree``. The leaves are + replicated from ``prefix_tree``. The number of replicas is determined by the corresponding + subtree in ``full_tree``. + + >>> broadcast_prefix(1, [1, 2, 3]) + [1, 1, 1] + >>> broadcast_prefix([1, 2, 3], [1, 2, 3]) + [1, 2, 3] + >>> broadcast_prefix([1, 2, 3], [1, 2, 3, 4]) + Traceback (most recent call last): + ... + ValueError: list arity mismatch; expected: 3, got: 4; list: [1, 2, 3, 4]. + >>> broadcast_prefix([1, 2, 3], [1, 2, (3, 4)]) + [1, 2, 3, 3] + >>> broadcast_prefix([1, 2, 3], [1, 2, {'a': 3, 'b': 4, 'c': (None, 5)}]) + [1, 2, 3, 3, 3, 3] + + Args: + prefix_tree (pytree): A pytree with the same structure as a prefix of ``full_tree``. + full_tree (pytree): A pytree with the same structure as a suffix of ``prefix_tree``. + is_leaf (callable, optional): An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns: + A list of leaves in ``prefix_tree`` broadcasted to match the number of leaves in ``full_tree``. + """ + return optree.broadcast_prefix( + prefix_tree, + full_tree, + is_leaf=is_leaf, + none_is_leaf=True, + namespace="torch", + ) + + +# Broadcasts a pytree to the provided TreeSpec and returns the flattened +# values. If this is not possible, then this function returns None. +# +# For example, given pytree=0 and spec=TreeSpec(list, None, [LeafSpec(), LeafSpec()]), +# would return [0, 0]. This is useful for part of the vmap implementation: +# a user can pass in vmap(fn, in_dims)(*inputs). `in_dims` should be +# broadcastable to the tree structure of `inputs` and we use +# _broadcast_to_and_flatten to check this. +def _broadcast_to_and_flatten( + tree: PyTree, + treespec: TreeSpec, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> Optional[List[Any]]: + assert isinstance(treespec, TreeSpec) + full_tree = tree_unflatten([0] * treespec.num_leaves, treespec) + try: + return broadcast_prefix(tree, full_tree, is_leaf=is_leaf) + except ValueError: + return None + + +def treespec_dumps(treespec: TreeSpec, protocol: Optional[int] = None) -> str: + """Serialize a treespec to a JSON string.""" + if not isinstance(treespec, TreeSpec): + raise TypeError( + f"treespec_dumps(spec): Expected `spec` to be instance of " + f"TreeSpec but got item of type {type(treespec)}." + ) + from ._pytree import ( + tree_structure as _tree_structure, + treespec_dumps as _treespec_dumps, + ) + + orig_treespec = _tree_structure(tree_unflatten([0] * treespec.num_leaves, treespec)) + return _treespec_dumps(orig_treespec, protocol=protocol) + + +def treespec_loads(serialized: str) -> TreeSpec: + """Deserialize a treespec from a JSON string.""" + from ._pytree import ( + tree_unflatten as _tree_unflatten, + treespec_loads as _treespec_loads, + ) + + orig_treespec = _treespec_loads(serialized) + dummy_tree = _tree_unflatten([0] * orig_treespec.num_leaves, orig_treespec) + treespec = tree_structure(dummy_tree) + return treespec + + +class _DummyLeaf: + def __repr__(self) -> str: + return "*" + + +def treespec_pprint(treespec: TreeSpec) -> str: + dummy_tree = tree_unflatten( + [_DummyLeaf() for _ in range(treespec.num_leaves)], + treespec, + ) + return repr(dummy_tree) + + +class LeafSpecMeta(type(TreeSpec)): # type: ignore[misc] + def __instancecheck__(self, instance: object) -> bool: + return isinstance(instance, TreeSpec) and instance.is_leaf() + + +class LeafSpec(TreeSpec, metaclass=LeafSpecMeta): + def __new__(cls) -> "LeafSpec": + return optree.treespec_leaf(none_is_leaf=True) # type: ignore[return-value] + + +def tree_flatten_with_path( + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> Tuple[List[Tuple[KeyPath, Any]], TreeSpec]: + """Flattens a pytree like :func:`tree_flatten`, but also returns each leaf's key path. + + Args: + tree: a pytree to flatten. If it contains a custom type, that type must be + registered with an appropriate `tree_flatten_with_path_fn` when registered + with :func:`register_pytree_node`. + is_leaf: An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + Returns: + A tuple where the first element is a list of (key path, leaf) pairs, and the + second element is a :class:`TreeSpec` representing the structure of the flattened + tree. + """ + raise NotImplementedError("KeyPaths are not yet supported in cxx_pytree.") + + +def tree_leaves_with_path( + tree: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> List[Tuple[KeyPath, Any]]: + """Gets the leaves of a pytree like ``tree_leaves`` and returns each leaf's key path. + + Args: + tree: a pytree. If it contains a custom type, that type must be + registered with an appropriate `tree_flatten_with_path_fn` when registered + with :func:`register_pytree_node`. + is_leaf: An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + Returns: + A list of (key path, leaf) pairs. + """ + raise NotImplementedError("KeyPaths are not yet supported in cxx_pytree.") + + +def tree_map_with_path( + func: Callable[..., Any], + tree: PyTree, + *rests: PyTree, + is_leaf: Optional[Callable[[PyTree], bool]] = None, +) -> PyTree: + """Like :func:`tree_map`, but the provided callable takes an additional key path argument. + + Args: + func: A function that takes ``2 + len(rests)`` arguments, to be applied at the + corresponding leaves of the pytrees. The first positional argument + to ``func`` is the key path of the leaf in question. The second + positional argument is the value of the leaf. + tree: A pytree to be mapped over, with each leaf providing the first positional + argument to function ``func``. + rests: A tuple of pytrees, each of which has the same structure as + ``tree`` or has ``tree`` as a prefix. + is_leaf: An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns + A new pytree with the same structure as ``tree`` but with the value at each leaf given by + ``func(keypath, x, *xs)`` where ``keypath`` is the key path at the + corresponding leaf in ``tree``, ``x`` is the value at that leaf, and + ``xs`` is the tuple of values at corresponding nodes in ``rests``. + """ + raise NotImplementedError("KeyPaths are not yet supported in cxx_pytree.") + + +def keystr(kp: KeyPath) -> str: + """Given a key path, return a pretty-printed representation.""" + raise NotImplementedError("KeyPaths are not yet supported in cxx_pytree.") + + +def key_get(obj: Any, kp: KeyPath) -> Any: + """Given an object and a key path, return the value at the key path.""" + raise NotImplementedError("KeyPaths are not yet supported in cxx_pytree.") diff --git a/shared/package-files/35/35ea5e0e47d4336acce1e4c4db89bca9fce5fcfe2a16d3afbf4e3d0ba0795cf2/leda.py b/shared/package-files/35/35ea5e0e47d4336acce1e4c4db89bca9fce5fcfe2a16d3afbf4e3d0ba0795cf2/leda.py new file mode 100644 index 0000000000000000000000000000000000000000..ee7ad6427a5c54564c54123b285987ef11441742 --- /dev/null +++ b/shared/package-files/35/35ea5e0e47d4336acce1e4c4db89bca9fce5fcfe2a16d3afbf4e3d0ba0795cf2/leda.py @@ -0,0 +1,106 @@ +""" +Read graphs in LEDA format. + +LEDA is a C++ class library for efficient data types and algorithms. + +Format +------ +See http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html + +""" +# Original author: D. Eppstein, UC Irvine, August 12, 2003. +# The original code at http://www.ics.uci.edu/~eppstein/PADS/ is public domain. + +__all__ = ["read_leda", "parse_leda"] + +import networkx as nx +from networkx.exception import NetworkXError +from networkx.utils import open_file + + +@open_file(0, mode="rb") +def read_leda(path, encoding="UTF-8"): + """Read graph in LEDA format from path. + + Parameters + ---------- + path : file or string + File or filename to read. Filenames ending in .gz or .bz2 will be + uncompressed. + + Returns + ------- + G : NetworkX graph + + Examples + -------- + G=nx.read_leda('file.leda') + + References + ---------- + .. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html + """ + lines = (line.decode(encoding) for line in path) + G = parse_leda(lines) + return G + + +def parse_leda(lines): + """Read graph in LEDA format from string or iterable. + + Parameters + ---------- + lines : string or iterable + Data in LEDA format. + + Returns + ------- + G : NetworkX graph + + Examples + -------- + G=nx.parse_leda(string) + + References + ---------- + .. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html + """ + if isinstance(lines, str): + lines = iter(lines.split("\n")) + lines = iter( + [ + line.rstrip("\n") + for line in lines + if not (line.startswith(("#", "\n")) or line == "") + ] + ) + for i in range(3): + next(lines) + # Graph + du = int(next(lines)) # -1=directed, -2=undirected + if du == -1: + G = nx.DiGraph() + else: + G = nx.Graph() + + # Nodes + n = int(next(lines)) # number of nodes + node = {} + for i in range(1, n + 1): # LEDA counts from 1 to n + symbol = next(lines).rstrip().strip("|{}| ") + if symbol == "": + symbol = str(i) # use int if no label - could be trouble + node[i] = symbol + + G.add_nodes_from([s for i, s in node.items()]) + + # Edges + m = int(next(lines)) # number of edges + for i in range(m): + try: + s, t, reversal, label = next(lines).split() + except BaseException as err: + raise NetworkXError(f"Too few fields in LEDA.GRAPH edge {i+1}") from err + # BEWARE: no handling of reversal edges + G.add_edge(node[int(s)], node[int(t)], label=label[2:-2]) + return G diff --git a/shared/package-files/35/35eb013bbad50cf180fa63bc030f4762c9d471fb358c72a5195599537473fa14/entry_points.txt b/shared/package-files/35/35eb013bbad50cf180fa63bc030f4762c9d471fb358c72a5195599537473fa14/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb6aed0c6f7b004724226743336bea351b6eb63b --- /dev/null +++ b/shared/package-files/35/35eb013bbad50cf180fa63bc030f4762c9d471fb358c72a5195599537473fa14/entry_points.txt @@ -0,0 +1,5 @@ +[conda] +index=conda_index.plugin + +[console_scripts] + diff --git a/shared/package-files/35/35eb46dd2a076b97bb2e88892ce6a59c1942468201a576e472783b4554d895c7/_upsample_nearest_exact3d_compositeimplicitautograd_dispatch.h b/shared/package-files/35/35eb46dd2a076b97bb2e88892ce6a59c1942468201a576e472783b4554d895c7/_upsample_nearest_exact3d_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1b01aa0c282b43e1667d8d4ca8d0ba41358e0f99 --- /dev/null +++ b/shared/package-files/35/35eb46dd2a076b97bb2e88892ce6a59c1942468201a576e472783b4554d895c7/_upsample_nearest_exact3d_compositeimplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor _upsample_nearest_exact3d(const at::Tensor & input, at::OptionalIntArrayRef output_size, c10::optional> scale_factors); +TORCH_API at::Tensor _upsample_nearest_exact3d_symint(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, c10::optional> scale_factors); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/35/35ec8ae0282e93b973466d2d28494e94a38891a7e95c43aa47f6433718c3528d/__init__.py b/shared/package-files/35/35ec8ae0282e93b973466d2d28494e94a38891a7e95c43aa47f6433718c3528d/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e0be696975584bbc0460e513eea0dd0d73736ea8 --- /dev/null +++ b/shared/package-files/35/35ec8ae0282e93b973466d2d28494e94a38891a7e95c43aa47f6433718c3528d/__init__.py @@ -0,0 +1,2 @@ +from .autocast_mode import _enter_autocast, _exit_autocast, autocast +from .grad_scaler import GradScaler diff --git a/shared/package-files/35/35f15eb61ac8169662c0139c78bec49343ec3061525c7e28fb97c66b82af778c/index_reduce_cuda_dispatch.h b/shared/package-files/35/35f15eb61ac8169662c0139c78bec49343ec3061525c7e28fb97c66b82af778c/index_reduce_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..3f0b9444b30a113e3d8df143d751a21797d6283b --- /dev/null +++ b/shared/package-files/35/35f15eb61ac8169662c0139c78bec49343ec3061525c7e28fb97c66b82af778c/index_reduce_cuda_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor index_reduce(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self=true); +TORCH_API at::Tensor & index_reduce_out(at::Tensor & out, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self=true); +TORCH_API at::Tensor & index_reduce_outf(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self, at::Tensor & out); +TORCH_API at::Tensor & index_reduce_(at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self=true); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/35/35f3b4bbd587a5a9aab5b33da2a3406ff1b829d7b38bf69759c0da6154a20fe3/libsolv.pc b/shared/package-files/35/35f3b4bbd587a5a9aab5b33da2a3406ff1b829d7b38bf69759c0da6154a20fe3/libsolv.pc new file mode 100644 index 0000000000000000000000000000000000000000..730b155fda82a971ca9845b5e2068c9bde4da0f5 --- /dev/null +++ b/shared/package-files/35/35f3b4bbd587a5a9aab5b33da2a3406ff1b829d7b38bf69759c0da6154a20fe3/libsolv.pc @@ -0,0 +1,8 @@ +libdir=/opt/conda/lib +includedir=/opt/conda/include + +Name: libsolv +Description: Library for solving packages +Version: 0.7.24 +Libs: -L${libdir} -lsolv +Cflags: -I${includedir} diff --git a/shared/package-files/35/35f48be73b22e77ee94b46b76538ff87de2c535fc13286a8f041159b6b496d6d/namespace.py b/shared/package-files/35/35f48be73b22e77ee94b46b76538ff87de2c535fc13286a8f041159b6b496d6d/namespace.py new file mode 100644 index 0000000000000000000000000000000000000000..595dc275f0b040915080e8a0b5986df3ddce6be4 --- /dev/null +++ b/shared/package-files/35/35f48be73b22e77ee94b46b76538ff87de2c535fc13286a8f041159b6b496d6d/namespace.py @@ -0,0 +1,243 @@ +from __future__ import annotations + +import operator +from functools import reduce +from typing import TYPE_CHECKING, Any, cast + +import ibis +import ibis.expr.types as ir + +from narwhals._compliant.namespace import AlignDiagonal +from narwhals._expression_parsing import ( + combine_alias_output_names, + combine_evaluate_output_names, + evaluate_output_names_and_aliases, +) +from narwhals._ibis.dataframe import IbisLazyFrame +from narwhals._ibis.expr import IbisExpr +from narwhals._ibis.selectors import IbisSelectorNamespace +from narwhals._ibis.utils import function, lit, narwhals_to_native_dtype +from narwhals._sql.namespace import SQLNamespace +from narwhals._utils import ( + Implementation, + check_column_names_are_unique, + ensure_path_source, + validate_separators, +) + +if TYPE_CHECKING: + from collections.abc import Iterable, Sequence + + from narwhals._utils import Version + from narwhals.typing import ( + ConcatMethod, + CorrelationMethod, + IntoDType, + NormalizedSource, + PythonLiteral, + ) + + +class IbisNamespace( + SQLNamespace[IbisLazyFrame, IbisExpr, "ir.Table", "ir.Value"], + AlignDiagonal[IbisLazyFrame, IbisExpr], +): + _implementation: Implementation = Implementation.IBIS + + def __init__(self, *, version: Version) -> None: + self._version = version + + @property + def selectors(self) -> IbisSelectorNamespace: + return IbisSelectorNamespace.from_namespace(self) + + @property + def _expr(self) -> type[IbisExpr]: + return IbisExpr + + @property + def _lazyframe(self) -> type[IbisLazyFrame]: + return IbisLazyFrame + + def scan_csv( + self, source: NormalizedSource, *, separator: str = ",", **kwds: Any + ) -> IbisLazyFrame: + validate_separators(separator, ("sep",), kwds) + native = ibis.read_csv( + ensure_path_source(source, self._implementation), sep=separator, **kwds + ) + return self._lazyframe.from_native(native, context=self) + + def scan_parquet(self, source: NormalizedSource, **kwds: Any) -> IbisLazyFrame: + native = ibis.read_parquet( + ensure_path_source(source, self._implementation), **kwds + ) + return self._lazyframe.from_native(native, context=self) + + def _function(self, name: str, *args: ir.Value | PythonLiteral) -> ir.Value: + return function(name, *args) + + def _lit(self, value: Any) -> ir.Value: + return lit(value) + + def _when( + self, condition: ir.Value, value: ir.Value, otherwise: ir.Expr | None = None + ) -> ir.Value: + if otherwise is None: + return ibis.cases((condition, value)) + return ibis.cases((condition, value), else_=otherwise) # pragma: no cover + + def _coalesce(self, *exprs: ir.Value) -> ir.Value: + return ibis.coalesce(*exprs) + + def concat( + self, items: Iterable[IbisLazyFrame], *, how: ConcatMethod + ) -> IbisLazyFrame: + frames: Sequence[IbisLazyFrame] = tuple(items) + if how == "diagonal": + frames = self.align_diagonal(frames) + try: + result = ibis.union(*(lf.native for lf in frames)) + except ibis.IbisError: + first = frames[0].schema + if not all(x.schema == first for x in frames[1:]): + msg = "inputs should all have the same schema" + raise TypeError(msg) from None + raise + return frames[0]._with_native(result) + + def concat_str( + self, *exprs: IbisExpr, separator: str, ignore_nulls: bool + ) -> IbisExpr: + def func(cols: Sequence[ir.Value]) -> ir.Value: + cols_casted = [s.cast("string") for s in cols] + + if ignore_nulls: + return lit(separator).join(cols_casted) + return reduce( + lambda acc, col: acc.concat(separator, col), + cols_casted[1:], + cols_casted[0], + ) + + return self._expr._from_elementwise_horizontal_op(func, *exprs) + + def mean_horizontal(self, *exprs: IbisExpr) -> IbisExpr: + def func(cols: Iterable[ir.Value]) -> ir.Value: + cols = list(cols) + numerator = reduce( + operator.add, + (cast("ir.NumericValue", col.fill_null(lit(0))) for col in cols), + ) + denominator = reduce( + operator.add, + ( + cast("ir.NumericValue", col.isnull().ifelse(lit(0), lit(1))) + for col in cols + ), + ) + return numerator / denominator + + return self._expr._from_elementwise_horizontal_op(func, *exprs) + + def lit(self, value: PythonLiteral, dtype: IntoDType | None) -> IbisExpr: + def func(_df: IbisLazyFrame) -> Sequence[ir.Value]: + ibis_dtype = narwhals_to_native_dtype(dtype, self._version) if dtype else None + if not isinstance(value, dict): + return [lit(value, ibis_dtype)] + if value: + return [ibis.struct(value, type=ibis_dtype)] + msg = "Cannot create an empty struct type for Ibis backend" + raise NotImplementedError(msg) + + return self._expr( + func, + evaluate_output_names=lambda _df: ["literal"], + alias_output_names=None, + version=self._version, + ) + + def len(self) -> IbisExpr: + def func(_df: IbisLazyFrame) -> list[ir.Value]: + return [_df.native.count()] + + return self._expr( + call=func, + evaluate_output_names=lambda _df: ["len"], + alias_output_names=None, + version=self._version, + ) + + def corr(self, a: IbisExpr, b: IbisExpr, *, method: CorrelationMethod) -> IbisExpr: + if method != "pearson": + msg = "Only 'pearson' correlation is supported for Ibis." + raise NotImplementedError(msg) + + def func(_df: IbisLazyFrame) -> list[ir.Value]: + a_ = _df._evaluate_single_output_expr(a) + b_ = _df._evaluate_single_output_expr(b) + return [a_.corr(b_, how="pop")] # pyright: ignore[reportAttributeAccessIssue] + + return self._expr( + func, + evaluate_output_names=combine_evaluate_output_names(a, b), + alias_output_names=combine_alias_output_names(a, b), + version=self._version, + ) + + def cov(self, a: IbisExpr, b: IbisExpr, *, ddof: int) -> IbisExpr: + def func(_df: IbisLazyFrame) -> list[ir.Value]: + a_ = cast("ir.NumericColumn", _df._evaluate_single_output_expr(a)) + b_ = cast("ir.NumericColumn", _df._evaluate_single_output_expr(b)) + if ddof == 0: + return [a_.cov(b_, how="pop")] + if ddof == 1: + return [a_.cov(b_, how="sample")] + n_samples = a_.count(where=a_.notnull() & b_.notnull()) + denominator = n_samples - ddof + rescaled = a_.cov(b_, how="sample") * ((n_samples - 1) / denominator) + return [self._when(denominator <= lit(0), lit(None), rescaled)] + + return self._expr( + func, + evaluate_output_names=combine_evaluate_output_names(a, b), + alias_output_names=combine_alias_output_names(a, b), + version=self._version, + ) + + def struct(self, *exprs: IbisExpr) -> IbisExpr: + version = self._version + + def func(df: IbisLazyFrame) -> list[ir.Value]: + fields = [ + (alias, native_expr) + for expr in exprs + for native_expr, _, alias in zip( + expr(df), + *evaluate_output_names_and_aliases(expr, df, []), + strict=True, + ) + ] + check_column_names_are_unique([name for name, _ in fields]) + return [ibis.struct(dict(fields))] + + return self._expr( + call=func, + evaluate_output_names=combine_evaluate_output_names(*exprs), + alias_output_names=combine_alias_output_names(*exprs), + version=version, + ) + + def list(self, *exprs: IbisExpr) -> IbisExpr: + version = self._version + + def func(df: IbisLazyFrame) -> list[ir.Value]: + cols = [native_expr for expr in exprs for native_expr in expr(df)] + return [ibis.array(cols)] + + return self._expr( + call=func, + evaluate_output_names=combine_evaluate_output_names(*exprs), + alias_output_names=combine_alias_output_names(*exprs), + version=version, + ) diff --git a/shared/package-files/35/35f5a43d638a026635b2afd1d53f3972de0261d1666148e68ed836bb03982086/test_transforms.py b/shared/package-files/35/35f5a43d638a026635b2afd1d53f3972de0261d1666148e68ed836bb03982086/test_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..96e78b6828f8d061ef61826678a7d5c91df8d884 --- /dev/null +++ b/shared/package-files/35/35f5a43d638a026635b2afd1d53f3972de0261d1666148e68ed836bb03982086/test_transforms.py @@ -0,0 +1,1131 @@ +import copy + +import numpy as np +from numpy.testing import (assert_allclose, assert_almost_equal, + assert_array_equal, assert_array_almost_equal) +import pytest + +from matplotlib import scale +import matplotlib.pyplot as plt +import matplotlib.patches as mpatches +import matplotlib.transforms as mtransforms +from matplotlib.transforms import Affine2D, Bbox, TransformedBbox, _ScaledRotation +from matplotlib.path import Path +from matplotlib.testing.decorators import image_comparison, check_figures_equal +from unittest.mock import MagicMock + + +class TestAffine2D: + single_point = [1.0, 1.0] + multiple_points = [[0.0, 2.0], [3.0, 3.0], [4.0, 0.0]] + pivot = single_point + + def test_init(self): + Affine2D([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + Affine2D(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], int)) + Affine2D(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], float)) + + def test_values(self): + np.random.seed(19680801) + values = np.random.random(6) + assert_array_equal(Affine2D.from_values(*values).to_values(), values) + + def test_modify_inplace(self): + # Some polar transforms require modifying the matrix in place. + trans = Affine2D() + mtx = trans.get_matrix() + mtx[0, 0] = 42 + assert_array_equal(trans.get_matrix(), [[42, 0, 0], [0, 1, 0], [0, 0, 1]]) + + def test_clear(self): + a = Affine2D(np.random.rand(3, 3) + 5) # Anything non-identity. + a.clear() + assert_array_equal(a.get_matrix(), [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) + + def test_rotate(self): + r_pi_2 = Affine2D().rotate(np.pi / 2) + r90 = Affine2D().rotate_deg(90) + assert_array_equal(r_pi_2.get_matrix(), r90.get_matrix()) + assert_array_almost_equal(r90.transform(self.single_point), [-1, 1]) + assert_array_almost_equal(r90.transform(self.multiple_points), + [[-2, 0], [-3, 3], [0, 4]]) + + r_pi = Affine2D().rotate(np.pi) + r180 = Affine2D().rotate_deg(180) + assert_array_equal(r_pi.get_matrix(), r180.get_matrix()) + assert_array_almost_equal(r180.transform(self.single_point), [-1, -1]) + assert_array_almost_equal(r180.transform(self.multiple_points), + [[0, -2], [-3, -3], [-4, 0]]) + + r_pi_3_2 = Affine2D().rotate(3 * np.pi / 2) + r270 = Affine2D().rotate_deg(270) + assert_array_equal(r_pi_3_2.get_matrix(), r270.get_matrix()) + assert_array_almost_equal(r270.transform(self.single_point), [1, -1]) + assert_array_almost_equal(r270.transform(self.multiple_points), + [[2, 0], [3, -3], [0, -4]]) + + assert_array_equal((r90 + r90).get_matrix(), r180.get_matrix()) + assert_array_equal((r90 + r180).get_matrix(), r270.get_matrix()) + + def test_rotate_around(self): + r_pi_2 = Affine2D().rotate_around(*self.pivot, np.pi / 2) + r90 = Affine2D().rotate_deg_around(*self.pivot, 90) + assert_array_equal(r_pi_2.get_matrix(), r90.get_matrix()) + assert_array_almost_equal(r90.transform(self.single_point), [1, 1]) + assert_array_almost_equal(r90.transform(self.multiple_points), + [[0, 0], [-1, 3], [2, 4]]) + + r_pi = Affine2D().rotate_around(*self.pivot, np.pi) + r180 = Affine2D().rotate_deg_around(*self.pivot, 180) + assert_array_equal(r_pi.get_matrix(), r180.get_matrix()) + assert_array_almost_equal(r180.transform(self.single_point), [1, 1]) + assert_array_almost_equal(r180.transform(self.multiple_points), + [[2, 0], [-1, -1], [-2, 2]]) + + r_pi_3_2 = Affine2D().rotate_around(*self.pivot, 3 * np.pi / 2) + r270 = Affine2D().rotate_deg_around(*self.pivot, 270) + assert_array_equal(r_pi_3_2.get_matrix(), r270.get_matrix()) + assert_array_almost_equal(r270.transform(self.single_point), [1, 1]) + assert_array_almost_equal(r270.transform(self.multiple_points), + [[2, 2], [3, -1], [0, -2]]) + + assert_array_almost_equal((r90 + r90).get_matrix(), r180.get_matrix()) + assert_array_almost_equal((r90 + r180).get_matrix(), r270.get_matrix()) + + def test_scale(self): + sx = Affine2D().scale(3, 1) + sy = Affine2D().scale(1, -2) + trans = Affine2D().scale(3, -2) + assert_array_equal((sx + sy).get_matrix(), trans.get_matrix()) + assert_array_equal(trans.transform(self.single_point), [3, -2]) + assert_array_equal(trans.transform(self.multiple_points), + [[0, -4], [9, -6], [12, 0]]) + + def test_skew(self): + trans_rad = Affine2D().skew(np.pi / 8, np.pi / 12) + trans_deg = Affine2D().skew_deg(22.5, 15) + assert_array_equal(trans_rad.get_matrix(), trans_deg.get_matrix()) + # Using ~atan(0.5), ~atan(0.25) produces roundish numbers on output. + trans = Affine2D().skew_deg(26.5650512, 14.0362435) + assert_array_almost_equal(trans.transform(self.single_point), [1.5, 1.25]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[1, 2], [4.5, 3.75], [4, 1]]) + + def test_translate(self): + tx = Affine2D().translate(23, 0) + ty = Affine2D().translate(0, 42) + trans = Affine2D().translate(23, 42) + assert_array_equal((tx + ty).get_matrix(), trans.get_matrix()) + assert_array_equal(trans.transform(self.single_point), [24, 43]) + assert_array_equal(trans.transform(self.multiple_points), + [[23, 44], [26, 45], [27, 42]]) + + def test_rotate_plus_other(self): + trans = Affine2D().rotate_deg(90).rotate_deg_around(*self.pivot, 180) + trans_added = (Affine2D().rotate_deg(90) + + Affine2D().rotate_deg_around(*self.pivot, 180)) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [3, 1]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[4, 2], [5, -1], [2, -2]]) + + trans = Affine2D().rotate_deg(90).scale(3, -2) + trans_added = Affine2D().rotate_deg(90) + Affine2D().scale(3, -2) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [-3, -2]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[-6, -0], [-9, -6], [0, -8]]) + + trans = (Affine2D().rotate_deg(90) + .skew_deg(26.5650512, 14.0362435)) # ~atan(0.5), ~atan(0.25) + trans_added = (Affine2D().rotate_deg(90) + + Affine2D().skew_deg(26.5650512, 14.0362435)) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [-0.5, 0.75]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[-2, -0.5], [-1.5, 2.25], [2, 4]]) + + trans = Affine2D().rotate_deg(90).translate(23, 42) + trans_added = Affine2D().rotate_deg(90) + Affine2D().translate(23, 42) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [22, 43]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[21, 42], [20, 45], [23, 46]]) + + def test_rotate_around_plus_other(self): + trans = Affine2D().rotate_deg_around(*self.pivot, 90).rotate_deg(180) + trans_added = (Affine2D().rotate_deg_around(*self.pivot, 90) + + Affine2D().rotate_deg(180)) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [-1, -1]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[0, 0], [1, -3], [-2, -4]]) + + trans = Affine2D().rotate_deg_around(*self.pivot, 90).scale(3, -2) + trans_added = (Affine2D().rotate_deg_around(*self.pivot, 90) + + Affine2D().scale(3, -2)) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [3, -2]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[0, 0], [-3, -6], [6, -8]]) + + trans = (Affine2D().rotate_deg_around(*self.pivot, 90) + .skew_deg(26.5650512, 14.0362435)) # ~atan(0.5), ~atan(0.25) + trans_added = (Affine2D().rotate_deg_around(*self.pivot, 90) + + Affine2D().skew_deg(26.5650512, 14.0362435)) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [1.5, 1.25]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[0, 0], [0.5, 2.75], [4, 4.5]]) + + trans = Affine2D().rotate_deg_around(*self.pivot, 90).translate(23, 42) + trans_added = (Affine2D().rotate_deg_around(*self.pivot, 90) + + Affine2D().translate(23, 42)) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [24, 43]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[23, 42], [22, 45], [25, 46]]) + + def test_scale_plus_other(self): + trans = Affine2D().scale(3, -2).rotate_deg(90) + trans_added = Affine2D().scale(3, -2) + Affine2D().rotate_deg(90) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_equal(trans.transform(self.single_point), [2, 3]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[4, 0], [6, 9], [0, 12]]) + + trans = Affine2D().scale(3, -2).rotate_deg_around(*self.pivot, 90) + trans_added = (Affine2D().scale(3, -2) + + Affine2D().rotate_deg_around(*self.pivot, 90)) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_equal(trans.transform(self.single_point), [4, 3]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[6, 0], [8, 9], [2, 12]]) + + trans = (Affine2D().scale(3, -2) + .skew_deg(26.5650512, 14.0362435)) # ~atan(0.5), ~atan(0.25) + trans_added = (Affine2D().scale(3, -2) + + Affine2D().skew_deg(26.5650512, 14.0362435)) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [2, -1.25]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[-2, -4], [6, -3.75], [12, 3]]) + + trans = Affine2D().scale(3, -2).translate(23, 42) + trans_added = Affine2D().scale(3, -2) + Affine2D().translate(23, 42) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_equal(trans.transform(self.single_point), [26, 40]) + assert_array_equal(trans.transform(self.multiple_points), + [[23, 38], [32, 36], [35, 42]]) + + def test_skew_plus_other(self): + # Using ~atan(0.5), ~atan(0.25) produces roundish numbers on output. + trans = Affine2D().skew_deg(26.5650512, 14.0362435).rotate_deg(90) + trans_added = (Affine2D().skew_deg(26.5650512, 14.0362435) + + Affine2D().rotate_deg(90)) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [-1.25, 1.5]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[-2, 1], [-3.75, 4.5], [-1, 4]]) + + trans = (Affine2D().skew_deg(26.5650512, 14.0362435) + .rotate_deg_around(*self.pivot, 90)) + trans_added = (Affine2D().skew_deg(26.5650512, 14.0362435) + + Affine2D().rotate_deg_around(*self.pivot, 90)) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [0.75, 1.5]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[0, 1], [-1.75, 4.5], [1, 4]]) + + trans = Affine2D().skew_deg(26.5650512, 14.0362435).scale(3, -2) + trans_added = (Affine2D().skew_deg(26.5650512, 14.0362435) + + Affine2D().scale(3, -2)) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [4.5, -2.5]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[3, -4], [13.5, -7.5], [12, -2]]) + + trans = Affine2D().skew_deg(26.5650512, 14.0362435).translate(23, 42) + trans_added = (Affine2D().skew_deg(26.5650512, 14.0362435) + + Affine2D().translate(23, 42)) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [24.5, 43.25]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[24, 44], [27.5, 45.75], [27, 43]]) + + def test_translate_plus_other(self): + trans = Affine2D().translate(23, 42).rotate_deg(90) + trans_added = Affine2D().translate(23, 42) + Affine2D().rotate_deg(90) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [-43, 24]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[-44, 23], [-45, 26], [-42, 27]]) + + trans = Affine2D().translate(23, 42).rotate_deg_around(*self.pivot, 90) + trans_added = (Affine2D().translate(23, 42) + + Affine2D().rotate_deg_around(*self.pivot, 90)) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [-41, 24]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[-42, 23], [-43, 26], [-40, 27]]) + + trans = Affine2D().translate(23, 42).scale(3, -2) + trans_added = Affine2D().translate(23, 42) + Affine2D().scale(3, -2) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [72, -86]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[69, -88], [78, -90], [81, -84]]) + + trans = (Affine2D().translate(23, 42) + .skew_deg(26.5650512, 14.0362435)) # ~atan(0.5), ~atan(0.25) + trans_added = (Affine2D().translate(23, 42) + + Affine2D().skew_deg(26.5650512, 14.0362435)) + assert_array_equal(trans.get_matrix(), trans_added.get_matrix()) + assert_array_almost_equal(trans.transform(self.single_point), [45.5, 49]) + assert_array_almost_equal(trans.transform(self.multiple_points), + [[45, 49.75], [48.5, 51.5], [48, 48.75]]) + + def test_invalid_transform(self): + t = mtransforms.Affine2D() + # There are two different exceptions, since the wrong number of + # dimensions is caught when constructing an array_view, and that + # raises a ValueError, and a wrong shape with a possible number + # of dimensions is caught by our CALL_CPP macro, which always + # raises the less precise RuntimeError. + with pytest.raises(ValueError): + t.transform(1) + with pytest.raises(ValueError): + t.transform([[[1]]]) + with pytest.raises(RuntimeError): + t.transform([]) + with pytest.raises(RuntimeError): + t.transform([1]) + with pytest.raises(ValueError): + t.transform([[1]]) + with pytest.raises(ValueError): + t.transform([[1, 2, 3]]) + + def test_copy(self): + a = mtransforms.Affine2D() + b = mtransforms.Affine2D() + s = a + b + # Updating a dependee should invalidate a copy of the dependent. + s.get_matrix() # resolve it. + s1 = copy.copy(s) + assert not s._invalid and not s1._invalid + a.translate(1, 2) + assert s._invalid and s1._invalid + assert (s1.get_matrix() == a.get_matrix()).all() + # Updating a copy of a dependee shouldn't invalidate a dependent. + s.get_matrix() # resolve it. + b1 = copy.copy(b) + b1.translate(3, 4) + assert not s._invalid + assert_array_equal(s.get_matrix(), a.get_matrix()) + + def test_deepcopy(self): + a = mtransforms.Affine2D() + b = mtransforms.Affine2D() + s = a + b + # Updating a dependee shouldn't invalidate a deepcopy of the dependent. + s.get_matrix() # resolve it. + s1 = copy.deepcopy(s) + assert not s._invalid and not s1._invalid + a.translate(1, 2) + assert s._invalid and not s1._invalid + assert_array_equal(s1.get_matrix(), mtransforms.Affine2D().get_matrix()) + # Updating a deepcopy of a dependee shouldn't invalidate a dependent. + s.get_matrix() # resolve it. + b1 = copy.deepcopy(b) + b1.translate(3, 4) + assert not s._invalid + assert_array_equal(s.get_matrix(), a.get_matrix()) + + +class TestAffineDeltaTransform: + def test_invalidate(self): + before = np.array([[1.0, 4.0, 0.0], + [5.0, 1.0, 0.0], + [0.0, 0.0, 1.0]]) + after = np.array([[1.0, 3.0, 0.0], + [5.0, 1.0, 0.0], + [0.0, 0.0, 1.0]]) + + # Translation and skew present + base = mtransforms.Affine2D.from_values(1, 5, 4, 1, 2, 3) + t = mtransforms.AffineDeltaTransform(base) + assert_array_equal(t.get_matrix(), before) + + # Mess with the internal structure of `base` without invalidating + # This should not affect this transform because it's a passthrough: + # it's always invalid + base.get_matrix()[0, 1:] = 3 + assert_array_equal(t.get_matrix(), after) + + # Invalidate the base + base.invalidate() + assert_array_equal(t.get_matrix(), after) + + +def test_non_affine_caching(): + class AssertingNonAffineTransform(mtransforms.Transform): + """ + This transform raises an assertion error when called when it + shouldn't be and ``self.raise_on_transform`` is True. + + """ + input_dims = output_dims = 2 + is_affine = False + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.raise_on_transform = False + self.underlying_transform = mtransforms.Affine2D().scale(10, 10) + + def transform_path_non_affine(self, path): + assert not self.raise_on_transform, \ + 'Invalidated affine part of transform unnecessarily.' + return self.underlying_transform.transform_path(path) + transform_path = transform_path_non_affine + + def transform_non_affine(self, path): + assert not self.raise_on_transform, \ + 'Invalidated affine part of transform unnecessarily.' + return self.underlying_transform.transform(path) + transform = transform_non_affine + + my_trans = AssertingNonAffineTransform() + ax = plt.axes() + plt.plot(np.arange(10), transform=my_trans + ax.transData) + plt.draw() + # enable the transform to raise an exception if it's non-affine transform + # method is triggered again. + my_trans.raise_on_transform = True + ax.transAxes.invalidate() + plt.draw() + + +def test_external_transform_api(): + class ScaledBy: + def __init__(self, scale_factor): + self._scale_factor = scale_factor + + def _as_mpl_transform(self, axes): + return (mtransforms.Affine2D().scale(self._scale_factor) + + axes.transData) + + ax = plt.axes() + line, = plt.plot(np.arange(10), transform=ScaledBy(10)) + ax.set_xlim(0, 100) + ax.set_ylim(0, 100) + # assert that the top transform of the line is the scale transform. + assert_allclose(line.get_transform()._a.get_matrix(), + mtransforms.Affine2D().scale(10).get_matrix()) + + +@image_comparison(['pre_transform_data'], remove_text=True, style='mpl20', + tol=0.05) +def test_pre_transform_plotting(): + # a catch-all for as many as possible plot layouts which handle + # pre-transforming the data NOTE: The axis range is important in this + # plot. It should be x10 what the data suggests it should be + + ax = plt.axes() + times10 = mtransforms.Affine2D().scale(10) + + ax.contourf(np.arange(48).reshape(6, 8), transform=times10 + ax.transData) + + ax.pcolormesh(np.linspace(0, 4, 7), + np.linspace(5.5, 8, 9), + np.arange(48).reshape(8, 6), + transform=times10 + ax.transData) + + ax.scatter(np.linspace(0, 10), np.linspace(10, 0), + transform=times10 + ax.transData) + + x = np.linspace(8, 10, 20) + y = np.linspace(1, 5, 20) + u = 2*np.sin(x) + np.cos(y[:, np.newaxis]) + v = np.sin(x) - np.cos(y[:, np.newaxis]) + + ax.streamplot(x, y, u, v, transform=times10 + ax.transData, + linewidth=np.hypot(u, v)) + + # reduce the vector data down a bit for barb and quiver plotting + x, y = x[::3], y[::3] + u, v = u[::3, ::3], v[::3, ::3] + + ax.quiver(x, y + 5, u, v, transform=times10 + ax.transData) + + ax.barbs(x - 3, y + 5, u**2, v**2, transform=times10 + ax.transData) + + +def test_contour_pre_transform_limits(): + ax = plt.axes() + xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20)) + ax.contourf(xs, ys, np.log(xs * ys), + transform=mtransforms.Affine2D().scale(0.1) + ax.transData) + + expected = np.array([[1.5, 1.24], + [2., 1.25]]) + assert_almost_equal(expected, ax.dataLim.get_points()) + + +def test_pcolor_pre_transform_limits(): + # Based on test_contour_pre_transform_limits() + ax = plt.axes() + xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20)) + ax.pcolor(xs, ys, np.log(xs * ys)[:-1, :-1], + transform=mtransforms.Affine2D().scale(0.1) + ax.transData) + + expected = np.array([[1.5, 1.24], + [2., 1.25]]) + assert_almost_equal(expected, ax.dataLim.get_points()) + + +def test_pcolormesh_pre_transform_limits(): + # Based on test_contour_pre_transform_limits() + ax = plt.axes() + xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20)) + ax.pcolormesh(xs, ys, np.log(xs * ys)[:-1, :-1], + transform=mtransforms.Affine2D().scale(0.1) + ax.transData) + + expected = np.array([[1.5, 1.24], + [2., 1.25]]) + assert_almost_equal(expected, ax.dataLim.get_points()) + + +def test_pcolormesh_gouraud_nans(): + np.random.seed(19680801) + + values = np.linspace(0, 180, 3) + radii = np.linspace(100, 1000, 10) + z, y = np.meshgrid(values, radii) + x = np.radians(np.random.rand(*z.shape) * 100) + + fig = plt.figure() + ax = fig.add_subplot(111, projection="polar") + # Setting the limit to cause clipping of the r values causes NaN to be + # introduced; these should not crash but be ignored as in other path + # operations. + ax.set_rlim(101, 1000) + ax.pcolormesh(x, y, z, shading="gouraud") + + fig.canvas.draw() + + +def test_Affine2D_from_values(): + points = np.array([[0, 0], + [10, 20], + [-1, 0], + ]) + + t = mtransforms.Affine2D.from_values(1, 0, 0, 0, 0, 0) + actual = t.transform(points) + expected = np.array([[0, 0], [10, 0], [-1, 0]]) + assert_almost_equal(actual, expected) + + t = mtransforms.Affine2D.from_values(0, 2, 0, 0, 0, 0) + actual = t.transform(points) + expected = np.array([[0, 0], [0, 20], [0, -2]]) + assert_almost_equal(actual, expected) + + t = mtransforms.Affine2D.from_values(0, 0, 3, 0, 0, 0) + actual = t.transform(points) + expected = np.array([[0, 0], [60, 0], [0, 0]]) + assert_almost_equal(actual, expected) + + t = mtransforms.Affine2D.from_values(0, 0, 0, 4, 0, 0) + actual = t.transform(points) + expected = np.array([[0, 0], [0, 80], [0, 0]]) + assert_almost_equal(actual, expected) + + t = mtransforms.Affine2D.from_values(0, 0, 0, 0, 5, 0) + actual = t.transform(points) + expected = np.array([[5, 0], [5, 0], [5, 0]]) + assert_almost_equal(actual, expected) + + t = mtransforms.Affine2D.from_values(0, 0, 0, 0, 0, 6) + actual = t.transform(points) + expected = np.array([[0, 6], [0, 6], [0, 6]]) + assert_almost_equal(actual, expected) + + +def test_affine_inverted_invalidated(): + # Ensure that the an affine transform is not declared valid on access + point = [1.0, 1.0] + t = mtransforms.Affine2D() + + assert_almost_equal(point, t.transform(t.inverted().transform(point))) + # Change and access the transform + t.translate(1.0, 1.0).get_matrix() + assert_almost_equal(point, t.transform(t.inverted().transform(point))) + + +def test_clipping_of_log(): + # issue 804 + path = Path._create_closed([(0.2, -99), (0.4, -99), (0.4, 20), (0.2, 20)]) + # something like this happens in plotting logarithmic histograms + trans = mtransforms.BlendedGenericTransform( + mtransforms.Affine2D(), scale.LogTransform(10, 'clip')) + tpath = trans.transform_path_non_affine(path) + result = tpath.iter_segments(trans.get_affine(), + clip=(0, 0, 100, 100), + simplify=False) + tpoints, tcodes = zip(*result) + assert_allclose(tcodes, path.codes[:-1]) # No longer closed. + + +class NonAffineForTest(mtransforms.Transform): + """ + A class which looks like a non affine transform, but does whatever + the given transform does (even if it is affine). This is very useful + for testing NonAffine behaviour with a simple Affine transform. + + """ + is_affine = False + output_dims = 2 + input_dims = 2 + + def __init__(self, real_trans, *args, **kwargs): + self.real_trans = real_trans + super().__init__(*args, **kwargs) + + def transform_non_affine(self, values): + return self.real_trans.transform(values) + + def transform_path_non_affine(self, path): + return self.real_trans.transform_path(path) + + +class TestBasicTransform: + def setup_method(self): + + self.ta1 = mtransforms.Affine2D(shorthand_name='ta1').rotate(np.pi / 2) + self.ta2 = mtransforms.Affine2D(shorthand_name='ta2').translate(10, 0) + self.ta3 = mtransforms.Affine2D(shorthand_name='ta3').scale(1, 2) + + self.tn1 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2), + shorthand_name='tn1') + self.tn2 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2), + shorthand_name='tn2') + self.tn3 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2), + shorthand_name='tn3') + + # creates a transform stack which looks like ((A, (N, A)), A) + self.stack1 = (self.ta1 + (self.tn1 + self.ta2)) + self.ta3 + # creates a transform stack which looks like (((A, N), A), A) + self.stack2 = self.ta1 + self.tn1 + self.ta2 + self.ta3 + # creates a transform stack which is a subset of stack2 + self.stack2_subset = self.tn1 + self.ta2 + self.ta3 + + # when in debug, the transform stacks can produce dot images: +# self.stack1.write_graphviz(file('stack1.dot', 'w')) +# self.stack2.write_graphviz(file('stack2.dot', 'w')) +# self.stack2_subset.write_graphviz(file('stack2_subset.dot', 'w')) + + def test_transform_depth(self): + assert self.stack1.depth == 4 + assert self.stack2.depth == 4 + assert self.stack2_subset.depth == 3 + + def test_left_to_right_iteration(self): + stack3 = (self.ta1 + (self.tn1 + (self.ta2 + self.tn2))) + self.ta3 +# stack3.write_graphviz(file('stack3.dot', 'w')) + + target_transforms = [stack3, + (self.tn1 + (self.ta2 + self.tn2)) + self.ta3, + (self.ta2 + self.tn2) + self.ta3, + self.tn2 + self.ta3, + self.ta3, + ] + r = [rh for _, rh in stack3._iter_break_from_left_to_right()] + assert len(r) == len(target_transforms) + + for target_stack, stack in zip(target_transforms, r): + assert target_stack == stack + + def test_transform_shortcuts(self): + assert self.stack1 - self.stack2_subset == self.ta1 + assert self.stack2 - self.stack2_subset == self.ta1 + + assert self.stack2_subset - self.stack2 == self.ta1.inverted() + assert (self.stack2_subset - self.stack2).depth == 1 + + with pytest.raises(ValueError): + self.stack1 - self.stack2 + + aff1 = self.ta1 + (self.ta2 + self.ta3) + aff2 = self.ta2 + self.ta3 + + assert aff1 - aff2 == self.ta1 + assert aff1 - self.ta2 == aff1 + self.ta2.inverted() + + assert self.stack1 - self.ta3 == self.ta1 + (self.tn1 + self.ta2) + assert self.stack2 - self.ta3 == self.ta1 + self.tn1 + self.ta2 + + assert ((self.ta2 + self.ta3) - self.ta3 + self.ta3 == + self.ta2 + self.ta3) + + def test_contains_branch(self): + r1 = (self.ta2 + self.ta1) + r2 = (self.ta2 + self.ta1) + assert r1 == r2 + assert r1 != self.ta1 + assert r1.contains_branch(r2) + assert r1.contains_branch(self.ta1) + assert not r1.contains_branch(self.ta2) + assert not r1.contains_branch(self.ta2 + self.ta2) + + assert r1 == r2 + + assert self.stack1.contains_branch(self.ta3) + assert self.stack2.contains_branch(self.ta3) + + assert self.stack1.contains_branch(self.stack2_subset) + assert self.stack2.contains_branch(self.stack2_subset) + + assert not self.stack2_subset.contains_branch(self.stack1) + assert not self.stack2_subset.contains_branch(self.stack2) + + assert self.stack1.contains_branch(self.ta2 + self.ta3) + assert self.stack2.contains_branch(self.ta2 + self.ta3) + + assert not self.stack1.contains_branch(self.tn1 + self.ta2) + + blend = mtransforms.BlendedGenericTransform(self.tn2, self.stack2) + x, y = blend.contains_branch_seperately(self.stack2_subset) + stack_blend = self.tn3 + blend + sx, sy = stack_blend.contains_branch_seperately(self.stack2_subset) + assert x is sx is False + assert y is sy is True + + def test_affine_simplification(self): + # tests that a transform stack only calls as much is absolutely + # necessary "non-affine" allowing the best possible optimization with + # complex transformation stacks. + points = np.array([[0, 0], [10, 20], [np.nan, 1], [-1, 0]], + dtype=np.float64) + na_pts = self.stack1.transform_non_affine(points) + all_pts = self.stack1.transform(points) + + na_expected = np.array([[1., 2.], [-19., 12.], + [np.nan, np.nan], [1., 1.]], dtype=np.float64) + all_expected = np.array([[11., 4.], [-9., 24.], + [np.nan, np.nan], [11., 2.]], + dtype=np.float64) + + # check we have the expected results from doing the affine part only + assert_array_almost_equal(na_pts, na_expected) + # check we have the expected results from a full transformation + assert_array_almost_equal(all_pts, all_expected) + # check we have the expected results from doing the transformation in + # two steps + assert_array_almost_equal(self.stack1.transform_affine(na_pts), + all_expected) + # check that getting the affine transformation first, then fully + # transforming using that yields the same result as before. + assert_array_almost_equal(self.stack1.get_affine().transform(na_pts), + all_expected) + + # check that the affine part of stack1 & stack2 are equivalent + # (i.e. the optimization is working) + expected_result = (self.ta2 + self.ta3).get_matrix() + result = self.stack1.get_affine().get_matrix() + assert_array_equal(expected_result, result) + + result = self.stack2.get_affine().get_matrix() + assert_array_equal(expected_result, result) + + +class TestTransformPlotInterface: + def test_line_extent_axes_coords(self): + # a simple line in axes coordinates + ax = plt.axes() + ax.plot([0.1, 1.2, 0.8], [0.9, 0.5, 0.8], transform=ax.transAxes) + assert_array_equal(ax.dataLim.get_points(), + np.array([[np.inf, np.inf], + [-np.inf, -np.inf]])) + + def test_line_extent_data_coords(self): + # a simple line in data coordinates + ax = plt.axes() + ax.plot([0.1, 1.2, 0.8], [0.9, 0.5, 0.8], transform=ax.transData) + assert_array_equal(ax.dataLim.get_points(), + np.array([[0.1, 0.5], [1.2, 0.9]])) + + def test_line_extent_compound_coords1(self): + # a simple line in data coordinates in the y component, and in axes + # coordinates in the x + ax = plt.axes() + trans = mtransforms.blended_transform_factory(ax.transAxes, + ax.transData) + ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans) + assert_array_equal(ax.dataLim.get_points(), + np.array([[np.inf, -5.], + [-np.inf, 35.]])) + + def test_line_extent_predata_transform_coords(self): + # a simple line in (offset + data) coordinates + ax = plt.axes() + trans = mtransforms.Affine2D().scale(10) + ax.transData + ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans) + assert_array_equal(ax.dataLim.get_points(), + np.array([[1., -50.], [12., 350.]])) + + def test_line_extent_compound_coords2(self): + # a simple line in (offset + data) coordinates in the y component, and + # in axes coordinates in the x + ax = plt.axes() + trans = mtransforms.blended_transform_factory( + ax.transAxes, mtransforms.Affine2D().scale(10) + ax.transData) + ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans) + assert_array_equal(ax.dataLim.get_points(), + np.array([[np.inf, -50.], [-np.inf, 350.]])) + + def test_line_extents_affine(self): + ax = plt.axes() + offset = mtransforms.Affine2D().translate(10, 10) + plt.plot(np.arange(10), transform=offset + ax.transData) + expected_data_lim = np.array([[0., 0.], [9., 9.]]) + 10 + assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim) + + def test_line_extents_non_affine(self): + ax = plt.axes() + offset = mtransforms.Affine2D().translate(10, 10) + na_offset = NonAffineForTest(mtransforms.Affine2D().translate(10, 10)) + plt.plot(np.arange(10), transform=offset + na_offset + ax.transData) + expected_data_lim = np.array([[0., 0.], [9., 9.]]) + 20 + assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim) + + def test_pathc_extents_non_affine(self): + ax = plt.axes() + offset = mtransforms.Affine2D().translate(10, 10) + na_offset = NonAffineForTest(mtransforms.Affine2D().translate(10, 10)) + pth = Path([[0, 0], [0, 10], [10, 10], [10, 0]]) + patch = mpatches.PathPatch(pth, + transform=offset + na_offset + ax.transData) + ax.add_patch(patch) + expected_data_lim = np.array([[0., 0.], [10., 10.]]) + 20 + assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim) + + def test_pathc_extents_affine(self): + ax = plt.axes() + offset = mtransforms.Affine2D().translate(10, 10) + pth = Path([[0, 0], [0, 10], [10, 10], [10, 0]]) + patch = mpatches.PathPatch(pth, transform=offset + ax.transData) + ax.add_patch(patch) + expected_data_lim = np.array([[0., 0.], [10., 10.]]) + 10 + assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim) + + def test_line_extents_for_non_affine_transData(self): + ax = plt.axes(projection='polar') + # add 10 to the radius of the data + offset = mtransforms.Affine2D().translate(0, 10) + + plt.plot(np.arange(10), transform=offset + ax.transData) + # the data lim of a polar plot is stored in coordinates + # before a transData transformation, hence the data limits + # are not what is being shown on the actual plot. + expected_data_lim = np.array([[0., 0.], [9., 9.]]) + [0, 10] + assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim) + + +def assert_bbox_eq(bbox1, bbox2): + assert_array_equal(bbox1.bounds, bbox2.bounds) + + +def test_bbox_frozen_copies_minpos(): + bbox = mtransforms.Bbox.from_extents(0.0, 0.0, 1.0, 1.0, minpos=1.0) + frozen = bbox.frozen() + assert_array_equal(frozen.minpos, bbox.minpos) + + +def test_bbox_intersection(): + bbox_from_ext = mtransforms.Bbox.from_extents + inter = mtransforms.Bbox.intersection + + r1 = bbox_from_ext(0, 0, 1, 1) + r2 = bbox_from_ext(0.5, 0.5, 1.5, 1.5) + r3 = bbox_from_ext(0.5, 0, 0.75, 0.75) + r4 = bbox_from_ext(0.5, 1.5, 1, 2.5) + r5 = bbox_from_ext(1, 1, 2, 2) + + # self intersection -> no change + assert_bbox_eq(inter(r1, r1), r1) + # simple intersection + assert_bbox_eq(inter(r1, r2), bbox_from_ext(0.5, 0.5, 1, 1)) + # r3 contains r2 + assert_bbox_eq(inter(r1, r3), r3) + # no intersection + assert inter(r1, r4) is None + # single point + assert_bbox_eq(inter(r1, r5), bbox_from_ext(1, 1, 1, 1)) + + +def test_bbox_as_strings(): + b = mtransforms.Bbox([[.5, 0], [.75, .75]]) + assert_bbox_eq(b, eval(repr(b), {'Bbox': mtransforms.Bbox})) + asdict = eval(str(b), {'Bbox': dict}) + for k, v in asdict.items(): + assert getattr(b, k) == v + fmt = '.1f' + asdict = eval(format(b, fmt), {'Bbox': dict}) + for k, v in asdict.items(): + assert eval(format(getattr(b, k), fmt)) == v + + +def test_str_transform(): + # The str here should not be considered as "absolutely stable", and may be + # reformatted later; this is just a smoketest for __str__. + assert str(plt.subplot(projection="polar").transData) == """\ +CompositeGenericTransform( + CompositeGenericTransform( + CompositeGenericTransform( + TransformWrapper( + BlendedAffine2D( + IdentityTransform(), + IdentityTransform())), + CompositeAffine2D( + Affine2D().scale(1.0), + Affine2D().scale(1.0))), + PolarTransform( + PolarAxes(0.125,0.1;0.775x0.8), + use_rmin=True, + apply_theta_transforms=False)), + CompositeGenericTransform( + CompositeGenericTransform( + PolarAffine( + TransformWrapper( + BlendedAffine2D( + IdentityTransform(), + IdentityTransform())), + LockableBbox( + Bbox(x0=0.0, y0=0.0, x1=6.283185307179586, y1=1.0), + [[-- --] + [-- --]])), + BboxTransformFrom( + _WedgeBbox( + (0.5, 0.5), + TransformedBbox( + Bbox(x0=0.0, y0=0.0, x1=6.283185307179586, y1=1.0), + CompositeAffine2D( + Affine2D().scale(1.0), + Affine2D().scale(1.0))), + LockableBbox( + Bbox(x0=0.0, y0=0.0, x1=6.283185307179586, y1=1.0), + [[-- --] + [-- --]])))), + BboxTransformTo( + TransformedBbox( + Bbox(x0=0.125, y0=0.09999999999999998, x1=0.9, y1=0.9), + BboxTransformTo( + TransformedBbox( + Bbox(x0=0.0, y0=0.0, x1=8.0, y1=6.0), + Affine2D().scale(80.0)))))))""" + + +def test_transform_single_point(): + t = mtransforms.Affine2D() + r = t.transform_affine((1, 1)) + assert r.shape == (2,) + + +def test_log_transform(): + # Tests that the last line runs without exception (previously the + # transform would fail if one of the axes was logarithmic). + fig, ax = plt.subplots() + ax.set_yscale('log') + ax.transData.transform((1, 1)) + + +def test_nan_overlap(): + a = mtransforms.Bbox([[0, 0], [1, 1]]) + b = mtransforms.Bbox([[0, 0], [1, np.nan]]) + assert not a.overlaps(b) + + +def test_transform_angles(): + t = mtransforms.Affine2D() # Identity transform + angles = np.array([20, 45, 60]) + points = np.array([[0, 0], [1, 1], [2, 2]]) + + # Identity transform does not change angles + new_angles = t.transform_angles(angles, points) + assert_array_almost_equal(angles, new_angles) + + # points missing a 2nd dimension + with pytest.raises(ValueError): + t.transform_angles(angles, points[0:2, 0:1]) + + # Number of angles != Number of points + with pytest.raises(ValueError): + t.transform_angles(angles, points[0:2, :]) + + +def test_nonsingular(): + # test for zero-expansion type cases; other cases may be added later + zero_expansion = np.array([-0.001, 0.001]) + cases = [(0, np.nan), (0, 0), (0, 7.9e-317)] + for args in cases: + out = np.array(mtransforms.nonsingular(*args)) + assert_array_equal(out, zero_expansion) + + +def test_transformed_path(): + points = [(0, 0), (1, 0), (1, 1), (0, 1)] + path = Path(points, closed=True) + + trans = mtransforms.Affine2D() + trans_path = mtransforms.TransformedPath(path, trans) + assert_allclose(trans_path.get_fully_transformed_path().vertices, points) + + # Changing the transform should change the result. + r2 = 1 / np.sqrt(2) + trans.rotate(np.pi / 4) + assert_allclose(trans_path.get_fully_transformed_path().vertices, + [(0, 0), (r2, r2), (0, 2 * r2), (-r2, r2)], + atol=1e-15) + + # Changing the path does not change the result (it's cached). + path.points = [(0, 0)] * 4 + assert_allclose(trans_path.get_fully_transformed_path().vertices, + [(0, 0), (r2, r2), (0, 2 * r2), (-r2, r2)], + atol=1e-15) + + +def test_transformed_patch_path(): + trans = mtransforms.Affine2D() + patch = mpatches.Wedge((0, 0), 1, 45, 135, transform=trans) + + tpatch = mtransforms.TransformedPatchPath(patch) + points = tpatch.get_fully_transformed_path().vertices + + # Changing the transform should change the result. + trans.scale(2) + assert_allclose(tpatch.get_fully_transformed_path().vertices, points * 2) + + # Changing the path should change the result (and cancel out the scaling + # from the transform). + patch.set_radius(0.5) + assert_allclose(tpatch.get_fully_transformed_path().vertices, points) + + +@pytest.mark.parametrize('locked_element', ['x0', 'y0', 'x1', 'y1']) +def test_lockable_bbox(locked_element): + other_elements = ['x0', 'y0', 'x1', 'y1'] + other_elements.remove(locked_element) + + orig = mtransforms.Bbox.unit() + locked = mtransforms.LockableBbox(orig, **{locked_element: 2}) + + # LockableBbox should keep its locked element as specified in __init__. + assert getattr(locked, locked_element) == 2 + assert getattr(locked, 'locked_' + locked_element) == 2 + for elem in other_elements: + assert getattr(locked, elem) == getattr(orig, elem) + + # Changing underlying Bbox should update everything but locked element. + orig.set_points(orig.get_points() + 10) + assert getattr(locked, locked_element) == 2 + assert getattr(locked, 'locked_' + locked_element) == 2 + for elem in other_elements: + assert getattr(locked, elem) == getattr(orig, elem) + + # Unlocking element should revert values back to the underlying Bbox. + setattr(locked, 'locked_' + locked_element, None) + assert getattr(locked, 'locked_' + locked_element) is None + assert np.all(orig.get_points() == locked.get_points()) + + # Relocking an element should change its value, but not others. + setattr(locked, 'locked_' + locked_element, 3) + assert getattr(locked, locked_element) == 3 + assert getattr(locked, 'locked_' + locked_element) == 3 + for elem in other_elements: + assert getattr(locked, elem) == getattr(orig, elem) + + +def test_transformwrapper(): + t = mtransforms.TransformWrapper(mtransforms.Affine2D()) + with pytest.raises(ValueError, match=( + r"The input and output dims of the new child \(1, 1\) " + r"do not match those of current child \(2, 2\)")): + t.set(scale.LogTransform(10)) + + +@check_figures_equal(extensions=["png"]) +def test_scale_swapping(fig_test, fig_ref): + np.random.seed(19680801) + samples = np.random.normal(size=10) + x = np.linspace(-5, 5, 10) + + for fig, log_state in zip([fig_test, fig_ref], [True, False]): + ax = fig.subplots() + ax.hist(samples, log=log_state, density=True) + ax.plot(x, np.exp(-(x**2) / 2) / np.sqrt(2 * np.pi)) + fig.canvas.draw() + ax.set_yscale('linear') + + +def test_offset_copy_errors(): + with pytest.raises(ValueError, + match="'fontsize' is not a valid value for units;" + " supported values are 'dots', 'points', 'inches'"): + mtransforms.offset_copy(None, units='fontsize') + + with pytest.raises(ValueError, + match='For units of inches or points a fig kwarg is needed'): + mtransforms.offset_copy(None, units='inches') + + +def test_transformedbbox_contains(): + bb = TransformedBbox(Bbox.unit(), Affine2D().rotate_deg(30)) + assert bb.contains(.8, .5) + assert bb.contains(-.4, .85) + assert not bb.contains(.9, .5) + bb = TransformedBbox(Bbox.unit(), Affine2D().translate(.25, .5)) + assert bb.contains(1.25, 1.5) + assert not bb.fully_contains(1.25, 1.5) + assert not bb.fully_contains(.1, .1) + + +def test_interval_contains(): + assert mtransforms.interval_contains((0, 1), 0.5) + assert mtransforms.interval_contains((0, 1), 0) + assert mtransforms.interval_contains((0, 1), 1) + assert not mtransforms.interval_contains((0, 1), -1) + assert not mtransforms.interval_contains((0, 1), 2) + assert mtransforms.interval_contains((1, 0), 0.5) + + +def test_interval_contains_open(): + assert mtransforms.interval_contains_open((0, 1), 0.5) + assert not mtransforms.interval_contains_open((0, 1), 0) + assert not mtransforms.interval_contains_open((0, 1), 1) + assert not mtransforms.interval_contains_open((0, 1), -1) + assert not mtransforms.interval_contains_open((0, 1), 2) + assert mtransforms.interval_contains_open((1, 0), 0.5) + + +def test_scaledrotation_initialization(): + """Test that the ScaledRotation object is initialized correctly.""" + theta = 1.0 # Arbitrary theta value for testing + trans_shift = MagicMock() # Mock the trans_shift transformation + scaled_rot = _ScaledRotation(theta, trans_shift) + assert scaled_rot._theta == theta + assert scaled_rot._trans_shift == trans_shift + assert scaled_rot._mtx is None + + +def test_scaledrotation_get_matrix_invalid(): + """Test get_matrix when the matrix is invalid and needs recalculation.""" + theta = np.pi / 2 + trans_shift = MagicMock(transform=MagicMock(return_value=[[theta, 0]])) + scaled_rot = _ScaledRotation(theta, trans_shift) + scaled_rot._invalid = True + matrix = scaled_rot.get_matrix() + trans_shift.transform.assert_called_once_with([[theta, 0]]) + expected_rotation = np.array([[0, -1], + [1, 0]]) + assert matrix is not None + assert_allclose(matrix[:2, :2], expected_rotation, atol=1e-15) diff --git a/shared/package-files/35/35f6852a6dd702b47bcb7bd90367c58cd533c6f0ebaea694062cacf2a31ea750/_nnpack_spatial_convolution.h b/shared/package-files/35/35f6852a6dd702b47bcb7bd90367c58cd533c6f0ebaea694062cacf2a31ea750/_nnpack_spatial_convolution.h new file mode 100644 index 0000000000000000000000000000000000000000..808a2a21c1690cc42bd44f11413efdc48cf7fd14 --- /dev/null +++ b/shared/package-files/35/35f6852a6dd702b47bcb7bd90367c58cd533c6f0ebaea694062cacf2a31ea750/_nnpack_spatial_convolution.h @@ -0,0 +1,91 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_nnpack_spatial_convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[2] padding, SymInt[2] stride=1) -> Tensor +inline at::Tensor _nnpack_spatial_convolution(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef padding, at::IntArrayRef stride=1) { + return at::_ops::_nnpack_spatial_convolution::call(input, weight, bias, c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(stride)); +} +namespace symint { + template ::value>> + at::Tensor _nnpack_spatial_convolution(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef padding, at::IntArrayRef stride=1) { + return at::_ops::_nnpack_spatial_convolution::call(input, weight, bias, c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(stride)); + } +} + +// aten::_nnpack_spatial_convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[2] padding, SymInt[2] stride=1) -> Tensor +inline at::Tensor _nnpack_spatial_convolution_symint(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride=c10::SymInt(1)) { + return at::_ops::_nnpack_spatial_convolution::call(input, weight, bias, padding, stride); +} +namespace symint { + template ::value>> + at::Tensor _nnpack_spatial_convolution(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride=c10::SymInt(1)) { + return at::_ops::_nnpack_spatial_convolution::call(input, weight, bias, padding, stride); + } +} + +// aten::_nnpack_spatial_convolution.out(Tensor input, Tensor weight, Tensor? bias, SymInt[2] padding, SymInt[2] stride=1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _nnpack_spatial_convolution_out(at::Tensor & out, const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef padding, at::IntArrayRef stride=1) { + return at::_ops::_nnpack_spatial_convolution_out::call(input, weight, bias, c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(stride), out); +} +namespace symint { + template ::value>> + at::Tensor & _nnpack_spatial_convolution_out(at::Tensor & out, const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef padding, at::IntArrayRef stride=1) { + return at::_ops::_nnpack_spatial_convolution_out::call(input, weight, bias, c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(stride), out); + } +} + +// aten::_nnpack_spatial_convolution.out(Tensor input, Tensor weight, Tensor? bias, SymInt[2] padding, SymInt[2] stride=1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _nnpack_spatial_convolution_outf(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef padding, at::IntArrayRef stride, at::Tensor & out) { + return at::_ops::_nnpack_spatial_convolution_out::call(input, weight, bias, c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(stride), out); +} +namespace symint { + template ::value>> + at::Tensor & _nnpack_spatial_convolution_outf(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef padding, at::IntArrayRef stride, at::Tensor & out) { + return at::_ops::_nnpack_spatial_convolution_out::call(input, weight, bias, c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(stride), out); + } +} + +// aten::_nnpack_spatial_convolution.out(Tensor input, Tensor weight, Tensor? bias, SymInt[2] padding, SymInt[2] stride=1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _nnpack_spatial_convolution_symint_out(at::Tensor & out, const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride=c10::SymInt(1)) { + return at::_ops::_nnpack_spatial_convolution_out::call(input, weight, bias, padding, stride, out); +} +namespace symint { + template ::value>> + at::Tensor & _nnpack_spatial_convolution_out(at::Tensor & out, const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride=c10::SymInt(1)) { + return at::_ops::_nnpack_spatial_convolution_out::call(input, weight, bias, padding, stride, out); + } +} + +// aten::_nnpack_spatial_convolution.out(Tensor input, Tensor weight, Tensor? bias, SymInt[2] padding, SymInt[2] stride=1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _nnpack_spatial_convolution_symint_outf(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, at::Tensor & out) { + return at::_ops::_nnpack_spatial_convolution_out::call(input, weight, bias, padding, stride, out); +} +namespace symint { + template ::value>> + at::Tensor & _nnpack_spatial_convolution_outf(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, at::Tensor & out) { + return at::_ops::_nnpack_spatial_convolution_out::call(input, weight, bias, padding, stride, out); + } +} + +} diff --git a/shared/package-files/35/35f91619465228ff52d4b8ebf051e3879f319ea4e7396add87a3ad128f0dd78f/test_sys_stdin_assignment.py b/shared/package-files/35/35f91619465228ff52d4b8ebf051e3879f319ea4e7396add87a3ad128f0dd78f/test_sys_stdin_assignment.py new file mode 100644 index 0000000000000000000000000000000000000000..f9d88e23547d098ed5c6ffcaaf4f8585b6bbba89 --- /dev/null +++ b/shared/package-files/35/35f91619465228ff52d4b8ebf051e3879f319ea4e7396add87a3ad128f0dd78f/test_sys_stdin_assignment.py @@ -0,0 +1,67 @@ +import sys + +import unittest +from numba import njit + + +@njit +def f0(a, b): + return a + b + + +@njit +def f1(begin1, end1, begin2, end2): + if begin1 > begin2: return f1(begin2, end2, begin1, end1) + return end1 + 1 >= begin2 + + +@njit +def f0_2(a, b): + return a + b + + +@njit +def f1_2(begin1, end1, begin2, end2): + if begin1 > begin2: return f1_2(begin2, end2, begin1, end1) + return end1 + 1 >= begin2 + + +class TestSysStdinAssignment(unittest.TestCase): + + def test_no_reassignment_of_stdout(self): + """ + https://github.com/numba/numba/issues/3027 + Older versions of colorama break stdout/err when recursive functions + are compiled. + + This test should work irrespective of colorama version, or indeed its + presence. If the version is too low, it should be disabled and the test + should work anyway, if it is a sufficiently high version or it is not + present, it should work anyway. + """ + + originally = sys.stdout, sys.stderr + + try: + sys.stdout = None + f0(0, 1) # Not changed stdout? + self.assertEqual(sys.stdout, None) + f1(0, 1, 2, 3) # Not changed stdout? + self.assertEqual(sys.stdout, None) + + sys.stderr = None + f0_2(0, 1) # Not changed stderr? + self.assertEqual(sys.stderr, None) + f1_2(0, 1, 2, 3) # Not changed stderr? + self.assertEqual(sys.stderr, None) + + finally: + sys.stdout, sys.stderr = originally + + self.assertNotEqual(sys.stderr, None) + self.assertNotEqual(sys.stdout, None) + + +if __name__ == '__main__': + unittest.main() + diff --git a/shared/package-files/35/35f9b094157f5269b9d314f07ee84984ab4d3e6ad45446893adf46593b1bdc34/test_cov_corr.py b/shared/package-files/35/35f9b094157f5269b9d314f07ee84984ab4d3e6ad45446893adf46593b1bdc34/test_cov_corr.py new file mode 100644 index 0000000000000000000000000000000000000000..a369145b4e884d740af39b236edbf2ce6e088cd0 --- /dev/null +++ b/shared/package-files/35/35f9b094157f5269b9d314f07ee84984ab4d3e6ad45446893adf46593b1bdc34/test_cov_corr.py @@ -0,0 +1,185 @@ +import math + +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + Series, + date_range, + isna, +) +import pandas._testing as tm + + +class TestSeriesCov: + def test_cov(self, datetime_series): + # full overlap + tm.assert_almost_equal( + datetime_series.cov(datetime_series), datetime_series.std() ** 2 + ) + + # partial overlap + tm.assert_almost_equal( + datetime_series[:15].cov(datetime_series[5:]), + datetime_series[5:15].std() ** 2, + ) + + # No overlap + assert np.isnan(datetime_series[::2].cov(datetime_series[1::2])) + + # all NA + cp = datetime_series[:10].copy() + cp[:] = np.nan + assert isna(cp.cov(cp)) + + # min_periods + assert isna(datetime_series[:15].cov(datetime_series[5:], min_periods=12)) + + ts1 = datetime_series[:15].reindex(datetime_series.index) + ts2 = datetime_series[5:].reindex(datetime_series.index) + assert isna(ts1.cov(ts2, min_periods=12)) + + @pytest.mark.parametrize("test_ddof", [None, 0, 1, 2, 3]) + @pytest.mark.parametrize("dtype", ["float64", "Float64"]) + def test_cov_ddof(self, test_ddof, dtype): + # GH#34611 + np_array1 = np.random.default_rng(2).random(10) + np_array2 = np.random.default_rng(2).random(10) + + s1 = Series(np_array1, dtype=dtype) + s2 = Series(np_array2, dtype=dtype) + + result = s1.cov(s2, ddof=test_ddof) + expected = np.cov(np_array1, np_array2, ddof=test_ddof)[0][1] + assert math.isclose(expected, result) + + +class TestSeriesCorr: + @pytest.mark.parametrize("dtype", ["float64", "Float64"]) + def test_corr(self, datetime_series, dtype): + stats = pytest.importorskip("scipy.stats") + + datetime_series = datetime_series.astype(dtype) + + # full overlap + tm.assert_almost_equal(datetime_series.corr(datetime_series), 1) + + # partial overlap + tm.assert_almost_equal(datetime_series[:15].corr(datetime_series[5:]), 1) + + assert isna(datetime_series[:15].corr(datetime_series[5:], min_periods=12)) + + ts1 = datetime_series[:15].reindex(datetime_series.index) + ts2 = datetime_series[5:].reindex(datetime_series.index) + assert isna(ts1.corr(ts2, min_periods=12)) + + # No overlap + assert np.isnan(datetime_series[::2].corr(datetime_series[1::2])) + + # all NA + cp = datetime_series[:10].copy() + cp[:] = np.nan + assert isna(cp.corr(cp)) + + A = Series( + np.arange(10, dtype=np.float64), + index=date_range("2020-01-01", periods=10), + name="ts", + ) + B = A.copy() + result = A.corr(B) + expected, _ = stats.pearsonr(A, B) + tm.assert_almost_equal(result, expected) + + def test_corr_rank(self): + stats = pytest.importorskip("scipy.stats") + + # kendall and spearman + A = Series( + np.arange(10, dtype=np.float64), + index=date_range("2020-01-01", periods=10), + name="ts", + ) + B = A.copy() + A[-5:] = A[:5].copy() + result = A.corr(B, method="kendall") + expected = stats.kendalltau(A, B)[0] + tm.assert_almost_equal(result, expected) + + result = A.corr(B, method="spearman") + expected = stats.spearmanr(A, B)[0] + tm.assert_almost_equal(result, expected) + + # results from R + A = Series( + [ + -0.89926396, + 0.94209606, + -1.03289164, + -0.95445587, + 0.76910310, + -0.06430576, + -2.09704447, + 0.40660407, + -0.89926396, + 0.94209606, + ] + ) + B = Series( + [ + -1.01270225, + -0.62210117, + -1.56895827, + 0.59592943, + -0.01680292, + 1.17258718, + -1.06009347, + -0.10222060, + -0.89076239, + 0.89372375, + ] + ) + kexp = 0.4319297 + sexp = 0.5853767 + tm.assert_almost_equal(A.corr(B, method="kendall"), kexp) + tm.assert_almost_equal(A.corr(B, method="spearman"), sexp) + + def test_corr_invalid_method(self): + # GH PR #22298 + s1 = Series(np.random.default_rng(2).standard_normal(10)) + s2 = Series(np.random.default_rng(2).standard_normal(10)) + msg = "method must be either 'pearson', 'spearman', 'kendall', or a callable, " + with pytest.raises(ValueError, match=msg): + s1.corr(s2, method="____") + + def test_corr_callable_method(self, datetime_series): + # simple correlation example + # returns 1 if exact equality, 0 otherwise + my_corr = lambda a, b: 1.0 if (a == b).all() else 0.0 + + # simple example + s1 = Series([1, 2, 3, 4, 5]) + s2 = Series([5, 4, 3, 2, 1]) + expected = 0 + tm.assert_almost_equal(s1.corr(s2, method=my_corr), expected) + + # full overlap + tm.assert_almost_equal( + datetime_series.corr(datetime_series, method=my_corr), 1.0 + ) + + # partial overlap + tm.assert_almost_equal( + datetime_series[:15].corr(datetime_series[5:], method=my_corr), 1.0 + ) + + # No overlap + assert np.isnan( + datetime_series[::2].corr(datetime_series[1::2], method=my_corr) + ) + + # dataframe example + df = pd.DataFrame([s1, s2]) + expected = pd.DataFrame([{0: 1.0, 1: 0}, {0: 0, 1: 1.0}]) + tm.assert_almost_equal(df.transpose().corr(method=my_corr), expected) diff --git a/shared/package-files/35/35fd7c3782fb04aa703e3b56c0bdee9cee2c7a500c10ba9d28c1697d54d7c124/linalg_eigh.h b/shared/package-files/35/35fd7c3782fb04aa703e3b56c0bdee9cee2c7a500c10ba9d28c1697d54d7c124/linalg_eigh.h new file mode 100644 index 0000000000000000000000000000000000000000..8a51c95e605ba492d6632e8d203bc49a32f430fb --- /dev/null +++ b/shared/package-files/35/35fd7c3782fb04aa703e3b56c0bdee9cee2c7a500c10ba9d28c1697d54d7c124/linalg_eigh.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::linalg_eigh(Tensor self, str UPLO="L") -> (Tensor eigenvalues, Tensor eigenvectors) +inline ::std::tuple linalg_eigh(const at::Tensor & self, c10::string_view UPLO="L") { + return at::_ops::linalg_eigh::call(self, UPLO); +} + +// aten::linalg_eigh.eigvals(Tensor self, str UPLO="L", *, Tensor(a!) eigvals, Tensor(b!) eigvecs) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) +inline ::std::tuple linalg_eigh_out(at::Tensor & eigvals, at::Tensor & eigvecs, const at::Tensor & self, c10::string_view UPLO="L") { + return at::_ops::linalg_eigh_eigvals::call(self, UPLO, eigvals, eigvecs); +} +// aten::linalg_eigh.eigvals(Tensor self, str UPLO="L", *, Tensor(a!) eigvals, Tensor(b!) eigvecs) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) +inline ::std::tuple linalg_eigh_outf(const at::Tensor & self, c10::string_view UPLO, at::Tensor & eigvals, at::Tensor & eigvecs) { + return at::_ops::linalg_eigh_eigvals::call(self, UPLO, eigvals, eigvecs); +} + +} diff --git a/shared/package-files/35/35fdbb24dd01b7a24fa6630d1010bf2de8eebdb0a2fcffae97d3d80ea59dd6df/ssh_exception.pyi b/shared/package-files/35/35fdbb24dd01b7a24fa6630d1010bf2de8eebdb0a2fcffae97d3d80ea59dd6df/ssh_exception.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d9ba145f25f871251f0e832ef3efa10025eafd8a --- /dev/null +++ b/shared/package-files/35/35fdbb24dd01b7a24fa6630d1010bf2de8eebdb0a2fcffae97d3d80ea59dd6df/ssh_exception.pyi @@ -0,0 +1,41 @@ +import socket +from typing import List, Mapping, Tuple, Union + +from paramiko.pkey import PKey + +class SSHException(Exception): ... +class AuthenticationException(SSHException): ... +class PasswordRequiredException(AuthenticationException): ... + +class BadAuthenticationType(AuthenticationException): + allowed_types: List[str] + explanation: str + def __init__(self, explanation: str, types: List[str]) -> None: ... + +class PartialAuthentication(AuthenticationException): + allowed_types: List[str] + def __init__(self, types: List[str]) -> None: ... + +class ChannelException(SSHException): + code: int + text: str + def __init__(self, code: int, text: str) -> None: ... + +class BadHostKeyException(SSHException): + hostname: str + key: PKey + expected_key: PKey + def __init__(self, hostname: str, got_key: PKey, expected_key: PKey) -> None: ... + +class ProxyCommandFailure(SSHException): + command: str + error: str + def __init__(self, command: str, error: str) -> None: ... + +class NoValidConnectionsError(socket.error): + errors: Mapping[Union[Tuple[str, int], Tuple[str, int, int, int]], Exception] + def __init__(self, errors: Mapping[Union[Tuple[str, int], Tuple[str, int, int, int]], Exception]) -> None: ... + def __reduce__(self) -> Tuple[type, Tuple[Mapping[Union[Tuple[str, int], Tuple[str, int, int, int]], Exception]]]: ... + +class CouldNotCanonicalize(SSHException): ... +class ConfigParseError(SSHException): ... diff --git a/shared/package-files/49/49002e65a327a4c08933c8dd049e4dd5bac53fbe2208854c9d67b5795e706729/test_fftnd.py b/shared/package-files/49/49002e65a327a4c08933c8dd049e4dd5bac53fbe2208854c9d67b5795e706729/test_fftnd.py new file mode 100644 index 0000000000000000000000000000000000000000..968217237f3bf851b88539af2e76f5f00ba2d982 --- /dev/null +++ b/shared/package-files/49/49002e65a327a4c08933c8dd049e4dd5bac53fbe2208854c9d67b5795e706729/test_fftnd.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python +# Copyright (c) 2017-2023, Intel Corporation +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of Intel Corporation nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import numpy as np +from numpy.testing import ( + TestCase, assert_, assert_raises, assert_equal, + assert_warns, assert_allclose) +from numpy import random as rnd +import sys +import warnings + +import mkl_fft + +reps_64 = (2**11)*np.finfo(np.float64).eps +reps_32 = (2**11)*np.finfo(np.float32).eps +atol_64 = (2**9)*np.finfo(np.float64).eps +atol_32 = (2**9)*np.finfo(np.float32).eps + +def _get_rtol_atol(x): + dt = x.dtype + if dt == np.float64 or dt == np.complex128: + return reps_64, atol_64 + elif dt == np.float32 or dt == np.complex64: + return reps_32, atol_32 + else: + assert (dt == np.float64 or dt == np.complex128 or dt == np.float32 or dt == np.complex64), "Unexpected dtype {}".format(dt) + return reps_64, atol_64 + + +class Test_mklfft_matrix(TestCase): + def setUp(self): + rnd.seed(123456) + self.md = rnd.randn(256, 256) + self.mf = self.md.astype(np.float32) + self.mz = rnd.randn(256, 256*2).view(np.complex128) + self.mc = self.mz.astype(np.complex64) + + def test_matrix1(self): + """fftn equals repeated fft""" + for ar in [self.md, self.mz, self.mf, self.mc]: + r_tol, a_tol = _get_rtol_atol(ar) + d = ar.copy() + t1 = mkl_fft.fftn(d) + t2 = mkl_fft.fft(mkl_fft.fft(d, axis=0), axis=1) + t3 = mkl_fft.fft(mkl_fft.fft(d, axis=1), axis=0) + assert_allclose(t1, t2, rtol=r_tol, atol=a_tol, err_msg = "failed test for dtype {}, max abs diff: {}".format(d.dtype, np.max(np.abs(t1-t2)))) + assert_allclose(t1, t3, rtol=r_tol, atol=a_tol, err_msg = "failed test for dtype {}, max abs diff: {}".format(d.dtype, np.max(np.abs(t1-t3)))) + + def test_matrix2(self): + """ifftn(fftn(x)) is x""" + for ar in [self.md, self.mz, self.mf, self.mc]: + d = ar.copy() + r_tol, a_tol = _get_rtol_atol(d) + t = mkl_fft.ifftn(mkl_fft.fftn(d)) + assert_allclose(d, t, rtol=r_tol, atol=a_tol, err_msg = "failed test for dtype {}, max abs diff: {}".format(d.dtype, np.max(np.abs(d-t)))) + + def test_matrix3(self): + """fftn(ifftn(x)) is x""" + for ar in [self.md, self.mz, self.mf, self.mc]: + d = ar.copy() + r_tol, a_tol = _get_rtol_atol(d) + t = mkl_fft.fftn(mkl_fft.ifftn(d)) + assert_allclose(d, t, rtol=r_tol, atol=a_tol, err_msg = "failed test for dtype {}, max abs diff: {}".format(d.dtype, np.max(np.abs(d-t)))) + + + def test_matrix4(self): + """fftn of strided array is same as fftn of a contiguous copy""" + for ar in [self.md, self.mz, self.mf, self.mc]: + r_tol, a_tol = _get_rtol_atol(ar) + d_strided = ar[::2,::2] + d_contig = d_strided.copy() + t_strided = mkl_fft.fftn(d_strided) + t_contig = mkl_fft.fftn(d_contig) + assert_allclose(t_strided, t_contig, rtol=r_tol, atol=a_tol) + + + def test_matrix5(self): + """fftn of strided array is same as fftn of a contiguous copy""" + rs = rnd.RandomState(1234) + x = rs.randn(6, 11, 12, 13) + y = x[::-2, :, :, ::3] + r_tol, a_tol = _get_rtol_atol(y) + f = mkl_fft.fftn(y, axes=(1,2)) + for i0 in range(y.shape[0]): + for i3 in range(y.shape[3]): + assert_allclose( + f[i0, :, :, i3], + mkl_fft.fftn(y[i0, :, : , i3]), + rtol=r_tol, atol=a_tol + ) + + def test_matrix6(self): + """fftn with tuple, list and ndarray axes and s""" + for ar in [self.md, self.mz, self.mf, self.mc]: + d = ar.copy() + for norm in ["forward", "backward", "ortho"]: + for container in [tuple, list, np.array]: + axes = container(range(d.ndim)) + s = container(d.shape) + kwargs = dict(s=s, axes=axes, norm=norm) + r_tol, a_tol = _get_rtol_atol(d) + t = mkl_fft._numpy_fft.fftn(mkl_fft._numpy_fft.ifftn(d, **kwargs), **kwargs) + assert_allclose(d, t, rtol=r_tol, atol=a_tol, err_msg = "failed test for dtype {}, max abs diff: {}".format(d.dtype, np.max(np.abs(d-t)))) + + + +class Test_Regressions(TestCase): + + def setUp(self): + rnd.seed(123456) + self.ad = rnd.randn(32, 17, 23) + self.af = self.ad.astype(np.float32) + self.az = rnd.randn(32, 17, 23*2).view(np.complex128) + self.ac = self.az.astype(np.complex64) + + def test_cf_contig(self): + """fft of F-contiguous array is the same as of C-contiguous with same data""" + for ar in [self.ad, self.af, self.az, self.ac]: + r_tol, a_tol = _get_rtol_atol(ar) + d_ccont = ar.copy() + d_fcont = np.asfortranarray(d_ccont) + for a in range(ar.ndim): + f1 = mkl_fft.fft(d_ccont, axis=a) + f2 = mkl_fft.fft(d_fcont, axis=a) + assert_allclose(f1, f2, rtol=r_tol, atol=a_tol) + + def test_rfftn_numpy(self): + """Test that rfftn_numpy works as expected""" + axes = [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)] + for x in [self.ad, self.af]: + for a in axes: + r_tol, a_tol = _get_rtol_atol(x) + rfft_tr = mkl_fft.rfftn_numpy(np.transpose(x, a)) + tr_rfft = np.transpose(mkl_fft.rfftn_numpy(x, axes=a), a) + assert_allclose(rfft_tr, tr_rfft, rtol=r_tol, atol=a_tol) + + def test_gh64(self): + """Test example from #64""" + a = np.arange(12).reshape((3,4)) + x = a.astype(np.cdouble) + # should executed successfully + r1 = mkl_fft.fftn(a, shape=None, axes=(-2,-1)) + r2 = mkl_fft.fftn(x) + r_tol, a_tol = _get_rtol_atol(x) + assert_allclose(r1, r2, rtol=r_tol, atol=a_tol) + + +class Test_Scales(TestCase): + def setUp(self): + pass + + def test_scale_1d_vector(self): + X = np.ones(128, dtype='d') + f1 = mkl_fft.fft(X, forward_scale=0.25) + f2 = mkl_fft.fft(X) + r_tol, a_tol = _get_rtol_atol(X) + assert_allclose(4*f1, f2, rtol=r_tol, atol=a_tol) + + X1 = mkl_fft.ifft(f1, forward_scale=0.25) + assert_allclose(X, X1, rtol=r_tol, atol=a_tol) + + f3 = mkl_fft.rfft(X, forward_scale=0.5) + X2 = mkl_fft.irfft(f3, forward_scale=0.5) + assert_allclose(X, X2, rtol=r_tol, atol=a_tol) + + def test_scale_1d_array(self): + X = np.ones((8, 4, 4,), dtype='d') + f1 = mkl_fft.fft(X, axis=1, forward_scale=0.25) + f2 = mkl_fft.fft(X, axis=1) + r_tol, a_tol = _get_rtol_atol(X) + assert_allclose(4*f1, f2, rtol=r_tol, atol=a_tol) + + X1 = mkl_fft.ifft(f1, axis=1, forward_scale=0.25) + assert_allclose(X, X1, rtol=r_tol, atol=a_tol) + + f3 = mkl_fft.rfft(X, axis=0, forward_scale=0.5) + X2 = mkl_fft.irfft(f3, axis=0, forward_scale=0.5) + assert_allclose(X, X2, rtol=r_tol, atol=a_tol) + + def test_scale_nd(self): + X = np.empty((2, 4, 8, 16), dtype='d') + X.flat[:] = np.cbrt(np.arange(0, X.size, dtype=X.dtype)) + f = mkl_fft.fftn(X) + f_scale = mkl_fft.fftn(X, forward_scale=0.2) + + r_tol, a_tol = _get_rtol_atol(X) + assert_allclose(f, 5*f_scale, rtol=r_tol, atol=a_tol) + + def test_scale_nd_axes(self): + X = np.empty((4, 2, 16, 8), dtype='d') + X.flat[:] = np.cbrt(np.arange(X.size, dtype=X.dtype)) + f = mkl_fft.fftn(X, axes=(0, 1, 2, 3)) + f_scale = mkl_fft.fftn(X, axes=(0, 1, 2, 3), forward_scale=0.2) + + r_tol, a_tol = _get_rtol_atol(X) + assert_allclose(f, 5*f_scale, rtol=r_tol, atol=a_tol) diff --git a/shared/package-files/49/4901c1c4253183adca250bdffff9e18efe80e546bd3ffaf7e45f5787a2d06521/after_aot.py b/shared/package-files/49/4901c1c4253183adca250bdffff9e18efe80e546bd3ffaf7e45f5787a2d06521/after_aot.py new file mode 100644 index 0000000000000000000000000000000000000000..d6d567f0c1c93d5b469b2ce9be8d29749fc03c85 --- /dev/null +++ b/shared/package-files/49/4901c1c4253183adca250bdffff9e18efe80e546bd3ffaf7e45f5787a2d06521/after_aot.py @@ -0,0 +1,932 @@ +import argparse +import copy +import functools +import io +import logging +import os +import shutil +import subprocess +import sys +import textwrap +import uuid +from importlib import import_module +from tempfile import TemporaryFile +from typing import Any, Callable, Dict, Union + +import torch +import torch.fx as fx +import torch.nn as nn +from torch._dynamo.debug_utils import ( + _cuda_system_info_comment, + AccuracyError, + backend_accuracy_fails, + BuckTargetWriter, + cast_to_fp64, + extra_imports, + generate_config_string, + helper_for_dump_minify, + InputReader, + InputWriter, + MAX_CONSTANT_NUMEL_INLINE, + minifier_dir, + NNModuleToString, + NopInputReader, + same_two_models, +) +from torch._dynamo.utils import clone_inputs, counters, same +from torch.fx.experimental.proxy_tensor import make_fx +from torch.fx.experimental.symbolic_shapes import ( + fx_placeholder_targets, + has_free_symbols, +) +from torch.hub import tqdm + +from .. import config + +log = logging.getLogger(__name__) + + +inductor_config = import_module("torch._inductor.config") +use_buck = inductor_config.is_fbcode() + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# MAIN ENTRY POINT +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def wrap_compiler_debug(unconfigured_compiler_fn, compiler_name: str): + """ + Minifier for Fx Graph modules after Aot Autograd has finished. We wrap both + forward and backward call separately with the backend compiler_fn - like + inductor or nvfuser. Intercepting after Aot Autograd presents neat + abstraction, where all the params are lifted as graph inputs, making it easy + to save the graph as a string. + """ + + @functools.wraps(unconfigured_compiler_fn) + def debug_wrapper(gm, example_inputs, **kwargs): + from torch._subclasses import FakeTensorMode + + compiler_fn = functools.partial(unconfigured_compiler_fn, **kwargs) + + from torch._functorch.aot_autograd import get_aot_graph_name + + graph_name = get_aot_graph_name() + + # TODO: why do we need to deepcopy the original graph? + orig_graph = copy.deepcopy(gm.graph) + assert config.repro_after in ("dynamo", "aot", None) + + try: + # Call the compiler_fn - which is either aot_autograd or inductor + # with fake inputs + inner_compiled_fn = compiler_fn(gm, example_inputs) + except Exception as e: + # TODO: Failures here are troublesome because no real inputs, + # need a different serialization strategy + if config.repro_after == "aot": + if config.repro_level == 1: + dump_compiler_graph_state( + fx.GraphModule(gm, orig_graph), + example_inputs, + compiler_name, + ) + elif config.repro_level == 2: + dump_to_minify( + fx.GraphModule(gm, orig_graph), + example_inputs, + compiler_name, + ) + log.error("CompilerError") + raise + + # We may run regular PyTorch compute that may trigger Dynamo, do NOT + # recursively attempt to accuracy minify in that case! + def deferred_for_real_inputs(real_inputs): + # This is a bit obscure: if we recursively try to accuracy minify + # the SAME function, this would trigger. But most of the time + # we should never hit this branch + if config.repro_after != "aot": + return inner_compiled_fn(real_inputs) + with config.patch(repro_after=None): + return inner_debug_fn(real_inputs) + + def inner_debug_fn(real_inputs): + """ + Aot Autograd fw_compiler and bw_compiler can have fake tensors. So, + example_inputs can be fake tensors. We can call compiler_fn (which is + inductor or nvfuser) with fake tensors but the actually compiled_fn + should be called with real tensors. Therefore, the actual invocation + is deferred. + """ + # Copy the tensor attrs like shape, stride etc by converting to Fake Tensor + # because inductor clears the tensor list in its codegen. And example_inputs + # are available only for the first invocation. + fake_mode = FakeTensorMode() + copy_tensor_attrs = [ + fake_mode.from_tensor(x) if isinstance(x, torch.Tensor) else x + for x in real_inputs + ] + if config.repro_level == 3: + # Always dump the original module in case we have segfaults + dump_to_minify( + fx.GraphModule(gm, orig_graph), real_inputs, compiler_name + ) + + if config.repro_level == 4: + if compiler_name != "inductor": + raise NotImplementedError( + "Accuracy minification is supported for inductor only" + ) + if backend_aot_accuracy_fails(gm, real_inputs, compiler_fn): + log.warning( + "Accuracy failed for the AOT Autograd graph %s", graph_name + ) + dump_compiler_graph_state( + fx.GraphModule(gm, orig_graph), + real_inputs, + f"{compiler_name}_accuracy", + ) + dump_to_minify( + fx.GraphModule(gm, orig_graph), + real_inputs, + f"{compiler_name}_accuracy", + ) + raise AccuracyError("Bad accuracy detected") + else: + # Call the compiled function with real inputs + return inner_compiled_fn(real_inputs) + else: + try: + # Call the compiled function with real inputs + out = inner_compiled_fn(real_inputs) + # sync cuda kernels to ensure IMA detection + for arg in example_inputs: + if isinstance(arg, torch.Tensor) and arg.is_cuda: + torch.cuda.synchronize() + break + return out + except Exception as e: + if config.repro_level == 1: + dump_compiler_graph_state( + fx.GraphModule(gm, orig_graph), + copy_tensor_attrs, + compiler_name, + ) + elif config.repro_level == 2: + dump_to_minify( + fx.GraphModule(gm, orig_graph), + copy_tensor_attrs, + compiler_name, + ) + raise + + if config.repro_after == "aot": + compiled_fn = deferred_for_real_inputs + compiled_fn._boxed_call = True # type: ignore[attr-defined] + return compiled_fn + else: + return inner_compiled_fn + + return debug_wrapper + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# DUMP REPROS +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def generate_compiler_repro_string(gm, args, *, stable_output=False, save_dir=None): + model_str = textwrap.dedent( + f""" +import torch +from torch import tensor, device +import torch.fx as fx +from torch._dynamo.testing import rand_strided +from math import inf +import torch._inductor.inductor_prims + +{generate_config_string(stable_output=stable_output)} + +isolate_fails_code_str = None + +{extra_imports} + + """ + ) + if not stable_output: + model_str += f"# torch version: {torch.version.__version__}\n" + if hasattr(torch.version, "cuda"): + model_str += f"# torch cuda version: {torch.version.cuda}\n" + if hasattr(torch.version, "git_version"): + model_str += f"# torch git version: {torch.version.git_version}\n\n\n" + model_str += _cuda_system_info_comment() + + model_str += NNModuleToString.convert(gm) + + # get hint shape/stride when dynamic shape enabled + def hint_if_symint(x): + return tuple(i.node.hint if isinstance(i, torch.SymInt) else i for i in x) + + writer = InputWriter(save_dir) + for placeholder, arg in zip(fx_placeholder_targets(gm), args): + if isinstance(arg, (int, torch.SymInt)): + writer.symint(placeholder, arg) + elif isinstance(arg, torch.Tensor): + # TODO: improve these names with FQN + writer.tensor(placeholder, arg) + else: + raise TypeError(f"arg is neither SymInt/int nor torch.Tensor, {arg}") + + model_str += "\n".join(writer.lines()) + "\n" + + model_str += "mod = Repro()\n" + return model_str + + +def save_graph_repro( + fd, + gm, + args, + compiler_name, + *, + stable_output=False, + save_dir=None, + command="run", + accuracy=None, + tracing_mode=None, + check_str=None, +): + fd.write( + generate_compiler_repro_string( + gm, + args, + stable_output=stable_output, + save_dir=save_dir, + ) + ) + if accuracy is None: + accuracy = "_accuracy" in compiler_name + if tracing_mode is None: + tracing_mode = "real" + if any(has_free_symbols(a) for a in args): + tracing_mode = "symbolic" + fd.write("if __name__ == '__main__':\n") + fd.write(" from torch._dynamo.repro.after_aot import run_repro\n") + fd.write( + f" with torch.no_grad():\n" + f" run_repro(mod, load_args, accuracy={accuracy!r}, command={command!r}, " + f"save_dir={save_dir!r}, tracing_mode={tracing_mode!r}, check_str={check_str!r}" + ")\n" + ) + + +def dump_compiler_graph_state(gm, args, compiler_name, *, accuracy=None): + subdir = os.path.join(minifier_dir(), "checkpoints") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + file_name = os.path.join(subdir, f"{len(gm.graph.nodes)}.py") + log.warning( + "Writing checkpoint with %s nodes to %s", len(gm.graph.nodes), file_name + ) + with open(file_name, "w") as fd: + save_graph_repro( + fd, gm, args, compiler_name, save_dir=subdir, accuracy=accuracy + ) + curdir = os.getcwd() + repro_path = os.path.join(curdir, "repro.py") + try: + shutil.copyfile(file_name, repro_path) + log.warning("Copying repro file for convenience to %s", repro_path) + if use_buck: + BuckTargetWriter(file_name).write() + except OSError: + log.warning("No write permissions for %s", repro_path) + pass + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# DUMP MINIFIER +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def dump_to_minify(gm, args, compiler_name: str): + out = io.StringIO() + # TODO: factor this out + subdir = os.path.join(minifier_dir(), "checkpoints") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + save_graph_repro(out, gm, args, compiler_name, save_dir=subdir, command="minify") + return helper_for_dump_minify(out.getvalue()) + + +def isolate_fails( + fx_g, + args, + compiler_name: str, + env=None, + save_dir=None, + accuracy=None, + tracing_mode=None, + check_str=None, +): + if env is None: + env = {} + subdir = os.path.join(os.getcwd(), "isolate") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + file_name = os.path.join(subdir, f"{str(uuid.uuid4())[:5]}.py") + with open(file_name, "w") as fd: + save_graph_repro( + fd, + fx_g, + args, + compiler_name, + save_dir=save_dir, + command="minifier-query", + accuracy=accuracy, + tracing_mode=tracing_mode, + check_str=check_str, + ) + # with open(file_name, "r") as fd: + # print(fd.read()) + new_env = os.environ.copy() + new_env = {**new_env, **env} + stdout, stderr = TemporaryFile(), TemporaryFile() + + if use_buck: + cmd = BuckTargetWriter(file_name).write(print_msg=False) + else: + cmd = ["python", file_name] + + p = subprocess.Popen( + cmd, + cwd=subdir, + stdout=stdout, + stderr=stderr, + env=new_env, + ) + p.wait() + + stdout.seek(0) + stderr.seek(0) + print( + textwrap.indent(stdout.read().decode("utf-8"), prefix=">> "), file=sys.stdout + ) + print( + textwrap.indent(stderr.read().decode("utf-8"), prefix=">> "), file=sys.stderr + ) + # print(f"Isolated test failed - {file_name}") + return p.returncode != 0 + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# MINIFIER TOOLS +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def inductor_fails(fx_g, args, check_str=None): + has_cuda = False + for arg in args: + if isinstance(arg, torch.Tensor) and arg.is_cuda: + has_cuda = True + break + + def sync(): + if has_cuda: + # Ensures that segfaults are surfaced + torch.cuda.synchronize() + + from torch._inductor.compile_fx import compile_fx_inner + + try: + result = fx_g(*args) + assert isinstance(result, (tuple, list)) + assert not any(isinstance(x, (tuple, list)) for x in result) + except Exception: + return False + + sync() + + try: + compile_mod = compile_fx_inner(fx_g, args) + compile_mod(args) + sync() + except Exception as e: + if check_str is not None and check_str not in repr(e): + return False + print(repr(e)) + return True + return False + + +def inductor_accuracy_fails( + fx_g, args, check_str=None, *, require_fp64=False, ignore_non_fp=False +): + from torch._inductor.compile_fx import compile_fx_inner + + return backend_aot_accuracy_fails( + fx_g, + args, + compile_fx_inner, + require_fp64=require_fp64, + ignore_non_fp=ignore_non_fp, + ) + + +backend_aot_accuracy_fails = functools.partial(backend_accuracy_fails, only_fwd=True) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# REPRO MAIN +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def repro_common(options, mod, load_args): + # Invariant for graphs we generate with the repro script + assert not any(mod.named_parameters()) + for n, b in mod.named_buffers(): + if b.numel() > MAX_CONSTANT_NUMEL_INLINE: + log.warning( + "Constant %s was not serialized, generated random data instead. " + "If you think this is affecting you, please comment on " + "https://github.com/pytorch/pytorch/issues/100468", + n, + ) + + if not hasattr(load_args, "_version"): + log.warning( + "load_args does not have a _version attribute, please file a bug to PyTorch " + "and describe how you generate this repro script" + ) + else: + if load_args._version > 0: + log.warning( + "load_args is version %s, but this version of PyTorch only supports " + "version 0. We will try to run it anyway but there may be an incompatibility; " + "if so, try upgrading your version of PyTorch.", + load_args._version, + ) + + nop_reader = NopInputReader() + load_args(nop_reader) + + with tqdm(desc="Loading inputs", total=nop_reader.total) as pbar: + input_reader = InputReader(save_dir=options.save_dir, pbar=pbar) + load_args(input_reader) + args = input_reader.args + + # Turn mod into a GraphModule the slow way + # TODO: speed this up + mod = make_fx(mod, tracing_mode=options.tracing_mode)(*args) + + torch._inductor.config.generate_intermediate_hooks = True + + return mod, args + + +ACCURACY_FAILS: Dict[str, Callable[[nn.Module, Any], bool]] = { + "": inductor_fails, + # This might look inverted but it's not. strict_accuracy means "we will + # minify any time we see anything that diverges", whereas accuracy is more + # conservative, and will only minify if there is a meaningful fp64 + # divergence + "accuracy": functools.partial( + inductor_accuracy_fails, require_fp64=True, ignore_non_fp=True + ), + "strict_accuracy": inductor_accuracy_fails, +} + + +def repro_minifier_query(options, mod, load_args): + mod, args = repro_common(options, mod, load_args) + fail_fn = functools.partial( + ACCURACY_FAILS[options.accuracy], check_str=options.check_str + ) + if fail_fn(mod, args): + sys.exit(1) + else: + sys.exit(0) + + +def repro_minify(options, mod, load_args): + from functorch.compile import minifier + + mod, args = repro_common(options, mod, load_args) + compiler_name = "inductor_accuracy" if options.accuracy != "" else "inductor" + + favored_device = 1 if torch.cuda.device_count() >= 2 else 0 + env_variables = {"CUDA_VISIBLE_DEVICES": str(favored_device)} + + module_fails: Any + if options.isolate: + module_fails = functools.partial( + isolate_fails, + env=env_variables, + compiler_name=compiler_name, + save_dir=options.save_dir, + accuracy=options.accuracy, + tracing_mode=options.tracing_mode, + ) + else: + module_fails = ACCURACY_FAILS[options.accuracy] + + minifier( + mod, + args, + module_fails=functools.partial(module_fails, check_str=options.check_str), + dump_state=functools.partial( + dump_compiler_graph_state, compiler_name=compiler_name + ), + save_dir=options.save_dir, + offload_to_disk=options.offload_to_disk, + skip_offload=options.skip_saving_eager_intermediates, + skip_sanity=options.skip_sanity, + max_granularity=options.max_granularity, + ) + + +def repro_analyze(options, mod, load_args): + from torch._inductor.compile_fx import compile_fx_inner + from torch._inductor.hooks import intermediate_hook + + mod, args = repro_common(options, mod, load_args) + + # TODO: The logic for cloning inputs/models here is intentionally + # modeled off of run_fwd_maybe_bwd, but arguably it is better not to + # clone inputs (as you are doubling your effective GPU memory usage). + # It is certainly faster though! It probably makes sense to let the + # user specify the offload strategy. + + with tqdm(desc="Compiling"): + compiled = compile_fx_inner(mod, args) + total = counters["inductor"]["intermediate_hooks"] + + known_names = set() + + def save_hook(name, val): + known_names.add(name) + if not options.skip_saving_inductor_intermediates: + writer.write_tensor(os.path.join("inductor", name), val) + pbar.update(1) # type: ignore[has-type] + + writer = torch.utils._content_store.ContentStoreWriter( + options.save_dir, stable_hash=options.stable_hash + ) + reader = torch.utils._content_store.ContentStoreReader(options.save_dir) + + new_args = clone_inputs(args) + with intermediate_hook(save_hook), tqdm( + desc="Saving inductor intermediates", total=total + ) as pbar: + compiled(new_args) + assert not new_args + + def compare_tuples(tuple1, tuple2): + diff_indices = [i for i in range(len(tuple1)) if tuple1[i] != tuple2[i]] + diff_values = [(tuple1[i], tuple2[i]) for i in diff_indices] + + if not diff_values: + return None + else: + return " and ".join(f"{a} != {b}" for a, b in diff_values) + + def check_hook(name, val): + meta = writer.compute_tensor_metadata(val) + meta2 = reader.read_tensor_metadata(os.path.join("inductor", name)) + reason = compare_tuples(meta, meta2) + if reason is not None: + pbar.write(f"NONDETERMINISTIC INDUCTOR at {name} ({reason})") + pbar.update(1) + + if not options.skip_check_deterministic: + new_args = clone_inputs(args) + with intermediate_hook(check_hook), tqdm( + desc="Checking inductor determinism", total=total + ) as pbar: + compiled(new_args) + assert not new_args + + class WriterInterp(fx.Interpreter): + def __init__(self, mod, subdir): + super().__init__(mod) + self.subdir = subdir + + def run_node(self, n): + r = super().run_node(n) + name = n.name + if name in known_names: + pbar.update(1) + writer.write_tensor(os.path.join(self.subdir, name), r) + return r + + # NB: the module cast doesn't actually do anything, since there are no + # parameters/buffers on the module + if not options.skip_saving_float64_intermediates: + new_mod, new_args = cast_to_fp64(copy.deepcopy(mod), clone_inputs(args)) + with tqdm(desc="Saving float64 intermediates", total=total) as pbar: + WriterInterp(new_mod, "float64").boxed_run(new_args) + assert not new_args + + class ExactReaderInterp(fx.Interpreter): + def run_node(self, n): + r = super().run_node(n) + name = n.name + if name in known_names: + meta = writer.compute_tensor_metadata(r) + meta2 = reader.read_tensor_metadata(os.path.join("float64", name)) + reason = compare_tuples(meta, meta2) + if reason is not None: + pbar.write(f"NONDETERMINISTIC FLOAT64 at {name} ({reason})") + pbar.update(1) + return r + + # TODO: check eager determinism + + if not options.skip_check_deterministic: + new_mod, new_args = cast_to_fp64(copy.deepcopy(mod), clone_inputs(args)) + with tqdm(desc="Checking float64 determinism", total=total) as pbar: + ExactReaderInterp(new_mod).boxed_run(new_args) + assert not new_args + + # Now that we've saved everything, interp through the eager graph + # and do comparisons + class ReaderInterp(fx.Interpreter): + def run_node(self, n): + r = super().run_node(n) + name = n.name + if name in known_names: + inductor = reader.read_tensor(os.path.join("inductor", name)) + float64 = reader.read_tensor(os.path.join("float64", name)) + logged = False + + def log_error(msg, *args): + nonlocal logged + logged = True + pbar.write(f"DIVERGED at {name}: {msg % args}") + + if not same( + r, + inductor, + float64, + tol=torch._dynamo.config.repro_tolerance, + equal_nan=True, + log_error=log_error, + ): + assert logged + pbar.update(1) + return r + + with tqdm(desc="Checking divergence", total=total) as pbar: + ReaderInterp(mod).boxed_run(args) + assert not args + + +def repro_run(options, mod, load_args): + from torch._inductor.compile_fx import compile_fx_inner + + mod, args = repro_common(options, mod, load_args) + + from torch.cuda import synchronize + + compiled = compile_fx_inner(mod, args) + + if options.accuracy != "": + # We don't really respect --accuracy vs --strict-accuracy here, it + # seems counterintuitive + if not same_two_models(mod, compiled, args, only_fwd=True): + raise AccuracyError("Bad accuracy detected") + else: + need_sync = False + for arg in args: + if isinstance(arg, torch.Tensor) and arg.is_cuda: + need_sync = True + break + ref = compiled(list(args)) + if need_sync: + synchronize() # ensure segfaults are surfaced + return lambda: compiled(list(args)) + + +# TODO: lazily load the inputs or something, rather than cloning them +def run_repro( + mod, + load_args, + *, + command="run", + accuracy: Union[bool, str] = "", + save_dir=None, + tracing_mode=None, + patch_code=None, + check_str=None, + **kwargs, +): + for k in kwargs: + log.warning( + "Unrecognized kwarg %s; perhaps this repro was made on a newer version of PyTorch", + k, + ) + + if accuracy is True: + accuracy = "accuracy" + elif accuracy is False: + accuracy = "" + + if patch_code is not None: + log.warning( + "patch_code no longer works on this version of PyTorch, silently ignoring" + ) + + parser = argparse.ArgumentParser( + description=f"""\ +An after_aot repro script, typically triggering a bug in PyTorch Inductor. +When run with no arguments, this script defaults to running '{command}'. +Extra flags may be available; to find out more, try '{command} --help'. +There are also alternate subcommands available, see below. + +default settings on this script: + {accuracy=} + {tracing_mode=} + {save_dir=} + {check_str=} +""", + formatter_class=argparse.RawTextHelpFormatter, + ) + + def common_flags(parser): + accuracy_group = parser.add_mutually_exclusive_group() + accuracy_group.add_argument( + "--no-accuracy", + dest="accuracy", + action="store_const", + const="", + default=accuracy, + help="do not test accuracy, just run the module and see if it errors", + ) + accuracy_group.add_argument( + "--accuracy", + action="store_const", + const="accuracy", + default=accuracy, + help="""\ +test if the RMSE between the compiled module and the fp64 reference is greater +than eager and the fp64 reference. This is usually more reliable than the +standard allclose test, as we expect numeric differences from compiling, often +improving accuracy over eager. RMSE test allows for compiled module to +diverge greatly from eager, as long as this divergence moves it closer to the +'true' mathematical value of the network. Caveats: (1) double precision can +still suffer from rounding error, so it is not a perfect reference (see for +example 'Herbie: Automatically Improving Floating Point Accuracy') for +approaches that detect the necessary working precision and compute it in +arbitrary precision floating point; unfortunately, this is not practical for +tensor computation; (2) if there are not enough samples in the output being +compared, we may get unlucky and have an unlucky greater RMSE than eager; this +could be overcome by applying a more rigorous statistical test at some +p-value, which we leave for future work. +""", + ) + accuracy_group.add_argument( + "--strict-accuracy", + dest="accuracy", + action="store_const", + const="strict_accuracy", + default=accuracy, + help="""\ +by default, when doing accuracy minification we will reject reductions which +change the divergence from a floating point divergence to a integral/boolean +divergence. This is because some operations like ReLU involve temporarily +sharp boundaries that smooth out again afterwards; without requiring +divergence on floating point, the minifier will often fixate on divergent +boolean tensor even though this is not the true source of the divergence. +However, rejecting these reductions makes it more difficult for the minifier +to make process. Using this option will let the minifier progress for ALL +divergences--you just might not end up with a useful repro in the end.""", + ) + + parser.add_argument( + "--save-dir", + type=str, + default=save_dir, + metavar="DIR", + help="directory where saved inputs live", + ) + parser.add_argument( + "--no-save-dir", + dest="save_dir", + action="store_const", + const=None, + help="don't use any directory for saved inputs", + ) + parser.add_argument( + "--tracing-mode", + type=str, + metavar="{real,fake,symbolic}", + default=tracing_mode, + help="how to trace the repro module into a GraphModule with metadata", + ) + + subparsers = parser.add_subparsers( + dest="command", metavar="{run,minify,analyze}", required=True + ) + + parser_run = subparsers.add_parser( + "run", + help="just run the repro", + ) + common_flags(parser_run) + + parser_minify = subparsers.add_parser( + "minify", help="run the minifier on the repro" + ) + common_flags(parser_minify) + parser_minify_isolate = parser_minify.add_mutually_exclusive_group() + parser_minify_isolate.add_argument( + "--isolate", + action="store_true", + default=True, + help="run in separate processes to avoid interference (default)", + ) + parser_minify_isolate.add_argument( + "--no-isolate", + dest="isolate", + action="store_false", + help="speed up by running all compilation in same process", + ) + parser_minify.add_argument( + "--skip-saving-eager-intermediates", + action="store_true", + help="skip saving eager intermediates on --minify", + ) + # TODO: make this an option for --analyze too + parser_minify.add_argument( + "--offload-to-disk", + action="store_true", + help="during minification, offload delta debugging intermediates to disk. Use if you're OOMing", + ) + parser_minify.add_argument( + "--skip-sanity", + action="store_true", + help="skip sanity check at beginning of minification on original graph", + ) + parser_minify.add_argument( + "--max-granularity", + type=int, + default=None, + help="start at this granularity and work down; must be power of 2", + ) + parser_minify.add_argument( + "--check-str", + type=str, + default=check_str, + help="require minified program to fail with error containing this string", + ) + + parser_analyze = subparsers.add_parser( + "analyze", help="run the accuracy analyzer on the repro" + ) + common_flags(parser_analyze) + parser_analyze.add_argument( + "--skip-saving-inductor-intermediates", + action="store_true", + help="skip saving inductor intermediates on --analyze", + ) + parser_analyze.add_argument( + "--skip-saving-float64-intermediates", + action="store_true", + help="skip saving float64 intermediates", + ) + parser_analyze.add_argument( + "--skip-check-deterministic", + action="store_true", + help="skip checking that the network is deterministic", + ) + parser_analyze.add_argument( + "--stable-hash", + action="store_true", + help="use SHA-1 checksum instead of fast (but possibly unsound) hash", + ) + + # Run the repro in the context of minification, inverting exit code meaning + parser_minifier_query = subparsers.add_parser( + "minifier-query", + ) + common_flags(parser_minifier_query) + parser_minifier_query.add_argument( + "--check-str", + type=str, + default=check_str, + help="require minified program to fail with error containing this string", + ) + + args = None + if len(sys.argv) <= 1: + args = [command, *sys.argv[1:]] + + options = parser.parse_args(args) + COMMAND_FNS = { + "minify": repro_minify, + "analyze": repro_analyze, + "minifier-query": repro_minifier_query, + "run": repro_run, + } + return COMMAND_FNS[options.command](options, mod, load_args) diff --git a/shared/package-files/49/4903f07034ae112bf77d32af4c4ea0d3172aa73c98d8c1e2184932c9b75a8381/random_cuda_dispatch.h b/shared/package-files/49/4903f07034ae112bf77d32af4c4ea0d3172aa73c98d8c1e2184932c9b75a8381/random_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..4c12198695e108160da0897ba9c431f80b839250 --- /dev/null +++ b/shared/package-files/49/4903f07034ae112bf77d32af4c4ea0d3172aa73c98d8c1e2184932c9b75a8381/random_cuda_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor & random_(at::Tensor & self, int64_t from, c10::optional to, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & random_(at::Tensor & self, int64_t to, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & random_(at::Tensor & self, c10::optional generator=c10::nullopt); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/49/490438b70d2e1b116421a163321570a8796953693206dfbb65bd6a50a6cd9863/windows_events.pyi b/shared/package-files/49/490438b70d2e1b116421a163321570a8796953693206dfbb65bd6a50a6cd9863/windows_events.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8b12a9f3539c0a73ea312cf62e265e8e2950a007 --- /dev/null +++ b/shared/package-files/49/490438b70d2e1b116421a163321570a8796953693206dfbb65bd6a50a6cd9863/windows_events.pyi @@ -0,0 +1,76 @@ +import socket +import sys +from typing import IO, Any, Callable, ClassVar, List, NoReturn, Optional, Tuple, Type + +from . import events, futures, proactor_events, selector_events, streams, windows_utils + +__all__ = [ + "SelectorEventLoop", + "ProactorEventLoop", + "IocpProactor", + "DefaultEventLoopPolicy", + "WindowsSelectorEventLoopPolicy", + "WindowsProactorEventLoopPolicy", +] + +NULL: int +INFINITE: int +ERROR_CONNECTION_REFUSED: int +ERROR_CONNECTION_ABORTED: int +CONNECT_PIPE_INIT_DELAY: float +CONNECT_PIPE_MAX_DELAY: float + +class PipeServer: + def __init__(self, address: str) -> None: ... + def __del__(self) -> None: ... + def closed(self) -> bool: ... + def close(self) -> None: ... + +class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop): ... + +class ProactorEventLoop(proactor_events.BaseProactorEventLoop): + def __init__(self, proactor: Optional[IocpProactor] = ...) -> None: ... + async def create_pipe_connection( + self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str + ) -> Tuple[proactor_events._ProactorDuplexPipeTransport, streams.StreamReaderProtocol]: ... + async def start_serving_pipe( + self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str + ) -> List[PipeServer]: ... + +class IocpProactor: + def __init__(self, concurrency: int = ...) -> None: ... + def __repr__(self) -> str: ... + def __del__(self) -> None: ... + def set_loop(self, loop: events.AbstractEventLoop) -> None: ... + def select(self, timeout: Optional[int] = ...) -> List[futures.Future[Any]]: ... + def recv(self, conn: socket.socket, nbytes: int, flags: int = ...) -> futures.Future[bytes]: ... + if sys.version_info >= (3, 7): + def recv_into(self, conn: socket.socket, buf: socket._WriteBuffer, flags: int = ...) -> futures.Future[Any]: ... + def send(self, conn: socket.socket, buf: socket._WriteBuffer, flags: int = ...) -> futures.Future[Any]: ... + def accept(self, listener: socket.socket) -> futures.Future[Any]: ... + def connect(self, conn: socket.socket, address: bytes) -> futures.Future[Any]: ... + if sys.version_info >= (3, 7): + def sendfile(self, sock: socket.socket, file: IO[bytes], offset: int, count: int) -> futures.Future[Any]: ... + def accept_pipe(self, pipe: socket.socket) -> futures.Future[Any]: ... + async def connect_pipe(self, address: bytes) -> windows_utils.PipeHandle: ... + def wait_for_handle(self, handle: windows_utils.PipeHandle, timeout: Optional[int] = ...) -> bool: ... + def close(self) -> None: ... + +SelectorEventLoop = _WindowsSelectorEventLoop + +if sys.version_info >= (3, 7): + class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[Type[SelectorEventLoop]] + def get_child_watcher(self) -> NoReturn: ... + def set_child_watcher(self, watcher: Any) -> NoReturn: ... + class WindowsProactorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[Type[ProactorEventLoop]] + def get_child_watcher(self) -> NoReturn: ... + def set_child_watcher(self, watcher: Any) -> NoReturn: ... + DefaultEventLoopPolicy = WindowsSelectorEventLoopPolicy +else: + class _WindowsDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[Type[SelectorEventLoop]] + def get_child_watcher(self) -> NoReturn: ... + def set_child_watcher(self, watcher: Any) -> NoReturn: ... + DefaultEventLoopPolicy = _WindowsDefaultEventLoopPolicy diff --git a/shared/package-files/49/4908bd229176dcb81a0c54e087cc725040988babad9e806a5052fb722cf5b511/ztx11 b/shared/package-files/49/4908bd229176dcb81a0c54e087cc725040988babad9e806a5052fb722cf5b511/ztx11 new file mode 100644 index 0000000000000000000000000000000000000000..91424b20cd42b800fc2d36c6f45a031ca8154522 Binary files /dev/null and b/shared/package-files/49/4908bd229176dcb81a0c54e087cc725040988babad9e806a5052fb722cf5b511/ztx11 differ diff --git a/shared/package-files/49/490c3e5bc77954705f17cd4461515b71249552bb081c6f5af58cdb91468a22a7/polysys.py b/shared/package-files/49/490c3e5bc77954705f17cd4461515b71249552bb081c6f5af58cdb91468a22a7/polysys.py new file mode 100644 index 0000000000000000000000000000000000000000..ef88f2fa82c9472c444e4ad2aed3903501f82b0a --- /dev/null +++ b/shared/package-files/49/490c3e5bc77954705f17cd4461515b71249552bb081c6f5af58cdb91468a22a7/polysys.py @@ -0,0 +1,440 @@ +"""Solvers of systems of polynomial equations. """ +import itertools + +from sympy.core import S +from sympy.core.sorting import default_sort_key +from sympy.polys import Poly, groebner, roots +from sympy.polys.polytools import parallel_poly_from_expr +from sympy.polys.polyerrors import (ComputationFailed, + PolificationFailed, CoercionFailed) +from sympy.simplify import rcollect +from sympy.utilities import postfixes +from sympy.utilities.misc import filldedent + + +class SolveFailed(Exception): + """Raised when solver's conditions were not met. """ + + +def solve_poly_system(seq, *gens, strict=False, **args): + """ + Return a list of solutions for the system of polynomial equations + or else None. + + Parameters + ========== + + seq: a list/tuple/set + Listing all the equations that are needed to be solved + gens: generators + generators of the equations in seq for which we want the + solutions + strict: a boolean (default is False) + if strict is True, NotImplementedError will be raised if + the solution is known to be incomplete (which can occur if + not all solutions are expressible in radicals) + args: Keyword arguments + Special options for solving the equations. + + + Returns + ======= + + List[Tuple] + a list of tuples with elements being solutions for the + symbols in the order they were passed as gens + None + None is returned when the computed basis contains only the ground. + + Examples + ======== + + >>> from sympy import solve_poly_system + >>> from sympy.abc import x, y + + >>> solve_poly_system([x*y - 2*y, 2*y**2 - x**2], x, y) + [(0, 0), (2, -sqrt(2)), (2, sqrt(2))] + + >>> solve_poly_system([x**5 - x + y**3, y**2 - 1], x, y, strict=True) + Traceback (most recent call last): + ... + UnsolvableFactorError + + """ + try: + polys, opt = parallel_poly_from_expr(seq, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('solve_poly_system', len(seq), exc) + + if len(polys) == len(opt.gens) == 2: + f, g = polys + + if all(i <= 2 for i in f.degree_list() + g.degree_list()): + try: + return solve_biquadratic(f, g, opt) + except SolveFailed: + pass + + return solve_generic(polys, opt, strict=strict) + + +def solve_biquadratic(f, g, opt): + """Solve a system of two bivariate quadratic polynomial equations. + + Parameters + ========== + + f: a single Expr or Poly + First equation + g: a single Expr or Poly + Second Equation + opt: an Options object + For specifying keyword arguments and generators + + Returns + ======= + + List[Tuple] + a list of tuples with elements being solutions for the + symbols in the order they were passed as gens + None + None is returned when the computed basis contains only the ground. + + Examples + ======== + + >>> from sympy import Options, Poly + >>> from sympy.abc import x, y + >>> from sympy.solvers.polysys import solve_biquadratic + >>> NewOption = Options((x, y), {'domain': 'ZZ'}) + + >>> a = Poly(y**2 - 4 + x, y, x, domain='ZZ') + >>> b = Poly(y*2 + 3*x - 7, y, x, domain='ZZ') + >>> solve_biquadratic(a, b, NewOption) + [(1/3, 3), (41/27, 11/9)] + + >>> a = Poly(y + x**2 - 3, y, x, domain='ZZ') + >>> b = Poly(-y + x - 4, y, x, domain='ZZ') + >>> solve_biquadratic(a, b, NewOption) + [(7/2 - sqrt(29)/2, -sqrt(29)/2 - 1/2), (sqrt(29)/2 + 7/2, -1/2 + \ + sqrt(29)/2)] + """ + G = groebner([f, g]) + + if len(G) == 1 and G[0].is_ground: + return None + + if len(G) != 2: + raise SolveFailed + + x, y = opt.gens + p, q = G + if not p.gcd(q).is_ground: + # not 0-dimensional + raise SolveFailed + + p = Poly(p, x, expand=False) + p_roots = [rcollect(expr, y) for expr in roots(p).keys()] + + q = q.ltrim(-1) + q_roots = list(roots(q).keys()) + + solutions = [(p_root.subs(y, q_root), q_root) for q_root, p_root in + itertools.product(q_roots, p_roots)] + + return sorted(solutions, key=default_sort_key) + + +def solve_generic(polys, opt, strict=False): + """ + Solve a generic system of polynomial equations. + + Returns all possible solutions over C[x_1, x_2, ..., x_m] of a + set F = { f_1, f_2, ..., f_n } of polynomial equations, using + Groebner basis approach. For now only zero-dimensional systems + are supported, which means F can have at most a finite number + of solutions. If the basis contains only the ground, None is + returned. + + The algorithm works by the fact that, supposing G is the basis + of F with respect to an elimination order (here lexicographic + order is used), G and F generate the same ideal, they have the + same set of solutions. By the elimination property, if G is a + reduced, zero-dimensional Groebner basis, then there exists an + univariate polynomial in G (in its last variable). This can be + solved by computing its roots. Substituting all computed roots + for the last (eliminated) variable in other elements of G, new + polynomial system is generated. Applying the above procedure + recursively, a finite number of solutions can be found. + + The ability of finding all solutions by this procedure depends + on the root finding algorithms. If no solutions were found, it + means only that roots() failed, but the system is solvable. To + overcome this difficulty use numerical algorithms instead. + + Parameters + ========== + + polys: a list/tuple/set + Listing all the polynomial equations that are needed to be solved + opt: an Options object + For specifying keyword arguments and generators + strict: a boolean + If strict is True, NotImplementedError will be raised if the solution + is known to be incomplete + + Returns + ======= + + List[Tuple] + a list of tuples with elements being solutions for the + symbols in the order they were passed as gens + None + None is returned when the computed basis contains only the ground. + + References + ========== + + .. [Buchberger01] B. Buchberger, Groebner Bases: A Short + Introduction for Systems Theorists, In: R. Moreno-Diaz, + B. Buchberger, J.L. Freire, Proceedings of EUROCAST'01, + February, 2001 + + .. [Cox97] D. Cox, J. Little, D. O'Shea, Ideals, Varieties + and Algorithms, Springer, Second Edition, 1997, pp. 112 + + Raises + ======== + + NotImplementedError + If the system is not zero-dimensional (does not have a finite + number of solutions) + + UnsolvableFactorError + If ``strict`` is True and not all solution components are + expressible in radicals + + Examples + ======== + + >>> from sympy import Poly, Options + >>> from sympy.solvers.polysys import solve_generic + >>> from sympy.abc import x, y + >>> NewOption = Options((x, y), {'domain': 'ZZ'}) + + >>> a = Poly(x - y + 5, x, y, domain='ZZ') + >>> b = Poly(x + y - 3, x, y, domain='ZZ') + >>> solve_generic([a, b], NewOption) + [(-1, 4)] + + >>> a = Poly(x - 2*y + 5, x, y, domain='ZZ') + >>> b = Poly(2*x - y - 3, x, y, domain='ZZ') + >>> solve_generic([a, b], NewOption) + [(11/3, 13/3)] + + >>> a = Poly(x**2 + y, x, y, domain='ZZ') + >>> b = Poly(x + y*4, x, y, domain='ZZ') + >>> solve_generic([a, b], NewOption) + [(0, 0), (1/4, -1/16)] + + >>> a = Poly(x**5 - x + y**3, x, y, domain='ZZ') + >>> b = Poly(y**2 - 1, x, y, domain='ZZ') + >>> solve_generic([a, b], NewOption, strict=True) + Traceback (most recent call last): + ... + UnsolvableFactorError + + """ + def _is_univariate(f): + """Returns True if 'f' is univariate in its last variable. """ + for monom in f.monoms(): + if any(monom[:-1]): + return False + + return True + + def _subs_root(f, gen, zero): + """Replace generator with a root so that the result is nice. """ + p = f.as_expr({gen: zero}) + + if f.degree(gen) >= 2: + p = p.expand(deep=False) + + return p + + def _solve_reduced_system(system, gens, entry=False): + """Recursively solves reduced polynomial systems. """ + if len(system) == len(gens) == 1: + # the below line will produce UnsolvableFactorError if + # strict=True and the solution from `roots` is incomplete + zeros = list(roots(system[0], gens[-1], strict=strict).keys()) + return [(zero,) for zero in zeros] + + basis = groebner(system, gens, polys=True) + + if len(basis) == 1 and basis[0].is_ground: + if not entry: + return [] + else: + return None + + univariate = list(filter(_is_univariate, basis)) + + if len(basis) < len(gens): + raise NotImplementedError(filldedent(''' + only zero-dimensional systems supported + (finite number of solutions) + ''')) + + if len(univariate) == 1: + f = univariate.pop() + else: + raise NotImplementedError(filldedent(''' + only zero-dimensional systems supported + (finite number of solutions) + ''')) + + gens = f.gens + gen = gens[-1] + + # the below line will produce UnsolvableFactorError if + # strict=True and the solution from `roots` is incomplete + zeros = list(roots(f.ltrim(gen), strict=strict).keys()) + + if not zeros: + return [] + + if len(basis) == 1: + return [(zero,) for zero in zeros] + + solutions = [] + + for zero in zeros: + new_system = [] + new_gens = gens[:-1] + + for b in basis[:-1]: + eq = _subs_root(b, gen, zero) + + if eq is not S.Zero: + new_system.append(eq) + + for solution in _solve_reduced_system(new_system, new_gens): + solutions.append(solution + (zero,)) + + if solutions and len(solutions[0]) != len(gens): + raise NotImplementedError(filldedent(''' + only zero-dimensional systems supported + (finite number of solutions) + ''')) + return solutions + + try: + result = _solve_reduced_system(polys, opt.gens, entry=True) + except CoercionFailed: + raise NotImplementedError + + if result is not None: + return sorted(result, key=default_sort_key) + + +def solve_triangulated(polys, *gens, **args): + """ + Solve a polynomial system using Gianni-Kalkbrenner algorithm. + + The algorithm proceeds by computing one Groebner basis in the ground + domain and then by iteratively computing polynomial factorizations in + appropriately constructed algebraic extensions of the ground domain. + + Parameters + ========== + + polys: a list/tuple/set + Listing all the equations that are needed to be solved + gens: generators + generators of the equations in polys for which we want the + solutions + args: Keyword arguments + Special options for solving the equations + + Returns + ======= + + List[Tuple] + A List of tuples. Solutions for symbols that satisfy the + equations listed in polys + + Examples + ======== + + >>> from sympy import solve_triangulated + >>> from sympy.abc import x, y, z + + >>> F = [x**2 + y + z - 1, x + y**2 + z - 1, x + y + z**2 - 1] + + >>> solve_triangulated(F, x, y, z) + [(0, 0, 1), (0, 1, 0), (1, 0, 0)] + + References + ========== + + 1. Patrizia Gianni, Teo Mora, Algebraic Solution of System of + Polynomial Equations using Groebner Bases, AAECC-5 on Applied Algebra, + Algebraic Algorithms and Error-Correcting Codes, LNCS 356 247--257, 1989 + + """ + G = groebner(polys, gens, polys=True) + G = list(reversed(G)) + + domain = args.get('domain') + + if domain is not None: + for i, g in enumerate(G): + G[i] = g.set_domain(domain) + + f, G = G[0].ltrim(-1), G[1:] + dom = f.get_domain() + + zeros = f.ground_roots() + solutions = set() + + for zero in zeros: + solutions.add(((zero,), dom)) + + var_seq = reversed(gens[:-1]) + vars_seq = postfixes(gens[1:]) + + for var, vars in zip(var_seq, vars_seq): + _solutions = set() + + for values, dom in solutions: + H, mapping = [], list(zip(vars, values)) + + for g in G: + _vars = (var,) + vars + + if g.has_only_gens(*_vars) and g.degree(var) != 0: + h = g.ltrim(var).eval(dict(mapping)) + + if g.degree(var) == h.degree(): + H.append(h) + + p = min(H, key=lambda h: h.degree()) + zeros = p.ground_roots() + + for zero in zeros: + if not zero.is_Rational: + dom_zero = dom.algebraic_field(zero) + else: + dom_zero = dom + + _solutions.add(((zero,) + values, dom_zero)) + + solutions = _solutions + + solutions = list(solutions) + + for i, (solution, _) in enumerate(solutions): + solutions[i] = solution + + return sorted(solutions, key=default_sort_key) diff --git a/shared/package-files/49/4911ed39ad1a3eae9f06752acae5dff554200c392249da8fa6a088e5371ffdfd/input_buffer.h b/shared/package-files/49/4911ed39ad1a3eae9f06752acae5dff554200c392249da8fa6a088e5371ffdfd/input_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..d8ef3396cb6d860520a9b950f8a9bbb7cc63da55 --- /dev/null +++ b/shared/package-files/49/4911ed39ad1a3eae9f06752acae5dff554200c392249da8fa6a088e5371ffdfd/input_buffer.h @@ -0,0 +1,45 @@ +#pragma once + +// The InputBuffer class accumulates a list of Variables for use by a +// function. It implements logic to avoid modifying the passed +// values in-place (adding an input twice will accumulate the result). +// This behaviour is needed and used only in backward graphs. + +#include +#include + +#include +#include +#include + +namespace torch::autograd { + +struct InputBuffer { + explicit InputBuffer(size_t size) : buffer(size) {} + InputBuffer(const InputBuffer& other) = delete; + InputBuffer(InputBuffer&& other) = default; + explicit InputBuffer(variable_list&& inputs) : buffer(std::move(inputs)){}; + InputBuffer& operator=(InputBuffer&& other) = default; + + // Accumulates the variable at a specified index. + // The optional CUDA streams determine which stream the accumulation + // is run on and how the addition is synchronized. + TORCH_API void add( + size_t pos, + Variable&& var, + const c10::optional& opt_producer_stream, + const c10::optional& opt_consumer_stream); + + at::Device device() const; + + Variable operator[](size_t pos) { + return buffer[pos]; + } + + // Returns the inputs as a list of variables. Destroys given InputBuffer. + static std::vector variables(InputBuffer&& g); + + std::vector buffer; +}; + +} // namespace torch::autograd diff --git a/shared/package-files/49/49178d1989f1a71f3ef09f43d04249055fd1e9718b7d020477bc02675979eb9a/__init__.py b/shared/package-files/49/49178d1989f1a71f3ef09f43d04249055fd1e9718b7d020477bc02675979eb9a/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9360b6bb8a1774ca7ef4e71af68487a1675d2d6f --- /dev/null +++ b/shared/package-files/49/49178d1989f1a71f3ef09f43d04249055fd1e9718b7d020477bc02675979eb9a/__init__.py @@ -0,0 +1,33 @@ +import etcd +import unittest +import urllib3 +import json +try: + import mock +except ImportError: + from unittest import mock + + +class TestClientApiBase(unittest.TestCase): + + def setUp(self): + self.client = etcd.Client() + + def _prepare_response(self, s, d, cluster_id=None): + if isinstance(d, dict): + data = json.dumps(d).encode('utf-8') + else: + data = d.encode('utf-8') + + r = mock.create_autospec(urllib3.response.HTTPResponse)() + r.status = s + r.data = data + r.getheader.return_value = cluster_id or "abcd1234" + return r + + def _mock_api(self, status, d, cluster_id=None): + resp = self._prepare_response(status, d, cluster_id=cluster_id) + self.client.api_execute = mock.MagicMock(return_value=resp) + + def _mock_exception(self, exc, msg): + self.client.api_execute = mock.Mock(side_effect=exc(msg)) diff --git a/shared/package-files/49/492bcc2c658da37b1dfdddf83798a3d3eb551cdb74ef50a15084aed9ff795a53/__main__.py b/shared/package-files/49/492bcc2c658da37b1dfdddf83798a3d3eb551cdb74ef50a15084aed9ff795a53/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..962e7c270d72f2a649a3ab2f8504fc079858f2cb --- /dev/null +++ b/shared/package-files/49/492bcc2c658da37b1dfdddf83798a3d3eb551cdb74ef50a15084aed9ff795a53/__main__.py @@ -0,0 +1,7 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +import sys + +from .cli import main + +sys.exit(main()) diff --git a/shared/package-files/49/4931dda1e0e5cc618d359eda68f27c933de932b474b8d43b33500b39f52f30d5/upsample_bicubic2d_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/49/4931dda1e0e5cc618d359eda68f27c933de932b474b8d43b33500b39f52f30d5/upsample_bicubic2d_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..d68aac275a5366a827b02c8eb86a1ebdcd5fc44a --- /dev/null +++ b/shared/package-files/49/4931dda1e0e5cc618d359eda68f27c933de932b474b8d43b33500b39f52f30d5/upsample_bicubic2d_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor upsample_bicubic2d(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor upsample_bicubic2d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/49/4938c74a555e5a8f84838b4aaa7ffb9b7ff779f7261cfd160a82f5fcf2b9b6dd/tcl.py b/shared/package-files/49/4938c74a555e5a8f84838b4aaa7ffb9b7ff779f7261cfd160a82f5fcf2b9b6dd/tcl.py new file mode 100644 index 0000000000000000000000000000000000000000..f444223aa1b08e8048a581d7b2140eb188bcd2a7 --- /dev/null +++ b/shared/package-files/49/4938c74a555e5a8f84838b4aaa7ffb9b7ff779f7261cfd160a82f5fcf2b9b6dd/tcl.py @@ -0,0 +1,149 @@ +""" + pygments.lexers.tcl + ~~~~~~~~~~~~~~~~~~~ + + Lexers for Tcl and related languages. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.lexer import RegexLexer, include, words +from pygments.token import Text, Comment, Operator, Keyword, Name, String, \ + Number, Whitespace +from pygments.util import shebang_matches + +__all__ = ['TclLexer'] + + +class TclLexer(RegexLexer): + """ + For Tcl source code. + + .. versionadded:: 0.10 + """ + + keyword_cmds_re = words(( + 'after', 'apply', 'array', 'break', 'catch', 'continue', 'elseif', + 'else', 'error', 'eval', 'expr', 'for', 'foreach', 'global', 'if', + 'namespace', 'proc', 'rename', 'return', 'set', 'switch', 'then', + 'trace', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', + 'while'), prefix=r'\b', suffix=r'\b') + + builtin_cmds_re = words(( + 'append', 'bgerror', 'binary', 'cd', 'chan', 'clock', 'close', + 'concat', 'dde', 'dict', 'encoding', 'eof', 'exec', 'exit', 'fblocked', + 'fconfigure', 'fcopy', 'file', 'fileevent', 'flush', 'format', 'gets', + 'glob', 'history', 'http', 'incr', 'info', 'interp', 'join', 'lappend', + 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'loadTk', + 'lrange', 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', + 'mathfunc', 'mathop', 'memory', 'msgcat', 'open', 'package', 'pid', + 'pkg::create', 'pkg_mkIndex', 'platform', 'platform::shell', 'puts', + 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', + 'scan', 'seek', 'socket', 'source', 'split', 'string', 'subst', 'tell', + 'time', 'tm', 'unknown', 'unload'), prefix=r'\b', suffix=r'\b') + + name = 'Tcl' + url = 'https://www.tcl.tk/about/language.html' + aliases = ['tcl'] + filenames = ['*.tcl', '*.rvt'] + mimetypes = ['text/x-tcl', 'text/x-script.tcl', 'application/x-tcl'] + + def _gen_command_rules(keyword_cmds_re, builtin_cmds_re, context=""): + return [ + (keyword_cmds_re, Keyword, 'params' + context), + (builtin_cmds_re, Name.Builtin, 'params' + context), + (r'([\w.-]+)', Name.Variable, 'params' + context), + (r'#', Comment, 'comment'), + ] + + tokens = { + 'root': [ + include('command'), + include('basic'), + include('data'), + (r'\}', Keyword), # HACK: somehow we miscounted our braces + ], + 'command': _gen_command_rules(keyword_cmds_re, builtin_cmds_re), + 'command-in-brace': _gen_command_rules(keyword_cmds_re, + builtin_cmds_re, + "-in-brace"), + 'command-in-bracket': _gen_command_rules(keyword_cmds_re, + builtin_cmds_re, + "-in-bracket"), + 'command-in-paren': _gen_command_rules(keyword_cmds_re, + builtin_cmds_re, + "-in-paren"), + 'basic': [ + (r'\(', Keyword, 'paren'), + (r'\[', Keyword, 'bracket'), + (r'\{', Keyword, 'brace'), + (r'"', String.Double, 'string'), + (r'(eq|ne|in|ni)\b', Operator.Word), + (r'!=|==|<<|>>|<=|>=|&&|\|\||\*\*|[-+~!*/%<>&^|?:]', Operator), + ], + 'data': [ + (r'\s+', Whitespace), + (r'0x[a-fA-F0-9]+', Number.Hex), + (r'0[0-7]+', Number.Oct), + (r'\d+\.\d+', Number.Float), + (r'\d+', Number.Integer), + (r'\$[\w.:-]+', Name.Variable), + (r'\$\{[\w.:-]+\}', Name.Variable), + (r'[\w.,@:-]+', Text), + ], + 'params': [ + (r';', Keyword, '#pop'), + (r'\n', Text, '#pop'), + (r'(else|elseif|then)\b', Keyword), + include('basic'), + include('data'), + ], + 'params-in-brace': [ + (r'\}', Keyword, ('#pop', '#pop')), + include('params') + ], + 'params-in-paren': [ + (r'\)', Keyword, ('#pop', '#pop')), + include('params') + ], + 'params-in-bracket': [ + (r'\]', Keyword, ('#pop', '#pop')), + include('params') + ], + 'string': [ + (r'\[', String.Double, 'string-square'), + (r'(?s)(\\\\|\\[0-7]+|\\.|[^"\\])', String.Double), + (r'"', String.Double, '#pop') + ], + 'string-square': [ + (r'\[', String.Double, 'string-square'), + (r'(?s)(\\\\|\\[0-7]+|\\.|\\\n|[^\]\\])', String.Double), + (r'\]', String.Double, '#pop') + ], + 'brace': [ + (r'\}', Keyword, '#pop'), + include('command-in-brace'), + include('basic'), + include('data'), + ], + 'paren': [ + (r'\)', Keyword, '#pop'), + include('command-in-paren'), + include('basic'), + include('data'), + ], + 'bracket': [ + (r'\]', Keyword, '#pop'), + include('command-in-bracket'), + include('basic'), + include('data'), + ], + 'comment': [ + (r'.*[^\\]\n', Comment, '#pop'), + (r'.*\\\n', Comment), + ], + } + + def analyse_text(text): + return shebang_matches(text, r'(tcl)') diff --git a/shared/package-files/49/493b6d1a620f06f673b766f9d5d50ec28597e5cadc302a4a64e8ac3377f904d7/filewrapper.py b/shared/package-files/49/493b6d1a620f06f673b766f9d5d50ec28597e5cadc302a4a64e8ac3377f904d7/filewrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..25143902a26b6c335c34a8304ba780ac15fb6704 --- /dev/null +++ b/shared/package-files/49/493b6d1a620f06f673b766f9d5d50ec28597e5cadc302a4a64e8ac3377f904d7/filewrapper.py @@ -0,0 +1,119 @@ +# SPDX-FileCopyrightText: 2015 Eric Larson +# +# SPDX-License-Identifier: Apache-2.0 +from __future__ import annotations + +import mmap +from tempfile import NamedTemporaryFile +from typing import TYPE_CHECKING, Any, Callable + +if TYPE_CHECKING: + from http.client import HTTPResponse + + +class CallbackFileWrapper: + """ + Small wrapper around a fp object which will tee everything read into a + buffer, and when that file is closed it will execute a callback with the + contents of that buffer. + + All attributes are proxied to the underlying file object. + + This class uses members with a double underscore (__) leading prefix so as + not to accidentally shadow an attribute. + + The data is stored in a temporary file until it is all available. As long + as the temporary files directory is disk-based (sometimes it's a + memory-backed-``tmpfs`` on Linux), data will be unloaded to disk if memory + pressure is high. For small files the disk usually won't be used at all, + it'll all be in the filesystem memory cache, so there should be no + performance impact. + """ + + def __init__( + self, fp: HTTPResponse, callback: Callable[[bytes], None] | None + ) -> None: + self.__buf = NamedTemporaryFile("rb+", delete=True) + self.__fp = fp + self.__callback = callback + + def __getattr__(self, name: str) -> Any: + # The vaguaries of garbage collection means that self.__fp is + # not always set. By using __getattribute__ and the private + # name[0] allows looking up the attribute value and raising an + # AttributeError when it doesn't exist. This stop thigns from + # infinitely recursing calls to getattr in the case where + # self.__fp hasn't been set. + # + # [0] https://docs.python.org/2/reference/expressions.html#atom-identifiers + fp = self.__getattribute__("_CallbackFileWrapper__fp") + return getattr(fp, name) + + def __is_fp_closed(self) -> bool: + try: + return self.__fp.fp is None + + except AttributeError: + pass + + try: + closed: bool = self.__fp.closed + return closed + + except AttributeError: + pass + + # We just don't cache it then. + # TODO: Add some logging here... + return False + + def _close(self) -> None: + if self.__callback: + if self.__buf.tell() == 0: + # Empty file: + result = b"" + else: + # Return the data without actually loading it into memory, + # relying on Python's buffer API and mmap(). mmap() just gives + # a view directly into the filesystem's memory cache, so it + # doesn't result in duplicate memory use. + self.__buf.seek(0, 0) + result = memoryview( + mmap.mmap(self.__buf.fileno(), 0, access=mmap.ACCESS_READ) + ) + self.__callback(result) + + # We assign this to None here, because otherwise we can get into + # really tricky problems where the CPython interpreter dead locks + # because the callback is holding a reference to something which + # has a __del__ method. Setting this to None breaks the cycle + # and allows the garbage collector to do it's thing normally. + self.__callback = None + + # Closing the temporary file releases memory and frees disk space. + # Important when caching big files. + self.__buf.close() + + def read(self, amt: int | None = None) -> bytes: + data: bytes = self.__fp.read(amt) + if data: + # We may be dealing with b'', a sign that things are over: + # it's passed e.g. after we've already closed self.__buf. + self.__buf.write(data) + if self.__is_fp_closed(): + self._close() + + return data + + def _safe_read(self, amt: int) -> bytes: + data: bytes = self.__fp._safe_read(amt) # type: ignore[attr-defined] + if amt == 2 and data == b"\r\n": + # urllib executes this read to toss the CRLF at the end + # of the chunk. + return data + + self.__buf.write(data) + if self.__is_fp_closed(): + self._close() + + return data diff --git a/shared/package-files/49/496924d6c036fa78a492e530fd5403e36a98e1b4046e8cc2a23199e7e438bb53/linalg_matmul_ops.h b/shared/package-files/49/496924d6c036fa78a492e530fd5403e36a98e1b4046e8cc2a23199e7e438bb53/linalg_matmul_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..13b07c429173e2ebf0900ebdadb67372b742c5b5 --- /dev/null +++ b/shared/package-files/49/496924d6c036fa78a492e530fd5403e36a98e1b4046e8cc2a23199e7e438bb53/linalg_matmul_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API linalg_matmul { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::linalg_matmul") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_matmul(Tensor self, Tensor other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API linalg_matmul_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::linalg_matmul") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_matmul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/49/49740f8f1f87a4042a6f0d52afa5e59ff9d1da4e3686e629cc504bc81bda4440/_pdist_backward_ops.h b/shared/package-files/49/49740f8f1f87a4042a6f0d52afa5e59ff9d1da4e3686e629cc504bc81bda4440/_pdist_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..5a064d2f185439faa725489778783c26862f914a --- /dev/null +++ b/shared/package-files/49/49740f8f1f87a4042a6f0d52afa5e59ff9d1da4e3686e629cc504bc81bda4440/_pdist_backward_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _pdist_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, double, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_pdist_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_pdist_backward(Tensor grad, Tensor self, float p, Tensor pdist) -> Tensor") + static at::Tensor call(const at::Tensor & grad, const at::Tensor & self, double p, const at::Tensor & pdist); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad, const at::Tensor & self, double p, const at::Tensor & pdist); +}; + +struct TORCH_API _pdist_backward_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, double, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_pdist_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_pdist_backward.out(Tensor grad, Tensor self, float p, Tensor pdist, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & grad, const at::Tensor & self, double p, const at::Tensor & pdist, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad, const at::Tensor & self, double p, const at::Tensor & pdist, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/49/49921db1428ad6a01cf697689cf19fd00fda8a4647731c7389c7b344647984bb/builder_run_end.h b/shared/package-files/49/49921db1428ad6a01cf697689cf19fd00fda8a4647731c7389c7b344647984bb/builder_run_end.h new file mode 100644 index 0000000000000000000000000000000000000000..ac92efbd0dbe6b470b8275219e75b41aa3f7ab3a --- /dev/null +++ b/shared/package-files/49/49921db1428ad6a01cf697689cf19fd00fda8a4647731c7389c7b344647984bb/builder_run_end.h @@ -0,0 +1,303 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/array.h" +#include "arrow/array/builder_base.h" + +namespace arrow { + +/// \addtogroup run-end-encoded-builders +/// +/// @{ + +namespace internal { + +/// \brief An ArrayBuilder that deduplicates repeated values as they are +/// appended to the inner-ArrayBuilder and reports the length of the current run +/// of identical values. +/// +/// The following sequence of calls +/// +/// Append(2) +/// Append(2) +/// Append(2) +/// Append(7) +/// Append(7) +/// Append(2) +/// FinishInternal() +/// +/// will cause the inner-builder to receive only 3 Append calls +/// +/// Append(2) +/// Append(7) +/// Append(2) +/// FinishInternal() +/// +/// Note that values returned by length(), null_count() and capacity() are +/// related to the compressed array built by the inner-ArrayBuilder. +class RunCompressorBuilder : public ArrayBuilder { + public: + RunCompressorBuilder(MemoryPool* pool, std::shared_ptr inner_builder, + std::shared_ptr type); + + ~RunCompressorBuilder() override; + + ARROW_DISALLOW_COPY_AND_ASSIGN(RunCompressorBuilder); + + /// \brief Called right before a run is being closed + /// + /// Subclasses can override this function to perform an additional action when + /// a run is closed (i.e. run-length is known and value is appended to the + /// inner builder). + /// + /// \param value can be NULLPTR if closing a run of NULLs + /// \param length the greater than 0 length of the value run being closed + virtual Status WillCloseRun(const std::shared_ptr& value, + int64_t length) { + return Status::OK(); + } + + /// \brief Called right before a run of empty values is being closed + /// + /// Subclasses can override this function to perform an additional action when + /// a run of empty values is appended (i.e. run-length is known and a single + /// empty value is appended to the inner builder). + /// + /// \param length the greater than 0 length of the value run being closed + virtual Status WillCloseRunOfEmptyValues(int64_t length) { return Status::OK(); } + + /// \brief Allocate enough memory for a given number of array elements. + /// + /// NOTE: Conservatively resizing a run-length compressed array for a given + /// number of logical elements is not possible, since the physical length will + /// vary depending on the values to be appended in the future. But we can + /// pessimistically assume that each run will contain a single value and + /// allocate that number of runs. + Status Resize(int64_t capacity) override { return ResizePhysical(capacity); } + + /// \brief Allocate enough memory for a given number of runs. + /// + /// Like Resize on non-encoded builders, it does not account for variable size + /// data. + Status ResizePhysical(int64_t capacity); + + Status ReservePhysical(int64_t additional_capacity) { + return Reserve(additional_capacity); + } + + void Reset() override; + + Status AppendNull() final { return AppendNulls(1); } + Status AppendNulls(int64_t length) override; + + Status AppendEmptyValue() final { return AppendEmptyValues(1); } + Status AppendEmptyValues(int64_t length) override; + + Status AppendScalar(const Scalar& scalar, int64_t n_repeats) override; + Status AppendScalars(const ScalarVector& scalars) override; + + // AppendArraySlice() is not implemented. + + /// \brief Append a slice of an array containing values from already + /// compressed runs. + /// + /// NOTE: WillCloseRun() is not called as the length of each run cannot be + /// determined at this point. Caller should ensure that !has_open_run() by + /// calling FinishCurrentRun() before calling this. + /// + /// Pre-condition: !has_open_run() + Status AppendRunCompressedArraySlice(const ArraySpan& array, int64_t offset, + int64_t length); + + /// \brief Forces the closing of the current run if one is currently open. + /// + /// This can be called when one wants to ensure the current run will not be + /// extended. This may cause identical values to appear close to each other in + /// the underlying array (i.e. two runs that could be a single run) if more + /// values are appended after this is called. + /// + /// Finish() and FinishInternal() call this automatically. + virtual Status FinishCurrentRun(); + + Status FinishInternal(std::shared_ptr* out) override; + + ArrayBuilder& inner_builder() const { return *inner_builder_; } + + std::shared_ptr type() const override { return inner_builder_->type(); } + + bool has_open_run() const { return current_run_length_ > 0; } + int64_t open_run_length() const { return current_run_length_; } + + private: + inline void UpdateDimensions() { + capacity_ = inner_builder_->capacity(); + length_ = inner_builder_->length(); + null_count_ = inner_builder_->null_count(); + } + + private: + std::shared_ptr inner_builder_; + std::shared_ptr current_value_ = NULLPTR; + int64_t current_run_length_ = 0; +}; + +} // namespace internal + +// ---------------------------------------------------------------------- +// RunEndEncoded builder + +/// \brief Run-end encoded array builder. +/// +/// NOTE: the value returned by and capacity() is related to the +/// compressed array (physical) and not the decoded array (logical) that is +/// run-end encoded. null_count() always returns 0. length(), on the other hand, +/// returns the logical length of the run-end encoded array. +class ARROW_EXPORT RunEndEncodedBuilder : public ArrayBuilder { + private: + // An internal::RunCompressorBuilder that produces a run-end in the + // RunEndEncodedBuilder every time a value-run is closed. + class ValueRunBuilder : public internal::RunCompressorBuilder { + public: + ValueRunBuilder(MemoryPool* pool, const std::shared_ptr& value_builder, + const std::shared_ptr& value_type, + RunEndEncodedBuilder& ree_builder); + + ~ValueRunBuilder() override = default; + + Status WillCloseRun(const std::shared_ptr&, int64_t length) override { + return ree_builder_.CloseRun(length); + } + + Status WillCloseRunOfEmptyValues(int64_t length) override { + return ree_builder_.CloseRun(length); + } + + private: + RunEndEncodedBuilder& ree_builder_; + }; + + public: + RunEndEncodedBuilder(MemoryPool* pool, + const std::shared_ptr& run_end_builder, + const std::shared_ptr& value_builder, + std::shared_ptr type); + + /// \brief Allocate enough memory for a given number of array elements. + /// + /// NOTE: Conservatively resizing an REE for a given number of logical + /// elements is not possible, since the physical length will vary depending on + /// the values to be appended in the future. But we can pessimistically assume + /// that each run will contain a single value and allocate that number of + /// runs. + Status Resize(int64_t capacity) override { return ResizePhysical(capacity); } + + /// \brief Allocate enough memory for a given number of runs. + Status ResizePhysical(int64_t capacity); + + /// \brief Ensure that there is enough space allocated to append the indicated + /// number of run without any further reallocation. Overallocation is + /// used in order to minimize the impact of incremental ReservePhysical() calls. + /// Note that additional_capacity is relative to the current number of elements + /// rather than to the current capacity, so calls to Reserve() which are not + /// interspersed with addition of new elements may not increase the capacity. + /// + /// \param[in] additional_capacity the number of additional runs + /// \return Status + Status ReservePhysical(int64_t additional_capacity) { + return Reserve(additional_capacity); + } + + void Reset() override; + + Status AppendNull() final { return AppendNulls(1); } + Status AppendNulls(int64_t length) override; + + Status AppendEmptyValue() final { return AppendEmptyValues(1); } + Status AppendEmptyValues(int64_t length) override; + Status AppendScalar(const Scalar& scalar, int64_t n_repeats) override; + Status AppendScalars(const ScalarVector& scalars) override; + Status AppendArraySlice(const ArraySpan& array, int64_t offset, + int64_t length) override; + Status FinishInternal(std::shared_ptr* out) override; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + /// \brief Forces the closing of the current run if one is currently open. + /// + /// This can be called when one wants to ensure the current run will not be + /// extended. This may cause identical values to appear close to each other in + /// the values array (i.e. two runs that could be a single run) if more + /// values are appended after this is called. + Status FinishCurrentRun(); + + std::shared_ptr type() const override; + + private: + /// \brief Update physical capacity and logical length + /// + /// \param committed_logical_length number of logical values that have been + /// committed to the values array + /// \param open_run_length number of logical values in the currently open run if any + inline void UpdateDimensions(int64_t committed_logical_length, + int64_t open_run_length) { + capacity_ = run_end_builder().capacity(); + length_ = committed_logical_length + open_run_length; + committed_logical_length_ = committed_logical_length; + } + + // Pre-condition: !value_run_builder_.has_open_run() + template + Status DoAppendArraySlice(const ArraySpan& array, int64_t offset, int64_t length); + + template + Status DoAppendRunEnd(int64_t run_end); + + /// \brief Cast run_end to the appropriate type and appends it to the run_ends + /// array. + Status AppendRunEnd(int64_t run_end); + + /// \brief Close a run by appending a value to the run_ends array and updating + /// length_ to reflect the new run. + /// + /// Pre-condition: run_length > 0. + [[nodiscard]] Status CloseRun(int64_t run_length); + + ArrayBuilder& run_end_builder(); + ArrayBuilder& value_builder(); + + private: + std::shared_ptr type_; + ValueRunBuilder* value_run_builder_; + // The length not counting the current open run in the value_run_builder_ + int64_t committed_logical_length_ = 0; +}; + +/// @} + +} // namespace arrow diff --git a/shared/package-files/49/4996f0ea3082a8b88b34263793adf61a6c07783febff1ac34b4761a95e3d5616/ipc.h b/shared/package-files/49/4996f0ea3082a8b88b34263793adf61a6c07783febff1ac34b4761a95e3d5616/ipc.h new file mode 100644 index 0000000000000000000000000000000000000000..2c16d8c967ff0bffc52e7803d4d894adb72b1215 --- /dev/null +++ b/shared/package-files/49/4996f0ea3082a8b88b34263793adf61a6c07783febff1ac34b4761a95e3d5616/ipc.h @@ -0,0 +1,72 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include "arrow/python/common.h" +#include "arrow/python/visibility.h" +#include "arrow/record_batch.h" +#include "arrow/result.h" +#include "arrow/util/macros.h" + +namespace arrow { +namespace py { + +class ARROW_PYTHON_EXPORT PyRecordBatchReader : public RecordBatchReader { + public: + std::shared_ptr schema() const override; + + Status ReadNext(std::shared_ptr* batch) override; + + // For use from Cython + // Assumes that `iterable` is borrowed + static Result> Make(std::shared_ptr, + PyObject* iterable); + + protected: + PyRecordBatchReader(); + + Status Init(std::shared_ptr, PyObject* iterable); + + std::shared_ptr schema_; + OwnedRefNoGIL iterator_; +}; + +class ARROW_PYTHON_EXPORT CastingRecordBatchReader : public RecordBatchReader { + public: + std::shared_ptr schema() const override; + + Status ReadNext(std::shared_ptr* batch) override; + + static Result> Make( + std::shared_ptr parent, std::shared_ptr schema); + + Status Close() override; + + protected: + CastingRecordBatchReader(); + + Status Init(std::shared_ptr parent, std::shared_ptr schema); + + std::shared_ptr parent_; + std::shared_ptr schema_; +}; + +} // namespace py +} // namespace arrow diff --git a/shared/package-files/49/49ab3ddf3faddbe2a3c69a36f84e06152d0908dc3a4e1e6bb66b590d82df21ad/mean_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/49/49ab3ddf3faddbe2a3c69a36f84e06152d0908dc3a4e1e6bb66b590d82df21ad/mean_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..c8d346b2f0e76412b1eed773c4c579e5e1c221e7 --- /dev/null +++ b/shared/package-files/49/49ab3ddf3faddbe2a3c69a36f84e06152d0908dc3a4e1e6bb66b590d82df21ad/mean_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor mean(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim=false, c10::optional dtype=c10::nullopt); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/49/49ad4fdc8139026f7f3773e3f50f09207ff6bd8e92a2c382545525235448e525/__init__.py b/shared/package-files/49/49ad4fdc8139026f7f3773e3f50f09207ff6bd8e92a2c382545525235448e525/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ce61883288aa350f877cd3b3caaeb6865f888bab --- /dev/null +++ b/shared/package-files/49/49ad4fdc8139026f7f3773e3f50f09207ff6bd8e92a2c382545525235448e525/__init__.py @@ -0,0 +1,176 @@ +"""A pure Python implementation of import.""" +__all__ = ['__import__', 'import_module', 'invalidate_caches', 'reload'] + +# Bootstrap help ##################################################### + +# Until bootstrapping is complete, DO NOT import any modules that attempt +# to import importlib._bootstrap (directly or indirectly). Since this +# partially initialised package would be present in sys.modules, those +# modules would get an uninitialised copy of the source version, instead +# of a fully initialised version (either the frozen one or the one +# initialised below if the frozen one is not available). +import _imp # Just the builtin component, NOT the full Python module +import sys + +try: + import _frozen_importlib as _bootstrap +except ImportError: + from . import _bootstrap + _bootstrap._setup(sys, _imp) +else: + # importlib._bootstrap is the built-in import, ensure we don't create + # a second copy of the module. + _bootstrap.__name__ = 'importlib._bootstrap' + _bootstrap.__package__ = 'importlib' + try: + _bootstrap.__file__ = __file__.replace('__init__.py', '_bootstrap.py') + except NameError: + # __file__ is not guaranteed to be defined, e.g. if this code gets + # frozen by a tool like cx_Freeze. + pass + sys.modules['importlib._bootstrap'] = _bootstrap + +try: + import _frozen_importlib_external as _bootstrap_external +except ImportError: + from . import _bootstrap_external + _bootstrap_external._set_bootstrap_module(_bootstrap) + _bootstrap._bootstrap_external = _bootstrap_external +else: + _bootstrap_external.__name__ = 'importlib._bootstrap_external' + _bootstrap_external.__package__ = 'importlib' + try: + _bootstrap_external.__file__ = __file__.replace('__init__.py', '_bootstrap_external.py') + except NameError: + # __file__ is not guaranteed to be defined, e.g. if this code gets + # frozen by a tool like cx_Freeze. + pass + sys.modules['importlib._bootstrap_external'] = _bootstrap_external + +# To simplify imports in test code +_pack_uint32 = _bootstrap_external._pack_uint32 +_unpack_uint32 = _bootstrap_external._unpack_uint32 + +# Fully bootstrapped at this point, import whatever you like, circular +# dependencies and startup overhead minimisation permitting :) + +import warnings + + +# Public API ######################################################### + +from ._bootstrap import __import__ + + +def invalidate_caches(): + """Call the invalidate_caches() method on all meta path finders stored in + sys.meta_path (where implemented).""" + for finder in sys.meta_path: + if hasattr(finder, 'invalidate_caches'): + finder.invalidate_caches() + + +def find_loader(name, path=None): + """Return the loader for the specified module. + + This is a backward-compatible wrapper around find_spec(). + + This function is deprecated in favor of importlib.util.find_spec(). + + """ + warnings.warn('Deprecated since Python 3.4 and slated for removal in ' + 'Python 3.12; use importlib.util.find_spec() instead', + DeprecationWarning, stacklevel=2) + try: + loader = sys.modules[name].__loader__ + if loader is None: + raise ValueError('{}.__loader__ is None'.format(name)) + else: + return loader + except KeyError: + pass + except AttributeError: + raise ValueError('{}.__loader__ is not set'.format(name)) from None + + spec = _bootstrap._find_spec(name, path) + # We won't worry about malformed specs (missing attributes). + if spec is None: + return None + if spec.loader is None: + if spec.submodule_search_locations is None: + raise ImportError('spec for {} missing loader'.format(name), + name=name) + raise ImportError('namespace packages do not have loaders', + name=name) + return spec.loader + + +def import_module(name, package=None): + """Import a module. + + The 'package' argument is required when performing a relative import. It + specifies the package to use as the anchor point from which to resolve the + relative import to an absolute import. + + """ + level = 0 + if name.startswith('.'): + if not package: + msg = ("the 'package' argument is required to perform a relative " + "import for {!r}") + raise TypeError(msg.format(name)) + for character in name: + if character != '.': + break + level += 1 + return _bootstrap._gcd_import(name[level:], package, level) + + +_RELOADING = {} + + +def reload(module): + """Reload the module and return it. + + The module must have been successfully imported before. + + """ + try: + name = module.__spec__.name + except AttributeError: + try: + name = module.__name__ + except AttributeError: + raise TypeError("reload() argument must be a module") + + if sys.modules.get(name) is not module: + msg = "module {} not in sys.modules" + raise ImportError(msg.format(name), name=name) + if name in _RELOADING: + return _RELOADING[name] + _RELOADING[name] = module + try: + parent_name = name.rpartition('.')[0] + if parent_name: + try: + parent = sys.modules[parent_name] + except KeyError: + msg = "parent {!r} not in sys.modules" + raise ImportError(msg.format(parent_name), + name=parent_name) from None + else: + pkgpath = parent.__path__ + else: + pkgpath = None + target = module + spec = module.__spec__ = _bootstrap._find_spec(name, pkgpath, target) + if spec is None: + raise ModuleNotFoundError(f"spec not found for the module {name!r}", name=name) + _bootstrap._exec(spec, module) + # The module may have replaced itself in sys.modules! + return sys.modules[name] + finally: + try: + del _RELOADING[name] + except KeyError: + pass diff --git a/shared/package-files/49/49b46164fd14e082e76e0ee5610bc67979af3ccfc1e9b6a2d7615333f1c3e114/test_flight_server.h b/shared/package-files/49/49b46164fd14e082e76e0ee5610bc67979af3ccfc1e9b6a2d7615333f1c3e114/test_flight_server.h new file mode 100644 index 0000000000000000000000000000000000000000..794dd834c014b12ba23acfbc85d15034babbba69 --- /dev/null +++ b/shared/package-files/49/49b46164fd14e082e76e0ee5610bc67979af3ccfc1e9b6a2d7615333f1c3e114/test_flight_server.h @@ -0,0 +1,92 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include "arrow/flight/server.h" +#include "arrow/flight/type_fwd.h" +#include "arrow/flight/visibility.h" +#include "arrow/status.h" + +namespace arrow::flight { + +class ARROW_FLIGHT_EXPORT TestFlightServer : public FlightServerBase { + public: + static std::unique_ptr Make(); + + Status ListFlights(const ServerCallContext& context, const Criteria* criteria, + std::unique_ptr* listings) override; + + Status GetFlightInfo(const ServerCallContext& context, const FlightDescriptor& request, + std::unique_ptr* out) override; + + Status DoGet(const ServerCallContext& context, const Ticket& request, + std::unique_ptr* data_stream) override; + + Status DoPut(const ServerCallContext&, std::unique_ptr reader, + std::unique_ptr writer) override; + + Status DoExchange(const ServerCallContext& context, + std::unique_ptr reader, + std::unique_ptr writer) override; + + // A simple example - act like DoGet. + Status RunExchangeGet(std::unique_ptr reader, + std::unique_ptr writer); + + // A simple example - act like DoPut + Status RunExchangePut(std::unique_ptr reader, + std::unique_ptr writer); + + // Read some number of record batches from the client, send a + // metadata message back with the count, then echo the batches back. + Status RunExchangeCounter(std::unique_ptr reader, + std::unique_ptr writer); + + // Read int64 batches from the client, each time sending back a + // batch with a running sum of columns. + Status RunExchangeTotal(std::unique_ptr reader, + std::unique_ptr writer); + + // Echo the client's messages back. + Status RunExchangeEcho(std::unique_ptr reader, + std::unique_ptr writer); + + // Regression test for ARROW-13253 + Status RunExchangeLargeBatch(std::unique_ptr, + std::unique_ptr writer); + + Status RunAction1(const Action& action, std::unique_ptr* out); + + Status RunAction2(std::unique_ptr* out); + + Status ListIncomingHeaders(const ServerCallContext& context, const Action& action, + std::unique_ptr* out); + + Status DoAction(const ServerCallContext& context, const Action& action, + std::unique_ptr* out) override; + + Status ListActions(const ServerCallContext& context, + std::vector* out) override; + + Status GetSchema(const ServerCallContext& context, const FlightDescriptor& request, + std::unique_ptr* schema) override; +}; + +} // namespace arrow::flight diff --git a/shared/package-files/49/49b4bd0b9b6031d04123724acd6729f2b269a0c8ba27d67a009acc9f075e8095/clip_ops.h b/shared/package-files/49/49b4bd0b9b6031d04123724acd6729f2b269a0c8ba27d67a009acc9f075e8095/clip_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..2b4a90c855b66e6cb5d872864fc9106c044da842 --- /dev/null +++ b/shared/package-files/49/49b4bd0b9b6031d04123724acd6729f2b269a0c8ba27d67a009acc9f075e8095/clip_ops.h @@ -0,0 +1,83 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API clip { + using schema = at::Tensor (const at::Tensor &, const c10::optional &, const c10::optional &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::clip") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "clip(Tensor self, Scalar? min=None, Scalar? max=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, const c10::optional & min, const c10::optional & max); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const c10::optional & min, const c10::optional & max); +}; + +struct TORCH_API clip_Tensor { + using schema = at::Tensor (const at::Tensor &, const c10::optional &, const c10::optional &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::clip") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "clip.Tensor(Tensor self, Tensor? min=None, Tensor? max=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, const c10::optional & min, const c10::optional & max); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const c10::optional & min, const c10::optional & max); +}; + +struct TORCH_API clip_ { + using schema = at::Tensor & (at::Tensor &, const c10::optional &, const c10::optional &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::clip_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "clip_(Tensor(a!) self, Scalar? min=None, Scalar? max=None) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const c10::optional & min, const c10::optional & max); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const c10::optional & min, const c10::optional & max); +}; + +struct TORCH_API clip__Tensor { + using schema = at::Tensor & (at::Tensor &, const c10::optional &, const c10::optional &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::clip_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "clip_.Tensor(Tensor(a!) self, Tensor? min=None, Tensor? max=None) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const c10::optional & min, const c10::optional & max); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const c10::optional & min, const c10::optional & max); +}; + +struct TORCH_API clip_out { + using schema = at::Tensor & (const at::Tensor &, const c10::optional &, const c10::optional &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::clip") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "clip.out(Tensor self, Scalar? min=None, Scalar? max=None, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const c10::optional & min, const c10::optional & max, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const c10::optional & min, const c10::optional & max, at::Tensor & out); +}; + +struct TORCH_API clip_Tensor_out { + using schema = at::Tensor & (const at::Tensor &, const c10::optional &, const c10::optional &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::clip") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "clip.Tensor_out(Tensor self, Tensor? min=None, Tensor? max=None, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const c10::optional & min, const c10::optional & max, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const c10::optional & min, const c10::optional & max, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/49/49b6dfb5a22d4a021d733cd3f2a395f261f59ba743dda33612f464e2295ae82a/whiley.py b/shared/package-files/49/49b6dfb5a22d4a021d733cd3f2a395f261f59ba743dda33612f464e2295ae82a/whiley.py new file mode 100644 index 0000000000000000000000000000000000000000..bf707d25cc7b0da3a99b44af16cafd9a772d2abd --- /dev/null +++ b/shared/package-files/49/49b6dfb5a22d4a021d733cd3f2a395f261f59ba743dda33612f464e2295ae82a/whiley.py @@ -0,0 +1,116 @@ +""" + pygments.lexers.whiley + ~~~~~~~~~~~~~~~~~~~~~~ + + Lexers for the Whiley language. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.lexer import RegexLexer, bygroups, words +from pygments.token import Comment, Keyword, Name, Number, Operator, \ + Punctuation, String, Text + +__all__ = ['WhileyLexer'] + + +class WhileyLexer(RegexLexer): + """ + Lexer for the Whiley programming language. + + .. versionadded:: 2.2 + """ + name = 'Whiley' + url = 'http://whiley.org/' + filenames = ['*.whiley'] + aliases = ['whiley'] + mimetypes = ['text/x-whiley'] + + # See the language specification: + # http://whiley.org/download/WhileyLanguageSpec.pdf + + tokens = { + 'root': [ + # Whitespace + (r'\s+', Text), + + # Comments + (r'//.*', Comment.Single), + # don't parse empty comment as doc comment + (r'/\*\*/', Comment.Multiline), + (r'(?s)/\*\*.*?\*/', String.Doc), + (r'(?s)/\*.*?\*/', Comment.Multiline), + + # Keywords + (words(( + 'if', 'else', 'while', 'for', 'do', 'return', + 'switch', 'case', 'default', 'break', 'continue', + 'requires', 'ensures', 'where', 'assert', 'assume', + 'all', 'no', 'some', 'in', 'is', 'new', + 'throw', 'try', 'catch', 'debug', 'skip', 'fail', + 'finite', 'total'), suffix=r'\b'), Keyword.Reserved), + (words(( + 'function', 'method', 'public', 'private', 'protected', + 'export', 'native'), suffix=r'\b'), Keyword.Declaration), + # "constant" & "type" are not keywords unless used in declarations + (r'(constant|type)(\s+)([a-zA-Z_]\w*)(\s+)(is)\b', + bygroups(Keyword.Declaration, Text, Name, Text, Keyword.Reserved)), + (r'(true|false|null)\b', Keyword.Constant), + (r'(bool|byte|int|real|any|void)\b', Keyword.Type), + # "from" is not a keyword unless used with import + (r'(import)(\s+)(\*)([^\S\n]+)(from)\b', + bygroups(Keyword.Namespace, Text, Punctuation, Text, Keyword.Namespace)), + (r'(import)(\s+)([a-zA-Z_]\w*)([^\S\n]+)(from)\b', + bygroups(Keyword.Namespace, Text, Name, Text, Keyword.Namespace)), + (r'(package|import)\b', Keyword.Namespace), + + # standard library: https://github.com/Whiley/WhileyLibs/ + (words(( + # types defined in whiley.lang.Int + 'i8', 'i16', 'i32', 'i64', + 'u8', 'u16', 'u32', 'u64', + 'uint', 'nat', + + # whiley.lang.Any + 'toString'), suffix=r'\b'), Name.Builtin), + + # byte literal + (r'[01]+b', Number.Bin), + + # decimal literal + (r'[0-9]+\.[0-9]+', Number.Float), + # match "1." but not ranges like "3..5" + (r'[0-9]+\.(?!\.)', Number.Float), + + # integer literal + (r'0x[0-9a-fA-F]+', Number.Hex), + (r'[0-9]+', Number.Integer), + + # character literal + (r"""'[^\\]'""", String.Char), + (r"""(')(\\['"\\btnfr])(')""", + bygroups(String.Char, String.Escape, String.Char)), + + # string literal + (r'"', String, 'string'), + + # operators and punctuation + (r'[{}()\[\],.;]', Punctuation), + (r'[+\-*/%&|<>^!~@=:?' + # unicode operators + r'\u2200\u2203\u2205\u2282\u2286\u2283\u2287' + r'\u222A\u2229\u2264\u2265\u2208\u2227\u2228' + r']', Operator), + + # identifier + (r'[a-zA-Z_]\w*', Name), + ], + 'string': [ + (r'"', String, '#pop'), + (r'\\[btnfr]', String.Escape), + (r'\\u[0-9a-fA-F]{4}', String.Escape), + (r'\\.', String), + (r'[^\\"]+', String), + ], + } diff --git a/shared/package-files/49/49bc24d1b32ecc61c9aafae1383978ee0d07d27fcb88597b6183b08c71d61959/utils.pyi b/shared/package-files/49/49bc24d1b32ecc61c9aafae1383978ee0d07d27fcb88597b6183b08c71d61959/utils.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c715278665eba66b6ae64915e4635cba27ebcdbf --- /dev/null +++ b/shared/package-files/49/49bc24d1b32ecc61c9aafae1383978ee0d07d27fcb88597b6183b08c71d61959/utils.pyi @@ -0,0 +1,9 @@ +from typing import Any + +from django.http.request import HttpRequest +from django.utils.safestring import SafeText + +def csrf_input(request: HttpRequest) -> SafeText: ... + +csrf_input_lazy: Any +csrf_token_lazy: Any diff --git a/shared/package-files/49/49bea4849f30e0133bb3dd421133b98c3239e9df184a1cc9ca2f31b0d7d9fcd8/test_quantile.py b/shared/package-files/49/49bea4849f30e0133bb3dd421133b98c3239e9df184a1cc9ca2f31b0d7d9fcd8/test_quantile.py new file mode 100644 index 0000000000000000000000000000000000000000..3943590b069ad9a8e32bfd36ee849bb036c7865f --- /dev/null +++ b/shared/package-files/49/49bea4849f30e0133bb3dd421133b98c3239e9df184a1cc9ca2f31b0d7d9fcd8/test_quantile.py @@ -0,0 +1,496 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + DataFrame, + Index, +) +import pandas._testing as tm + + +@pytest.mark.parametrize( + "interpolation", ["linear", "lower", "higher", "nearest", "midpoint"] +) +@pytest.mark.parametrize( + "a_vals,b_vals", + [ + # Ints + ([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]), + ([1, 2, 3, 4], [4, 3, 2, 1]), + ([1, 2, 3, 4, 5], [4, 3, 2, 1]), + # Floats + ([1.0, 2.0, 3.0, 4.0, 5.0], [5.0, 4.0, 3.0, 2.0, 1.0]), + # Missing data + ([1.0, np.nan, 3.0, np.nan, 5.0], [5.0, np.nan, 3.0, np.nan, 1.0]), + ([np.nan, 4.0, np.nan, 2.0, np.nan], [np.nan, 4.0, np.nan, 2.0, np.nan]), + # Timestamps + ( + pd.date_range("1/1/18", freq="D", periods=5), + pd.date_range("1/1/18", freq="D", periods=5)[::-1], + ), + ( + pd.date_range("1/1/18", freq="D", periods=5).as_unit("s"), + pd.date_range("1/1/18", freq="D", periods=5)[::-1].as_unit("s"), + ), + # All NA + ([np.nan] * 5, [np.nan] * 5), + ], +) +@pytest.mark.parametrize("q", [0, 0.25, 0.5, 0.75, 1]) +def test_quantile(interpolation, a_vals, b_vals, q, request): + if ( + interpolation == "nearest" + and q == 0.5 + and isinstance(b_vals, list) + and b_vals == [4, 3, 2, 1] + ): + request.applymarker( + pytest.mark.xfail( + reason="Unclear numpy expectation for nearest " + "result with equidistant data" + ) + ) + all_vals = pd.concat([pd.Series(a_vals), pd.Series(b_vals)]) + + a_expected = pd.Series(a_vals).quantile(q, interpolation=interpolation) + b_expected = pd.Series(b_vals).quantile(q, interpolation=interpolation) + + df = DataFrame({"key": ["a"] * len(a_vals) + ["b"] * len(b_vals), "val": all_vals}) + + expected = DataFrame( + [a_expected, b_expected], columns=["val"], index=Index(["a", "b"], name="key") + ) + if all_vals.dtype.kind == "M" and expected.dtypes.values[0].kind == "M": + # TODO(non-nano): this should be unnecessary once array_to_datetime + # correctly infers non-nano from Timestamp.unit + expected = expected.astype(all_vals.dtype) + result = df.groupby("key").quantile(q, interpolation=interpolation) + + tm.assert_frame_equal(result, expected) + + +def test_quantile_array(): + # https://github.com/pandas-dev/pandas/issues/27526 + df = DataFrame({"A": [0, 1, 2, 3, 4]}) + key = np.array([0, 0, 1, 1, 1], dtype=np.int64) + result = df.groupby(key).quantile([0.25]) + + index = pd.MultiIndex.from_product([[0, 1], [0.25]]) + expected = DataFrame({"A": [0.25, 2.50]}, index=index) + tm.assert_frame_equal(result, expected) + + df = DataFrame({"A": [0, 1, 2, 3], "B": [4, 5, 6, 7]}) + index = pd.MultiIndex.from_product([[0, 1], [0.25, 0.75]]) + + key = np.array([0, 0, 1, 1], dtype=np.int64) + result = df.groupby(key).quantile([0.25, 0.75]) + expected = DataFrame( + {"A": [0.25, 0.75, 2.25, 2.75], "B": [4.25, 4.75, 6.25, 6.75]}, index=index + ) + tm.assert_frame_equal(result, expected) + + +def test_quantile_array2(): + # https://github.com/pandas-dev/pandas/pull/28085#issuecomment-524066959 + arr = np.random.default_rng(2).integers(0, 5, size=(10, 3), dtype=np.int64) + df = DataFrame(arr, columns=list("ABC")) + result = df.groupby("A").quantile([0.3, 0.7]) + expected = DataFrame( + { + "B": [2.0, 2.0, 2.3, 2.7, 0.3, 0.7, 3.2, 4.0, 0.3, 0.7], + "C": [1.0, 1.0, 1.9, 3.0999999999999996, 0.3, 0.7, 2.6, 3.0, 1.2, 2.8], + }, + index=pd.MultiIndex.from_product( + [[0, 1, 2, 3, 4], [0.3, 0.7]], names=["A", None] + ), + ) + tm.assert_frame_equal(result, expected) + + +def test_quantile_array_no_sort(): + df = DataFrame({"A": [0, 1, 2], "B": [3, 4, 5]}) + key = np.array([1, 0, 1], dtype=np.int64) + result = df.groupby(key, sort=False).quantile([0.25, 0.5, 0.75]) + expected = DataFrame( + {"A": [0.5, 1.0, 1.5, 1.0, 1.0, 1.0], "B": [3.5, 4.0, 4.5, 4.0, 4.0, 4.0]}, + index=pd.MultiIndex.from_product([[1, 0], [0.25, 0.5, 0.75]]), + ) + tm.assert_frame_equal(result, expected) + + result = df.groupby(key, sort=False).quantile([0.75, 0.25]) + expected = DataFrame( + {"A": [1.5, 0.5, 1.0, 1.0], "B": [4.5, 3.5, 4.0, 4.0]}, + index=pd.MultiIndex.from_product([[1, 0], [0.75, 0.25]]), + ) + tm.assert_frame_equal(result, expected) + + +def test_quantile_array_multiple_levels(): + df = DataFrame( + {"A": [0, 1, 2], "B": [3, 4, 5], "c": ["a", "a", "a"], "d": ["a", "a", "b"]} + ) + result = df.groupby(["c", "d"]).quantile([0.25, 0.75]) + index = pd.MultiIndex.from_tuples( + [("a", "a", 0.25), ("a", "a", 0.75), ("a", "b", 0.25), ("a", "b", 0.75)], + names=["c", "d", None], + ) + expected = DataFrame( + {"A": [0.25, 0.75, 2.0, 2.0], "B": [3.25, 3.75, 5.0, 5.0]}, index=index + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("frame_size", [(2, 3), (100, 10)]) +@pytest.mark.parametrize("groupby", [[0], [0, 1]]) +@pytest.mark.parametrize("q", [[0.5, 0.6]]) +def test_groupby_quantile_with_arraylike_q_and_int_columns(frame_size, groupby, q): + # GH30289 + nrow, ncol = frame_size + df = DataFrame(np.array([ncol * [_ % 4] for _ in range(nrow)]), columns=range(ncol)) + + idx_levels = [np.arange(min(nrow, 4))] * len(groupby) + [q] + idx_codes = [[x for x in range(min(nrow, 4)) for _ in q]] * len(groupby) + [ + list(range(len(q))) * min(nrow, 4) + ] + expected_index = pd.MultiIndex( + levels=idx_levels, codes=idx_codes, names=groupby + [None] + ) + expected_values = [ + [float(x)] * (ncol - len(groupby)) for x in range(min(nrow, 4)) for _ in q + ] + expected_columns = [x for x in range(ncol) if x not in groupby] + expected = DataFrame( + expected_values, index=expected_index, columns=expected_columns + ) + result = df.groupby(groupby).quantile(q) + + tm.assert_frame_equal(result, expected) + + +def test_quantile_raises(): + df = DataFrame([["foo", "a"], ["foo", "b"], ["foo", "c"]], columns=["key", "val"]) + + msg = "dtype '(object|str)' does not support operation 'quantile'" + with pytest.raises(TypeError, match=msg): + df.groupby("key").quantile() + + +def test_quantile_out_of_bounds_q_raises(): + # https://github.com/pandas-dev/pandas/issues/27470 + df = DataFrame({"a": [0, 0, 0, 1, 1, 1], "b": range(6)}) + g = df.groupby([0, 0, 0, 1, 1, 1]) + with pytest.raises(ValueError, match="Got '50.0' instead"): + g.quantile(50) + + with pytest.raises(ValueError, match="Got '-1.0' instead"): + g.quantile(-1) + + +def test_quantile_missing_group_values_no_segfaults(): + # GH 28662 + data = np.array([1.0, np.nan, 1.0]) + df = DataFrame({"key": data, "val": range(3)}) + + # Random segfaults; would have been guaranteed in loop + grp = df.groupby("key") + for _ in range(100): + grp.quantile() + + +@pytest.mark.parametrize( + "key, val, expected_key, expected_val", + [ + ([1.0, np.nan, 3.0, np.nan], range(4), [1.0, 3.0], [0.0, 2.0]), + ([1.0, np.nan, 2.0, 2.0], range(4), [1.0, 2.0], [0.0, 2.5]), + (["a", "b", "b", np.nan], range(4), ["a", "b"], [0, 1.5]), + ([0], [42], [0], [42.0]), + ([], [], np.array([], dtype="float64"), np.array([], dtype="float64")), + ], +) +def test_quantile_missing_group_values_correct_results( + key, val, expected_key, expected_val +): + # GH 28662, GH 33200, GH 33569 + df = DataFrame({"key": key, "val": val}) + + expected = DataFrame( + expected_val, index=Index(expected_key, name="key"), columns=["val"] + ) + + grp = df.groupby("key") + + result = grp.quantile(0.5) + tm.assert_frame_equal(result, expected) + + result = grp.quantile() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "values", + [ + pd.array([1, 0, None] * 2, dtype="Int64"), + pd.array([True, False, None] * 2, dtype="boolean"), + ], +) +@pytest.mark.parametrize("q", [0.5, [0.0, 0.5, 1.0]]) +def test_groupby_quantile_nullable_array(values, q): + # https://github.com/pandas-dev/pandas/issues/33136 + df = DataFrame({"a": ["x"] * 3 + ["y"] * 3, "b": values}) + result = df.groupby("a")["b"].quantile(q) + + if isinstance(q, list): + idx = pd.MultiIndex.from_product((["x", "y"], q), names=["a", None]) + true_quantiles = [0.0, 0.5, 1.0] + else: + idx = Index(["x", "y"], name="a") + true_quantiles = [0.5] + + expected = pd.Series(true_quantiles * 2, index=idx, name="b", dtype="Float64") + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("q", [0.5, [0.0, 0.5, 1.0]]) +@pytest.mark.parametrize("numeric_only", [True, False]) +def test_groupby_quantile_raises_on_invalid_dtype(q, numeric_only): + df = DataFrame({"a": [1], "b": [2.0], "c": ["x"]}) + if numeric_only: + result = df.groupby("a").quantile(q, numeric_only=numeric_only) + expected = df.groupby("a")[["b"]].quantile(q) + tm.assert_frame_equal(result, expected) + else: + msg = "dtype '.*' does not support operation 'quantile'" + with pytest.raises(TypeError, match=msg): + df.groupby("a").quantile(q, numeric_only=numeric_only) + + +def test_groupby_quantile_NA_float(any_float_dtype): + # GH#42849 + df = DataFrame({"x": [1, 1], "y": [0.2, np.nan]}, dtype=any_float_dtype) + result = df.groupby("x")["y"].quantile(0.5) + exp_index = Index([1.0], dtype=any_float_dtype, name="x") + + if any_float_dtype in ["Float32", "Float64"]: + expected_dtype = any_float_dtype + else: + expected_dtype = None + + expected = pd.Series([0.2], dtype=expected_dtype, index=exp_index, name="y") + tm.assert_series_equal(result, expected) + + result = df.groupby("x")["y"].quantile([0.5, 0.75]) + expected = pd.Series( + [0.2] * 2, + index=pd.MultiIndex.from_product((exp_index, [0.5, 0.75]), names=["x", None]), + name="y", + dtype=expected_dtype, + ) + tm.assert_series_equal(result, expected) + + +def test_groupby_quantile_NA_int(any_int_ea_dtype): + # GH#42849 + df = DataFrame({"x": [1, 1], "y": [2, 5]}, dtype=any_int_ea_dtype) + result = df.groupby("x")["y"].quantile(0.5) + expected = pd.Series( + [3.5], + dtype="Float64", + index=Index([1], name="x", dtype=any_int_ea_dtype), + name="y", + ) + tm.assert_series_equal(expected, result) + + result = df.groupby("x").quantile(0.5) + expected = DataFrame( + {"y": 3.5}, dtype="Float64", index=Index([1], name="x", dtype=any_int_ea_dtype) + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "interpolation, val1, val2", [("lower", 2, 2), ("higher", 2, 3), ("nearest", 2, 2)] +) +def test_groupby_quantile_all_na_group_masked( + interpolation, val1, val2, any_numeric_ea_dtype +): + # GH#37493 + df = DataFrame( + {"a": [1, 1, 1, 2], "b": [1, 2, 3, pd.NA]}, dtype=any_numeric_ea_dtype + ) + result = df.groupby("a").quantile(q=[0.5, 0.7], interpolation=interpolation) + expected = DataFrame( + {"b": [val1, val2, pd.NA, pd.NA]}, + dtype=any_numeric_ea_dtype, + index=pd.MultiIndex.from_arrays( + [pd.Series([1, 1, 2, 2], dtype=any_numeric_ea_dtype), [0.5, 0.7, 0.5, 0.7]], + names=["a", None], + ), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("interpolation", ["midpoint", "linear"]) +def test_groupby_quantile_all_na_group_masked_interp( + interpolation, any_numeric_ea_dtype +): + # GH#37493 + df = DataFrame( + {"a": [1, 1, 1, 2], "b": [1, 2, 3, pd.NA]}, dtype=any_numeric_ea_dtype + ) + result = df.groupby("a").quantile(q=[0.5, 0.75], interpolation=interpolation) + + if any_numeric_ea_dtype == "Float32": + expected_dtype = any_numeric_ea_dtype + else: + expected_dtype = "Float64" + + expected = DataFrame( + {"b": [2.0, 2.5, pd.NA, pd.NA]}, + dtype=expected_dtype, + index=pd.MultiIndex.from_arrays( + [ + pd.Series([1, 1, 2, 2], dtype=any_numeric_ea_dtype), + [0.5, 0.75, 0.5, 0.75], + ], + names=["a", None], + ), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("dtype", ["Float64", "Float32"]) +def test_groupby_quantile_allNA_column(dtype): + # GH#42849 + df = DataFrame({"x": [1, 1], "y": [pd.NA] * 2}, dtype=dtype) + result = df.groupby("x")["y"].quantile(0.5) + expected = pd.Series( + [np.nan], dtype=dtype, index=Index([1.0], dtype=dtype), name="y" + ) + expected.index.name = "x" + tm.assert_series_equal(expected, result) + + +def test_groupby_timedelta_quantile(): + # GH: 29485 + df = DataFrame( + {"value": pd.to_timedelta(np.arange(4), unit="s"), "group": [1, 1, 2, 2]} + ) + result = df.groupby("group").quantile(0.99) + expected = DataFrame( + { + "value": [ + pd.Timedelta("0 days 00:00:00.990000"), + pd.Timedelta("0 days 00:00:02.990000"), + ] + }, + index=Index([1, 2], name="group"), + ) + tm.assert_frame_equal(result, expected) + + +def test_columns_groupby_quantile(): + # GH 33795 + df = DataFrame( + np.arange(12).reshape(3, -1), + index=list("XYZ"), + columns=pd.Series(list("ABAB"), name="col"), + ) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby("col", axis=1) + result = gb.quantile(q=[0.8, 0.2]) + expected = DataFrame( + [ + [1.6, 0.4, 2.6, 1.4], + [5.6, 4.4, 6.6, 5.4], + [9.6, 8.4, 10.6, 9.4], + ], + index=list("XYZ"), + columns=pd.MultiIndex.from_tuples( + [("A", 0.8), ("A", 0.2), ("B", 0.8), ("B", 0.2)], names=["col", None] + ), + ) + + tm.assert_frame_equal(result, expected) + + +def test_timestamp_groupby_quantile(unit): + # GH 33168 + dti = pd.date_range( + start="2020-04-19 00:00:00", freq="1min", periods=100, tz="UTC", unit=unit + ).floor("1h") + df = DataFrame( + { + "timestamp": dti, + "category": list(range(1, 101)), + "value": list(range(101, 201)), + } + ) + + result = df.groupby("timestamp").quantile([0.2, 0.8]) + + mi = pd.MultiIndex.from_product([dti[::99], [0.2, 0.8]], names=("timestamp", None)) + expected = DataFrame( + [ + {"category": 12.8, "value": 112.8}, + {"category": 48.2, "value": 148.2}, + {"category": 68.8, "value": 168.8}, + {"category": 92.2, "value": 192.2}, + ], + index=mi, + ) + + tm.assert_frame_equal(result, expected) + + +def test_groupby_quantile_dt64tz_period(): + # GH#51373 + dti = pd.date_range("2016-01-01", periods=1000) + df = pd.Series(dti).to_frame().copy() + df[1] = dti.tz_localize("US/Pacific") + df[2] = dti.to_period("D") + df[3] = dti - dti[0] + df.iloc[-1] = pd.NaT + + by = np.tile(np.arange(5), 200) + gb = df.groupby(by) + + result = gb.quantile(0.5) + + # Check that we match the group-by-group result + exp = {i: df.iloc[i::5].quantile(0.5) for i in range(5)} + expected = DataFrame(exp).T.infer_objects() + expected.index = expected.index.astype(int) + + tm.assert_frame_equal(result, expected) + + +def test_groupby_quantile_nonmulti_levels_order(): + # Non-regression test for GH #53009 + ind = pd.MultiIndex.from_tuples( + [ + (0, "a", "B"), + (0, "a", "A"), + (0, "b", "B"), + (0, "b", "A"), + (1, "a", "B"), + (1, "a", "A"), + (1, "b", "B"), + (1, "b", "A"), + ], + names=["sample", "cat0", "cat1"], + ) + ser = pd.Series(range(8), index=ind) + result = ser.groupby(level="cat1", sort=False).quantile([0.2, 0.8]) + + qind = pd.MultiIndex.from_tuples( + [("B", 0.2), ("B", 0.8), ("A", 0.2), ("A", 0.8)], names=["cat1", None] + ) + expected = pd.Series([1.2, 4.8, 2.2, 5.8], index=qind) + + tm.assert_series_equal(result, expected) + + # We need to check that index levels are not sorted + expected_levels = pd.core.indexes.frozen.FrozenList([["B", "A"], [0.2, 0.8]]) + tm.assert_equal(result.index.levels, expected_levels) diff --git a/shared/package-files/49/49bf60f3d063a1fab43827cd510942deb7ef1f2184fffcd6897036caf3e189bf/__init__.py b/shared/package-files/49/49bf60f3d063a1fab43827cd510942deb7ef1f2184fffcd6897036caf3e189bf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8e0a1125ef04198083da041736a7ebc2ffeafe6a --- /dev/null +++ b/shared/package-files/49/49bf60f3d063a1fab43827cd510942deb7ef1f2184fffcd6897036caf3e189bf/__init__.py @@ -0,0 +1,16 @@ +"""Tools for model inspection.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from ._partial_dependence import partial_dependence +from ._permutation_importance import permutation_importance +from ._plot.decision_boundary import DecisionBoundaryDisplay +from ._plot.partial_dependence import PartialDependenceDisplay + +__all__ = [ + "DecisionBoundaryDisplay", + "PartialDependenceDisplay", + "partial_dependence", + "permutation_importance", +] diff --git a/shared/package-files/49/49c1ed9e89edca6443367f6a1080b49deb9ee667c6f36ca107c6f011339bd19e/__init__.py b/shared/package-files/49/49c1ed9e89edca6443367f6a1080b49deb9ee667c6f36ca107c6f011339bd19e/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a3dbc29a6a840214338e63074703b6f74debdc05 --- /dev/null +++ b/shared/package-files/49/49c1ed9e89edca6443367f6a1080b49deb9ee667c6f36ca107c6f011339bd19e/__init__.py @@ -0,0 +1,4 @@ +from . import ffmpeg_utils + + +__all__ = ["ffmpeg_utils"] diff --git a/shared/package-files/49/49c4ca7ed10d7bbf2299b31cd08e68b8194831c10499982ef0754a58030daf9f/testfunc_7.4_GLNX86.mat b/shared/package-files/49/49c4ca7ed10d7bbf2299b31cd08e68b8194831c10499982ef0754a58030daf9f/testfunc_7.4_GLNX86.mat new file mode 100644 index 0000000000000000000000000000000000000000..adb6c28ee95d1cf8bf3bfeb72295d1a7848020f8 Binary files /dev/null and b/shared/package-files/49/49c4ca7ed10d7bbf2299b31cd08e68b8194831c10499982ef0754a58030daf9f/testfunc_7.4_GLNX86.mat differ diff --git a/shared/package-files/49/49cd3af89f0951acdd7d1dfa51a98784f9dd2683cad0590ecc747eba71d6a01c/zeros.py b/shared/package-files/49/49cd3af89f0951acdd7d1dfa51a98784f9dd2683cad0590ecc747eba71d6a01c/zeros.py new file mode 100644 index 0000000000000000000000000000000000000000..907d49d37fc1e7476e81a25dbbc0d3910cbbe004 --- /dev/null +++ b/shared/package-files/49/49cd3af89f0951acdd7d1dfa51a98784f9dd2683cad0590ecc747eba71d6a01c/zeros.py @@ -0,0 +1,26 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'RootResults', + 'bisect', + 'brenth', + 'brentq', + 'newton', + 'ridder', + 'toms748', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="zeros", + private_modules=["_zeros_py"], all=__all__, + attribute=name) diff --git a/shared/package-files/49/49cf452eef0b8970bc56a7b8e040ba088215508228a77032cba0035522412f86/cs.msg b/shared/package-files/49/49cf452eef0b8970bc56a7b8e040ba088215508228a77032cba0035522412f86/cs.msg new file mode 100644 index 0000000000000000000000000000000000000000..8db8bdd86f6079a48a5f7f15ac9e6923d2a76532 --- /dev/null +++ b/shared/package-files/49/49cf452eef0b8970bc56a7b8e040ba088215508228a77032cba0035522412f86/cs.msg @@ -0,0 +1,54 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset cs DAYS_OF_WEEK_ABBREV [list \ + "Ne"\ + "Po"\ + "\u00dat"\ + "St"\ + "\u010ct"\ + "P\u00e1"\ + "So"] + ::msgcat::mcset cs DAYS_OF_WEEK_FULL [list \ + "Ned\u011ble"\ + "Pond\u011bl\u00ed"\ + "\u00dater\u00fd"\ + "St\u0159eda"\ + "\u010ctvrtek"\ + "P\u00e1tek"\ + "Sobota"] + ::msgcat::mcset cs MONTHS_ABBREV [list \ + "I"\ + "II"\ + "III"\ + "IV"\ + "V"\ + "VI"\ + "VII"\ + "VIII"\ + "IX"\ + "X"\ + "XI"\ + "XII"\ + ""] + ::msgcat::mcset cs MONTHS_FULL [list \ + "leden"\ + "\u00fanor"\ + "b\u0159ezen"\ + "duben"\ + "kv\u011bten"\ + "\u010derven"\ + "\u010dervenec"\ + "srpen"\ + "z\u00e1\u0159\u00ed"\ + "\u0159\u00edjen"\ + "listopad"\ + "prosinec"\ + ""] + ::msgcat::mcset cs BCE "p\u0159.Kr." + ::msgcat::mcset cs CE "po Kr." + ::msgcat::mcset cs AM "dop." + ::msgcat::mcset cs PM "odp." + ::msgcat::mcset cs DATE_FORMAT "%e.%m.%Y" + ::msgcat::mcset cs TIME_FORMAT "%k:%M:%S" + ::msgcat::mcset cs DATE_TIME_FORMAT "%e.%m.%Y %k:%M:%S %z" +} diff --git a/shared/package-files/49/49d333ce04e2cd0f3cc09051553995220c44f04db4fec80b16e9cfdd61e59195/test_calendar.py b/shared/package-files/49/49d333ce04e2cd0f3cc09051553995220c44f04db4fec80b16e9cfdd61e59195/test_calendar.py new file mode 100644 index 0000000000000000000000000000000000000000..99829857e68363ec845dd9dff3d90917c31adaa0 --- /dev/null +++ b/shared/package-files/49/49d333ce04e2cd0f3cc09051553995220c44f04db4fec80b16e9cfdd61e59195/test_calendar.py @@ -0,0 +1,119 @@ +from datetime import datetime + +import pytest + +from pandas import ( + DatetimeIndex, + offsets, + to_datetime, +) +import pandas._testing as tm + +from pandas.tseries.holiday import ( + AbstractHolidayCalendar, + Holiday, + Timestamp, + USFederalHolidayCalendar, + USLaborDay, + USThanksgivingDay, + get_calendar, +) + + +@pytest.mark.parametrize( + "transform", [lambda x: x, lambda x: x.strftime("%Y-%m-%d"), lambda x: Timestamp(x)] +) +def test_calendar(transform): + start_date = datetime(2012, 1, 1) + end_date = datetime(2012, 12, 31) + + calendar = USFederalHolidayCalendar() + holidays = calendar.holidays(transform(start_date), transform(end_date)) + + expected = [ + datetime(2012, 1, 2), + datetime(2012, 1, 16), + datetime(2012, 2, 20), + datetime(2012, 5, 28), + datetime(2012, 7, 4), + datetime(2012, 9, 3), + datetime(2012, 10, 8), + datetime(2012, 11, 12), + datetime(2012, 11, 22), + datetime(2012, 12, 25), + ] + + assert list(holidays.to_pydatetime()) == expected + + +def test_calendar_caching(): + # see gh-9552. + + class TestCalendar(AbstractHolidayCalendar): + def __init__(self, name=None, rules=None) -> None: + super().__init__(name=name, rules=rules) + + jan1 = TestCalendar(rules=[Holiday("jan1", year=2015, month=1, day=1)]) + jan2 = TestCalendar(rules=[Holiday("jan2", year=2015, month=1, day=2)]) + + # Getting holidays for Jan 1 should not alter results for Jan 2. + expected = DatetimeIndex(["01-Jan-2015"]).as_unit("ns") + tm.assert_index_equal(jan1.holidays(), expected) + + expected2 = DatetimeIndex(["02-Jan-2015"]).as_unit("ns") + tm.assert_index_equal(jan2.holidays(), expected2) + + +def test_calendar_observance_dates(): + # see gh-11477 + us_fed_cal = get_calendar("USFederalHolidayCalendar") + holidays0 = us_fed_cal.holidays( + datetime(2015, 7, 3), datetime(2015, 7, 3) + ) # <-- same start and end dates + holidays1 = us_fed_cal.holidays( + datetime(2015, 7, 3), datetime(2015, 7, 6) + ) # <-- different start and end dates + holidays2 = us_fed_cal.holidays( + datetime(2015, 7, 3), datetime(2015, 7, 3) + ) # <-- same start and end dates + + # These should all produce the same result. + # + # In addition, calling with different start and end + # dates should not alter the output if we call the + # function again with the same start and end date. + tm.assert_index_equal(holidays0, holidays1) + tm.assert_index_equal(holidays0, holidays2) + + +def test_rule_from_name(): + us_fed_cal = get_calendar("USFederalHolidayCalendar") + assert us_fed_cal.rule_from_name("Thanksgiving Day") == USThanksgivingDay + + +def test_calendar_2031(): + # See gh-27790 + # + # Labor Day 2031 is on September 1. Saturday before is August 30. + # Next working day after August 30 ought to be Tuesday, September 2. + + class testCalendar(AbstractHolidayCalendar): + rules = [USLaborDay] + + cal = testCalendar() + workDay = offsets.CustomBusinessDay(calendar=cal) + Sat_before_Labor_Day_2031 = to_datetime("2031-08-30") + next_working_day = Sat_before_Labor_Day_2031 + 0 * workDay + assert next_working_day == to_datetime("2031-09-02") + + +def test_no_holidays_calendar(): + # Test for issue #31415 + + class NoHolidaysCalendar(AbstractHolidayCalendar): + pass + + cal = NoHolidaysCalendar() + holidays = cal.holidays(Timestamp("01-Jan-2020"), Timestamp("01-Jan-2021")) + empty_index = DatetimeIndex([]) # Type is DatetimeIndex since return_name=False + tm.assert_index_equal(holidays, empty_index) diff --git a/shared/package-files/49/49d6d4b8214aa53e89b159997c553d737fcd1eb5e1133e0eb4c99b59e9ba788f/server.py b/shared/package-files/49/49d6d4b8214aa53e89b159997c553d737fcd1eb5e1133e0eb4c99b59e9ba788f/server.py new file mode 100644 index 0000000000000000000000000000000000000000..9a5d4022a006cf6fef64df77a4d06f20d2c6b3b4 --- /dev/null +++ b/shared/package-files/49/49d6d4b8214aa53e89b159997c553d737fcd1eb5e1133e0eb4c99b59e9ba788f/server.py @@ -0,0 +1,177 @@ +""" +Utility for running a prompt_toolkit application in an asyncssh server. +""" +from __future__ import annotations + +import asyncio +import traceback +from asyncio import get_running_loop +from typing import Any, Callable, Coroutine, TextIO, cast + +import asyncssh + +from prompt_toolkit.application.current import AppSession, create_app_session +from prompt_toolkit.data_structures import Size +from prompt_toolkit.input import PipeInput, create_pipe_input +from prompt_toolkit.output.vt100 import Vt100_Output + +__all__ = ["PromptToolkitSSHSession", "PromptToolkitSSHServer"] + + +class PromptToolkitSSHSession(asyncssh.SSHServerSession): # type: ignore + def __init__( + self, + interact: Callable[[PromptToolkitSSHSession], Coroutine[Any, Any, None]], + *, + enable_cpr: bool, + ) -> None: + self.interact = interact + self.enable_cpr = enable_cpr + self.interact_task: asyncio.Task[None] | None = None + self._chan: Any | None = None + self.app_session: AppSession | None = None + + # PipInput object, for sending input in the CLI. + # (This is something that we can use in the prompt_toolkit event loop, + # but still write date in manually.) + self._input: PipeInput | None = None + self._output: Vt100_Output | None = None + + # Output object. Don't render to the real stdout, but write everything + # in the SSH channel. + class Stdout: + def write(s, data: str) -> None: + try: + if self._chan is not None: + self._chan.write(data.replace("\n", "\r\n")) + except BrokenPipeError: + pass # Channel not open for sending. + + def isatty(s) -> bool: + return True + + def flush(s) -> None: + pass + + @property + def encoding(s) -> str: + assert self._chan is not None + return str(self._chan._orig_chan.get_encoding()[0]) + + self.stdout = cast(TextIO, Stdout()) + + def _get_size(self) -> Size: + """ + Callable that returns the current `Size`, required by Vt100_Output. + """ + if self._chan is None: + return Size(rows=20, columns=79) + else: + width, height, pixwidth, pixheight = self._chan.get_terminal_size() + return Size(rows=height, columns=width) + + def connection_made(self, chan: Any) -> None: + self._chan = chan + + def shell_requested(self) -> bool: + return True + + def session_started(self) -> None: + self.interact_task = get_running_loop().create_task(self._interact()) + + async def _interact(self) -> None: + if self._chan is None: + # Should not happen. + raise Exception("`_interact` called before `connection_made`.") + + if hasattr(self._chan, "set_line_mode") and self._chan._editor is not None: + # Disable the line editing provided by asyncssh. Prompt_toolkit + # provides the line editing. + self._chan.set_line_mode(False) + + term = self._chan.get_terminal_type() + + self._output = Vt100_Output( + self.stdout, self._get_size, term=term, enable_cpr=self.enable_cpr + ) + + with create_pipe_input() as self._input: + with create_app_session(input=self._input, output=self._output) as session: + self.app_session = session + try: + await self.interact(self) + except BaseException: + traceback.print_exc() + finally: + # Close the connection. + self._chan.close() + self._input.close() + + def terminal_size_changed( + self, width: int, height: int, pixwidth: object, pixheight: object + ) -> None: + # Send resize event to the current application. + if self.app_session and self.app_session.app: + self.app_session.app._on_resize() + + def data_received(self, data: str, datatype: object) -> None: + if self._input is None: + # Should not happen. + return + + self._input.send_text(data) + + +class PromptToolkitSSHServer(asyncssh.SSHServer): + """ + Run a prompt_toolkit application over an asyncssh server. + + This takes one argument, an `interact` function, which is called for each + connection. This should be an asynchronous function that runs the + prompt_toolkit applications. This function runs in an `AppSession`, which + means that we can have multiple UI interactions concurrently. + + Example usage: + + .. code:: python + + async def interact(ssh_session: PromptToolkitSSHSession) -> None: + await yes_no_dialog("my title", "my text").run_async() + + prompt_session = PromptSession() + text = await prompt_session.prompt_async("Type something: ") + print_formatted_text('You said: ', text) + + server = PromptToolkitSSHServer(interact=interact) + loop = get_running_loop() + loop.run_until_complete( + asyncssh.create_server( + lambda: MySSHServer(interact), + "", + port, + server_host_keys=["/etc/ssh/..."], + ) + ) + loop.run_forever() + + :param enable_cpr: When `True`, the default, try to detect whether the SSH + client runs in a terminal that responds to "cursor position requests". + That way, we can properly determine how much space there is available + for the UI (especially for drop down menus) to render. + """ + + def __init__( + self, + interact: Callable[[PromptToolkitSSHSession], Coroutine[Any, Any, None]], + *, + enable_cpr: bool = True, + ) -> None: + self.interact = interact + self.enable_cpr = enable_cpr + + def begin_auth(self, username: str) -> bool: + # No authentication. + return False + + def session_requested(self) -> PromptToolkitSSHSession: + return PromptToolkitSSHSession(self.interact, enable_cpr=self.enable_cpr) diff --git a/shared/package-files/49/49dd7851945f91309784d330d24cd28bdfd736da7f93048177e9003e7a545ab6/abs_compositeexplicitautograd_dispatch.h b/shared/package-files/49/49dd7851945f91309784d330d24cd28bdfd736da7f93048177e9003e7a545ab6/abs_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..525396d407c731a5137f91f307b58e6d620e097f --- /dev/null +++ b/shared/package-files/49/49dd7851945f91309784d330d24cd28bdfd736da7f93048177e9003e7a545ab6/abs_compositeexplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor abs(const at::Tensor & self); +TORCH_API at::Tensor & abs_(at::Tensor & self); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/49/49ead4c7e2d6388645c378babb1590f4a9095f99f7056649645b7a9442c7d531/_missing.py b/shared/package-files/49/49ead4c7e2d6388645c378babb1590f4a9095f99f7056649645b7a9442c7d531/_missing.py new file mode 100644 index 0000000000000000000000000000000000000000..daeb9ba68cc1cc0a73cb5f1ce19bd8eff13045b9 --- /dev/null +++ b/shared/package-files/49/49ead4c7e2d6388645c378babb1590f4a9095f99f7056649645b7a9442c7d531/_missing.py @@ -0,0 +1,68 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import math +import numbers +from contextlib import suppress + + +def is_scalar_nan(x): + """Test if x is NaN. + + This function is meant to overcome the issue that np.isnan does not allow + non-numerical types as input, and that np.nan is not float('nan'). + + Parameters + ---------- + x : any type + Any scalar value. + + Returns + ------- + bool + Returns true if x is NaN, and false otherwise. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.utils._missing import is_scalar_nan + >>> is_scalar_nan(np.nan) + True + >>> is_scalar_nan(float("nan")) + True + >>> is_scalar_nan(None) + False + >>> is_scalar_nan("") + False + >>> is_scalar_nan([np.nan]) + False + """ + return ( + not isinstance(x, numbers.Integral) + and isinstance(x, numbers.Real) + and math.isnan(x) + ) + + +def is_pandas_na(x): + """Test if x is pandas.NA. + + We intentionally do not use this function to return `True` for `pd.NA` in + `is_scalar_nan`, because estimators that support `pd.NA` are the exception + rather than the rule at the moment. When `pd.NA` is more universally + supported, we may reconsider this decision. + + Parameters + ---------- + x : any type + + Returns + ------- + boolean + """ + with suppress(ImportError): + from pandas import NA + + return x is NA + + return False diff --git a/shared/package-files/49/49f08eab56fca2d13a8a7e27b271f49b429bca5da36d66b11b0701a1e6a94c79/relativedelta.pyi b/shared/package-files/49/49f08eab56fca2d13a8a7e27b271f49b429bca5da36d66b11b0701a1e6a94c79/relativedelta.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a0de3e7fd549afe95c9d5bf6322238d573772f5e --- /dev/null +++ b/shared/package-files/49/49f08eab56fca2d13a8a7e27b271f49b429bca5da36d66b11b0701a1e6a94c79/relativedelta.pyi @@ -0,0 +1,97 @@ +from datetime import date, datetime, timedelta +from typing import Optional, SupportsFloat, TypeVar, Union, overload + +from ._common import weekday + +_SelfT = TypeVar("_SelfT", bound=relativedelta) +_DateT = TypeVar("_DateT", date, datetime) +# Work around attribute and type having the same name. +_weekday = weekday + +MO: weekday +TU: weekday +WE: weekday +TH: weekday +FR: weekday +SA: weekday +SU: weekday + +class relativedelta(object): + years: int + months: int + days: int + leapdays: int + hours: int + minutes: int + seconds: int + microseconds: int + year: Optional[int] + month: Optional[int] + weekday: Optional[_weekday] + day: Optional[int] + hour: Optional[int] + minute: Optional[int] + second: Optional[int] + microsecond: Optional[int] + def __init__( + self, + dt1: Optional[date] = ..., + dt2: Optional[date] = ..., + years: Optional[int] = ..., + months: Optional[int] = ..., + days: Optional[int] = ..., + leapdays: Optional[int] = ..., + weeks: Optional[int] = ..., + hours: Optional[int] = ..., + minutes: Optional[int] = ..., + seconds: Optional[int] = ..., + microseconds: Optional[int] = ..., + year: Optional[int] = ..., + month: Optional[int] = ..., + day: Optional[int] = ..., + weekday: Optional[Union[int, _weekday]] = ..., + yearday: Optional[int] = ..., + nlyearday: Optional[int] = ..., + hour: Optional[int] = ..., + minute: Optional[int] = ..., + second: Optional[int] = ..., + microsecond: Optional[int] = ..., + ) -> None: ... + @property + def weeks(self) -> int: ... + @weeks.setter + def weeks(self, value: int) -> None: ... + def normalized(self: _SelfT) -> _SelfT: ... + # TODO: use Union when mypy will handle it properly in overloaded operator + # methods (#2129, #1442, #1264 in mypy) + @overload + def __add__(self: _SelfT, other: relativedelta) -> _SelfT: ... + @overload + def __add__(self: _SelfT, other: timedelta) -> _SelfT: ... + @overload + def __add__(self, other: _DateT) -> _DateT: ... + @overload + def __radd__(self: _SelfT, other: relativedelta) -> _SelfT: ... + @overload + def __radd__(self: _SelfT, other: timedelta) -> _SelfT: ... + @overload + def __radd__(self, other: _DateT) -> _DateT: ... + @overload + def __rsub__(self: _SelfT, other: relativedelta) -> _SelfT: ... + @overload + def __rsub__(self: _SelfT, other: timedelta) -> _SelfT: ... + @overload + def __rsub__(self, other: _DateT) -> _DateT: ... + def __sub__(self: _SelfT, other: relativedelta) -> _SelfT: ... + def __neg__(self: _SelfT) -> _SelfT: ... + def __bool__(self) -> bool: ... + def __nonzero__(self) -> bool: ... + def __mul__(self: _SelfT, other: SupportsFloat) -> _SelfT: ... + def __rmul__(self: _SelfT, other: SupportsFloat) -> _SelfT: ... + def __eq__(self, other) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __div__(self: _SelfT, other: SupportsFloat) -> _SelfT: ... + def __truediv__(self: _SelfT, other: SupportsFloat) -> _SelfT: ... + def __repr__(self) -> str: ... + def __abs__(self: _SelfT) -> _SelfT: ... + def __hash__(self) -> int: ... diff --git a/shared/package-files/49/49fc2b10403fd3dd6d9b2238bcddc134bb3bca9527ac5fd56d383a80f97ea1cb/cpu_asimdhp.c b/shared/package-files/49/49fc2b10403fd3dd6d9b2238bcddc134bb3bca9527ac5fd56d383a80f97ea1cb/cpu_asimdhp.c new file mode 100644 index 0000000000000000000000000000000000000000..e2de0306e0acaeda3b861756e598a132f8e1ca9f --- /dev/null +++ b/shared/package-files/49/49fc2b10403fd3dd6d9b2238bcddc134bb3bca9527ac5fd56d383a80f97ea1cb/cpu_asimdhp.c @@ -0,0 +1,15 @@ +#ifdef _MSC_VER + #include +#endif +#include + +int main(int argc, char **argv) +{ + float16_t *src = (float16_t*)argv[argc-1]; + float16x8_t vhp = vdupq_n_f16(src[0]); + float16x4_t vlhp = vdup_n_f16(src[1]); + + int ret = (int)vgetq_lane_f16(vabdq_f16(vhp, vhp), 0); + ret += (int)vget_lane_f16(vabd_f16(vlhp, vlhp), 0); + return ret; +} diff --git a/shared/package-files/49/49fd901c12df130f4a5b1fca6425e1340ca498308ecd757b0e3ddc0e9fe7cc44/libtbbmalloc_proxy.so.2 b/shared/package-files/49/49fd901c12df130f4a5b1fca6425e1340ca498308ecd757b0e3ddc0e9fe7cc44/libtbbmalloc_proxy.so.2 new file mode 100644 index 0000000000000000000000000000000000000000..a5952c616780897fb28eb687c1632f53bcbad357 Binary files /dev/null and b/shared/package-files/49/49fd901c12df130f4a5b1fca6425e1340ca498308ecd757b0e3ddc0e9fe7cc44/libtbbmalloc_proxy.so.2 differ diff --git a/shared/package-files/49/49fd901c12df130f4a5b1fca6425e1340ca498308ecd757b0e3ddc0e9fe7cc44/libtbbmalloc_proxy.so.2.8 b/shared/package-files/49/49fd901c12df130f4a5b1fca6425e1340ca498308ecd757b0e3ddc0e9fe7cc44/libtbbmalloc_proxy.so.2.8 new file mode 100644 index 0000000000000000000000000000000000000000..a5952c616780897fb28eb687c1632f53bcbad357 Binary files /dev/null and b/shared/package-files/49/49fd901c12df130f4a5b1fca6425e1340ca498308ecd757b0e3ddc0e9fe7cc44/libtbbmalloc_proxy.so.2.8 differ diff --git a/shared/package-files/6b/6b006327b67f67c4a4b262cf774977a880d3a8d59a020548ecf3a71712b3edf3/_apply_pyprojecttoml.py b/shared/package-files/6b/6b006327b67f67c4a4b262cf774977a880d3a8d59a020548ecf3a71712b3edf3/_apply_pyprojecttoml.py new file mode 100644 index 0000000000000000000000000000000000000000..4489d2243764491d2ade89e6fb21ebe5e11ca584 --- /dev/null +++ b/shared/package-files/6b/6b006327b67f67c4a4b262cf774977a880d3a8d59a020548ecf3a71712b3edf3/_apply_pyprojecttoml.py @@ -0,0 +1,416 @@ +"""Translation layer between pyproject config and setuptools distribution and +metadata objects. + +The distribution and metadata objects are modeled after (an old version of) +core metadata, therefore configs in the format specified for ``pyproject.toml`` +need to be processed before being applied. + +**PRIVATE MODULE**: API reserved for setuptools internal usage only. +""" +import logging +import os +from collections.abc import Mapping +from email.headerregistry import Address +from functools import partial, reduce +from itertools import chain +from types import MappingProxyType +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + List, + Optional, + Set, + Tuple, + Type, + Union, + cast, +) + +from ..warnings import SetuptoolsWarning, SetuptoolsDeprecationWarning + +if TYPE_CHECKING: + from setuptools._importlib import metadata # noqa + from setuptools.dist import Distribution # noqa + +EMPTY: Mapping = MappingProxyType({}) # Immutable dict-like +_Path = Union[os.PathLike, str] +_DictOrStr = Union[dict, str] +_CorrespFn = Callable[["Distribution", Any, _Path], None] +_Correspondence = Union[str, _CorrespFn] + +_logger = logging.getLogger(__name__) + + +def apply(dist: "Distribution", config: dict, filename: _Path) -> "Distribution": + """Apply configuration dict read with :func:`read_configuration`""" + + if not config: + return dist # short-circuit unrelated pyproject.toml file + + root_dir = os.path.dirname(filename) or "." + + _apply_project_table(dist, config, root_dir) + _apply_tool_table(dist, config, filename) + + current_directory = os.getcwd() + os.chdir(root_dir) + try: + dist._finalize_requires() + dist._finalize_license_files() + finally: + os.chdir(current_directory) + + return dist + + +def _apply_project_table(dist: "Distribution", config: dict, root_dir: _Path): + project_table = config.get("project", {}).copy() + if not project_table: + return # short-circuit + + _handle_missing_dynamic(dist, project_table) + _unify_entry_points(project_table) + + for field, value in project_table.items(): + norm_key = json_compatible_key(field) + corresp = PYPROJECT_CORRESPONDENCE.get(norm_key, norm_key) + if callable(corresp): + corresp(dist, value, root_dir) + else: + _set_config(dist, corresp, value) + + +def _apply_tool_table(dist: "Distribution", config: dict, filename: _Path): + tool_table = config.get("tool", {}).get("setuptools", {}) + if not tool_table: + return # short-circuit + + for field, value in tool_table.items(): + norm_key = json_compatible_key(field) + + if norm_key in TOOL_TABLE_DEPRECATIONS: + suggestion, kwargs = TOOL_TABLE_DEPRECATIONS[norm_key] + msg = f"The parameter `{norm_key}` is deprecated, {suggestion}" + SetuptoolsDeprecationWarning.emit( + "Deprecated config", msg, **kwargs # type: ignore + ) + + norm_key = TOOL_TABLE_RENAMES.get(norm_key, norm_key) + _set_config(dist, norm_key, value) + + _copy_command_options(config, dist, filename) + + +def _handle_missing_dynamic(dist: "Distribution", project_table: dict): + """Be temporarily forgiving with ``dynamic`` fields not listed in ``dynamic``""" + # TODO: Set fields back to `None` once the feature stabilizes + dynamic = set(project_table.get("dynamic", [])) + for field, getter in _PREVIOUSLY_DEFINED.items(): + if not (field in project_table or field in dynamic): + value = getter(dist) + if value: + _WouldIgnoreField.emit(field=field, value=value) + + +def json_compatible_key(key: str) -> str: + """As defined in :pep:`566#json-compatible-metadata`""" + return key.lower().replace("-", "_") + + +def _set_config(dist: "Distribution", field: str, value: Any): + setter = getattr(dist.metadata, f"set_{field}", None) + if setter: + setter(value) + elif hasattr(dist.metadata, field) or field in SETUPTOOLS_PATCHES: + setattr(dist.metadata, field, value) + else: + setattr(dist, field, value) + + +_CONTENT_TYPES = { + ".md": "text/markdown", + ".rst": "text/x-rst", + ".txt": "text/plain", +} + + +def _guess_content_type(file: str) -> Optional[str]: + _, ext = os.path.splitext(file.lower()) + if not ext: + return None + + if ext in _CONTENT_TYPES: + return _CONTENT_TYPES[ext] + + valid = ", ".join(f"{k} ({v})" for k, v in _CONTENT_TYPES.items()) + msg = f"only the following file extensions are recognized: {valid}." + raise ValueError(f"Undefined content type for {file}, {msg}") + + +def _long_description(dist: "Distribution", val: _DictOrStr, root_dir: _Path): + from setuptools.config import expand + + if isinstance(val, str): + file: Union[str, list] = val + text = expand.read_files(file, root_dir) + ctype = _guess_content_type(val) + else: + file = val.get("file") or [] + text = val.get("text") or expand.read_files(file, root_dir) + ctype = val["content-type"] + + _set_config(dist, "long_description", text) + + if ctype: + _set_config(dist, "long_description_content_type", ctype) + + if file: + dist._referenced_files.add(cast(str, file)) + + +def _license(dist: "Distribution", val: dict, root_dir: _Path): + from setuptools.config import expand + + if "file" in val: + _set_config(dist, "license", expand.read_files([val["file"]], root_dir)) + dist._referenced_files.add(val["file"]) + else: + _set_config(dist, "license", val["text"]) + + +def _people(dist: "Distribution", val: List[dict], _root_dir: _Path, kind: str): + field = [] + email_field = [] + for person in val: + if "name" not in person: + email_field.append(person["email"]) + elif "email" not in person: + field.append(person["name"]) + else: + addr = Address(display_name=person["name"], addr_spec=person["email"]) + email_field.append(str(addr)) + + if field: + _set_config(dist, kind, ", ".join(field)) + if email_field: + _set_config(dist, f"{kind}_email", ", ".join(email_field)) + + +def _project_urls(dist: "Distribution", val: dict, _root_dir): + _set_config(dist, "project_urls", val) + + +def _python_requires(dist: "Distribution", val: dict, _root_dir): + from setuptools.extern.packaging.specifiers import SpecifierSet + + _set_config(dist, "python_requires", SpecifierSet(val)) + + +def _dependencies(dist: "Distribution", val: list, _root_dir): + if getattr(dist, "install_requires", []): + msg = "`install_requires` overwritten in `pyproject.toml` (dependencies)" + SetuptoolsWarning.emit(msg) + dist.install_requires = val + + +def _optional_dependencies(dist: "Distribution", val: dict, _root_dir): + existing = getattr(dist, "extras_require", None) or {} + dist.extras_require = {**existing, **val} + + +def _unify_entry_points(project_table: dict): + project = project_table + entry_points = project.pop("entry-points", project.pop("entry_points", {})) + renaming = {"scripts": "console_scripts", "gui_scripts": "gui_scripts"} + for key, value in list(project.items()): # eager to allow modifications + norm_key = json_compatible_key(key) + if norm_key in renaming and value: + entry_points[renaming[norm_key]] = project.pop(key) + + if entry_points: + project["entry-points"] = { + name: [f"{k} = {v}" for k, v in group.items()] + for name, group in entry_points.items() + } + + +def _copy_command_options(pyproject: dict, dist: "Distribution", filename: _Path): + tool_table = pyproject.get("tool", {}) + cmdclass = tool_table.get("setuptools", {}).get("cmdclass", {}) + valid_options = _valid_command_options(cmdclass) + + cmd_opts = dist.command_options + for cmd, config in pyproject.get("tool", {}).get("distutils", {}).items(): + cmd = json_compatible_key(cmd) + valid = valid_options.get(cmd, set()) + cmd_opts.setdefault(cmd, {}) + for key, value in config.items(): + key = json_compatible_key(key) + cmd_opts[cmd][key] = (str(filename), value) + if key not in valid: + # To avoid removing options that are specified dynamically we + # just log a warn... + _logger.warning(f"Command option {cmd}.{key} is not defined") + + +def _valid_command_options(cmdclass: Mapping = EMPTY) -> Dict[str, Set[str]]: + from .._importlib import metadata + from setuptools.dist import Distribution + + valid_options = {"global": _normalise_cmd_options(Distribution.global_options)} + + unloaded_entry_points = metadata.entry_points(group='distutils.commands') + loaded_entry_points = (_load_ep(ep) for ep in unloaded_entry_points) + entry_points = (ep for ep in loaded_entry_points if ep) + for cmd, cmd_class in chain(entry_points, cmdclass.items()): + opts = valid_options.get(cmd, set()) + opts = opts | _normalise_cmd_options(getattr(cmd_class, "user_options", [])) + valid_options[cmd] = opts + + return valid_options + + +def _load_ep(ep: "metadata.EntryPoint") -> Optional[Tuple[str, Type]]: + # Ignore all the errors + try: + return (ep.name, ep.load()) + except Exception as ex: + msg = f"{ex.__class__.__name__} while trying to load entry-point {ep.name}" + _logger.warning(f"{msg}: {ex}") + return None + + +def _normalise_cmd_option_key(name: str) -> str: + return json_compatible_key(name).strip("_=") + + +def _normalise_cmd_options(desc: List[Tuple[str, Optional[str], str]]) -> Set[str]: + return {_normalise_cmd_option_key(fancy_option[0]) for fancy_option in desc} + + +def _get_previous_entrypoints(dist: "Distribution") -> Dict[str, list]: + ignore = ("console_scripts", "gui_scripts") + value = getattr(dist, "entry_points", None) or {} + return {k: v for k, v in value.items() if k not in ignore} + + +def _get_previous_scripts(dist: "Distribution") -> Optional[list]: + value = getattr(dist, "entry_points", None) or {} + return value.get("console_scripts") + + +def _get_previous_gui_scripts(dist: "Distribution") -> Optional[list]: + value = getattr(dist, "entry_points", None) or {} + return value.get("gui_scripts") + + +def _attrgetter(attr): + """ + Similar to ``operator.attrgetter`` but returns None if ``attr`` is not found + >>> from types import SimpleNamespace + >>> obj = SimpleNamespace(a=42, b=SimpleNamespace(c=13)) + >>> _attrgetter("a")(obj) + 42 + >>> _attrgetter("b.c")(obj) + 13 + >>> _attrgetter("d")(obj) is None + True + """ + return partial(reduce, lambda acc, x: getattr(acc, x, None), attr.split(".")) + + +def _some_attrgetter(*items): + """ + Return the first "truth-y" attribute or None + >>> from types import SimpleNamespace + >>> obj = SimpleNamespace(a=42, b=SimpleNamespace(c=13)) + >>> _some_attrgetter("d", "a", "b.c")(obj) + 42 + >>> _some_attrgetter("d", "e", "b.c", "a")(obj) + 13 + >>> _some_attrgetter("d", "e", "f")(obj) is None + True + """ + + def _acessor(obj): + values = (_attrgetter(i)(obj) for i in items) + return next((i for i in values if i is not None), None) + + return _acessor + + +PYPROJECT_CORRESPONDENCE: Dict[str, _Correspondence] = { + "readme": _long_description, + "license": _license, + "authors": partial(_people, kind="author"), + "maintainers": partial(_people, kind="maintainer"), + "urls": _project_urls, + "dependencies": _dependencies, + "optional_dependencies": _optional_dependencies, + "requires_python": _python_requires, +} + +TOOL_TABLE_RENAMES = {"script_files": "scripts"} +TOOL_TABLE_DEPRECATIONS = { + "namespace_packages": ( + "consider using implicit namespaces instead (PEP 420).", + {"due_date": (2023, 10, 30)}, # warning introduced in May 2022 + ) +} + +SETUPTOOLS_PATCHES = { + "long_description_content_type", + "project_urls", + "provides_extras", + "license_file", + "license_files", +} + +_PREVIOUSLY_DEFINED = { + "name": _attrgetter("metadata.name"), + "version": _attrgetter("metadata.version"), + "description": _attrgetter("metadata.description"), + "readme": _attrgetter("metadata.long_description"), + "requires-python": _some_attrgetter("python_requires", "metadata.python_requires"), + "license": _attrgetter("metadata.license"), + "authors": _some_attrgetter("metadata.author", "metadata.author_email"), + "maintainers": _some_attrgetter("metadata.maintainer", "metadata.maintainer_email"), + "keywords": _attrgetter("metadata.keywords"), + "classifiers": _attrgetter("metadata.classifiers"), + "urls": _attrgetter("metadata.project_urls"), + "entry-points": _get_previous_entrypoints, + "scripts": _get_previous_scripts, + "gui-scripts": _get_previous_gui_scripts, + "dependencies": _attrgetter("install_requires"), + "optional-dependencies": _attrgetter("extras_require"), +} + + +class _WouldIgnoreField(SetuptoolsDeprecationWarning): + _SUMMARY = "`{field}` defined outside of `pyproject.toml` would be ignored." + + _DETAILS = """ + ########################################################################## + # configuration would be ignored/result in error due to `pyproject.toml` # + ########################################################################## + + The following seems to be defined outside of `pyproject.toml`: + + `{field} = {value!r}` + + According to the spec (see the link below), however, setuptools CANNOT + consider this value unless `{field}` is listed as `dynamic`. + + https://packaging.python.org/en/latest/specifications/declaring-project-metadata/ + + For the time being, `setuptools` will still consider the given value (as a + **transitional** measure), but please note that future releases of setuptools will + follow strictly the standard. + + To prevent this warning, you can list `{field}` under `dynamic` or alternatively + remove the `[project]` table from your file and rely entirely on other means of + configuration. + """ + _DUE_DATE = (2023, 10, 30) # Initially introduced in 27 May 2022 diff --git a/shared/package-files/6b/6b026cdcb00868a3dc1f24f7072a1ce3ac0c3ff83b3d847fee5f3cc01fa85f50/Casablanca b/shared/package-files/6b/6b026cdcb00868a3dc1f24f7072a1ce3ac0c3ff83b3d847fee5f3cc01fa85f50/Casablanca new file mode 100644 index 0000000000000000000000000000000000000000..fb2f5cc0893d5ba9e7df40296c8883f06014be99 Binary files /dev/null and b/shared/package-files/6b/6b026cdcb00868a3dc1f24f7072a1ce3ac0c3ff83b3d847fee5f3cc01fa85f50/Casablanca differ diff --git a/shared/package-files/6b/6b03d75f3d559479720862dcf96331aa618e23c81e1ba6dbe8e1fe2e68404004/ansi80x25 b/shared/package-files/6b/6b03d75f3d559479720862dcf96331aa618e23c81e1ba6dbe8e1fe2e68404004/ansi80x25 new file mode 100644 index 0000000000000000000000000000000000000000..4043099f37cef6decd107ceae59ad5c134b69d18 Binary files /dev/null and b/shared/package-files/6b/6b03d75f3d559479720862dcf96331aa618e23c81e1ba6dbe8e1fe2e68404004/ansi80x25 differ diff --git a/shared/package-files/6b/6b03d75f3d559479720862dcf96331aa618e23c81e1ba6dbe8e1fe2e68404004/ansis b/shared/package-files/6b/6b03d75f3d559479720862dcf96331aa618e23c81e1ba6dbe8e1fe2e68404004/ansis new file mode 100644 index 0000000000000000000000000000000000000000..4043099f37cef6decd107ceae59ad5c134b69d18 Binary files /dev/null and b/shared/package-files/6b/6b03d75f3d559479720862dcf96331aa618e23c81e1ba6dbe8e1fe2e68404004/ansis differ diff --git a/shared/package-files/6b/6b03d75f3d559479720862dcf96331aa618e23c81e1ba6dbe8e1fe2e68404004/cons25 b/shared/package-files/6b/6b03d75f3d559479720862dcf96331aa618e23c81e1ba6dbe8e1fe2e68404004/cons25 new file mode 100644 index 0000000000000000000000000000000000000000..4043099f37cef6decd107ceae59ad5c134b69d18 Binary files /dev/null and b/shared/package-files/6b/6b03d75f3d559479720862dcf96331aa618e23c81e1ba6dbe8e1fe2e68404004/cons25 differ diff --git a/shared/package-files/6b/6b047cd4606d25bc5cb08f2bc7696fe287c4dcd96065f3b3dd4eaf70d6563fa7/_base.py b/shared/package-files/6b/6b047cd4606d25bc5cb08f2bc7696fe287c4dcd96065f3b3dd4eaf70d6563fa7/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..0b43523193782ec89ca1f2f573da01683fdaae6f --- /dev/null +++ b/shared/package-files/6b/6b047cd4606d25bc5cb08f2bc7696fe287c4dcd96065f3b3dd4eaf70d6563fa7/_base.py @@ -0,0 +1,1777 @@ +from __future__ import annotations +import warnings +import itertools +from copy import copy +from collections import UserString +from collections.abc import Iterable, Sequence, Mapping +from numbers import Number +from datetime import datetime + +import numpy as np +import pandas as pd +import matplotlib as mpl + +from seaborn._core.data import PlotData +from seaborn.palettes import ( + QUAL_PALETTES, + color_palette, +) +from seaborn.utils import ( + _check_argument, + _version_predates, + desaturate, + locator_to_legend_entries, + get_color_cycle, + remove_na, +) + + +class SemanticMapping: + """Base class for mapping data values to plot attributes.""" + + # -- Default attributes that all SemanticMapping subclasses must set + + # Whether the mapping is numeric, categorical, or datetime + map_type: str | None = None + + # Ordered list of unique values in the input data + levels = None + + # A mapping from the data values to corresponding plot attributes + lookup_table = None + + def __init__(self, plotter): + + # TODO Putting this here so we can continue to use a lot of the + # logic that's built into the library, but the idea of this class + # is to move towards semantic mappings that are agnostic about the + # kind of plot they're going to be used to draw. + # Fully achieving that is going to take some thinking. + self.plotter = plotter + + def _check_list_length(self, levels, values, variable): + """Input check when values are provided as a list.""" + # Copied from _core/properties; eventually will be replaced for that. + message = "" + if len(levels) > len(values): + message = " ".join([ + f"\nThe {variable} list has fewer values ({len(values)})", + f"than needed ({len(levels)}) and will cycle, which may", + "produce an uninterpretable plot." + ]) + values = [x for _, x in zip(levels, itertools.cycle(values))] + + elif len(values) > len(levels): + message = " ".join([ + f"The {variable} list has more values ({len(values)})", + f"than needed ({len(levels)}), which may not be intended.", + ]) + values = values[:len(levels)] + + if message: + warnings.warn(message, UserWarning, stacklevel=6) + + return values + + def _lookup_single(self, key): + """Apply the mapping to a single data value.""" + return self.lookup_table[key] + + def __call__(self, key, *args, **kwargs): + """Get the attribute(s) values for the data key.""" + if isinstance(key, (list, np.ndarray, pd.Series)): + return [self._lookup_single(k, *args, **kwargs) for k in key] + else: + return self._lookup_single(key, *args, **kwargs) + + +class HueMapping(SemanticMapping): + """Mapping that sets artist colors according to data values.""" + # A specification of the colors that should appear in the plot + palette = None + + # An object that normalizes data values to [0, 1] range for color mapping + norm = None + + # A continuous colormap object for interpolating in a numeric context + cmap = None + + def __init__( + self, plotter, palette=None, order=None, norm=None, saturation=1, + ): + """Map the levels of the `hue` variable to distinct colors. + + Parameters + ---------- + # TODO add generic parameters + + """ + super().__init__(plotter) + + data = plotter.plot_data.get("hue", pd.Series(dtype=float)) + + if isinstance(palette, np.ndarray): + msg = ( + "Numpy array is not a supported type for `palette`. " + "Please convert your palette to a list. " + "This will become an error in v0.14" + ) + warnings.warn(msg, stacklevel=4) + palette = palette.tolist() + + if data.isna().all(): + if palette is not None: + msg = "Ignoring `palette` because no `hue` variable has been assigned." + warnings.warn(msg, stacklevel=4) + else: + + map_type = self.infer_map_type( + palette, norm, plotter.input_format, plotter.var_types["hue"] + ) + + # Our goal is to end up with a dictionary mapping every unique + # value in `data` to a color. We will also keep track of the + # metadata about this mapping we will need for, e.g., a legend + + # --- Option 1: numeric mapping with a matplotlib colormap + + if map_type == "numeric": + + data = pd.to_numeric(data) + levels, lookup_table, norm, cmap = self.numeric_mapping( + data, palette, norm, + ) + + # --- Option 2: categorical mapping using seaborn palette + + elif map_type == "categorical": + + cmap = norm = None + levels, lookup_table = self.categorical_mapping( + data, palette, order, + ) + + # --- Option 3: datetime mapping + + else: + # TODO this needs actual implementation + cmap = norm = None + levels, lookup_table = self.categorical_mapping( + # Casting data to list to handle differences in the way + # pandas and numpy represent datetime64 data + list(data), palette, order, + ) + + self.saturation = saturation + self.map_type = map_type + self.lookup_table = lookup_table + self.palette = palette + self.levels = levels + self.norm = norm + self.cmap = cmap + + def _lookup_single(self, key): + """Get the color for a single value, using colormap to interpolate.""" + try: + # Use a value that's in the original data vector + value = self.lookup_table[key] + except KeyError: + + if self.norm is None: + # Currently we only get here in scatterplot with hue_order, + # because scatterplot does not consider hue a grouping variable + # So unused hue levels are in the data, but not the lookup table + return (0, 0, 0, 0) + + # Use the colormap to interpolate between existing datapoints + # (e.g. in the context of making a continuous legend) + try: + normed = self.norm(key) + except TypeError as err: + if np.isnan(key): + value = (0, 0, 0, 0) + else: + raise err + else: + if np.ma.is_masked(normed): + normed = np.nan + value = self.cmap(normed) + + if self.saturation < 1: + value = desaturate(value, self.saturation) + + return value + + def infer_map_type(self, palette, norm, input_format, var_type): + """Determine how to implement the mapping.""" + if palette in QUAL_PALETTES: + map_type = "categorical" + elif norm is not None: + map_type = "numeric" + elif isinstance(palette, (dict, list)): + map_type = "categorical" + elif input_format == "wide": + map_type = "categorical" + else: + map_type = var_type + + return map_type + + def categorical_mapping(self, data, palette, order): + """Determine colors when the hue mapping is categorical.""" + # -- Identify the order and name of the levels + + levels = categorical_order(data, order) + n_colors = len(levels) + + # -- Identify the set of colors to use + + if isinstance(palette, dict): + + missing = set(levels) - set(palette) + if any(missing): + err = "The palette dictionary is missing keys: {}" + raise ValueError(err.format(missing)) + + lookup_table = palette + + else: + + if palette is None: + if n_colors <= len(get_color_cycle()): + colors = color_palette(None, n_colors) + else: + colors = color_palette("husl", n_colors) + elif isinstance(palette, list): + colors = self._check_list_length(levels, palette, "palette") + else: + colors = color_palette(palette, n_colors) + + lookup_table = dict(zip(levels, colors)) + + return levels, lookup_table + + def numeric_mapping(self, data, palette, norm): + """Determine colors when the hue variable is quantitative.""" + if isinstance(palette, dict): + + # The presence of a norm object overrides a dictionary of hues + # in specifying a numeric mapping, so we need to process it here. + levels = list(sorted(palette)) + colors = [palette[k] for k in sorted(palette)] + cmap = mpl.colors.ListedColormap(colors) + lookup_table = palette.copy() + + else: + + # The levels are the sorted unique values in the data + levels = list(np.sort(remove_na(data.unique()))) + + # --- Sort out the colormap to use from the palette argument + + # Default numeric palette is our default cubehelix palette + # TODO do we want to do something complicated to ensure contrast? + palette = "ch:" if palette is None else palette + + if isinstance(palette, mpl.colors.Colormap): + cmap = palette + else: + cmap = color_palette(palette, as_cmap=True) + + # Now sort out the data normalization + if norm is None: + norm = mpl.colors.Normalize() + elif isinstance(norm, tuple): + norm = mpl.colors.Normalize(*norm) + elif not isinstance(norm, mpl.colors.Normalize): + err = "``hue_norm`` must be None, tuple, or Normalize object." + raise ValueError(err) + + if not norm.scaled(): + norm(np.asarray(data.dropna())) + + lookup_table = dict(zip(levels, cmap(norm(levels)))) + + return levels, lookup_table, norm, cmap + + +class SizeMapping(SemanticMapping): + """Mapping that sets artist sizes according to data values.""" + # An object that normalizes data values to [0, 1] range + norm = None + + def __init__( + self, plotter, sizes=None, order=None, norm=None, + ): + """Map the levels of the `size` variable to distinct values. + + Parameters + ---------- + # TODO add generic parameters + + """ + super().__init__(plotter) + + data = plotter.plot_data.get("size", pd.Series(dtype=float)) + + if data.notna().any(): + + map_type = self.infer_map_type( + norm, sizes, plotter.var_types["size"] + ) + + # --- Option 1: numeric mapping + + if map_type == "numeric": + + levels, lookup_table, norm, size_range = self.numeric_mapping( + data, sizes, norm, + ) + + # --- Option 2: categorical mapping + + elif map_type == "categorical": + + levels, lookup_table = self.categorical_mapping( + data, sizes, order, + ) + size_range = None + + # --- Option 3: datetime mapping + + # TODO this needs an actual implementation + else: + + levels, lookup_table = self.categorical_mapping( + # Casting data to list to handle differences in the way + # pandas and numpy represent datetime64 data + list(data), sizes, order, + ) + size_range = None + + self.map_type = map_type + self.levels = levels + self.norm = norm + self.sizes = sizes + self.size_range = size_range + self.lookup_table = lookup_table + + def infer_map_type(self, norm, sizes, var_type): + + if norm is not None: + map_type = "numeric" + elif isinstance(sizes, (dict, list)): + map_type = "categorical" + else: + map_type = var_type + + return map_type + + def _lookup_single(self, key): + + try: + value = self.lookup_table[key] + except KeyError: + normed = self.norm(key) + if np.ma.is_masked(normed): + normed = np.nan + value = self.size_range[0] + normed * np.ptp(self.size_range) + return value + + def categorical_mapping(self, data, sizes, order): + + levels = categorical_order(data, order) + + if isinstance(sizes, dict): + + # Dict inputs map existing data values to the size attribute + missing = set(levels) - set(sizes) + if any(missing): + err = f"Missing sizes for the following levels: {missing}" + raise ValueError(err) + lookup_table = sizes.copy() + + elif isinstance(sizes, list): + + # List inputs give size values in the same order as the levels + sizes = self._check_list_length(levels, sizes, "sizes") + lookup_table = dict(zip(levels, sizes)) + + else: + + if isinstance(sizes, tuple): + + # Tuple input sets the min, max size values + if len(sizes) != 2: + err = "A `sizes` tuple must have only 2 values" + raise ValueError(err) + + elif sizes is not None: + + err = f"Value for `sizes` not understood: {sizes}" + raise ValueError(err) + + else: + + # Otherwise, we need to get the min, max size values from + # the plotter object we are attached to. + + # TODO this is going to cause us trouble later, because we + # want to restructure things so that the plotter is generic + # across the visual representation of the data. But at this + # point, we don't know the visual representation. Likely we + # want to change the logic of this Mapping so that it gives + # points on a normalized range that then gets un-normalized + # when we know what we're drawing. But given the way the + # package works now, this way is cleanest. + sizes = self.plotter._default_size_range + + # For categorical sizes, use regularly-spaced linear steps + # between the minimum and maximum sizes. Then reverse the + # ramp so that the largest value is used for the first entry + # in size_order, etc. This is because "ordered" categories + # are often though to go in decreasing priority. + sizes = np.linspace(*sizes, len(levels))[::-1] + lookup_table = dict(zip(levels, sizes)) + + return levels, lookup_table + + def numeric_mapping(self, data, sizes, norm): + + if isinstance(sizes, dict): + # The presence of a norm object overrides a dictionary of sizes + # in specifying a numeric mapping, so we need to process it + # dictionary here + levels = list(np.sort(list(sizes))) + size_values = sizes.values() + size_range = min(size_values), max(size_values) + + else: + + # The levels here will be the unique values in the data + levels = list(np.sort(remove_na(data.unique()))) + + if isinstance(sizes, tuple): + + # For numeric inputs, the size can be parametrized by + # the minimum and maximum artist values to map to. The + # norm object that gets set up next specifies how to + # do the mapping. + + if len(sizes) != 2: + err = "A `sizes` tuple must have only 2 values" + raise ValueError(err) + + size_range = sizes + + elif sizes is not None: + + err = f"Value for `sizes` not understood: {sizes}" + raise ValueError(err) + + else: + + # When not provided, we get the size range from the plotter + # object we are attached to. See the note in the categorical + # method about how this is suboptimal for future development. + size_range = self.plotter._default_size_range + + # Now that we know the minimum and maximum sizes that will get drawn, + # we need to map the data values that we have into that range. We will + # use a matplotlib Normalize class, which is typically used for numeric + # color mapping but works fine here too. It takes data values and maps + # them into a [0, 1] interval, potentially nonlinear-ly. + + if norm is None: + # Default is a linear function between the min and max data values + norm = mpl.colors.Normalize() + elif isinstance(norm, tuple): + # It is also possible to give different limits in data space + norm = mpl.colors.Normalize(*norm) + elif not isinstance(norm, mpl.colors.Normalize): + err = f"Value for size `norm` parameter not understood: {norm}" + raise ValueError(err) + else: + # If provided with Normalize object, copy it so we can modify + norm = copy(norm) + + # Set the mapping so all output values are in [0, 1] + norm.clip = True + + # If the input range is not set, use the full range of the data + if not norm.scaled(): + norm(levels) + + # Map from data values to [0, 1] range + sizes_scaled = norm(levels) + + # Now map from the scaled range into the artist units + if isinstance(sizes, dict): + lookup_table = sizes + else: + lo, hi = size_range + sizes = lo + sizes_scaled * (hi - lo) + lookup_table = dict(zip(levels, sizes)) + + return levels, lookup_table, norm, size_range + + +class StyleMapping(SemanticMapping): + """Mapping that sets artist style according to data values.""" + + # Style mapping is always treated as categorical + map_type = "categorical" + + def __init__(self, plotter, markers=None, dashes=None, order=None): + """Map the levels of the `style` variable to distinct values. + + Parameters + ---------- + # TODO add generic parameters + + """ + super().__init__(plotter) + + data = plotter.plot_data.get("style", pd.Series(dtype=float)) + + if data.notna().any(): + + # Cast to list to handle numpy/pandas datetime quirks + if variable_type(data) == "datetime": + data = list(data) + + # Find ordered unique values + levels = categorical_order(data, order) + + markers = self._map_attributes( + markers, levels, unique_markers(len(levels)), "markers", + ) + dashes = self._map_attributes( + dashes, levels, unique_dashes(len(levels)), "dashes", + ) + + # Build the paths matplotlib will use to draw the markers + paths = {} + filled_markers = [] + for k, m in markers.items(): + if not isinstance(m, mpl.markers.MarkerStyle): + m = mpl.markers.MarkerStyle(m) + paths[k] = m.get_path().transformed(m.get_transform()) + filled_markers.append(m.is_filled()) + + # Mixture of filled and unfilled markers will show line art markers + # in the edge color, which defaults to white. This can be handled, + # but there would be additional complexity with specifying the + # weight of the line art markers without overwhelming the filled + # ones with the edges. So for now, we will disallow mixtures. + if any(filled_markers) and not all(filled_markers): + err = "Filled and line art markers cannot be mixed" + raise ValueError(err) + + lookup_table = {} + for key in levels: + lookup_table[key] = {} + if markers: + lookup_table[key]["marker"] = markers[key] + lookup_table[key]["path"] = paths[key] + if dashes: + lookup_table[key]["dashes"] = dashes[key] + + self.levels = levels + self.lookup_table = lookup_table + + def _lookup_single(self, key, attr=None): + """Get attribute(s) for a given data point.""" + if attr is None: + value = self.lookup_table[key] + else: + value = self.lookup_table[key][attr] + return value + + def _map_attributes(self, arg, levels, defaults, attr): + """Handle the specification for a given style attribute.""" + if arg is True: + lookup_table = dict(zip(levels, defaults)) + elif isinstance(arg, dict): + missing = set(levels) - set(arg) + if missing: + err = f"These `{attr}` levels are missing values: {missing}" + raise ValueError(err) + lookup_table = arg + elif isinstance(arg, Sequence): + arg = self._check_list_length(levels, arg, attr) + lookup_table = dict(zip(levels, arg)) + elif arg: + err = f"This `{attr}` argument was not understood: {arg}" + raise ValueError(err) + else: + lookup_table = {} + + return lookup_table + + +# =========================================================================== # + + +class VectorPlotter: + """Base class for objects underlying *plot functions.""" + + wide_structure = { + "x": "@index", "y": "@values", "hue": "@columns", "style": "@columns", + } + flat_structure = {"x": "@index", "y": "@values"} + + _default_size_range = 1, 2 # Unused but needed in tests, ugh + + def __init__(self, data=None, variables={}): + + self._var_levels = {} + # var_ordered is relevant only for categorical axis variables, and may + # be better handled by an internal axis information object that tracks + # such information and is set up by the scale_* methods. The analogous + # information for numeric axes would be information about log scales. + self._var_ordered = {"x": False, "y": False} # alt., used DefaultDict + self.assign_variables(data, variables) + + # TODO Lots of tests assume that these are called to initialize the + # mappings to default values on class initialization. I'd prefer to + # move away from that and only have a mapping when explicitly called. + for var in ["hue", "size", "style"]: + if var in variables: + getattr(self, f"map_{var}")() + + @property + def has_xy_data(self): + """Return True at least one of x or y is defined.""" + return bool({"x", "y"} & set(self.variables)) + + @property + def var_levels(self): + """Property interface to ordered list of variables levels. + + Each time it's accessed, it updates the var_levels dictionary with the + list of levels in the current semantic mappers. But it also allows the + dictionary to persist, so it can be used to set levels by a key. This is + used to track the list of col/row levels using an attached FacetGrid + object, but it's kind of messy and ideally fixed by improving the + faceting logic so it interfaces better with the modern approach to + tracking plot variables. + + """ + for var in self.variables: + if (map_obj := getattr(self, f"_{var}_map", None)) is not None: + self._var_levels[var] = map_obj.levels + return self._var_levels + + def assign_variables(self, data=None, variables={}): + """Define plot variables, optionally using lookup from `data`.""" + x = variables.get("x", None) + y = variables.get("y", None) + + if x is None and y is None: + self.input_format = "wide" + frame, names = self._assign_variables_wideform(data, **variables) + else: + # When dealing with long-form input, use the newer PlotData + # object (internal but introduced for the objects interface) + # to centralize / standardize data consumption logic. + self.input_format = "long" + plot_data = PlotData(data, variables) + frame = plot_data.frame + names = plot_data.names + + self.plot_data = frame + self.variables = names + self.var_types = { + v: variable_type( + frame[v], + boolean_type="numeric" if v in "xy" else "categorical" + ) + for v in names + } + + return self + + def _assign_variables_wideform(self, data=None, **kwargs): + """Define plot variables given wide-form data. + + Parameters + ---------- + data : flat vector or collection of vectors + Data can be a vector or mapping that is coerceable to a Series + or a sequence- or mapping-based collection of such vectors, or a + rectangular numpy array, or a Pandas DataFrame. + kwargs : variable -> data mappings + Behavior with keyword arguments is currently undefined. + + Returns + ------- + plot_data : :class:`pandas.DataFrame` + Long-form data object mapping seaborn variables (x, y, hue, ...) + to data vectors. + variables : dict + Keys are defined seaborn variables; values are names inferred from + the inputs (or None when no name can be determined). + + """ + # Raise if semantic or other variables are assigned in wide-form mode + assigned = [k for k, v in kwargs.items() if v is not None] + if any(assigned): + s = "s" if len(assigned) > 1 else "" + err = f"The following variable{s} cannot be assigned with wide-form data: " + err += ", ".join(f"`{v}`" for v in assigned) + raise ValueError(err) + + # Determine if the data object actually has any data in it + empty = data is None or not len(data) + + # Then, determine if we have "flat" data (a single vector) + if isinstance(data, dict): + values = data.values() + else: + values = np.atleast_1d(np.asarray(data, dtype=object)) + flat = not any( + isinstance(v, Iterable) and not isinstance(v, (str, bytes)) + for v in values + ) + + if empty: + + # Make an object with the structure of plot_data, but empty + plot_data = pd.DataFrame() + variables = {} + + elif flat: + + # Handle flat data by converting to pandas Series and using the + # index and/or values to define x and/or y + # (Could be accomplished with a more general to_series() interface) + flat_data = pd.Series(data).copy() + names = { + "@values": flat_data.name, + "@index": flat_data.index.name + } + + plot_data = {} + variables = {} + + for var in ["x", "y"]: + if var in self.flat_structure: + attr = self.flat_structure[var] + plot_data[var] = getattr(flat_data, attr[1:]) + variables[var] = names[self.flat_structure[var]] + + plot_data = pd.DataFrame(plot_data) + + else: + + # Otherwise assume we have some collection of vectors. + + # Handle Python sequences such that entries end up in the columns, + # not in the rows, of the intermediate wide DataFrame. + # One way to accomplish this is to convert to a dict of Series. + if isinstance(data, Sequence): + data_dict = {} + for i, var in enumerate(data): + key = getattr(var, "name", i) + # TODO is there a safer/more generic way to ensure Series? + # sort of like np.asarray, but for pandas? + data_dict[key] = pd.Series(var) + + data = data_dict + + # Pandas requires that dict values either be Series objects + # or all have the same length, but we want to allow "ragged" inputs + if isinstance(data, Mapping): + data = {key: pd.Series(val) for key, val in data.items()} + + # Otherwise, delegate to the pandas DataFrame constructor + # This is where we'd prefer to use a general interface that says + # "give me this data as a pandas DataFrame", so we can accept + # DataFrame objects from other libraries + wide_data = pd.DataFrame(data, copy=True) + + # At this point we should reduce the dataframe to numeric cols + numeric_cols = [ + k for k, v in wide_data.items() if variable_type(v) == "numeric" + ] + wide_data = wide_data[numeric_cols] + + # Now melt the data to long form + melt_kws = {"var_name": "@columns", "value_name": "@values"} + use_index = "@index" in self.wide_structure.values() + if use_index: + melt_kws["id_vars"] = "@index" + try: + orig_categories = wide_data.columns.categories + orig_ordered = wide_data.columns.ordered + wide_data.columns = wide_data.columns.add_categories("@index") + except AttributeError: + category_columns = False + else: + category_columns = True + wide_data["@index"] = wide_data.index.to_series() + + plot_data = wide_data.melt(**melt_kws) + + if use_index and category_columns: + plot_data["@columns"] = pd.Categorical(plot_data["@columns"], + orig_categories, + orig_ordered) + + # Assign names corresponding to plot semantics + for var, attr in self.wide_structure.items(): + plot_data[var] = plot_data[attr] + + # Define the variable names + variables = {} + for var, attr in self.wide_structure.items(): + obj = getattr(wide_data, attr[1:]) + variables[var] = getattr(obj, "name", None) + + # Remove redundant columns from plot_data + plot_data = plot_data[list(variables)] + + return plot_data, variables + + def map_hue(self, palette=None, order=None, norm=None, saturation=1): + mapping = HueMapping(self, palette, order, norm, saturation) + self._hue_map = mapping + + def map_size(self, sizes=None, order=None, norm=None): + mapping = SizeMapping(self, sizes, order, norm) + self._size_map = mapping + + def map_style(self, markers=None, dashes=None, order=None): + mapping = StyleMapping(self, markers, dashes, order) + self._style_map = mapping + + def iter_data( + self, grouping_vars=None, *, + reverse=False, from_comp_data=False, + by_facet=True, allow_empty=False, dropna=True, + ): + """Generator for getting subsets of data defined by semantic variables. + + Also injects "col" and "row" into grouping semantics. + + Parameters + ---------- + grouping_vars : string or list of strings + Semantic variables that define the subsets of data. + reverse : bool + If True, reverse the order of iteration. + from_comp_data : bool + If True, use self.comp_data rather than self.plot_data + by_facet : bool + If True, add faceting variables to the set of grouping variables. + allow_empty : bool + If True, yield an empty dataframe when no observations exist for + combinations of grouping variables. + dropna : bool + If True, remove rows with missing data. + + Yields + ------ + sub_vars : dict + Keys are semantic names, values are the level of that semantic. + sub_data : :class:`pandas.DataFrame` + Subset of ``plot_data`` for this combination of semantic values. + + """ + # TODO should this default to using all (non x/y?) semantics? + # or define grouping vars somewhere? + if grouping_vars is None: + grouping_vars = [] + elif isinstance(grouping_vars, str): + grouping_vars = [grouping_vars] + elif isinstance(grouping_vars, tuple): + grouping_vars = list(grouping_vars) + + # Always insert faceting variables + if by_facet: + facet_vars = {"col", "row"} + grouping_vars.extend( + facet_vars & set(self.variables) - set(grouping_vars) + ) + + # Reduce to the semantics used in this plot + grouping_vars = [var for var in grouping_vars if var in self.variables] + + if from_comp_data: + data = self.comp_data + else: + data = self.plot_data + + if dropna: + data = data.dropna() + + levels = self.var_levels.copy() + if from_comp_data: + for axis in {"x", "y"} & set(grouping_vars): + converter = self.converters[axis].iloc[0] + if self.var_types[axis] == "categorical": + if self._var_ordered[axis]: + # If the axis is ordered, then the axes in a possible + # facet grid are by definition "shared", or there is a + # single axis with a unique cat -> idx mapping. + # So we can just take the first converter object. + levels[axis] = converter.convert_units(levels[axis]) + else: + # Otherwise, the mappings may not be unique, but we can + # use the unique set of index values in comp_data. + levels[axis] = np.sort(data[axis].unique()) + else: + transform = converter.get_transform().transform + levels[axis] = transform(converter.convert_units(levels[axis])) + + if grouping_vars: + + grouped_data = data.groupby( + grouping_vars, sort=False, as_index=False, observed=False, + ) + + grouping_keys = [] + for var in grouping_vars: + key = levels.get(var) + grouping_keys.append([] if key is None else key) + + iter_keys = itertools.product(*grouping_keys) + if reverse: + iter_keys = reversed(list(iter_keys)) + + for key in iter_keys: + + pd_key = ( + key[0] if len(key) == 1 and _version_predates(pd, "2.2.0") else key + ) + try: + data_subset = grouped_data.get_group(pd_key) + except KeyError: + # XXX we are adding this to allow backwards compatibility + # with the empty artists that old categorical plots would + # add (before 0.12), which we may decide to break, in which + # case this option could be removed + data_subset = data.loc[[]] + + if data_subset.empty and not allow_empty: + continue + + sub_vars = dict(zip(grouping_vars, key)) + + yield sub_vars, data_subset.copy() + + else: + + yield {}, data.copy() + + @property + def comp_data(self): + """Dataframe with numeric x and y, after unit conversion and log scaling.""" + if not hasattr(self, "ax"): + # Probably a good idea, but will need a bunch of tests updated + # Most of these tests should just use the external interface + # Then this can be re-enabled. + # raise AttributeError("No Axes attached to plotter") + return self.plot_data + + if not hasattr(self, "_comp_data"): + + comp_data = ( + self.plot_data + .copy(deep=False) + .drop(["x", "y"], axis=1, errors="ignore") + ) + + for var in "yx": + if var not in self.variables: + continue + + parts = [] + grouped = self.plot_data[var].groupby(self.converters[var], sort=False) + for converter, orig in grouped: + orig = orig.mask(orig.isin([np.inf, -np.inf]), np.nan) + orig = orig.dropna() + if var in self.var_levels: + # TODO this should happen in some centralized location + # it is similar to GH2419, but more complicated because + # supporting `order` in categorical plots is tricky + orig = orig[orig.isin(self.var_levels[var])] + comp = pd.to_numeric(converter.convert_units(orig)).astype(float) + transform = converter.get_transform().transform + parts.append(pd.Series(transform(comp), orig.index, name=orig.name)) + if parts: + comp_col = pd.concat(parts) + else: + comp_col = pd.Series(dtype=float, name=var) + comp_data.insert(0, var, comp_col) + + self._comp_data = comp_data + + return self._comp_data + + def _get_axes(self, sub_vars): + """Return an Axes object based on existence of row/col variables.""" + row = sub_vars.get("row", None) + col = sub_vars.get("col", None) + if row is not None and col is not None: + return self.facets.axes_dict[(row, col)] + elif row is not None: + return self.facets.axes_dict[row] + elif col is not None: + return self.facets.axes_dict[col] + elif self.ax is None: + return self.facets.ax + else: + return self.ax + + def _attach( + self, + obj, + allowed_types=None, + log_scale=None, + ): + """Associate the plotter with an Axes manager and initialize its units. + + Parameters + ---------- + obj : :class:`matplotlib.axes.Axes` or :class:'FacetGrid` + Structural object that we will eventually plot onto. + allowed_types : str or list of str + If provided, raise when either the x or y variable does not have + one of the declared seaborn types. + log_scale : bool, number, or pair of bools or numbers + If not False, set the axes to use log scaling, with the given + base or defaulting to 10. If a tuple, interpreted as separate + arguments for the x and y axes. + + """ + from .axisgrid import FacetGrid + if isinstance(obj, FacetGrid): + self.ax = None + self.facets = obj + ax_list = obj.axes.flatten() + if obj.col_names is not None: + self.var_levels["col"] = obj.col_names + if obj.row_names is not None: + self.var_levels["row"] = obj.row_names + else: + self.ax = obj + self.facets = None + ax_list = [obj] + + # Identify which "axis" variables we have defined + axis_variables = set("xy").intersection(self.variables) + + # -- Verify the types of our x and y variables here. + # This doesn't really make complete sense being here here, but it's a fine + # place for it, given the current system. + # (Note that for some plots, there might be more complicated restrictions) + # e.g. the categorical plots have their own check that as specific to the + # non-categorical axis. + if allowed_types is None: + allowed_types = ["numeric", "datetime", "categorical"] + elif isinstance(allowed_types, str): + allowed_types = [allowed_types] + + for var in axis_variables: + var_type = self.var_types[var] + if var_type not in allowed_types: + err = ( + f"The {var} variable is {var_type}, but one of " + f"{allowed_types} is required" + ) + raise TypeError(err) + + # -- Get axis objects for each row in plot_data for type conversions and scaling + + facet_dim = {"x": "col", "y": "row"} + + self.converters = {} + for var in axis_variables: + other_var = {"x": "y", "y": "x"}[var] + + converter = pd.Series(index=self.plot_data.index, name=var, dtype=object) + share_state = getattr(self.facets, f"_share{var}", True) + + # Simplest cases are that we have a single axes, all axes are shared, + # or sharing is only on the orthogonal facet dimension. In these cases, + # all datapoints get converted the same way, so use the first axis + if share_state is True or share_state == facet_dim[other_var]: + converter.loc[:] = getattr(ax_list[0], f"{var}axis") + + else: + + # Next simplest case is when no axes are shared, and we can + # use the axis objects within each facet + if share_state is False: + for axes_vars, axes_data in self.iter_data(): + ax = self._get_axes(axes_vars) + converter.loc[axes_data.index] = getattr(ax, f"{var}axis") + + # In the more complicated case, the axes are shared within each + # "file" of the facetgrid. In that case, we need to subset the data + # for that file and assign it the first axis in the slice of the grid + else: + + names = getattr(self.facets, f"{share_state}_names") + for i, level in enumerate(names): + idx = (i, 0) if share_state == "row" else (0, i) + axis = getattr(self.facets.axes[idx], f"{var}axis") + converter.loc[self.plot_data[share_state] == level] = axis + + # Store the converter vector, which we use elsewhere (e.g comp_data) + self.converters[var] = converter + + # Now actually update the matplotlib objects to do the conversion we want + grouped = self.plot_data[var].groupby(self.converters[var], sort=False) + for converter, seed_data in grouped: + if self.var_types[var] == "categorical": + if self._var_ordered[var]: + order = self.var_levels[var] + else: + order = None + seed_data = categorical_order(seed_data, order) + converter.update_units(seed_data) + + # -- Set numerical axis scales + + # First unpack the log_scale argument + if log_scale is None: + scalex = scaley = False + else: + # Allow single value or x, y tuple + try: + scalex, scaley = log_scale + except TypeError: + scalex = log_scale if self.var_types.get("x") == "numeric" else False + scaley = log_scale if self.var_types.get("y") == "numeric" else False + + # Now use it + for axis, scale in zip("xy", (scalex, scaley)): + if scale: + for ax in ax_list: + set_scale = getattr(ax, f"set_{axis}scale") + if scale is True: + set_scale("log", nonpositive="mask") + else: + set_scale("log", base=scale, nonpositive="mask") + + # For categorical y, we want the "first" level to be at the top of the axis + if self.var_types.get("y", None) == "categorical": + for ax in ax_list: + ax.yaxis.set_inverted(True) + + # TODO -- Add axes labels + + def _get_scale_transforms(self, axis): + """Return a function implementing the scale transform (or its inverse).""" + if self.ax is None: + axis_list = [getattr(ax, f"{axis}axis") for ax in self.facets.axes.flat] + scales = {axis.get_scale() for axis in axis_list} + if len(scales) > 1: + # It is a simplifying assumption that faceted axes will always have + # the same scale (even if they are unshared and have distinct limits). + # Nothing in the seaborn API allows you to create a FacetGrid with + # a mixture of scales, although it's possible via matplotlib. + # This is constraining, but no more so than previous behavior that + # only (properly) handled log scales, and there are some places where + # it would be much too complicated to use axes-specific transforms. + err = "Cannot determine transform with mixed scales on faceted axes." + raise RuntimeError(err) + transform_obj = axis_list[0].get_transform() + else: + # This case is more straightforward + transform_obj = getattr(self.ax, f"{axis}axis").get_transform() + + return transform_obj.transform, transform_obj.inverted().transform + + def _add_axis_labels(self, ax, default_x="", default_y=""): + """Add axis labels if not present, set visibility to match ticklabels.""" + # TODO ax could default to None and use attached axes if present + # but what to do about the case of facets? Currently using FacetGrid's + # set_axis_labels method, which doesn't add labels to the interior even + # when the axes are not shared. Maybe that makes sense? + if not ax.get_xlabel(): + x_visible = any(t.get_visible() for t in ax.get_xticklabels()) + ax.set_xlabel(self.variables.get("x", default_x), visible=x_visible) + if not ax.get_ylabel(): + y_visible = any(t.get_visible() for t in ax.get_yticklabels()) + ax.set_ylabel(self.variables.get("y", default_y), visible=y_visible) + + def add_legend_data( + self, ax, func, common_kws=None, attrs=None, semantic_kws=None, + ): + """Add labeled artists to represent the different plot semantics.""" + verbosity = self.legend + if isinstance(verbosity, str) and verbosity not in ["auto", "brief", "full"]: + err = "`legend` must be 'auto', 'brief', 'full', or a boolean." + raise ValueError(err) + elif verbosity is True: + verbosity = "auto" + + keys = [] + legend_kws = {} + common_kws = {} if common_kws is None else common_kws.copy() + semantic_kws = {} if semantic_kws is None else semantic_kws.copy() + + # Assign a legend title if there is only going to be one sub-legend, + # otherwise, subtitles will be inserted into the texts list with an + # invisible handle (which is a hack) + titles = { + title for title in + (self.variables.get(v, None) for v in ["hue", "size", "style"]) + if title is not None + } + title = "" if len(titles) != 1 else titles.pop() + title_kws = dict( + visible=False, color="w", s=0, linewidth=0, marker="", dashes="" + ) + + def update(var_name, val_name, **kws): + + key = var_name, val_name + if key in legend_kws: + legend_kws[key].update(**kws) + else: + keys.append(key) + legend_kws[key] = dict(**kws) + + if attrs is None: + attrs = {"hue": "color", "size": ["linewidth", "s"], "style": None} + for var, names in attrs.items(): + self._update_legend_data( + update, var, verbosity, title, title_kws, names, semantic_kws.get(var), + ) + + legend_data = {} + legend_order = [] + + # Don't allow color=None so we can set a neutral color for size/style legends + if common_kws.get("color", False) is None: + common_kws.pop("color") + + for key in keys: + + _, label = key + kws = legend_kws[key] + level_kws = {} + use_attrs = [ + *self._legend_attributes, + *common_kws, + *[attr for var_attrs in semantic_kws.values() for attr in var_attrs], + ] + for attr in use_attrs: + if attr in kws: + level_kws[attr] = kws[attr] + artist = func(label=label, **{"color": ".2", **common_kws, **level_kws}) + if _version_predates(mpl, "3.5.0"): + if isinstance(artist, mpl.lines.Line2D): + ax.add_line(artist) + elif isinstance(artist, mpl.patches.Patch): + ax.add_patch(artist) + elif isinstance(artist, mpl.collections.Collection): + ax.add_collection(artist) + else: + ax.add_artist(artist) + legend_data[key] = artist + legend_order.append(key) + + self.legend_title = title + self.legend_data = legend_data + self.legend_order = legend_order + + def _update_legend_data( + self, + update, + var, + verbosity, + title, + title_kws, + attr_names, + other_props, + ): + """Generate legend tick values and formatted labels.""" + brief_ticks = 6 + mapper = getattr(self, f"_{var}_map", None) + if mapper is None: + return + + brief = mapper.map_type == "numeric" and ( + verbosity == "brief" + or (verbosity == "auto" and len(mapper.levels) > brief_ticks) + ) + if brief: + if isinstance(mapper.norm, mpl.colors.LogNorm): + locator = mpl.ticker.LogLocator(numticks=brief_ticks) + else: + locator = mpl.ticker.MaxNLocator(nbins=brief_ticks) + limits = min(mapper.levels), max(mapper.levels) + levels, formatted_levels = locator_to_legend_entries( + locator, limits, self.plot_data[var].infer_objects().dtype + ) + elif mapper.levels is None: + levels = formatted_levels = [] + else: + levels = formatted_levels = mapper.levels + + if not title and self.variables.get(var, None) is not None: + update((self.variables[var], "title"), self.variables[var], **title_kws) + + other_props = {} if other_props is None else other_props + + for level, formatted_level in zip(levels, formatted_levels): + if level is not None: + attr = mapper(level) + if isinstance(attr_names, list): + attr = {name: attr for name in attr_names} + elif attr_names is not None: + attr = {attr_names: attr} + attr.update({k: v[level] for k, v in other_props.items() if level in v}) + update(self.variables[var], formatted_level, **attr) + + # XXX If the scale_* methods are going to modify the plot_data structure, they + # can't be called twice. That means that if they are called twice, they should + # raise. Alternatively, we could store an original version of plot_data and each + # time they are called they operate on the store, not the current state. + + def scale_native(self, axis, *args, **kwargs): + + # Default, defer to matplotlib + + raise NotImplementedError + + def scale_numeric(self, axis, *args, **kwargs): + + # Feels needed to completeness, what should it do? + # Perhaps handle log scaling? Set the ticker/formatter/limits? + + raise NotImplementedError + + def scale_datetime(self, axis, *args, **kwargs): + + # Use pd.to_datetime to convert strings or numbers to datetime objects + # Note, use day-resolution for numeric->datetime to match matplotlib + + raise NotImplementedError + + def scale_categorical(self, axis, order=None, formatter=None): + """ + Enforce categorical (fixed-scale) rules for the data on given axis. + + Parameters + ---------- + axis : "x" or "y" + Axis of the plot to operate on. + order : list + Order that unique values should appear in. + formatter : callable + Function mapping values to a string representation. + + Returns + ------- + self + + """ + # This method both modifies the internal representation of the data + # (converting it to string) and sets some attributes on self. It might be + # a good idea to have a separate object attached to self that contains the + # information in those attributes (i.e. whether to enforce variable order + # across facets, the order to use) similar to the SemanticMapping objects + # we have for semantic variables. That object could also hold the converter + # objects that get used, if we can decouple those from an existing axis + # (cf. https://github.com/matplotlib/matplotlib/issues/19229). + # There are some interactions with faceting information that would need + # to be thought through, since the converts to use depend on facets. + # If we go that route, these methods could become "borrowed" methods similar + # to what happens with the alternate semantic mapper constructors, although + # that approach is kind of fussy and confusing. + + # TODO this method could also set the grid state? Since we like to have no + # grid on the categorical axis by default. Again, a case where we'll need to + # store information until we use it, so best to have a way to collect the + # attributes that this method sets. + + # TODO if we are going to set visual properties of the axes with these methods, + # then we could do the steps currently in CategoricalPlotter._adjust_cat_axis + + # TODO another, and distinct idea, is to expose a cut= param here + + _check_argument("axis", ["x", "y"], axis) + + # Categorical plots can be "univariate" in which case they get an anonymous + # category label on the opposite axis. + if axis not in self.variables: + self.variables[axis] = None + self.var_types[axis] = "categorical" + self.plot_data[axis] = "" + + # If the "categorical" variable has a numeric type, sort the rows so that + # the default result from categorical_order has those values sorted after + # they have been coerced to strings. The reason for this is so that later + # we can get facet-wise orders that are correct. + # XXX Should this also sort datetimes? + # It feels more consistent, but technically will be a default change + # If so, should also change categorical_order to behave that way + if self.var_types[axis] == "numeric": + self.plot_data = self.plot_data.sort_values(axis, kind="mergesort") + + # Now get a reference to the categorical data vector and remove na values + cat_data = self.plot_data[axis].dropna() + + # Get the initial categorical order, which we do before string + # conversion to respect the original types of the order list. + # Track whether the order is given explicitly so that we can know + # whether or not to use the order constructed here downstream + self._var_ordered[axis] = order is not None or cat_data.dtype.name == "category" + order = pd.Index(categorical_order(cat_data, order), name=axis) + + # Then convert data to strings. This is because in matplotlib, + # "categorical" data really mean "string" data, so doing this artists + # will be drawn on the categorical axis with a fixed scale. + # TODO implement formatter here; check that it returns strings? + if formatter is not None: + cat_data = cat_data.map(formatter) + order = order.map(formatter) + else: + cat_data = cat_data.astype(str) + order = order.astype(str) + + # Update the levels list with the type-converted order variable + self.var_levels[axis] = order + + # Now ensure that seaborn will use categorical rules internally + self.var_types[axis] = "categorical" + + # Put the string-typed categorical vector back into the plot_data structure + self.plot_data[axis] = cat_data + + return self + + +class VariableType(UserString): + """ + Prevent comparisons elsewhere in the library from using the wrong name. + + Errors are simple assertions because users should not be able to trigger + them. If that changes, they should be more verbose. + + """ + # TODO we can replace this with typing.Literal on Python 3.8+ + allowed = "numeric", "datetime", "categorical" + + def __init__(self, data): + assert data in self.allowed, data + super().__init__(data) + + def __eq__(self, other): + assert other in self.allowed, other + return self.data == other + + +def variable_type(vector, boolean_type="numeric"): + """ + Determine whether a vector contains numeric, categorical, or datetime data. + + This function differs from the pandas typing API in two ways: + + - Python sequences or object-typed PyData objects are considered numeric if + all of their entries are numeric. + - String or mixed-type data are considered categorical even if not + explicitly represented as a :class:`pandas.api.types.CategoricalDtype`. + + Parameters + ---------- + vector : :func:`pandas.Series`, :func:`numpy.ndarray`, or Python sequence + Input data to test. + boolean_type : 'numeric' or 'categorical' + Type to use for vectors containing only 0s and 1s (and NAs). + + Returns + ------- + var_type : 'numeric', 'categorical', or 'datetime' + Name identifying the type of data in the vector. + """ + vector = pd.Series(vector) + + # If a categorical dtype is set, infer categorical + if isinstance(vector.dtype, pd.CategoricalDtype): + return VariableType("categorical") + + # Special-case all-na data, which is always "numeric" + if pd.isna(vector).all(): + return VariableType("numeric") + + # At this point, drop nans to simplify further type inference + vector = vector.dropna() + + # Special-case binary/boolean data, allow caller to determine + # This triggers a numpy warning when vector has strings/objects + # https://github.com/numpy/numpy/issues/6784 + # Because we reduce with .all(), we are agnostic about whether the + # comparison returns a scalar or vector, so we will ignore the warning. + # It triggers a separate DeprecationWarning when the vector has datetimes: + # https://github.com/numpy/numpy/issues/13548 + # This is considered a bug by numpy and will likely go away. + with warnings.catch_warnings(): + warnings.simplefilter( + action='ignore', category=(FutureWarning, DeprecationWarning) + ) + try: + if np.isin(vector, [0, 1]).all(): + return VariableType(boolean_type) + except TypeError: + # .isin comparison is not guaranteed to be possible under NumPy + # casting rules, depending on the (unknown) dtype of 'vector' + pass + + # Defer to positive pandas tests + if pd.api.types.is_numeric_dtype(vector): + return VariableType("numeric") + + if pd.api.types.is_datetime64_dtype(vector): + return VariableType("datetime") + + # --- If we get to here, we need to check the entries + + # Check for a collection where everything is a number + + def all_numeric(x): + for x_i in x: + if not isinstance(x_i, Number): + return False + return True + + if all_numeric(vector): + return VariableType("numeric") + + # Check for a collection where everything is a datetime + + def all_datetime(x): + for x_i in x: + if not isinstance(x_i, (datetime, np.datetime64)): + return False + return True + + if all_datetime(vector): + return VariableType("datetime") + + # Otherwise, our final fallback is to consider things categorical + + return VariableType("categorical") + + +def infer_orient(x=None, y=None, orient=None, require_numeric=True): + """Determine how the plot should be oriented based on the data. + + For historical reasons, the convention is to call a plot "horizontally" + or "vertically" oriented based on the axis representing its dependent + variable. Practically, this is used when determining the axis for + numerical aggregation. + + Parameters + ---------- + x, y : Vector data or None + Positional data vectors for the plot. + orient : string or None + Specified orientation. If not None, can be "x" or "y", or otherwise + must start with "v" or "h". + require_numeric : bool + If set, raise when the implied dependent variable is not numeric. + + Returns + ------- + orient : "x" or "y" + + Raises + ------ + ValueError: When `orient` is an unknown string. + TypeError: When dependent variable is not numeric, with `require_numeric` + + """ + + x_type = None if x is None else variable_type(x) + y_type = None if y is None else variable_type(y) + + nonnumeric_dv_error = "{} orientation requires numeric `{}` variable." + single_var_warning = "{} orientation ignored with only `{}` specified." + + if x is None: + if str(orient).startswith("h"): + warnings.warn(single_var_warning.format("Horizontal", "y")) + if require_numeric and y_type != "numeric": + raise TypeError(nonnumeric_dv_error.format("Vertical", "y")) + return "x" + + elif y is None: + if str(orient).startswith("v"): + warnings.warn(single_var_warning.format("Vertical", "x")) + if require_numeric and x_type != "numeric": + raise TypeError(nonnumeric_dv_error.format("Horizontal", "x")) + return "y" + + elif str(orient).startswith("v") or orient == "x": + if require_numeric and y_type != "numeric": + raise TypeError(nonnumeric_dv_error.format("Vertical", "y")) + return "x" + + elif str(orient).startswith("h") or orient == "y": + if require_numeric and x_type != "numeric": + raise TypeError(nonnumeric_dv_error.format("Horizontal", "x")) + return "y" + + elif orient is not None: + err = ( + "`orient` must start with 'v' or 'h' or be None, " + f"but `{repr(orient)}` was passed." + ) + raise ValueError(err) + + elif x_type != "categorical" and y_type == "categorical": + return "y" + + elif x_type != "numeric" and y_type == "numeric": + return "x" + + elif x_type == "numeric" and y_type != "numeric": + return "y" + + elif require_numeric and "numeric" not in (x_type, y_type): + err = "Neither the `x` nor `y` variable appears to be numeric." + raise TypeError(err) + + else: + return "x" + + +def unique_dashes(n): + """Build an arbitrarily long list of unique dash styles for lines. + + Parameters + ---------- + n : int + Number of unique dash specs to generate. + + Returns + ------- + dashes : list of strings or tuples + Valid arguments for the ``dashes`` parameter on + :class:`matplotlib.lines.Line2D`. The first spec is a solid + line (``""``), the remainder are sequences of long and short + dashes. + + """ + # Start with dash specs that are well distinguishable + dashes = [ + "", + (4, 1.5), + (1, 1), + (3, 1.25, 1.5, 1.25), + (5, 1, 1, 1), + ] + + # Now programmatically build as many as we need + p = 3 + while len(dashes) < n: + + # Take combinations of long and short dashes + a = itertools.combinations_with_replacement([3, 1.25], p) + b = itertools.combinations_with_replacement([4, 1], p) + + # Interleave the combinations, reversing one of the streams + segment_list = itertools.chain(*zip( + list(a)[1:-1][::-1], + list(b)[1:-1] + )) + + # Now insert the gaps + for segments in segment_list: + gap = min(segments) + spec = tuple(itertools.chain(*((seg, gap) for seg in segments))) + dashes.append(spec) + + p += 1 + + return dashes[:n] + + +def unique_markers(n): + """Build an arbitrarily long list of unique marker styles for points. + + Parameters + ---------- + n : int + Number of unique marker specs to generate. + + Returns + ------- + markers : list of string or tuples + Values for defining :class:`matplotlib.markers.MarkerStyle` objects. + All markers will be filled. + + """ + # Start with marker specs that are well distinguishable + markers = [ + "o", + "X", + (4, 0, 45), + "P", + (4, 0, 0), + (4, 1, 0), + "^", + (4, 1, 45), + "v", + ] + + # Now generate more from regular polygons of increasing order + s = 5 + while len(markers) < n: + a = 360 / (s + 1) / 2 + markers.extend([ + (s + 1, 1, a), + (s + 1, 0, a), + (s, 1, 0), + (s, 0, 0), + ]) + s += 1 + + # Convert to MarkerStyle object, using only exactly what we need + # markers = [mpl.markers.MarkerStyle(m) for m in markers[:n]] + + return markers[:n] + + +def categorical_order(vector, order=None): + """Return a list of unique data values. + + Determine an ordered list of levels in ``values``. + + Parameters + ---------- + vector : list, array, Categorical, or Series + Vector of "categorical" values + order : list-like, optional + Desired order of category levels to override the order determined + from the ``values`` object. + + Returns + ------- + order : list + Ordered list of category levels not including null values. + + """ + if order is None: + if hasattr(vector, "categories"): + order = vector.categories + else: + try: + order = vector.cat.categories + except (TypeError, AttributeError): + + order = pd.Series(vector).unique() + + if variable_type(vector) == "numeric": + order = np.sort(order) + + order = filter(pd.notnull, order) + return list(order) diff --git a/shared/package-files/6b/6b08d83c2a24817bd80af9b4c7eaf5288acc16fda97bc507d5dcaf70ee753270/dgkeys+11 b/shared/package-files/6b/6b08d83c2a24817bd80af9b4c7eaf5288acc16fda97bc507d5dcaf70ee753270/dgkeys+11 new file mode 100644 index 0000000000000000000000000000000000000000..b3fa2a35184493613c6c2342b18c9221d414ed73 Binary files /dev/null and b/shared/package-files/6b/6b08d83c2a24817bd80af9b4c7eaf5288acc16fda97bc507d5dcaf70ee753270/dgkeys+11 differ diff --git a/shared/package-files/6b/6b093b15c13f89da15186d1f73dd11dea3450fe0459e0857b85dcaaf2b41ee12/extensions.py b/shared/package-files/6b/6b093b15c13f89da15186d1f73dd11dea3450fe0459e0857b85dcaaf2b41ee12/extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..b05f12295a729176aadae19bb1d17f3191f98806 --- /dev/null +++ b/shared/package-files/6b/6b093b15c13f89da15186d1f73dd11dea3450fe0459e0857b85dcaaf2b41ee12/extensions.py @@ -0,0 +1,585 @@ +# Disable type checking for this module since numba's internals +# are not typed, and we use numba's internals via its extension API +# mypy: ignore-errors +""" +Utility classes/functions to let numba recognize +pandas Index/Series/DataFrame + +Mostly vendored from https://github.com/numba/numba/blob/main/numba/tests/pdlike_usecase.py +""" + +from __future__ import annotations + +from contextlib import contextmanager +import operator + +import numba +from numba import types +from numba.core import cgutils +from numba.core.datamodel import models +from numba.core.extending import ( + NativeValue, + box, + lower_builtin, + make_attribute_wrapper, + overload, + overload_attribute, + overload_method, + register_model, + type_callable, + typeof_impl, + unbox, +) +from numba.core.imputils import impl_ret_borrowed +import numpy as np + +from pandas._libs import lib + +from pandas.core.indexes.base import Index +from pandas.core.indexing import _iLocIndexer +from pandas.core.internals import SingleBlockManager +from pandas.core.series import Series + + +# Helper function to hack around fact that Index casts numpy string dtype to object +# +# Idea is to set an attribute on a Index called _numba_data +# that is the original data, or the object data casted to numpy string dtype, +# with a context manager that is unset afterwards +@contextmanager +def set_numba_data(index: Index): + numba_data = index._data + if numba_data.dtype in (object, "string"): + numba_data = np.asarray(numba_data) + if not lib.is_string_array(numba_data): + raise ValueError( + "The numba engine only supports using string or numeric column names" + ) + numba_data = numba_data.astype("U") + try: + index._numba_data = numba_data + yield index + finally: + del index._numba_data + + +# TODO: Range index support +# (this currently lowers OK, but does not round-trip) +class IndexType(types.Type): + """ + The type class for Index objects. + """ + + def __init__(self, dtype, layout, pyclass: any) -> None: + self.pyclass = pyclass + name = f"index({dtype}, {layout})" + self.dtype = dtype + self.layout = layout + super().__init__(name) + + @property + def key(self): + return self.pyclass, self.dtype, self.layout + + @property + def as_array(self): + return types.Array(self.dtype, 1, self.layout) + + def copy(self, dtype=None, ndim: int = 1, layout=None): + assert ndim == 1 + if dtype is None: + dtype = self.dtype + layout = layout or self.layout + return type(self)(dtype, layout, self.pyclass) + + +class SeriesType(types.Type): + """ + The type class for Series objects. + """ + + def __init__(self, dtype, index, namety) -> None: + assert isinstance(index, IndexType) + self.dtype = dtype + self.index = index + self.values = types.Array(self.dtype, 1, "C") + self.namety = namety + name = f"series({dtype}, {index}, {namety})" + super().__init__(name) + + @property + def key(self): + return self.dtype, self.index, self.namety + + @property + def as_array(self): + return self.values + + def copy(self, dtype=None, ndim: int = 1, layout: str = "C"): + assert ndim == 1 + assert layout == "C" + if dtype is None: + dtype = self.dtype + return type(self)(dtype, self.index, self.namety) + + +@typeof_impl.register(Index) +def typeof_index(val, c): + """ + This will assume that only strings are in object dtype + index. + (you should check this before this gets lowered down to numba) + """ + # arrty = typeof_impl(val._data, c) + arrty = typeof_impl(val._numba_data, c) + assert arrty.ndim == 1 + return IndexType(arrty.dtype, arrty.layout, type(val)) + + +@typeof_impl.register(Series) +def typeof_series(val, c): + index = typeof_impl(val.index, c) + arrty = typeof_impl(val.values, c) + namety = typeof_impl(val.name, c) + assert arrty.ndim == 1 + assert arrty.layout == "C" + return SeriesType(arrty.dtype, index, namety) + + +@type_callable(Series) +def type_series_constructor(context): + def typer(data, index, name=None): + if isinstance(index, IndexType) and isinstance(data, types.Array): + assert data.ndim == 1 + if name is None: + name = types.intp + return SeriesType(data.dtype, index, name) + + return typer + + +@type_callable(Index) +def type_index_constructor(context): + def typer(data, hashmap=None): + if isinstance(data, types.Array): + assert data.layout == "C" + assert data.ndim == 1 + assert hashmap is None or isinstance(hashmap, types.DictType) + return IndexType(data.dtype, layout=data.layout, pyclass=Index) + + return typer + + +# Backend extensions for Index and Series and Frame +@register_model(IndexType) +class IndexModel(models.StructModel): + def __init__(self, dmm, fe_type) -> None: + # We don't want the numpy string scalar type in our hashmap + members = [ + ("data", fe_type.as_array), + # This is an attempt to emulate our hashtable code with a numba + # typed dict + # It maps from values in the index to their integer positions in the array + ("hashmap", types.DictType(fe_type.dtype, types.intp)), + # Pointer to the Index object this was created from, or that it + # boxes to + # https://numba.discourse.group/t/qst-how-to-cache-the-boxing-of-an-object/2128/2?u=lithomas1 + ("parent", types.pyobject), + ] + models.StructModel.__init__(self, dmm, fe_type, members) + + +@register_model(SeriesType) +class SeriesModel(models.StructModel): + def __init__(self, dmm, fe_type) -> None: + members = [ + ("index", fe_type.index), + ("values", fe_type.as_array), + ("name", fe_type.namety), + ] + models.StructModel.__init__(self, dmm, fe_type, members) + + +make_attribute_wrapper(IndexType, "data", "_data") +make_attribute_wrapper(IndexType, "hashmap", "hashmap") + +make_attribute_wrapper(SeriesType, "index", "index") +make_attribute_wrapper(SeriesType, "values", "values") +make_attribute_wrapper(SeriesType, "name", "name") + + +@lower_builtin(Series, types.Array, IndexType) +def pdseries_constructor(context, builder, sig, args): + data, index = args + series = cgutils.create_struct_proxy(sig.return_type)(context, builder) + series.index = index + series.values = data + series.name = context.get_constant(types.intp, 0) + return impl_ret_borrowed(context, builder, sig.return_type, series._getvalue()) + + +@lower_builtin(Series, types.Array, IndexType, types.intp) +@lower_builtin(Series, types.Array, IndexType, types.float64) +@lower_builtin(Series, types.Array, IndexType, types.unicode_type) +def pdseries_constructor_with_name(context, builder, sig, args): + data, index, name = args + series = cgutils.create_struct_proxy(sig.return_type)(context, builder) + series.index = index + series.values = data + series.name = name + return impl_ret_borrowed(context, builder, sig.return_type, series._getvalue()) + + +@lower_builtin(Index, types.Array, types.DictType, types.pyobject) +def index_constructor_2arg(context, builder, sig, args): + (data, hashmap, parent) = args + index = cgutils.create_struct_proxy(sig.return_type)(context, builder) + + index.data = data + index.hashmap = hashmap + index.parent = parent + return impl_ret_borrowed(context, builder, sig.return_type, index._getvalue()) + + +@lower_builtin(Index, types.Array, types.DictType) +def index_constructor_2arg_parent(context, builder, sig, args): + # Basically same as index_constructor_1arg, but also lets you specify the + # parent object + (data, hashmap) = args + index = cgutils.create_struct_proxy(sig.return_type)(context, builder) + + index.data = data + index.hashmap = hashmap + return impl_ret_borrowed(context, builder, sig.return_type, index._getvalue()) + + +@lower_builtin(Index, types.Array) +def index_constructor_1arg(context, builder, sig, args): + from numba.typed import Dict + + key_type = sig.return_type.dtype + value_type = types.intp + + def index_impl(data): + return Index(data, Dict.empty(key_type, value_type)) + + return context.compile_internal(builder, index_impl, sig, args) + + +# Helper to convert the unicodecharseq (numpy string scalar) into a unicode_type +# (regular string) +def maybe_cast_str(x): + # Dummy function that numba can overload + pass + + +@overload(maybe_cast_str) +def maybe_cast_str_impl(x): + """Converts numba UnicodeCharSeq (numpy string scalar) -> unicode type (string). + Is a no-op for other types.""" + if isinstance(x, types.UnicodeCharSeq): + return lambda x: str(x) + else: + return lambda x: x + + +@unbox(IndexType) +def unbox_index(typ, obj, c): + """ + Convert a Index object to a native structure. + + Note: Object dtype is not allowed here + """ + data_obj = c.pyapi.object_getattr_string(obj, "_numba_data") + index = cgutils.create_struct_proxy(typ)(c.context, c.builder) + # If we see an object array, assume its been validated as only containing strings + # We still need to do the conversion though + index.data = c.unbox(typ.as_array, data_obj).value + typed_dict_obj = c.pyapi.unserialize(c.pyapi.serialize_object(numba.typed.Dict)) + # Create an empty typed dict in numba for the hashmap for indexing + # equiv of numba.typed.Dict.empty(typ.dtype, types.intp) + arr_type_obj = c.pyapi.unserialize(c.pyapi.serialize_object(typ.dtype)) + intp_type_obj = c.pyapi.unserialize(c.pyapi.serialize_object(types.intp)) + hashmap_obj = c.pyapi.call_method( + typed_dict_obj, "empty", (arr_type_obj, intp_type_obj) + ) + index.hashmap = c.unbox(types.DictType(typ.dtype, types.intp), hashmap_obj).value + # Set the parent for speedy boxing. + index.parent = obj + + # Decrefs + c.pyapi.decref(data_obj) + c.pyapi.decref(arr_type_obj) + c.pyapi.decref(intp_type_obj) + c.pyapi.decref(typed_dict_obj) + + return NativeValue(index._getvalue()) + + +@unbox(SeriesType) +def unbox_series(typ, obj, c): + """ + Convert a Series object to a native structure. + """ + index_obj = c.pyapi.object_getattr_string(obj, "index") + values_obj = c.pyapi.object_getattr_string(obj, "values") + name_obj = c.pyapi.object_getattr_string(obj, "name") + + series = cgutils.create_struct_proxy(typ)(c.context, c.builder) + series.index = c.unbox(typ.index, index_obj).value + series.values = c.unbox(typ.values, values_obj).value + series.name = c.unbox(typ.namety, name_obj).value + + # Decrefs + c.pyapi.decref(index_obj) + c.pyapi.decref(values_obj) + c.pyapi.decref(name_obj) + + return NativeValue(series._getvalue()) + + +@box(IndexType) +def box_index(typ, val, c): + """ + Convert a native index structure to a Index object. + + If our native index is of a numpy string dtype, we'll cast it to + object. + """ + # First build a Numpy array object, then wrap it in a Index + index = cgutils.create_struct_proxy(typ)(c.context, c.builder, value=val) + + res = cgutils.alloca_once_value(c.builder, index.parent) + + # Does parent exist? + # (it means already boxed once, or Index same as original df.index or df.columns) + # xref https://github.com/numba/numba/blob/596e8a55334cc46854e3192766e643767bd7c934/numba/core/boxing.py#L593C17-L593C17 + with c.builder.if_else(cgutils.is_not_null(c.builder, index.parent)) as ( + has_parent, + otherwise, + ): + with has_parent: + c.pyapi.incref(index.parent) + with otherwise: + # TODO: preserve the original class for the index + # Also need preserve the name of the Index + # class_obj = c.pyapi.unserialize(c.pyapi.serialize_object(typ.pyclass)) + class_obj = c.pyapi.unserialize(c.pyapi.serialize_object(Index)) + array_obj = c.box(typ.as_array, index.data) + if isinstance(typ.dtype, types.UnicodeCharSeq): + # We converted to numpy string dtype, convert back + # to object since _simple_new won't do that for uss + object_str_obj = c.pyapi.unserialize(c.pyapi.serialize_object("object")) + array_obj = c.pyapi.call_method(array_obj, "astype", (object_str_obj,)) + c.pyapi.decref(object_str_obj) + # this is basically Index._simple_new(array_obj, name_obj) in python + index_obj = c.pyapi.call_method(class_obj, "_simple_new", (array_obj,)) + index.parent = index_obj + c.builder.store(index_obj, res) + + # Decrefs + c.pyapi.decref(class_obj) + c.pyapi.decref(array_obj) + return c.builder.load(res) + + +@box(SeriesType) +def box_series(typ, val, c): + """ + Convert a native series structure to a Series object. + """ + series = cgutils.create_struct_proxy(typ)(c.context, c.builder, value=val) + series_const_obj = c.pyapi.unserialize(c.pyapi.serialize_object(Series._from_mgr)) + mgr_const_obj = c.pyapi.unserialize( + c.pyapi.serialize_object(SingleBlockManager.from_array) + ) + index_obj = c.box(typ.index, series.index) + array_obj = c.box(typ.as_array, series.values) + name_obj = c.box(typ.namety, series.name) + # This is basically equivalent of + # pd.Series(data=array_obj, index=index_obj) + # To improve perf, we will construct the Series from a manager + # object to avoid checks. + # We'll also set the name attribute manually to avoid validation + mgr_obj = c.pyapi.call_function_objargs( + mgr_const_obj, + ( + array_obj, + index_obj, + ), + ) + mgr_axes_obj = c.pyapi.object_getattr_string(mgr_obj, "axes") + # Series._constructor_from_mgr(mgr, axes) + series_obj = c.pyapi.call_function_objargs( + series_const_obj, (mgr_obj, mgr_axes_obj) + ) + c.pyapi.object_setattr_string(series_obj, "_name", name_obj) + + # Decrefs + c.pyapi.decref(series_const_obj) + c.pyapi.decref(mgr_axes_obj) + c.pyapi.decref(mgr_obj) + c.pyapi.decref(mgr_const_obj) + c.pyapi.decref(index_obj) + c.pyapi.decref(array_obj) + c.pyapi.decref(name_obj) + + return series_obj + + +# Add common series reductions (e.g. mean, sum), +# and also add common binops (e.g. add, sub, mul, div) +def generate_series_reduction(ser_reduction, ser_method): + @overload_method(SeriesType, ser_reduction) + def series_reduction(series): + def series_reduction_impl(series): + return ser_method(series.values) + + return series_reduction_impl + + return series_reduction + + +def generate_series_binop(binop): + @overload(binop) + def series_binop(series1, value): + if isinstance(series1, SeriesType): + if isinstance(value, SeriesType): + + def series_binop_impl(series1, series2): + # TODO: Check index matching? + return Series( + binop(series1.values, series2.values), + series1.index, + series1.name, + ) + + return series_binop_impl + else: + + def series_binop_impl(series1, value): + return Series( + binop(series1.values, value), series1.index, series1.name + ) + + return series_binop_impl + + return series_binop + + +series_reductions = [ + ("sum", np.sum), + ("mean", np.mean), + # Disabled due to discrepancies between numba std. dev + # and pandas std. dev (no way to specify dof) + # ("std", np.std), + # ("var", np.var), + ("min", np.min), + ("max", np.max), +] +for reduction, reduction_method in series_reductions: + generate_series_reduction(reduction, reduction_method) + +series_binops = [operator.add, operator.sub, operator.mul, operator.truediv] + +for ser_binop in series_binops: + generate_series_binop(ser_binop) + + +# get_loc on Index +@overload_method(IndexType, "get_loc") +def index_get_loc(index, item): + def index_get_loc_impl(index, item): + # Initialize the hash table if not initialized + if len(index.hashmap) == 0: + for i, val in enumerate(index._data): + index.hashmap[val] = i + return index.hashmap[item] + + return index_get_loc_impl + + +# Indexing for Series/Index +@overload(operator.getitem) +def series_indexing(series, item): + if isinstance(series, SeriesType): + + def series_getitem(series, item): + loc = series.index.get_loc(item) + return series.iloc[loc] + + return series_getitem + + +@overload(operator.getitem) +def index_indexing(index, idx): + if isinstance(index, IndexType): + + def index_getitem(index, idx): + return index._data[idx] + + return index_getitem + + +class IlocType(types.Type): + def __init__(self, obj_type) -> None: + self.obj_type = obj_type + name = f"iLocIndexer({obj_type})" + super().__init__(name=name) + + @property + def key(self): + return self.obj_type + + +@typeof_impl.register(_iLocIndexer) +def typeof_iloc(val, c): + objtype = typeof_impl(val.obj, c) + return IlocType(objtype) + + +@type_callable(_iLocIndexer) +def type_iloc_constructor(context): + def typer(obj): + if isinstance(obj, SeriesType): + return IlocType(obj) + + return typer + + +@lower_builtin(_iLocIndexer, SeriesType) +def iloc_constructor(context, builder, sig, args): + (obj,) = args + iloc_indexer = cgutils.create_struct_proxy(sig.return_type)(context, builder) + iloc_indexer.obj = obj + return impl_ret_borrowed( + context, builder, sig.return_type, iloc_indexer._getvalue() + ) + + +@register_model(IlocType) +class ILocModel(models.StructModel): + def __init__(self, dmm, fe_type) -> None: + members = [("obj", fe_type.obj_type)] + models.StructModel.__init__(self, dmm, fe_type, members) + + +make_attribute_wrapper(IlocType, "obj", "obj") + + +@overload_attribute(SeriesType, "iloc") +def series_iloc(series): + def get(series): + return _iLocIndexer(series) + + return get + + +@overload(operator.getitem) +def iloc_getitem(iloc_indexer, i): + if isinstance(iloc_indexer, IlocType): + + def getitem_impl(iloc_indexer, i): + return iloc_indexer.obj.values[i] + + return getitem_impl diff --git a/shared/package-files/6b/6b0ccea677d9d1d098873c3f2787de913eeed05d15c20b086a9ba201b064c718/astype.py b/shared/package-files/6b/6b0ccea677d9d1d098873c3f2787de913eeed05d15c20b086a9ba201b064c718/astype.py new file mode 100644 index 0000000000000000000000000000000000000000..f5579082c679bf131c056f3f2029b2485e88bd0d --- /dev/null +++ b/shared/package-files/6b/6b0ccea677d9d1d098873c3f2787de913eeed05d15c20b086a9ba201b064c718/astype.py @@ -0,0 +1,301 @@ +""" +Functions for implementing 'astype' methods according to pandas conventions, +particularly ones that differ from numpy. +""" +from __future__ import annotations + +import inspect +from typing import ( + TYPE_CHECKING, + overload, +) +import warnings + +import numpy as np + +from pandas._libs import lib +from pandas._libs.tslibs.timedeltas import array_to_timedelta64 +from pandas.errors import IntCastingNaNError + +from pandas.core.dtypes.common import ( + is_object_dtype, + is_string_dtype, + pandas_dtype, +) +from pandas.core.dtypes.dtypes import ( + ExtensionDtype, + NumpyEADtype, +) + +if TYPE_CHECKING: + from pandas._typing import ( + ArrayLike, + DtypeObj, + IgnoreRaise, + ) + + from pandas.core.arrays import ExtensionArray + +_dtype_obj = np.dtype(object) + + +@overload +def _astype_nansafe( + arr: np.ndarray, dtype: np.dtype, copy: bool = ..., skipna: bool = ... +) -> np.ndarray: + ... + + +@overload +def _astype_nansafe( + arr: np.ndarray, dtype: ExtensionDtype, copy: bool = ..., skipna: bool = ... +) -> ExtensionArray: + ... + + +def _astype_nansafe( + arr: np.ndarray, dtype: DtypeObj, copy: bool = True, skipna: bool = False +) -> ArrayLike: + """ + Cast the elements of an array to a given dtype a nan-safe manner. + + Parameters + ---------- + arr : ndarray + dtype : np.dtype or ExtensionDtype + copy : bool, default True + If False, a view will be attempted but may fail, if + e.g. the item sizes don't align. + skipna: bool, default False + Whether or not we should skip NaN when casting as a string-type. + + Raises + ------ + ValueError + The dtype was a datetime64/timedelta64 dtype, but it had no unit. + """ + + # dispatch on extension dtype if needed + if isinstance(dtype, ExtensionDtype): + return dtype.construct_array_type()._from_sequence(arr, dtype=dtype, copy=copy) + + elif not isinstance(dtype, np.dtype): # pragma: no cover + raise ValueError("dtype must be np.dtype or ExtensionDtype") + + if arr.dtype.kind in "mM": + from pandas.core.construction import ensure_wrapped_if_datetimelike + + arr = ensure_wrapped_if_datetimelike(arr) + res = arr.astype(dtype, copy=copy) + return np.asarray(res) + + if issubclass(dtype.type, str): + shape = arr.shape + if arr.ndim > 1: + arr = arr.ravel() + return lib.ensure_string_array( + arr, skipna=skipna, convert_na_value=False + ).reshape(shape) + + elif np.issubdtype(arr.dtype, np.floating) and dtype.kind in "iu": + return _astype_float_to_int_nansafe(arr, dtype, copy) + + elif arr.dtype == object: + # if we have a datetime/timedelta array of objects + # then coerce to datetime64[ns] and use DatetimeArray.astype + + if lib.is_np_dtype(dtype, "M"): + from pandas.core.arrays import DatetimeArray + + dta = DatetimeArray._from_sequence(arr, dtype=dtype) + return dta._ndarray + + elif lib.is_np_dtype(dtype, "m"): + from pandas.core.construction import ensure_wrapped_if_datetimelike + + # bc we know arr.dtype == object, this is equivalent to + # `np.asarray(to_timedelta(arr))`, but using a lower-level API that + # does not require a circular import. + tdvals = array_to_timedelta64(arr).view("m8[ns]") + + tda = ensure_wrapped_if_datetimelike(tdvals) + return tda.astype(dtype, copy=False)._ndarray + + if dtype.name in ("datetime64", "timedelta64"): + msg = ( + f"The '{dtype.name}' dtype has no unit. Please pass in " + f"'{dtype.name}[ns]' instead." + ) + raise ValueError(msg) + + if copy or arr.dtype == object or dtype == object: + # Explicit copy, or required since NumPy can't view from / to object. + return arr.astype(dtype, copy=True) + + return arr.astype(dtype, copy=copy) + + +def _astype_float_to_int_nansafe( + values: np.ndarray, dtype: np.dtype, copy: bool +) -> np.ndarray: + """ + astype with a check preventing converting NaN to an meaningless integer value. + """ + if not np.isfinite(values).all(): + raise IntCastingNaNError( + "Cannot convert non-finite values (NA or inf) to integer" + ) + if dtype.kind == "u": + # GH#45151 + if not (values >= 0).all(): + raise ValueError(f"Cannot losslessly cast from {values.dtype} to {dtype}") + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=RuntimeWarning) + return values.astype(dtype, copy=copy) + + +def astype_array(values: ArrayLike, dtype: DtypeObj, copy: bool = False) -> ArrayLike: + """ + Cast array (ndarray or ExtensionArray) to the new dtype. + + Parameters + ---------- + values : ndarray or ExtensionArray + dtype : dtype object + copy : bool, default False + copy if indicated + + Returns + ------- + ndarray or ExtensionArray + """ + if values.dtype == dtype: + if copy: + return values.copy() + return values + + if not isinstance(values, np.ndarray): + # i.e. ExtensionArray + values = values.astype(dtype, copy=copy) + + else: + values = _astype_nansafe(values, dtype, copy=copy) + + # in pandas we don't store numpy str dtypes, so convert to object + if isinstance(dtype, np.dtype) and issubclass(values.dtype.type, str): + values = np.array(values, dtype=object) + + return values + + +def astype_array_safe( + values: ArrayLike, dtype, copy: bool = False, errors: IgnoreRaise = "raise" +) -> ArrayLike: + """ + Cast array (ndarray or ExtensionArray) to the new dtype. + + This basically is the implementation for DataFrame/Series.astype and + includes all custom logic for pandas (NaN-safety, converting str to object, + not allowing ) + + Parameters + ---------- + values : ndarray or ExtensionArray + dtype : str, dtype convertible + copy : bool, default False + copy if indicated + errors : str, {'raise', 'ignore'}, default 'raise' + - ``raise`` : allow exceptions to be raised + - ``ignore`` : suppress exceptions. On error return original object + + Returns + ------- + ndarray or ExtensionArray + """ + errors_legal_values = ("raise", "ignore") + + if errors not in errors_legal_values: + invalid_arg = ( + "Expected value of kwarg 'errors' to be one of " + f"{list(errors_legal_values)}. Supplied value is '{errors}'" + ) + raise ValueError(invalid_arg) + + if inspect.isclass(dtype) and issubclass(dtype, ExtensionDtype): + msg = ( + f"Expected an instance of {dtype.__name__}, " + "but got the class instead. Try instantiating 'dtype'." + ) + raise TypeError(msg) + + dtype = pandas_dtype(dtype) + if isinstance(dtype, NumpyEADtype): + # Ensure we don't end up with a NumpyExtensionArray + dtype = dtype.numpy_dtype + + try: + new_values = astype_array(values, dtype, copy=copy) + except (ValueError, TypeError): + # e.g. _astype_nansafe can fail on object-dtype of strings + # trying to convert to float + if errors == "ignore": + new_values = values + else: + raise + + return new_values + + +def astype_is_view(dtype: DtypeObj, new_dtype: DtypeObj) -> bool: + """Checks if astype avoided copying the data. + + Parameters + ---------- + dtype : Original dtype + new_dtype : target dtype + + Returns + ------- + True if new data is a view or not guaranteed to be a copy, False otherwise + """ + if isinstance(dtype, np.dtype) and not isinstance(new_dtype, np.dtype): + new_dtype, dtype = dtype, new_dtype + + if dtype == new_dtype: + return True + + elif isinstance(dtype, np.dtype) and isinstance(new_dtype, np.dtype): + # Only equal numpy dtypes avoid a copy + return False + + elif is_string_dtype(dtype) and is_string_dtype(new_dtype): + # Potentially! a view when converting from object to string + return True + + elif is_object_dtype(dtype) and new_dtype.kind == "O": + # When the underlying array has dtype object, we don't have to make a copy + return True + + elif dtype.kind in "mM" and new_dtype.kind in "mM": + dtype = getattr(dtype, "numpy_dtype", dtype) + new_dtype = getattr(new_dtype, "numpy_dtype", new_dtype) + return getattr(dtype, "unit", None) == getattr(new_dtype, "unit", None) + + numpy_dtype = getattr(dtype, "numpy_dtype", None) + new_numpy_dtype = getattr(new_dtype, "numpy_dtype", None) + + if numpy_dtype is None and isinstance(dtype, np.dtype): + numpy_dtype = dtype + + if new_numpy_dtype is None and isinstance(new_dtype, np.dtype): + new_numpy_dtype = new_dtype + + if numpy_dtype is not None and new_numpy_dtype is not None: + # if both have NumPy dtype or one of them is a numpy dtype + # they are only a view when the numpy dtypes are equal, e.g. + # int64 -> Int64 or int64[pyarrow] + # int64 -> Int32 copies + return numpy_dtype == new_numpy_dtype + + # Assume this is a view since we don't know for sure if a copy was made + return True diff --git a/shared/package-files/6b/6b11723489b0c31ea0ecdc372a5713b3bb150a7437a55323edf8e8f0516ff035/lt_meta_dispatch.h b/shared/package-files/6b/6b11723489b0c31ea0ecdc372a5713b3bb150a7437a55323edf8e8f0516ff035/lt_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..04177f190653f7bf80c171f52a0f369d3659ddc6 --- /dev/null +++ b/shared/package-files/6b/6b11723489b0c31ea0ecdc372a5713b3bb150a7437a55323edf8e8f0516ff035/lt_meta_dispatch.h @@ -0,0 +1,30 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor lt(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & lt_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & lt_outf(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +TORCH_API at::Tensor & lt_(at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor lt(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & lt_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & lt_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor & lt_(at::Tensor & self, const at::Tensor & other); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/6b/6b13f2d8430b1e4217f37fe472c2a8445969ab7c7fd18c4e123cedec51e0c5ce/cnf.py b/shared/package-files/6b/6b13f2d8430b1e4217f37fe472c2a8445969ab7c7fd18c4e123cedec51e0c5ce/cnf.py new file mode 100644 index 0000000000000000000000000000000000000000..43a4f093621f221ad668fefb1d13877c8788a30f --- /dev/null +++ b/shared/package-files/6b/6b13f2d8430b1e4217f37fe472c2a8445969ab7c7fd18c4e123cedec51e0c5ce/cnf.py @@ -0,0 +1,453 @@ +""" +The classes used here are for the internal use of assumptions system +only and should not be used anywhere else as these do not possess the +signatures common to SymPy objects. For general use of logic constructs +please refer to sympy.logic classes And, Or, Not, etc. +""" +from itertools import combinations, product, zip_longest +from sympy.assumptions.assume import AppliedPredicate, Predicate +from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le +from sympy.core.singleton import S +from sympy.logic.boolalg import Or, And, Not, Xnor +from sympy.logic.boolalg import (Equivalent, ITE, Implies, Nand, Nor, Xor) + + +class Literal: + """ + The smallest element of a CNF object. + + Parameters + ========== + + lit : Boolean expression + + is_Not : bool + + Examples + ======== + + >>> from sympy import Q + >>> from sympy.assumptions.cnf import Literal + >>> from sympy.abc import x + >>> Literal(Q.even(x)) + Literal(Q.even(x), False) + >>> Literal(~Q.even(x)) + Literal(Q.even(x), True) + """ + + def __new__(cls, lit, is_Not=False): + if isinstance(lit, Not): + lit = lit.args[0] + is_Not = True + elif isinstance(lit, (AND, OR, Literal)): + return ~lit if is_Not else lit + obj = super().__new__(cls) + obj.lit = lit + obj.is_Not = is_Not + return obj + + @property + def arg(self): + return self.lit + + def rcall(self, expr): + if callable(self.lit): + lit = self.lit(expr) + else: + try: + lit = self.lit.apply(expr) + except AttributeError: + lit = self.lit.rcall(expr) + return type(self)(lit, self.is_Not) + + def __invert__(self): + is_Not = not self.is_Not + return Literal(self.lit, is_Not) + + def __str__(self): + return '{}({}, {})'.format(type(self).__name__, self.lit, self.is_Not) + + __repr__ = __str__ + + def __eq__(self, other): + return self.arg == other.arg and self.is_Not == other.is_Not + + def __hash__(self): + h = hash((type(self).__name__, self.arg, self.is_Not)) + return h + + +class OR: + """ + A low-level implementation for Or + """ + def __init__(self, *args): + self._args = args + + @property + def args(self): + return sorted(self._args, key=str) + + def rcall(self, expr): + return type(self)(*[arg.rcall(expr) + for arg in self._args + ]) + + def __invert__(self): + return AND(*[~arg for arg in self._args]) + + def __hash__(self): + return hash((type(self).__name__,) + tuple(self.args)) + + def __eq__(self, other): + return self.args == other.args + + def __str__(self): + s = '(' + ' | '.join([str(arg) for arg in self.args]) + ')' + return s + + __repr__ = __str__ + + +class AND: + """ + A low-level implementation for And + """ + def __init__(self, *args): + self._args = args + + def __invert__(self): + return OR(*[~arg for arg in self._args]) + + @property + def args(self): + return sorted(self._args, key=str) + + def rcall(self, expr): + return type(self)(*[arg.rcall(expr) + for arg in self._args + ]) + + def __hash__(self): + return hash((type(self).__name__,) + tuple(self.args)) + + def __eq__(self, other): + return self.args == other.args + + def __str__(self): + s = '('+' & '.join([str(arg) for arg in self.args])+')' + return s + + __repr__ = __str__ + + +def to_NNF(expr, composite_map=None): + """ + Generates the Negation Normal Form of any boolean expression in terms + of AND, OR, and Literal objects. + + Examples + ======== + + >>> from sympy import Q, Eq + >>> from sympy.assumptions.cnf import to_NNF + >>> from sympy.abc import x, y + >>> expr = Q.even(x) & ~Q.positive(x) + >>> to_NNF(expr) + (Literal(Q.even(x), False) & Literal(Q.positive(x), True)) + + Supported boolean objects are converted to corresponding predicates. + + >>> to_NNF(Eq(x, y)) + Literal(Q.eq(x, y), False) + + If ``composite_map`` argument is given, ``to_NNF`` decomposes the + specified predicate into a combination of primitive predicates. + + >>> cmap = {Q.nonpositive: Q.negative | Q.zero} + >>> to_NNF(Q.nonpositive, cmap) + (Literal(Q.negative, False) | Literal(Q.zero, False)) + >>> to_NNF(Q.nonpositive(x), cmap) + (Literal(Q.negative(x), False) | Literal(Q.zero(x), False)) + """ + from sympy.assumptions.ask import Q + + if composite_map is None: + composite_map = {} + + + binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le} + if type(expr) in binrelpreds: + pred = binrelpreds[type(expr)] + expr = pred(*expr.args) + + if isinstance(expr, Not): + arg = expr.args[0] + tmp = to_NNF(arg, composite_map) # Strategy: negate the NNF of expr + return ~tmp + + if isinstance(expr, Or): + return OR(*[to_NNF(x, composite_map) for x in Or.make_args(expr)]) + + if isinstance(expr, And): + return AND(*[to_NNF(x, composite_map) for x in And.make_args(expr)]) + + if isinstance(expr, Nand): + tmp = AND(*[to_NNF(x, composite_map) for x in expr.args]) + return ~tmp + + if isinstance(expr, Nor): + tmp = OR(*[to_NNF(x, composite_map) for x in expr.args]) + return ~tmp + + if isinstance(expr, Xor): + cnfs = [] + for i in range(0, len(expr.args) + 1, 2): + for neg in combinations(expr.args, i): + clause = [~to_NNF(s, composite_map) if s in neg else to_NNF(s, composite_map) + for s in expr.args] + cnfs.append(OR(*clause)) + return AND(*cnfs) + + if isinstance(expr, Xnor): + cnfs = [] + for i in range(0, len(expr.args) + 1, 2): + for neg in combinations(expr.args, i): + clause = [~to_NNF(s, composite_map) if s in neg else to_NNF(s, composite_map) + for s in expr.args] + cnfs.append(OR(*clause)) + return ~AND(*cnfs) + + if isinstance(expr, Implies): + L, R = to_NNF(expr.args[0], composite_map), to_NNF(expr.args[1], composite_map) + return OR(~L, R) + + if isinstance(expr, Equivalent): + cnfs = [] + for a, b in zip_longest(expr.args, expr.args[1:], fillvalue=expr.args[0]): + a = to_NNF(a, composite_map) + b = to_NNF(b, composite_map) + cnfs.append(OR(~a, b)) + return AND(*cnfs) + + if isinstance(expr, ITE): + L = to_NNF(expr.args[0], composite_map) + M = to_NNF(expr.args[1], composite_map) + R = to_NNF(expr.args[2], composite_map) + return AND(OR(~L, M), OR(L, R)) + + if isinstance(expr, AppliedPredicate): + pred, args = expr.function, expr.arguments + newpred = composite_map.get(pred, None) + if newpred is not None: + return to_NNF(newpred.rcall(*args), composite_map) + + if isinstance(expr, Predicate): + newpred = composite_map.get(expr, None) + if newpred is not None: + return to_NNF(newpred, composite_map) + + return Literal(expr) + + +def distribute_AND_over_OR(expr): + """ + Distributes AND over OR in the NNF expression. + Returns the result( Conjunctive Normal Form of expression) + as a CNF object. + """ + if not isinstance(expr, (AND, OR)): + tmp = set() + tmp.add(frozenset((expr,))) + return CNF(tmp) + + if isinstance(expr, OR): + return CNF.all_or(*[distribute_AND_over_OR(arg) + for arg in expr._args]) + + if isinstance(expr, AND): + return CNF.all_and(*[distribute_AND_over_OR(arg) + for arg in expr._args]) + + +class CNF: + """ + Class to represent CNF of a Boolean expression. + Consists of set of clauses, which themselves are stored as + frozenset of Literal objects. + + Examples + ======== + + >>> from sympy import Q + >>> from sympy.assumptions.cnf import CNF + >>> from sympy.abc import x + >>> cnf = CNF.from_prop(Q.real(x) & ~Q.zero(x)) + >>> cnf.clauses + {frozenset({Literal(Q.zero(x), True)}), + frozenset({Literal(Q.negative(x), False), + Literal(Q.positive(x), False), Literal(Q.zero(x), False)})} + """ + def __init__(self, clauses=None): + if not clauses: + clauses = set() + self.clauses = clauses + + def add(self, prop): + clauses = CNF.to_CNF(prop).clauses + self.add_clauses(clauses) + + def __str__(self): + s = ' & '.join( + ['(' + ' | '.join([str(lit) for lit in clause]) +')' + for clause in self.clauses] + ) + return s + + def extend(self, props): + for p in props: + self.add(p) + return self + + def copy(self): + return CNF(set(self.clauses)) + + def add_clauses(self, clauses): + self.clauses |= clauses + + @classmethod + def from_prop(cls, prop): + res = cls() + res.add(prop) + return res + + def __iand__(self, other): + self.add_clauses(other.clauses) + return self + + def all_predicates(self): + predicates = set() + for c in self.clauses: + predicates |= {arg.lit for arg in c} + return predicates + + def _or(self, cnf): + clauses = set() + for a, b in product(self.clauses, cnf.clauses): + tmp = set(a) + for t in b: + tmp.add(t) + clauses.add(frozenset(tmp)) + return CNF(clauses) + + def _and(self, cnf): + clauses = self.clauses.union(cnf.clauses) + return CNF(clauses) + + def _not(self): + clss = list(self.clauses) + ll = set() + for x in clss[-1]: + ll.add(frozenset((~x,))) + ll = CNF(ll) + + for rest in clss[:-1]: + p = set() + for x in rest: + p.add(frozenset((~x,))) + ll = ll._or(CNF(p)) + return ll + + def rcall(self, expr): + clause_list = [] + for clause in self.clauses: + lits = [arg.rcall(expr) for arg in clause] + clause_list.append(OR(*lits)) + expr = AND(*clause_list) + return distribute_AND_over_OR(expr) + + @classmethod + def all_or(cls, *cnfs): + b = cnfs[0].copy() + for rest in cnfs[1:]: + b = b._or(rest) + return b + + @classmethod + def all_and(cls, *cnfs): + b = cnfs[0].copy() + for rest in cnfs[1:]: + b = b._and(rest) + return b + + @classmethod + def to_CNF(cls, expr): + from sympy.assumptions.facts import get_composite_predicates + expr = to_NNF(expr, get_composite_predicates()) + expr = distribute_AND_over_OR(expr) + return expr + + @classmethod + def CNF_to_cnf(cls, cnf): + """ + Converts CNF object to SymPy's boolean expression + retaining the form of expression. + """ + def remove_literal(arg): + return Not(arg.lit) if arg.is_Not else arg.lit + + return And(*(Or(*(remove_literal(arg) for arg in clause)) for clause in cnf.clauses)) + + +class EncodedCNF: + """ + Class for encoding the CNF expression. + """ + def __init__(self, data=None, encoding=None): + if not data and not encoding: + data = [] + encoding = {} + self.data = data + self.encoding = encoding + self._symbols = list(encoding.keys()) + + def from_cnf(self, cnf): + self._symbols = list(cnf.all_predicates()) + n = len(self._symbols) + self.encoding = dict(zip(self._symbols, range(1, n + 1))) + self.data = [self.encode(clause) for clause in cnf.clauses] + + @property + def symbols(self): + return self._symbols + + @property + def variables(self): + return range(1, len(self._symbols) + 1) + + def copy(self): + new_data = [set(clause) for clause in self.data] + return EncodedCNF(new_data, dict(self.encoding)) + + def add_prop(self, prop): + cnf = CNF.from_prop(prop) + self.add_from_cnf(cnf) + + def add_from_cnf(self, cnf): + clauses = [self.encode(clause) for clause in cnf.clauses] + self.data += clauses + + def encode_arg(self, arg): + literal = arg.lit + value = self.encoding.get(literal, None) + if value is None: + n = len(self._symbols) + self._symbols.append(literal) + value = self.encoding[literal] = n + 1 + if arg.is_Not: + return -value + else: + return value + + def encode(self, clause): + return {self.encode_arg(arg) if not arg.lit == S.false else 0 for arg in clause} diff --git a/shared/package-files/6b/6b15d194a0b6e1ddbd1c2d0304b6e375b4b7e25ad166efaa052324b5fd219196/roll_cpu_dispatch.h b/shared/package-files/6b/6b15d194a0b6e1ddbd1c2d0304b6e375b4b7e25ad166efaa052324b5fd219196/roll_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..dee2d129a38b72de591ea99507136c0bc9c7bbb8 --- /dev/null +++ b/shared/package-files/6b/6b15d194a0b6e1ddbd1c2d0304b6e375b4b7e25ad166efaa052324b5fd219196/roll_cpu_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor roll(const at::Tensor & self, at::IntArrayRef shifts, at::IntArrayRef dims={}); +TORCH_API at::Tensor roll_symint(const at::Tensor & self, c10::SymIntArrayRef shifts, at::IntArrayRef dims={}); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/6b/6b1709f3b80894c45dd87111fed0609be6379b03389f8a5120734243c8f093e7/test_to_numpy.py b/shared/package-files/6b/6b1709f3b80894c45dd87111fed0609be6379b03389f8a5120734243c8f093e7/test_to_numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..0731750aed0cf4b46fe7598b87d459036bc68146 --- /dev/null +++ b/shared/package-files/6b/6b1709f3b80894c45dd87111fed0609be6379b03389f8a5120734243c8f093e7/test_to_numpy.py @@ -0,0 +1,53 @@ +import numpy as np +import pytest + +import pandas.util._test_decorators as td + +from pandas import ( + DataFrame, + Timestamp, +) +import pandas._testing as tm + + +class TestToNumpy: + def test_to_numpy(self): + df = DataFrame({"A": [1, 2], "B": [3, 4.5]}) + expected = np.array([[1, 3], [2, 4.5]]) + result = df.to_numpy() + tm.assert_numpy_array_equal(result, expected) + + def test_to_numpy_dtype(self): + df = DataFrame({"A": [1, 2], "B": [3, 4.5]}) + expected = np.array([[1, 3], [2, 4]], dtype="int64") + result = df.to_numpy(dtype="int64") + tm.assert_numpy_array_equal(result, expected) + + @td.skip_array_manager_invalid_test + def test_to_numpy_copy(self, using_copy_on_write): + arr = np.random.default_rng(2).standard_normal((4, 3)) + df = DataFrame(arr) + if using_copy_on_write: + assert df.values.base is not arr + assert df.to_numpy(copy=False).base is df.values.base + else: + assert df.values.base is arr + assert df.to_numpy(copy=False).base is arr + assert df.to_numpy(copy=True).base is not arr + + # we still don't want a copy when na_value=np.nan is passed, + # and that can be respected because we are already numpy-float + if using_copy_on_write: + assert df.to_numpy(copy=False).base is df.values.base + else: + assert df.to_numpy(copy=False, na_value=np.nan).base is arr + + @pytest.mark.filterwarnings( + "ignore:invalid value encountered in cast:RuntimeWarning" + ) + def test_to_numpy_mixed_dtype_to_str(self): + # https://github.com/pandas-dev/pandas/issues/35455 + df = DataFrame([[Timestamp("2020-01-01 00:00:00"), 100.0]]) + result = df.to_numpy(dtype=str) + expected = np.array([["2020-01-01 00:00:00", "100.0"]], dtype=str) + tm.assert_numpy_array_equal(result, expected) diff --git a/shared/package-files/6b/6b1925ff62b3f95a9e66442002c182cbdb29c55eb63e48092a14e4950c96596b/api_vector.h b/shared/package-files/6b/6b1925ff62b3f95a9e66442002c182cbdb29c55eb63e48092a14e4950c96596b/api_vector.h new file mode 100644 index 0000000000000000000000000000000000000000..159a787641ee5216ac2f19ec304d3d8e25303e39 --- /dev/null +++ b/shared/package-files/6b/6b1925ff62b3f95a9e66442002c182cbdb29c55eb63e48092a14e4950c96596b/api_vector.h @@ -0,0 +1,835 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/compute/function_options.h" +#include "arrow/compute/ordering.h" +#include "arrow/result.h" +#include "arrow/type_fwd.h" + +namespace arrow { +namespace compute { + +class ExecContext; + +/// \addtogroup compute-concrete-options +/// @{ + +class ARROW_EXPORT FilterOptions : public FunctionOptions { + public: + /// Configure the action taken when a slot of the selection mask is null + enum NullSelectionBehavior { + /// The corresponding filtered value will be removed in the output. + DROP, + /// The corresponding filtered value will be null in the output. + EMIT_NULL, + }; + + explicit FilterOptions(NullSelectionBehavior null_selection = DROP); + static constexpr const char kTypeName[] = "FilterOptions"; + static FilterOptions Defaults() { return FilterOptions(); } + + NullSelectionBehavior null_selection_behavior = DROP; +}; + +class ARROW_EXPORT TakeOptions : public FunctionOptions { + public: + explicit TakeOptions(bool boundscheck = true); + static constexpr const char kTypeName[] = "TakeOptions"; + static TakeOptions BoundsCheck() { return TakeOptions(true); } + static TakeOptions NoBoundsCheck() { return TakeOptions(false); } + static TakeOptions Defaults() { return BoundsCheck(); } + + bool boundscheck = true; +}; + +/// \brief Options for the dictionary encode function +class ARROW_EXPORT DictionaryEncodeOptions : public FunctionOptions { + public: + /// Configure how null values will be encoded + enum NullEncodingBehavior { + /// The null value will be added to the dictionary with a proper index. + ENCODE, + /// The null value will be masked in the indices array. + MASK + }; + + explicit DictionaryEncodeOptions(NullEncodingBehavior null_encoding = MASK); + static constexpr const char kTypeName[] = "DictionaryEncodeOptions"; + static DictionaryEncodeOptions Defaults() { return DictionaryEncodeOptions(); } + + NullEncodingBehavior null_encoding_behavior = MASK; +}; + +/// \brief Options for the run-end encode function +class ARROW_EXPORT RunEndEncodeOptions : public FunctionOptions { + public: + explicit RunEndEncodeOptions(std::shared_ptr run_end_type = int32()); + static constexpr const char kTypeName[] = "RunEndEncodeOptions"; + static RunEndEncodeOptions Defaults() { return RunEndEncodeOptions(); } + + std::shared_ptr run_end_type; +}; + +class ARROW_EXPORT ArraySortOptions : public FunctionOptions { + public: + explicit ArraySortOptions(SortOrder order = SortOrder::Ascending, + NullPlacement null_placement = NullPlacement::AtEnd); + static constexpr const char kTypeName[] = "ArraySortOptions"; + static ArraySortOptions Defaults() { return ArraySortOptions(); } + + /// Sorting order + SortOrder order; + /// Whether nulls and NaNs are placed at the start or at the end + NullPlacement null_placement; +}; + +class ARROW_EXPORT SortOptions : public FunctionOptions { + public: + explicit SortOptions(std::vector sort_keys = {}, + NullPlacement null_placement = NullPlacement::AtEnd); + explicit SortOptions(const Ordering& ordering); + static constexpr const char kTypeName[] = "SortOptions"; + static SortOptions Defaults() { return SortOptions(); } + /// Convenience constructor to create an ordering from SortOptions + /// + /// Note: Both classes contain the exact same information. However, + /// sort_options should only be used in a "function options" context while Ordering + /// is used more generally. + Ordering AsOrdering() && { return Ordering(std::move(sort_keys), null_placement); } + Ordering AsOrdering() const& { return Ordering(sort_keys, null_placement); } + + /// Column key(s) to order by and how to order by these sort keys. + std::vector sort_keys; + /// Whether nulls and NaNs are placed at the start or at the end + NullPlacement null_placement; +}; + +/// \brief SelectK options +class ARROW_EXPORT SelectKOptions : public FunctionOptions { + public: + explicit SelectKOptions(int64_t k = -1, std::vector sort_keys = {}); + static constexpr const char kTypeName[] = "SelectKOptions"; + static SelectKOptions Defaults() { return SelectKOptions(); } + + static SelectKOptions TopKDefault(int64_t k, std::vector key_names = {}) { + std::vector keys; + for (const auto& name : key_names) { + keys.emplace_back(SortKey(name, SortOrder::Descending)); + } + if (key_names.empty()) { + keys.emplace_back(SortKey("not-used", SortOrder::Descending)); + } + return SelectKOptions{k, keys}; + } + static SelectKOptions BottomKDefault(int64_t k, + std::vector key_names = {}) { + std::vector keys; + for (const auto& name : key_names) { + keys.emplace_back(SortKey(name, SortOrder::Ascending)); + } + if (key_names.empty()) { + keys.emplace_back(SortKey("not-used", SortOrder::Ascending)); + } + return SelectKOptions{k, keys}; + } + + /// The number of `k` elements to keep. + int64_t k; + /// Column key(s) to order by and how to order by these sort keys. + std::vector sort_keys; +}; + +/// \brief Rank options +class ARROW_EXPORT RankOptions : public FunctionOptions { + public: + /// Configure how ties between equal values are handled + enum Tiebreaker { + /// Ties get the smallest possible rank in sorted order. + Min, + /// Ties get the largest possible rank in sorted order. + Max, + /// Ranks are assigned in order of when ties appear in the input. + /// This ensures the ranks are a stable permutation of the input. + First, + /// The ranks span a dense [1, M] interval where M is the number + /// of distinct values in the input. + Dense + }; + + explicit RankOptions(std::vector sort_keys = {}, + NullPlacement null_placement = NullPlacement::AtEnd, + Tiebreaker tiebreaker = RankOptions::First); + /// Convenience constructor for array inputs + explicit RankOptions(SortOrder order, + NullPlacement null_placement = NullPlacement::AtEnd, + Tiebreaker tiebreaker = RankOptions::First) + : RankOptions({SortKey("", order)}, null_placement, tiebreaker) {} + + static constexpr const char kTypeName[] = "RankOptions"; + static RankOptions Defaults() { return RankOptions(); } + + /// Column key(s) to order by and how to order by these sort keys. + std::vector sort_keys; + /// Whether nulls and NaNs are placed at the start or at the end + NullPlacement null_placement; + /// Tiebreaker for dealing with equal values in ranks + Tiebreaker tiebreaker; +}; + +/// \brief Quantile rank options +class ARROW_EXPORT RankQuantileOptions : public FunctionOptions { + public: + explicit RankQuantileOptions(std::vector sort_keys = {}, + NullPlacement null_placement = NullPlacement::AtEnd); + /// Convenience constructor for array inputs + explicit RankQuantileOptions(SortOrder order, + NullPlacement null_placement = NullPlacement::AtEnd) + : RankQuantileOptions({SortKey("", order)}, null_placement) {} + + static constexpr const char kTypeName[] = "RankQuantileOptions"; + static RankQuantileOptions Defaults() { return RankQuantileOptions(); } + + /// Column key(s) to order by and how to order by these sort keys. + std::vector sort_keys; + /// Whether nulls and NaNs are placed at the start or at the end + NullPlacement null_placement; +}; + +/// \brief Partitioning options for NthToIndices +class ARROW_EXPORT PartitionNthOptions : public FunctionOptions { + public: + explicit PartitionNthOptions(int64_t pivot, + NullPlacement null_placement = NullPlacement::AtEnd); + PartitionNthOptions() : PartitionNthOptions(0) {} + static constexpr const char kTypeName[] = "PartitionNthOptions"; + + /// The index into the equivalent sorted array of the partition pivot element. + int64_t pivot; + /// Whether nulls and NaNs are partitioned at the start or at the end + NullPlacement null_placement; +}; + +class ARROW_EXPORT WinsorizeOptions : public FunctionOptions { + public: + WinsorizeOptions(double lower_limit, double upper_limit); + WinsorizeOptions() : WinsorizeOptions(0, 1) {} + static constexpr const char kTypeName[] = "WinsorizeOptions"; + + /// The quantile below which all values are replaced with the quantile's value. + /// + /// For example, if lower_limit = 0.05, then all values in the lower 5% percentile + /// will be replaced with the 5% percentile value. + double lower_limit; + + /// The quantile above which all values are replaced with the quantile's value. + /// + /// For example, if upper_limit = 0.95, then all values in the upper 95% percentile + /// will be replaced with the 95% percentile value. + double upper_limit; +}; + +/// \brief Options for cumulative functions +/// \note Also aliased as CumulativeSumOptions for backward compatibility +class ARROW_EXPORT CumulativeOptions : public FunctionOptions { + public: + explicit CumulativeOptions(bool skip_nulls = false); + explicit CumulativeOptions(double start, bool skip_nulls = false); + explicit CumulativeOptions(std::shared_ptr start, bool skip_nulls = false); + static constexpr const char kTypeName[] = "CumulativeOptions"; + static CumulativeOptions Defaults() { return CumulativeOptions(); } + + /// Optional starting value for cumulative operation computation, default depends on the + /// operation and input type. + /// - sum: 0 + /// - prod: 1 + /// - min: maximum of the input type + /// - max: minimum of the input type + /// - mean: start is ignored because it has no meaning for mean + std::optional> start; + + /// If true, nulls in the input are ignored and produce a corresponding null output. + /// When false, the first null encountered is propagated through the remaining output. + bool skip_nulls = false; +}; +using CumulativeSumOptions = CumulativeOptions; // For backward compatibility + +/// \brief Options for pairwise functions +class ARROW_EXPORT PairwiseOptions : public FunctionOptions { + public: + explicit PairwiseOptions(int64_t periods = 1); + static constexpr const char kTypeName[] = "PairwiseOptions"; + static PairwiseOptions Defaults() { return PairwiseOptions(); } + + /// Periods to shift for applying the binary operation, accepts negative values. + int64_t periods = 1; +}; + +/// \brief Options for list_flatten function +class ARROW_EXPORT ListFlattenOptions : public FunctionOptions { + public: + explicit ListFlattenOptions(bool recursive = false); + static constexpr const char kTypeName[] = "ListFlattenOptions"; + static ListFlattenOptions Defaults() { return ListFlattenOptions(); } + + /// \brief If true, the list is flattened recursively until a non-list + /// array is formed. + bool recursive = false; +}; + +/// \brief Options for inverse_permutation function +class ARROW_EXPORT InversePermutationOptions : public FunctionOptions { + public: + explicit InversePermutationOptions( + int64_t max_index = -1, + std::optional> output_type = std::nullopt); + static constexpr const char kTypeName[] = "InversePermutationOptions"; + static InversePermutationOptions Defaults() { return InversePermutationOptions(); } + + /// \brief The max value in the input indices to allow. The length of the function's + /// output will be this value plus 1. If negative, this value will be set to the length + /// of the input indices minus 1 and the length of the function's output will be the + /// length of the input indices. + int64_t max_index = -1; + /// \brief The data type for the output array of inverse permutation. Defaults to the + /// type of the input indices when `nullopt`. Must be a signed integer type. An + /// invalid error will be reported if this type is not able to store the length of the + /// input indices. + std::optional> output_type; +}; + +/// \brief Options for scatter function +class ARROW_EXPORT ScatterOptions : public FunctionOptions { + public: + explicit ScatterOptions(int64_t max_index = -1); + static constexpr const char kTypeName[] = "ScatterOptions"; + static ScatterOptions Defaults() { return ScatterOptions(); } + + /// \brief The max value in the input indices to allow. The length of the function's + /// output will be this value plus 1. If negative, this value will be set to the length + /// of the input indices minus 1 and the length of the function's output will be the + /// length of the input indices. + int64_t max_index = -1; +}; + +/// @} + +/// \brief Filter with a boolean selection filter +/// +/// The output will be populated with values from the input at positions +/// where the selection filter is not 0. Nulls in the filter will be handled +/// based on options.null_selection_behavior. +/// +/// For example given values = ["a", "b", "c", null, "e", "f"] and +/// filter = [0, 1, 1, 0, null, 1], the output will be +/// (null_selection_behavior == DROP) = ["b", "c", "f"] +/// (null_selection_behavior == EMIT_NULL) = ["b", "c", null, "f"] +/// +/// \param[in] values array to filter +/// \param[in] filter indicates which values should be filtered out +/// \param[in] options configures null_selection_behavior +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +ARROW_EXPORT +Result Filter(const Datum& values, const Datum& filter, + const FilterOptions& options = FilterOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +namespace internal { + +// These internal functions are implemented in kernels/vector_selection.cc + +/// \brief Return the number of selected indices in the boolean filter +/// +/// \param filter a plain or run-end encoded boolean array with or without nulls +/// \param null_selection how to handle nulls in the filter +ARROW_EXPORT +int64_t GetFilterOutputSize(const ArraySpan& filter, + FilterOptions::NullSelectionBehavior null_selection); + +/// \brief Compute uint64 selection indices for use with Take given a boolean +/// filter +/// +/// \param filter a plain or run-end encoded boolean array with or without nulls +/// \param null_selection how to handle nulls in the filter +ARROW_EXPORT +Result> GetTakeIndices( + const ArraySpan& filter, FilterOptions::NullSelectionBehavior null_selection, + MemoryPool* memory_pool = default_memory_pool()); + +} // namespace internal + +/// \brief ReplaceWithMask replaces each value in the array corresponding +/// to a true value in the mask with the next element from `replacements`. +/// +/// \param[in] values Array input to replace +/// \param[in] mask Array or Scalar of Boolean mask values +/// \param[in] replacements The replacement values to draw from. There must +/// be as many replacement values as true values in the mask. +/// \param[in] ctx the function execution context, optional +/// +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result ReplaceWithMask(const Datum& values, const Datum& mask, + const Datum& replacements, ExecContext* ctx = NULLPTR); + +/// \brief FillNullForward fill null values in forward direction +/// +/// The output array will be of the same type as the input values +/// array, with replaced null values in forward direction. +/// +/// For example given values = ["a", "b", "c", null, null, "f"], +/// the output will be = ["a", "b", "c", "c", "c", "f"] +/// +/// \param[in] values datum from which to take +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +ARROW_EXPORT +Result FillNullForward(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief FillNullBackward fill null values in backward direction +/// +/// The output array will be of the same type as the input values +/// array, with replaced null values in backward direction. +/// +/// For example given values = ["a", "b", "c", null, null, "f"], +/// the output will be = ["a", "b", "c", "f", "f", "f"] +/// +/// \param[in] values datum from which to take +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +ARROW_EXPORT +Result FillNullBackward(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief Take from an array of values at indices in another array +/// +/// The output array will be of the same type as the input values +/// array, with elements taken from the values array at the given +/// indices. If an index is null then the taken element will be null. +/// +/// For example given values = ["a", "b", "c", null, "e", "f"] and +/// indices = [2, 1, null, 3], the output will be +/// = [values[2], values[1], null, values[3]] +/// = ["c", "b", null, null] +/// +/// \param[in] values datum from which to take +/// \param[in] indices which values to take +/// \param[in] options options +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +ARROW_EXPORT +Result Take(const Datum& values, const Datum& indices, + const TakeOptions& options = TakeOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Take with Array inputs and output +ARROW_EXPORT +Result> Take(const Array& values, const Array& indices, + const TakeOptions& options = TakeOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Drop Null from an array of values +/// +/// The output array will be of the same type as the input values +/// array, with elements taken from the values array without nulls. +/// +/// For example given values = ["a", "b", "c", null, "e", "f"], +/// the output will be = ["a", "b", "c", "e", "f"] +/// +/// \param[in] values datum from which to take +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +ARROW_EXPORT +Result DropNull(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief DropNull with Array inputs and output +ARROW_EXPORT +Result> DropNull(const Array& values, ExecContext* ctx = NULLPTR); + +/// \brief Return indices that partition an array around n-th sorted element. +/// +/// Find index of n-th(0 based) smallest value and perform indirect +/// partition of an array around that element. Output indices[0 ~ n-1] +/// holds values no greater than n-th element, and indices[n+1 ~ end] +/// holds values no less than n-th element. Elements in each partition +/// is not sorted. Nulls will be partitioned to the end of the output. +/// Output is not guaranteed to be stable. +/// +/// \param[in] values array to be partitioned +/// \param[in] n pivot array around sorted n-th element +/// \param[in] ctx the function execution context, optional +/// \return offsets indices that would partition an array +ARROW_EXPORT +Result> NthToIndices(const Array& values, int64_t n, + ExecContext* ctx = NULLPTR); + +/// \brief Return indices that partition an array around n-th sorted element. +/// +/// This overload takes a PartitionNthOptions specifying the pivot index +/// and the null handling. +/// +/// \param[in] values array to be partitioned +/// \param[in] options options including pivot index and null handling +/// \param[in] ctx the function execution context, optional +/// \return offsets indices that would partition an array +ARROW_EXPORT +Result> NthToIndices(const Array& values, + const PartitionNthOptions& options, + ExecContext* ctx = NULLPTR); + +/// \brief Return indices that would select the first `k` elements. +/// +/// Perform an indirect sort of the datum, keeping only the first `k` elements. The output +/// array will contain indices such that the item indicated by the k-th index will be in +/// the position it would be if the datum were sorted by `options.sort_keys`. However, +/// indices of null values will not be part of the output. The sort is not guaranteed to +/// be stable. +/// +/// \param[in] datum datum to be partitioned +/// \param[in] options options +/// \param[in] ctx the function execution context, optional +/// \return a datum with the same schema as the input +ARROW_EXPORT +Result> SelectKUnstable(const Datum& datum, + const SelectKOptions& options, + ExecContext* ctx = NULLPTR); + +/// \brief Return the indices that would sort an array. +/// +/// Perform an indirect sort of array. The output array will contain +/// indices that would sort an array, which would be the same length +/// as input. Nulls will be stably partitioned to the end of the output +/// regardless of order. +/// +/// For example given array = [null, 1, 3.3, null, 2, 5.3] and order +/// = SortOrder::DESCENDING, the output will be [5, 2, 4, 1, 0, +/// 3]. +/// +/// \param[in] array array to sort +/// \param[in] order ascending or descending +/// \param[in] ctx the function execution context, optional +/// \return offsets indices that would sort an array +ARROW_EXPORT +Result> SortIndices(const Array& array, + SortOrder order = SortOrder::Ascending, + ExecContext* ctx = NULLPTR); + +/// \brief Return the indices that would sort an array. +/// +/// This overload takes a ArraySortOptions specifying the sort order +/// and the null handling. +/// +/// \param[in] array array to sort +/// \param[in] options options including sort order and null handling +/// \param[in] ctx the function execution context, optional +/// \return offsets indices that would sort an array +ARROW_EXPORT +Result> SortIndices(const Array& array, + const ArraySortOptions& options, + ExecContext* ctx = NULLPTR); + +/// \brief Return the indices that would sort a chunked array. +/// +/// Perform an indirect sort of chunked array. The output array will +/// contain indices that would sort a chunked array, which would be +/// the same length as input. Nulls will be stably partitioned to the +/// end of the output regardless of order. +/// +/// For example given chunked_array = [[null, 1], [3.3], [null, 2, +/// 5.3]] and order = SortOrder::DESCENDING, the output will be [5, 2, +/// 4, 1, 0, 3]. +/// +/// \param[in] chunked_array chunked array to sort +/// \param[in] order ascending or descending +/// \param[in] ctx the function execution context, optional +/// \return offsets indices that would sort an array +ARROW_EXPORT +Result> SortIndices(const ChunkedArray& chunked_array, + SortOrder order = SortOrder::Ascending, + ExecContext* ctx = NULLPTR); + +/// \brief Return the indices that would sort a chunked array. +/// +/// This overload takes a ArraySortOptions specifying the sort order +/// and the null handling. +/// +/// \param[in] chunked_array chunked array to sort +/// \param[in] options options including sort order and null handling +/// \param[in] ctx the function execution context, optional +/// \return offsets indices that would sort an array +ARROW_EXPORT +Result> SortIndices(const ChunkedArray& chunked_array, + const ArraySortOptions& options, + ExecContext* ctx = NULLPTR); + +/// \brief Return the indices that would sort an input in the +/// specified order. Input is one of array, chunked array record batch +/// or table. +/// +/// Perform an indirect sort of input. The output array will contain +/// indices that would sort an input, which would be the same length +/// as input. Nulls will be stably partitioned to the start or to the end +/// of the output depending on SortOrder::null_placement. +/// +/// For example given input (table) = { +/// "column1": [[null, 1], [ 3, null, 2, 1]], +/// "column2": [[ 5], [3, null, null, 5, 5]], +/// } and options = { +/// {"column1", SortOrder::Ascending}, +/// {"column2", SortOrder::Descending}, +/// }, the output will be [5, 1, 4, 2, 0, 3]. +/// +/// \param[in] datum array, chunked array, record batch or table to sort +/// \param[in] options options +/// \param[in] ctx the function execution context, optional +/// \return offsets indices that would sort a table +ARROW_EXPORT +Result> SortIndices(const Datum& datum, const SortOptions& options, + ExecContext* ctx = NULLPTR); + +/// \brief Compute unique elements from an array-like object +/// +/// Note if a null occurs in the input it will NOT be included in the output. +/// +/// \param[in] datum array-like input +/// \param[in] ctx the function execution context, optional +/// \return result as Array +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result> Unique(const Datum& datum, ExecContext* ctx = NULLPTR); + +// Constants for accessing the output of ValueCounts +ARROW_EXPORT extern const char kValuesFieldName[]; +ARROW_EXPORT extern const char kCountsFieldName[]; +ARROW_EXPORT extern const int32_t kValuesFieldIndex; +ARROW_EXPORT extern const int32_t kCountsFieldIndex; + +/// \brief Return counts of unique elements from an array-like object. +/// +/// Note that the counts do not include counts for nulls in the array. These can be +/// obtained separately from metadata. +/// +/// For floating point arrays there is no attempt to normalize -0.0, 0.0 and NaN values +/// which can lead to unexpected results if the input Array has these values. +/// +/// \param[in] value array-like input +/// \param[in] ctx the function execution context, optional +/// \return counts An array of structs. +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result> ValueCounts(const Datum& value, + ExecContext* ctx = NULLPTR); + +/// \brief Dictionary-encode values in an array-like object +/// +/// Any nulls encountered in the dictionary will be handled according to the +/// specified null encoding behavior. +/// +/// For example, given values ["a", "b", null, "a", null] the output will be +/// (null_encoding == ENCODE) Indices: [0, 1, 2, 0, 2] / Dict: ["a", "b", null] +/// (null_encoding == MASK) Indices: [0, 1, null, 0, null] / Dict: ["a", "b"] +/// +/// If the input is already dictionary encoded this function is a no-op unless +/// it needs to modify the null_encoding (TODO) +/// +/// \param[in] data array-like input +/// \param[in] ctx the function execution context, optional +/// \param[in] options configures null encoding behavior +/// \return result with same shape and type as input +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result DictionaryEncode( + const Datum& data, + const DictionaryEncodeOptions& options = DictionaryEncodeOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Run-end-encode values in an array-like object +/// +/// The returned run-end encoded type uses the same value type of the input and +/// run-end type defined in the options. +/// +/// \param[in] value array-like input +/// \param[in] options configures encoding behavior +/// \param[in] ctx the function execution context, optional +/// \return result with same shape but run-end encoded +/// +/// \since 12.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result RunEndEncode( + const Datum& value, + const RunEndEncodeOptions& options = RunEndEncodeOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Decode a Run-End Encoded array to a plain array +/// +/// The output data type is the same as the values array type of run-end encoded +/// input. +/// +/// \param[in] value run-end-encoded input +/// \param[in] ctx the function execution context, optional +/// \return plain array resulting from decoding the run-end encoded input +/// +/// \since 12.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result RunEndDecode(const Datum& value, ExecContext* ctx = NULLPTR); + +/// \brief Compute the cumulative sum of an array-like object +/// +/// \param[in] values array-like input +/// \param[in] options configures cumulative sum behavior +/// \param[in] check_overflow whether to check for overflow, if true, return Invalid +/// status on overflow, otherwise wrap around on overflow +/// \param[in] ctx the function execution context, optional +ARROW_EXPORT +Result CumulativeSum( + const Datum& values, const CumulativeOptions& options = CumulativeOptions::Defaults(), + bool check_overflow = false, ExecContext* ctx = NULLPTR); + +/// \brief Compute the cumulative product of an array-like object +/// +/// \param[in] values array-like input +/// \param[in] options configures cumulative prod behavior +/// \param[in] check_overflow whether to check for overflow, if true, return Invalid +/// status on overflow, otherwise wrap around on overflow +/// \param[in] ctx the function execution context, optional +ARROW_EXPORT +Result CumulativeProd( + const Datum& values, const CumulativeOptions& options = CumulativeOptions::Defaults(), + bool check_overflow = false, ExecContext* ctx = NULLPTR); + +/// \brief Compute the cumulative max of an array-like object +/// +/// \param[in] values array-like input +/// \param[in] options configures cumulative max behavior +/// \param[in] ctx the function execution context, optional +ARROW_EXPORT +Result CumulativeMax( + const Datum& values, const CumulativeOptions& options = CumulativeOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Compute the cumulative min of an array-like object +/// +/// \param[in] values array-like input +/// \param[in] options configures cumulative min behavior +/// \param[in] ctx the function execution context, optional +ARROW_EXPORT +Result CumulativeMin( + const Datum& values, const CumulativeOptions& options = CumulativeOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Compute the cumulative mean of an array-like object +/// +/// \param[in] values array-like input +/// \param[in] options configures cumulative mean behavior, `start` is ignored +/// \param[in] ctx the function execution context, optional +ARROW_EXPORT +Result CumulativeMean( + const Datum& values, const CumulativeOptions& options = CumulativeOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Return the first order difference of an array. +/// +/// Computes the first order difference of an array, i.e. +/// output[i] = input[i] - input[i - p] if i >= p +/// output[i] = null otherwise +/// where p is the period. For example, with p = 1, +/// Diff([1, 4, 9, 10, 15]) = [null, 3, 5, 1, 5]. +/// With p = 2, +/// Diff([1, 4, 9, 10, 15]) = [null, null, 8, 6, 6] +/// p can also be negative, in which case the diff is computed in +/// the opposite direction. +/// \param[in] array array input +/// \param[in] options options, specifying overflow behavior and period +/// \param[in] check_overflow whether to return error on overflow +/// \param[in] ctx the function execution context, optional +/// \return result as array +ARROW_EXPORT +Result> PairwiseDiff(const Array& array, + const PairwiseOptions& options, + bool check_overflow = false, + ExecContext* ctx = NULLPTR); + +/// \brief Return the inverse permutation of the given indices. +/// +/// For indices[i] = x, inverse_permutation[x] = i. And inverse_permutation[x] = null if x +/// does not appear in the input indices. Indices must be in the range of [0, max_index], +/// or null, which will be ignored. If multiple indices point to the same value, the last +/// one is used. +/// +/// For example, with +/// indices = [null, 0, null, 2, 4, 1, 1] +/// the inverse permutation is +/// [1, 6, 3, null, 4, null, null] +/// if max_index = 6. +/// +/// \param[in] indices array-like indices +/// \param[in] options configures the max index and the output type +/// \param[in] ctx the function execution context, optional +/// \return the resulting inverse permutation +/// +/// \since 20.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result InversePermutation( + const Datum& indices, + const InversePermutationOptions& options = InversePermutationOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Scatter the values into specified positions according to the indices. +/// +/// For indices[i] = x, output[x] = values[i]. And output[x] = null if x does not appear +/// in the input indices. Indices must be in the range of [0, max_index], or null, in +/// which case the corresponding value will be ignored. If multiple indices point to the +/// same value, the last one is used. +/// +/// For example, with +/// values = [a, b, c, d, e, f, g] +/// indices = [null, 0, null, 2, 4, 1, 1] +/// the output is +/// [b, g, d, null, e, null, null] +/// if max_index = 6. +/// +/// \param[in] values datum to scatter +/// \param[in] indices array-like indices +/// \param[in] options configures the max index of to scatter +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 20.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Scatter(const Datum& values, const Datum& indices, + const ScatterOptions& options = ScatterOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +} // namespace compute +} // namespace arrow diff --git a/shared/package-files/6b/6b1b13632584bf133c0eb73b84ef410d6296c068058bfc17aa6072220176d405/_affinity_propagation.py b/shared/package-files/6b/6b1b13632584bf133c0eb73b84ef410d6296c068058bfc17aa6072220176d405/_affinity_propagation.py new file mode 100644 index 0000000000000000000000000000000000000000..c7ae6ed63580d60eb2d889c11cfe84875380c55c --- /dev/null +++ b/shared/package-files/6b/6b1b13632584bf133c0eb73b84ef410d6296c068058bfc17aa6072220176d405/_affinity_propagation.py @@ -0,0 +1,607 @@ +"""Affinity Propagation clustering algorithm.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Integral, Real + +import numpy as np + +from .._config import config_context +from ..base import BaseEstimator, ClusterMixin, _fit_context +from ..exceptions import ConvergenceWarning +from ..metrics import euclidean_distances, pairwise_distances_argmin +from ..utils import check_random_state +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.validation import check_is_fitted, validate_data + + +def _equal_similarities_and_preferences(S, preference): + def all_equal_preferences(): + return np.all(preference == preference.flat[0]) + + def all_equal_similarities(): + # Create mask to ignore diagonal of S + mask = np.ones(S.shape, dtype=bool) + np.fill_diagonal(mask, 0) + + return np.all(S[mask].flat == S[mask].flat[0]) + + return all_equal_preferences() and all_equal_similarities() + + +def _affinity_propagation( + S, + *, + preference, + convergence_iter, + max_iter, + damping, + verbose, + return_n_iter, + random_state, +): + """Main affinity propagation algorithm.""" + n_samples = S.shape[0] + if n_samples == 1 or _equal_similarities_and_preferences(S, preference): + # It makes no sense to run the algorithm in this case, so return 1 or + # n_samples clusters, depending on preferences + warnings.warn( + "All samples have mutually equal similarities. " + "Returning arbitrary cluster center(s)." + ) + if preference.flat[0] > S.flat[n_samples - 1]: + return ( + (np.arange(n_samples), np.arange(n_samples), 0) + if return_n_iter + else (np.arange(n_samples), np.arange(n_samples)) + ) + else: + return ( + (np.array([0]), np.array([0] * n_samples), 0) + if return_n_iter + else (np.array([0]), np.array([0] * n_samples)) + ) + + # Place preference on the diagonal of S + S.flat[:: (n_samples + 1)] = preference + + A = np.zeros((n_samples, n_samples)) + R = np.zeros((n_samples, n_samples)) # Initialize messages + # Intermediate results + tmp = np.zeros((n_samples, n_samples)) + + # Remove degeneracies + S += ( + np.finfo(S.dtype).eps * S + np.finfo(S.dtype).tiny * 100 + ) * random_state.standard_normal(size=(n_samples, n_samples)) + + # Execute parallel affinity propagation updates + e = np.zeros((n_samples, convergence_iter)) + + ind = np.arange(n_samples) + + for it in range(max_iter): + # tmp = A + S; compute responsibilities + np.add(A, S, tmp) + I = np.argmax(tmp, axis=1) + Y = tmp[ind, I] # np.max(A + S, axis=1) + tmp[ind, I] = -np.inf + Y2 = np.max(tmp, axis=1) + + # tmp = Rnew + np.subtract(S, Y[:, None], tmp) + tmp[ind, I] = S[ind, I] - Y2 + + # Damping + tmp *= 1 - damping + R *= damping + R += tmp + + # tmp = Rp; compute availabilities + np.maximum(R, 0, tmp) + tmp.flat[:: n_samples + 1] = R.flat[:: n_samples + 1] + + # tmp = -Anew + tmp -= np.sum(tmp, axis=0) + dA = np.diag(tmp).copy() + tmp.clip(0, np.inf, tmp) + tmp.flat[:: n_samples + 1] = dA + + # Damping + tmp *= 1 - damping + A *= damping + A -= tmp + + # Check for convergence + E = (np.diag(A) + np.diag(R)) > 0 + e[:, it % convergence_iter] = E + K = np.sum(E, axis=0) + + if it >= convergence_iter: + se = np.sum(e, axis=1) + unconverged = np.sum((se == convergence_iter) + (se == 0)) != n_samples + if (not unconverged and (K > 0)) or (it == max_iter): + never_converged = False + if verbose: + print("Converged after %d iterations." % it) + break + else: + never_converged = True + if verbose: + print("Did not converge") + + I = np.flatnonzero(E) + K = I.size # Identify exemplars + + if K > 0: + if never_converged: + warnings.warn( + ( + "Affinity propagation did not converge, this model " + "may return degenerate cluster centers and labels." + ), + ConvergenceWarning, + ) + c = np.argmax(S[:, I], axis=1) + c[I] = np.arange(K) # Identify clusters + # Refine the final set of exemplars and clusters and return results + for k in range(K): + ii = np.asarray(c == k).nonzero()[0] + j = np.argmax(np.sum(S[ii[:, np.newaxis], ii], axis=0)) + I[k] = ii[j] + + c = np.argmax(S[:, I], axis=1) + c[I] = np.arange(K) + labels = I[c] + # Reduce labels to a sorted, gapless, list + cluster_centers_indices = np.unique(labels) + labels = np.searchsorted(cluster_centers_indices, labels) + else: + warnings.warn( + ( + "Affinity propagation did not converge and this model " + "will not have any cluster centers." + ), + ConvergenceWarning, + ) + labels = np.array([-1] * n_samples) + cluster_centers_indices = [] + + if return_n_iter: + return cluster_centers_indices, labels, it + 1 + else: + return cluster_centers_indices, labels + + +############################################################################### +# Public API + + +@validate_params( + { + "S": ["array-like"], + "return_n_iter": ["boolean"], + }, + prefer_skip_nested_validation=False, +) +def affinity_propagation( + S, + *, + preference=None, + convergence_iter=15, + max_iter=200, + damping=0.5, + copy=True, + verbose=False, + return_n_iter=False, + random_state=None, +): + """Perform Affinity Propagation Clustering of data. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + S : array-like of shape (n_samples, n_samples) + Matrix of similarities between points. + + preference : array-like of shape (n_samples,) or float, default=None + Preferences for each point - points with larger values of + preferences are more likely to be chosen as exemplars. The number of + exemplars, i.e. of clusters, is influenced by the input preferences + value. If the preferences are not passed as arguments, they will be + set to the median of the input similarities (resulting in a moderate + number of clusters). For a smaller amount of clusters, this can be set + to the minimum value of the similarities. + + convergence_iter : int, default=15 + Number of iterations with no change in the number + of estimated clusters that stops the convergence. + + max_iter : int, default=200 + Maximum number of iterations. + + damping : float, default=0.5 + Damping factor between 0.5 and 1. + + copy : bool, default=True + If copy is False, the affinity matrix is modified inplace by the + algorithm, for memory efficiency. + + verbose : bool, default=False + The verbosity level. + + return_n_iter : bool, default=False + Whether or not to return the number of iterations. + + random_state : int, RandomState instance or None, default=None + Pseudo-random number generator to control the starting state. + Use an int for reproducible results across function calls. + See the :term:`Glossary `. + + .. versionadded:: 0.23 + this parameter was previously hardcoded as 0. + + Returns + ------- + cluster_centers_indices : ndarray of shape (n_clusters,) + Index of clusters centers. + + labels : ndarray of shape (n_samples,) + Cluster labels for each point. + + n_iter : int + Number of iterations run. Returned only if `return_n_iter` is + set to True. + + Notes + ----- + For an example usage, + see :ref:`sphx_glr_auto_examples_cluster_plot_affinity_propagation.py`. + You may also check out, + :ref:`sphx_glr_auto_examples_applications_plot_stock_market.py` + + When the algorithm does not converge, it will still return a arrays of + ``cluster_center_indices`` and labels if there are any exemplars/clusters, + however they may be degenerate and should be used with caution. + + When all training samples have equal similarities and equal preferences, + the assignment of cluster centers and labels depends on the preference. + If the preference is smaller than the similarities, a single cluster center + and label ``0`` for every sample will be returned. Otherwise, every + training sample becomes its own cluster center and is assigned a unique + label. + + References + ---------- + Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages + Between Data Points", Science Feb. 2007 + + Examples + -------- + >>> import numpy as np + >>> from sklearn.cluster import affinity_propagation + >>> from sklearn.metrics.pairwise import euclidean_distances + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [4, 2], [4, 4], [4, 0]]) + >>> S = -euclidean_distances(X, squared=True) + >>> cluster_centers_indices, labels = affinity_propagation(S, random_state=0) + >>> cluster_centers_indices + array([0, 3]) + >>> labels + array([0, 0, 0, 1, 1, 1]) + """ + estimator = AffinityPropagation( + damping=damping, + max_iter=max_iter, + convergence_iter=convergence_iter, + copy=copy, + preference=preference, + affinity="precomputed", + verbose=verbose, + random_state=random_state, + ).fit(S) + + if return_n_iter: + return estimator.cluster_centers_indices_, estimator.labels_, estimator.n_iter_ + return estimator.cluster_centers_indices_, estimator.labels_ + + +class AffinityPropagation(ClusterMixin, BaseEstimator): + """Perform Affinity Propagation Clustering of data. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + damping : float, default=0.5 + Damping factor in the range `[0.5, 1.0)` is the extent to + which the current value is maintained relative to + incoming values (weighted 1 - damping). This in order + to avoid numerical oscillations when updating these + values (messages). + + max_iter : int, default=200 + Maximum number of iterations. + + convergence_iter : int, default=15 + Number of iterations with no change in the number + of estimated clusters that stops the convergence. + + copy : bool, default=True + Make a copy of input data. + + preference : array-like of shape (n_samples,) or float, default=None + Preferences for each point - points with larger values of + preferences are more likely to be chosen as exemplars. The number + of exemplars, ie of clusters, is influenced by the input + preferences value. If the preferences are not passed as arguments, + they will be set to the median of the input similarities. + + affinity : {'euclidean', 'precomputed'}, default='euclidean' + Which affinity to use. At the moment 'precomputed' and + ``euclidean`` are supported. 'euclidean' uses the + negative squared euclidean distance between points. + + verbose : bool, default=False + Whether to be verbose. + + random_state : int, RandomState instance or None, default=None + Pseudo-random number generator to control the starting state. + Use an int for reproducible results across function calls. + See the :term:`Glossary `. + + .. versionadded:: 0.23 + this parameter was previously hardcoded as 0. + + Attributes + ---------- + cluster_centers_indices_ : ndarray of shape (n_clusters,) + Indices of cluster centers. + + cluster_centers_ : ndarray of shape (n_clusters, n_features) + Cluster centers (if affinity != ``precomputed``). + + labels_ : ndarray of shape (n_samples,) + Labels of each point. + + affinity_matrix_ : ndarray of shape (n_samples, n_samples) + Stores the affinity matrix used in ``fit``. + + n_iter_ : int + Number of iterations taken to converge. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + AgglomerativeClustering : Recursively merges the pair of + clusters that minimally increases a given linkage distance. + FeatureAgglomeration : Similar to AgglomerativeClustering, + but recursively merges features instead of samples. + KMeans : K-Means clustering. + MiniBatchKMeans : Mini-Batch K-Means clustering. + MeanShift : Mean shift clustering using a flat kernel. + SpectralClustering : Apply clustering to a projection + of the normalized Laplacian. + + Notes + ----- + The algorithmic complexity of affinity propagation is quadratic + in the number of points. + + When the algorithm does not converge, it will still return a arrays of + ``cluster_center_indices`` and labels if there are any exemplars/clusters, + however they may be degenerate and should be used with caution. + + When ``fit`` does not converge, ``cluster_centers_`` is still populated + however it may be degenerate. In such a case, proceed with caution. + If ``fit`` does not converge and fails to produce any ``cluster_centers_`` + then ``predict`` will label every sample as ``-1``. + + When all training samples have equal similarities and equal preferences, + the assignment of cluster centers and labels depends on the preference. + If the preference is smaller than the similarities, ``fit`` will result in + a single cluster center and label ``0`` for every sample. Otherwise, every + training sample becomes its own cluster center and is assigned a unique + label. + + References + ---------- + + Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages + Between Data Points", Science Feb. 2007 + + Examples + -------- + >>> from sklearn.cluster import AffinityPropagation + >>> import numpy as np + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [4, 2], [4, 4], [4, 0]]) + >>> clustering = AffinityPropagation(random_state=5).fit(X) + >>> clustering + AffinityPropagation(random_state=5) + >>> clustering.labels_ + array([0, 0, 0, 1, 1, 1]) + >>> clustering.predict([[0, 0], [4, 4]]) + array([0, 1]) + >>> clustering.cluster_centers_ + array([[1, 2], + [4, 2]]) + + For an example usage, + see :ref:`sphx_glr_auto_examples_cluster_plot_affinity_propagation.py`. + + For a comparison of Affinity Propagation with other clustering algorithms, see + :ref:`sphx_glr_auto_examples_cluster_plot_cluster_comparison.py` + """ + + _parameter_constraints: dict = { + "damping": [Interval(Real, 0.5, 1.0, closed="left")], + "max_iter": [Interval(Integral, 1, None, closed="left")], + "convergence_iter": [Interval(Integral, 1, None, closed="left")], + "copy": ["boolean"], + "preference": [ + "array-like", + Interval(Real, None, None, closed="neither"), + None, + ], + "affinity": [StrOptions({"euclidean", "precomputed"})], + "verbose": ["verbose"], + "random_state": ["random_state"], + } + + def __init__( + self, + *, + damping=0.5, + max_iter=200, + convergence_iter=15, + copy=True, + preference=None, + affinity="euclidean", + verbose=False, + random_state=None, + ): + self.damping = damping + self.max_iter = max_iter + self.convergence_iter = convergence_iter + self.copy = copy + self.verbose = verbose + self.preference = preference + self.affinity = affinity + self.random_state = random_state + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.pairwise = self.affinity == "precomputed" + tags.input_tags.sparse = self.affinity != "precomputed" + return tags + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit the clustering from features, or affinity matrix. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), or \ + array-like of shape (n_samples, n_samples) + Training instances to cluster, or similarities / affinities between + instances if ``affinity='precomputed'``. If a sparse feature matrix + is provided, it will be converted into a sparse ``csr_matrix``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self + Returns the instance itself. + """ + if self.affinity == "precomputed": + X = validate_data(self, X, copy=self.copy, force_writeable=True) + self.affinity_matrix_ = X + else: # self.affinity == "euclidean" + X = validate_data(self, X, accept_sparse="csr") + self.affinity_matrix_ = -euclidean_distances(X, squared=True) + + if self.affinity_matrix_.shape[0] != self.affinity_matrix_.shape[1]: + raise ValueError( + "The matrix of similarities must be a square array. " + f"Got {self.affinity_matrix_.shape} instead." + ) + + if self.preference is None: + preference = np.median(self.affinity_matrix_) + else: + preference = self.preference + preference = np.asarray(preference) + + random_state = check_random_state(self.random_state) + + ( + self.cluster_centers_indices_, + self.labels_, + self.n_iter_, + ) = _affinity_propagation( + self.affinity_matrix_, + max_iter=self.max_iter, + convergence_iter=self.convergence_iter, + preference=preference, + damping=self.damping, + verbose=self.verbose, + return_n_iter=True, + random_state=random_state, + ) + + if self.affinity != "precomputed": + self.cluster_centers_ = X[self.cluster_centers_indices_].copy() + + return self + + def predict(self, X): + """Predict the closest cluster each sample in X belongs to. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + New data to predict. If a sparse matrix is provided, it will be + converted into a sparse ``csr_matrix``. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Cluster labels. + """ + check_is_fitted(self) + X = validate_data(self, X, reset=False, accept_sparse="csr") + if not hasattr(self, "cluster_centers_"): + raise ValueError( + "Predict method is not supported when affinity='precomputed'." + ) + + if self.cluster_centers_.shape[0] > 0: + with config_context(assume_finite=True): + return pairwise_distances_argmin(X, self.cluster_centers_) + else: + warnings.warn( + ( + "This model does not have any cluster centers " + "because affinity propagation did not converge. " + "Labeling every sample as '-1'." + ), + ConvergenceWarning, + ) + return np.array([-1] * X.shape[0]) + + def fit_predict(self, X, y=None): + """Fit clustering from features/affinity matrix; return cluster labels. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), or \ + array-like of shape (n_samples, n_samples) + Training instances to cluster, or similarities / affinities between + instances if ``affinity='precomputed'``. If a sparse feature matrix + is provided, it will be converted into a sparse ``csr_matrix``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Cluster labels. + """ + return super().fit_predict(X, y) diff --git a/shared/package-files/6b/6b2030c5fac0d5201f7d0b5ad27c120e6dd30d3e0a62220637f0fd678e41df5d/loaders.py b/shared/package-files/6b/6b2030c5fac0d5201f7d0b5ad27c120e6dd30d3e0a62220637f0fd678e41df5d/loaders.py new file mode 100644 index 0000000000000000000000000000000000000000..32f3a74e7d912ace28c4eee0e4c231c989c2c93c --- /dev/null +++ b/shared/package-files/6b/6b2030c5fac0d5201f7d0b5ad27c120e6dd30d3e0a62220637f0fd678e41df5d/loaders.py @@ -0,0 +1,661 @@ +"""API and implementations for loading templates from different data +sources. +""" +import importlib.util +import os +import posixpath +import sys +import typing as t +import weakref +import zipimport +from collections import abc +from hashlib import sha1 +from importlib import import_module +from types import ModuleType + +from .exceptions import TemplateNotFound +from .utils import internalcode + +if t.TYPE_CHECKING: + from .environment import Environment + from .environment import Template + + +def split_template_path(template: str) -> t.List[str]: + """Split a path into segments and perform a sanity check. If it detects + '..' in the path it will raise a `TemplateNotFound` error. + """ + pieces = [] + for piece in template.split("/"): + if ( + os.path.sep in piece + or (os.path.altsep and os.path.altsep in piece) + or piece == os.path.pardir + ): + raise TemplateNotFound(template) + elif piece and piece != ".": + pieces.append(piece) + return pieces + + +class BaseLoader: + """Baseclass for all loaders. Subclass this and override `get_source` to + implement a custom loading mechanism. The environment provides a + `get_template` method that calls the loader's `load` method to get the + :class:`Template` object. + + A very basic example for a loader that looks up templates on the file + system could look like this:: + + from jinja2 import BaseLoader, TemplateNotFound + from os.path import join, exists, getmtime + + class MyLoader(BaseLoader): + + def __init__(self, path): + self.path = path + + def get_source(self, environment, template): + path = join(self.path, template) + if not exists(path): + raise TemplateNotFound(template) + mtime = getmtime(path) + with open(path) as f: + source = f.read() + return source, path, lambda: mtime == getmtime(path) + """ + + #: if set to `False` it indicates that the loader cannot provide access + #: to the source of templates. + #: + #: .. versionadded:: 2.4 + has_source_access = True + + def get_source( + self, environment: "Environment", template: str + ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]: + """Get the template source, filename and reload helper for a template. + It's passed the environment and template name and has to return a + tuple in the form ``(source, filename, uptodate)`` or raise a + `TemplateNotFound` error if it can't locate the template. + + The source part of the returned tuple must be the source of the + template as a string. The filename should be the name of the + file on the filesystem if it was loaded from there, otherwise + ``None``. The filename is used by Python for the tracebacks + if no loader extension is used. + + The last item in the tuple is the `uptodate` function. If auto + reloading is enabled it's always called to check if the template + changed. No arguments are passed so the function must store the + old state somewhere (for example in a closure). If it returns `False` + the template will be reloaded. + """ + if not self.has_source_access: + raise RuntimeError( + f"{type(self).__name__} cannot provide access to the source" + ) + raise TemplateNotFound(template) + + def list_templates(self) -> t.List[str]: + """Iterates over all templates. If the loader does not support that + it should raise a :exc:`TypeError` which is the default behavior. + """ + raise TypeError("this loader cannot iterate over all templates") + + @internalcode + def load( + self, + environment: "Environment", + name: str, + globals: t.Optional[t.MutableMapping[str, t.Any]] = None, + ) -> "Template": + """Loads a template. This method looks up the template in the cache + or loads one by calling :meth:`get_source`. Subclasses should not + override this method as loaders working on collections of other + loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`) + will not call this method but `get_source` directly. + """ + code = None + if globals is None: + globals = {} + + # first we try to get the source for this template together + # with the filename and the uptodate function. + source, filename, uptodate = self.get_source(environment, name) + + # try to load the code from the bytecode cache if there is a + # bytecode cache configured. + bcc = environment.bytecode_cache + if bcc is not None: + bucket = bcc.get_bucket(environment, name, filename, source) + code = bucket.code + + # if we don't have code so far (not cached, no longer up to + # date) etc. we compile the template + if code is None: + code = environment.compile(source, name, filename) + + # if the bytecode cache is available and the bucket doesn't + # have a code so far, we give the bucket the new code and put + # it back to the bytecode cache. + if bcc is not None and bucket.code is None: + bucket.code = code + bcc.set_bucket(bucket) + + return environment.template_class.from_code( + environment, code, globals, uptodate + ) + + +class FileSystemLoader(BaseLoader): + """Load templates from a directory in the file system. + + The path can be relative or absolute. Relative paths are relative to + the current working directory. + + .. code-block:: python + + loader = FileSystemLoader("templates") + + A list of paths can be given. The directories will be searched in + order, stopping at the first matching template. + + .. code-block:: python + + loader = FileSystemLoader(["/override/templates", "/default/templates"]) + + :param searchpath: A path, or list of paths, to the directory that + contains the templates. + :param encoding: Use this encoding to read the text from template + files. + :param followlinks: Follow symbolic links in the path. + + .. versionchanged:: 2.8 + Added the ``followlinks`` parameter. + """ + + def __init__( + self, + searchpath: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]], + encoding: str = "utf-8", + followlinks: bool = False, + ) -> None: + if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str): + searchpath = [searchpath] + + self.searchpath = [os.fspath(p) for p in searchpath] + self.encoding = encoding + self.followlinks = followlinks + + def get_source( + self, environment: "Environment", template: str + ) -> t.Tuple[str, str, t.Callable[[], bool]]: + pieces = split_template_path(template) + + for searchpath in self.searchpath: + # Use posixpath even on Windows to avoid "drive:" or UNC + # segments breaking out of the search directory. + filename = posixpath.join(searchpath, *pieces) + + if os.path.isfile(filename): + break + else: + raise TemplateNotFound(template) + + with open(filename, encoding=self.encoding) as f: + contents = f.read() + + mtime = os.path.getmtime(filename) + + def uptodate() -> bool: + try: + return os.path.getmtime(filename) == mtime + except OSError: + return False + + # Use normpath to convert Windows altsep to sep. + return contents, os.path.normpath(filename), uptodate + + def list_templates(self) -> t.List[str]: + found = set() + for searchpath in self.searchpath: + walk_dir = os.walk(searchpath, followlinks=self.followlinks) + for dirpath, _, filenames in walk_dir: + for filename in filenames: + template = ( + os.path.join(dirpath, filename)[len(searchpath) :] + .strip(os.path.sep) + .replace(os.path.sep, "/") + ) + if template[:2] == "./": + template = template[2:] + if template not in found: + found.add(template) + return sorted(found) + + +class PackageLoader(BaseLoader): + """Load templates from a directory in a Python package. + + :param package_name: Import name of the package that contains the + template directory. + :param package_path: Directory within the imported package that + contains the templates. + :param encoding: Encoding of template files. + + The following example looks up templates in the ``pages`` directory + within the ``project.ui`` package. + + .. code-block:: python + + loader = PackageLoader("project.ui", "pages") + + Only packages installed as directories (standard pip behavior) or + zip/egg files (less common) are supported. The Python API for + introspecting data in packages is too limited to support other + installation methods the way this loader requires. + + There is limited support for :pep:`420` namespace packages. The + template directory is assumed to only be in one namespace + contributor. Zip files contributing to a namespace are not + supported. + + .. versionchanged:: 3.0 + No longer uses ``setuptools`` as a dependency. + + .. versionchanged:: 3.0 + Limited PEP 420 namespace package support. + """ + + def __init__( + self, + package_name: str, + package_path: "str" = "templates", + encoding: str = "utf-8", + ) -> None: + package_path = os.path.normpath(package_path).rstrip(os.path.sep) + + # normpath preserves ".", which isn't valid in zip paths. + if package_path == os.path.curdir: + package_path = "" + elif package_path[:2] == os.path.curdir + os.path.sep: + package_path = package_path[2:] + + self.package_path = package_path + self.package_name = package_name + self.encoding = encoding + + # Make sure the package exists. This also makes namespace + # packages work, otherwise get_loader returns None. + import_module(package_name) + spec = importlib.util.find_spec(package_name) + assert spec is not None, "An import spec was not found for the package." + loader = spec.loader + assert loader is not None, "A loader was not found for the package." + self._loader = loader + self._archive = None + template_root = None + + if isinstance(loader, zipimport.zipimporter): + self._archive = loader.archive + pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore + template_root = os.path.join(pkgdir, package_path).rstrip(os.path.sep) + else: + roots: t.List[str] = [] + + # One element for regular packages, multiple for namespace + # packages, or None for single module file. + if spec.submodule_search_locations: + roots.extend(spec.submodule_search_locations) + # A single module file, use the parent directory instead. + elif spec.origin is not None: + roots.append(os.path.dirname(spec.origin)) + + for root in roots: + root = os.path.join(root, package_path) + + if os.path.isdir(root): + template_root = root + break + + if template_root is None: + raise ValueError( + f"The {package_name!r} package was not installed in a" + " way that PackageLoader understands." + ) + + self._template_root = template_root + + def get_source( + self, environment: "Environment", template: str + ) -> t.Tuple[str, str, t.Optional[t.Callable[[], bool]]]: + # Use posixpath even on Windows to avoid "drive:" or UNC + # segments breaking out of the search directory. Use normpath to + # convert Windows altsep to sep. + p = os.path.normpath( + posixpath.join(self._template_root, *split_template_path(template)) + ) + up_to_date: t.Optional[t.Callable[[], bool]] + + if self._archive is None: + # Package is a directory. + if not os.path.isfile(p): + raise TemplateNotFound(template) + + with open(p, "rb") as f: + source = f.read() + + mtime = os.path.getmtime(p) + + def up_to_date() -> bool: + return os.path.isfile(p) and os.path.getmtime(p) == mtime + + else: + # Package is a zip file. + try: + source = self._loader.get_data(p) # type: ignore + except OSError as e: + raise TemplateNotFound(template) from e + + # Could use the zip's mtime for all template mtimes, but + # would need to safely reload the module if it's out of + # date, so just report it as always current. + up_to_date = None + + return source.decode(self.encoding), p, up_to_date + + def list_templates(self) -> t.List[str]: + results: t.List[str] = [] + + if self._archive is None: + # Package is a directory. + offset = len(self._template_root) + + for dirpath, _, filenames in os.walk(self._template_root): + dirpath = dirpath[offset:].lstrip(os.path.sep) + results.extend( + os.path.join(dirpath, name).replace(os.path.sep, "/") + for name in filenames + ) + else: + if not hasattr(self._loader, "_files"): + raise TypeError( + "This zip import does not have the required" + " metadata to list templates." + ) + + # Package is a zip file. + prefix = ( + self._template_root[len(self._archive) :].lstrip(os.path.sep) + + os.path.sep + ) + offset = len(prefix) + + for name in self._loader._files.keys(): + # Find names under the templates directory that aren't directories. + if name.startswith(prefix) and name[-1] != os.path.sep: + results.append(name[offset:].replace(os.path.sep, "/")) + + results.sort() + return results + + +class DictLoader(BaseLoader): + """Loads a template from a Python dict mapping template names to + template source. This loader is useful for unittesting: + + >>> loader = DictLoader({'index.html': 'source here'}) + + Because auto reloading is rarely useful this is disabled per default. + """ + + def __init__(self, mapping: t.Mapping[str, str]) -> None: + self.mapping = mapping + + def get_source( + self, environment: "Environment", template: str + ) -> t.Tuple[str, None, t.Callable[[], bool]]: + if template in self.mapping: + source = self.mapping[template] + return source, None, lambda: source == self.mapping.get(template) + raise TemplateNotFound(template) + + def list_templates(self) -> t.List[str]: + return sorted(self.mapping) + + +class FunctionLoader(BaseLoader): + """A loader that is passed a function which does the loading. The + function receives the name of the template and has to return either + a string with the template source, a tuple in the form ``(source, + filename, uptodatefunc)`` or `None` if the template does not exist. + + >>> def load_template(name): + ... if name == 'index.html': + ... return '...' + ... + >>> loader = FunctionLoader(load_template) + + The `uptodatefunc` is a function that is called if autoreload is enabled + and has to return `True` if the template is still up to date. For more + details have a look at :meth:`BaseLoader.get_source` which has the same + return value. + """ + + def __init__( + self, + load_func: t.Callable[ + [str], + t.Optional[ + t.Union[ + str, t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]] + ] + ], + ], + ) -> None: + self.load_func = load_func + + def get_source( + self, environment: "Environment", template: str + ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]: + rv = self.load_func(template) + + if rv is None: + raise TemplateNotFound(template) + + if isinstance(rv, str): + return rv, None, None + + return rv + + +class PrefixLoader(BaseLoader): + """A loader that is passed a dict of loaders where each loader is bound + to a prefix. The prefix is delimited from the template by a slash per + default, which can be changed by setting the `delimiter` argument to + something else:: + + loader = PrefixLoader({ + 'app1': PackageLoader('mypackage.app1'), + 'app2': PackageLoader('mypackage.app2') + }) + + By loading ``'app1/index.html'`` the file from the app1 package is loaded, + by loading ``'app2/index.html'`` the file from the second. + """ + + def __init__( + self, mapping: t.Mapping[str, BaseLoader], delimiter: str = "/" + ) -> None: + self.mapping = mapping + self.delimiter = delimiter + + def get_loader(self, template: str) -> t.Tuple[BaseLoader, str]: + try: + prefix, name = template.split(self.delimiter, 1) + loader = self.mapping[prefix] + except (ValueError, KeyError) as e: + raise TemplateNotFound(template) from e + return loader, name + + def get_source( + self, environment: "Environment", template: str + ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]: + loader, name = self.get_loader(template) + try: + return loader.get_source(environment, name) + except TemplateNotFound as e: + # re-raise the exception with the correct filename here. + # (the one that includes the prefix) + raise TemplateNotFound(template) from e + + @internalcode + def load( + self, + environment: "Environment", + name: str, + globals: t.Optional[t.MutableMapping[str, t.Any]] = None, + ) -> "Template": + loader, local_name = self.get_loader(name) + try: + return loader.load(environment, local_name, globals) + except TemplateNotFound as e: + # re-raise the exception with the correct filename here. + # (the one that includes the prefix) + raise TemplateNotFound(name) from e + + def list_templates(self) -> t.List[str]: + result = [] + for prefix, loader in self.mapping.items(): + for template in loader.list_templates(): + result.append(prefix + self.delimiter + template) + return result + + +class ChoiceLoader(BaseLoader): + """This loader works like the `PrefixLoader` just that no prefix is + specified. If a template could not be found by one loader the next one + is tried. + + >>> loader = ChoiceLoader([ + ... FileSystemLoader('/path/to/user/templates'), + ... FileSystemLoader('/path/to/system/templates') + ... ]) + + This is useful if you want to allow users to override builtin templates + from a different location. + """ + + def __init__(self, loaders: t.Sequence[BaseLoader]) -> None: + self.loaders = loaders + + def get_source( + self, environment: "Environment", template: str + ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]: + for loader in self.loaders: + try: + return loader.get_source(environment, template) + except TemplateNotFound: + pass + raise TemplateNotFound(template) + + @internalcode + def load( + self, + environment: "Environment", + name: str, + globals: t.Optional[t.MutableMapping[str, t.Any]] = None, + ) -> "Template": + for loader in self.loaders: + try: + return loader.load(environment, name, globals) + except TemplateNotFound: + pass + raise TemplateNotFound(name) + + def list_templates(self) -> t.List[str]: + found = set() + for loader in self.loaders: + found.update(loader.list_templates()) + return sorted(found) + + +class _TemplateModule(ModuleType): + """Like a normal module but with support for weak references""" + + +class ModuleLoader(BaseLoader): + """This loader loads templates from precompiled templates. + + Example usage: + + >>> loader = ChoiceLoader([ + ... ModuleLoader('/path/to/compiled/templates'), + ... FileSystemLoader('/path/to/templates') + ... ]) + + Templates can be precompiled with :meth:`Environment.compile_templates`. + """ + + has_source_access = False + + def __init__( + self, path: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]] + ) -> None: + package_name = f"_jinja2_module_templates_{id(self):x}" + + # create a fake module that looks for the templates in the + # path given. + mod = _TemplateModule(package_name) + + if not isinstance(path, abc.Iterable) or isinstance(path, str): + path = [path] + + mod.__path__ = [os.fspath(p) for p in path] + + sys.modules[package_name] = weakref.proxy( + mod, lambda x: sys.modules.pop(package_name, None) + ) + + # the only strong reference, the sys.modules entry is weak + # so that the garbage collector can remove it once the + # loader that created it goes out of business. + self.module = mod + self.package_name = package_name + + @staticmethod + def get_template_key(name: str) -> str: + return "tmpl_" + sha1(name.encode("utf-8")).hexdigest() + + @staticmethod + def get_module_filename(name: str) -> str: + return ModuleLoader.get_template_key(name) + ".py" + + @internalcode + def load( + self, + environment: "Environment", + name: str, + globals: t.Optional[t.MutableMapping[str, t.Any]] = None, + ) -> "Template": + key = self.get_template_key(name) + module = f"{self.package_name}.{key}" + mod = getattr(self.module, module, None) + + if mod is None: + try: + mod = __import__(module, None, None, ["root"]) + except ImportError as e: + raise TemplateNotFound(name) from e + + # remove the entry from sys.modules, we only want the attribute + # on the module object we have stored on the loader. + sys.modules.pop(module, None) + + if globals is None: + globals = {} + + return environment.template_class.from_module_dict( + environment, mod.__dict__, globals + ) diff --git a/shared/package-files/6b/6b2059c1d69c2f19227e39d583acaefa46d73025517c764947f6559697807dbc/user_input_mutation.py b/shared/package-files/6b/6b2059c1d69c2f19227e39d583acaefa46d73025517c764947f6559697807dbc/user_input_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..2bb16cd64a56fce4c4ccfdbb257f32f11514439c --- /dev/null +++ b/shared/package-files/6b/6b2059c1d69c2f19227e39d583acaefa46d73025517c764947f6559697807dbc/user_input_mutation.py @@ -0,0 +1,18 @@ +import torch + +from torch._export.db.case import export_case, SupportLevel + + +@export_case( + example_inputs=(torch.ones(3, 2),), + tags={"torch.mutation"}, + support_level=SupportLevel.SUPPORTED, +) +class UserInputMutation(torch.nn.Module): + """ + Directly mutate user input in forward + """ + + def forward(self, x): + x.mul_(2) + return x.cos() diff --git a/shared/package-files/6b/6b236a52f7c4fadd3787fc0fd8a93b13486e9eac6ca71643385d230e47faae4f/rref_proxy.py b/shared/package-files/6b/6b236a52f7c4fadd3787fc0fd8a93b13486e9eac6ca71643385d230e47faae4f/rref_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..89986be8b9287d28fc5d4ad057de8be2d3f8b065 --- /dev/null +++ b/shared/package-files/6b/6b236a52f7c4fadd3787fc0fd8a93b13486e9eac6ca71643385d230e47faae4f/rref_proxy.py @@ -0,0 +1,74 @@ +from functools import partial + +from . import functions +from . import rpc_async + +import torch +from .constants import UNSET_RPC_TIMEOUT +from torch.futures import Future + +def _local_invoke(rref, func_name, args, kwargs): + return getattr(rref.local_value(), func_name)(*args, **kwargs) + +@functions.async_execution +def _local_invoke_async_execution(rref, func_name, args, kwargs): + return getattr(rref.local_value(), func_name)(*args, **kwargs) + +def _invoke_rpc(rref, rpc_api, func_name, timeout, *args, **kwargs): + def _rref_type_cont(rref_fut): + rref_type = rref_fut.value() + + _invoke_func = _local_invoke + # Bypass ScriptModules when checking for async function attribute. + bypass_type = issubclass(rref_type, torch.jit.ScriptModule) or issubclass( + rref_type, torch._C.ScriptModule + ) + if not bypass_type: + func = getattr(rref_type, func_name) + if hasattr(func, "_wrapped_async_rpc_function"): + _invoke_func = _local_invoke_async_execution + + return rpc_api( + rref.owner(), + _invoke_func, + args=(rref, func_name, args, kwargs), + timeout=timeout + ) + + rref_fut = rref._get_type(timeout=timeout, blocking=False) + + if rpc_api != rpc_async: + rref_fut.wait() + return _rref_type_cont(rref_fut) + else: + # A little explanation on this. + # rpc_async returns a Future pointing to the return value of `func_name`, it returns a `Future[T]` + # Calling _rref_type_cont from the `then` lambda causes Future wrapping. IOW, `then` returns a `Future[Future[T]]` + # To address that, we return a Future that is completed with the result of the async call. + result: Future = Future() + + def _wrap_rref_type_cont(fut): + try: + _rref_type_cont(fut).then(_complete_op) + except BaseException as ex: + result.set_exception(ex) + + def _complete_op(fut): + try: + result.set_result(fut.value()) + except BaseException as ex: + result.set_exception(ex) + + rref_fut.then(_wrap_rref_type_cont) + return result + +# This class manages proxied RPC API calls for RRefs. It is entirely used from +# C++ (see python_rpc_handler.cpp). +class RRefProxy: + def __init__(self, rref, rpc_api, timeout=UNSET_RPC_TIMEOUT): + self.rref = rref + self.rpc_api = rpc_api + self.rpc_timeout = timeout + + def __getattr__(self, func_name): + return partial(_invoke_rpc, self.rref, self.rpc_api, func_name, self.rpc_timeout) diff --git a/shared/package-files/6b/6b2b4e9b8793fd23efb3b1c2dbc658e06ba478de38abe484d0910c091f2454e9/Solarize_Light2.mplstyle b/shared/package-files/6b/6b2b4e9b8793fd23efb3b1c2dbc658e06ba478de38abe484d0910c091f2454e9/Solarize_Light2.mplstyle new file mode 100644 index 0000000000000000000000000000000000000000..418721314335afad04ff288d897636d24d89be70 --- /dev/null +++ b/shared/package-files/6b/6b2b4e9b8793fd23efb3b1c2dbc658e06ba478de38abe484d0910c091f2454e9/Solarize_Light2.mplstyle @@ -0,0 +1,53 @@ +# Solarized color palette taken from https://ethanschoonover.com/solarized/ +# Inspired by, and copied from ggthemes https://github.com/jrnold/ggthemes + +#TODO: +# 1. Padding to title from face +# 2. Remove top & right ticks +# 3. Give Title a Magenta Color(?) + +#base00 ='#657b83' +#base01 ='#93a1a1' +#base2 ='#eee8d5' +#base3 ='#fdf6e3' +#base01 ='#586e75' +#Magenta ='#d33682' +#Blue ='#268bd2' +#cyan ='#2aa198' +#violet ='#6c71c4' +#green ='#859900' +#orange ='#cb4b16' + +figure.facecolor : FDF6E3 + +patch.antialiased : True + +lines.linewidth : 2.0 +lines.solid_capstyle: butt + +axes.titlesize : 16 +axes.labelsize : 12 +axes.labelcolor : 657b83 +axes.facecolor : eee8d5 +axes.edgecolor : eee8d5 +axes.axisbelow : True +axes.prop_cycle : cycler('color', ['268BD2', '2AA198', '859900', 'B58900', 'CB4B16', 'DC322F', 'D33682', '6C71C4']) +# Blue +# Cyan +# Green +# Yellow +# Orange +# Red +# Magenta +# Violet +axes.grid : True +grid.color : fdf6e3 # grid color +grid.linestyle : - # line +grid.linewidth : 1 # in points + +### TICKS +xtick.color : 657b83 +xtick.direction : out + +ytick.color : 657b83 +ytick.direction : out diff --git a/shared/package-files/6b/6b2dcbbf6d57dd0aaccf2b0137bd7176bf4a190b82e640c197dd1ad928f1ea93/exceptions.py b/shared/package-files/6b/6b2dcbbf6d57dd0aaccf2b0137bd7176bf4a190b82e640c197dd1ad928f1ea93/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..b1e5a4195c66aceed2d5ac1994381d3dec6a64ba --- /dev/null +++ b/shared/package-files/6b/6b2dcbbf6d57dd0aaccf2b0137bd7176bf4a190b82e640c197dd1ad928f1ea93/exceptions.py @@ -0,0 +1,67 @@ +""" + +Module to define exceptions to be used in sympy.polys.matrices modules and +classes. + +Ideally all exceptions raised in these modules would be defined and documented +here and not e.g. imported from matrices. Also ideally generic exceptions like +ValueError/TypeError would not be raised anywhere. + +""" + + +class DMError(Exception): + """Base class for errors raised by DomainMatrix""" + pass + + +class DMBadInputError(DMError): + """list of lists is inconsistent with shape""" + pass + + +class DMDomainError(DMError): + """domains do not match""" + pass + + +class DMNotAField(DMDomainError): + """domain is not a field""" + pass + + +class DMFormatError(DMError): + """mixed dense/sparse not supported""" + pass + + +class DMNonInvertibleMatrixError(DMError): + """The matrix in not invertible""" + pass + + +class DMRankError(DMError): + """matrix does not have expected rank""" + pass + + +class DMShapeError(DMError): + """shapes are inconsistent""" + pass + + +class DMNonSquareMatrixError(DMShapeError): + """The matrix is not square""" + pass + + +class DMValueError(DMError): + """The value passed is invalid""" + pass + + +__all__ = [ + 'DMError', 'DMBadInputError', 'DMDomainError', 'DMFormatError', + 'DMRankError', 'DMShapeError', 'DMNotAField', + 'DMNonInvertibleMatrixError', 'DMNonSquareMatrixError', 'DMValueError' +] diff --git a/shared/package-files/6b/6b346891059a79136b392ce9fae26a69b70305b3e267edde6ce332b44c6ef881/5051 b/shared/package-files/6b/6b346891059a79136b392ce9fae26a69b70305b3e267edde6ce332b44c6ef881/5051 new file mode 100644 index 0000000000000000000000000000000000000000..ec3766c15e5dd99b01f87136841fbdd54fa56a37 Binary files /dev/null and b/shared/package-files/6b/6b346891059a79136b392ce9fae26a69b70305b3e267edde6ce332b44c6ef881/5051 differ diff --git a/shared/package-files/6b/6b346891059a79136b392ce9fae26a69b70305b3e267edde6ce332b44c6ef881/ibm-pc b/shared/package-files/6b/6b346891059a79136b392ce9fae26a69b70305b3e267edde6ce332b44c6ef881/ibm-pc new file mode 100644 index 0000000000000000000000000000000000000000..ec3766c15e5dd99b01f87136841fbdd54fa56a37 Binary files /dev/null and b/shared/package-files/6b/6b346891059a79136b392ce9fae26a69b70305b3e267edde6ce332b44c6ef881/ibm-pc differ diff --git a/shared/package-files/6b/6b346891059a79136b392ce9fae26a69b70305b3e267edde6ce332b44c6ef881/ibm5051 b/shared/package-files/6b/6b346891059a79136b392ce9fae26a69b70305b3e267edde6ce332b44c6ef881/ibm5051 new file mode 100644 index 0000000000000000000000000000000000000000..ec3766c15e5dd99b01f87136841fbdd54fa56a37 Binary files /dev/null and b/shared/package-files/6b/6b346891059a79136b392ce9fae26a69b70305b3e267edde6ce332b44c6ef881/ibm5051 differ diff --git a/shared/package-files/6b/6b391aff978e694ae8debdefef63e6113d2863cf9a6a8264cd510aee4baa5c20/issubset.py b/shared/package-files/6b/6b391aff978e694ae8debdefef63e6113d2863cf9a6a8264cd510aee4baa5c20/issubset.py new file mode 100644 index 0000000000000000000000000000000000000000..cc23e8bf56f1743cd7f08452dd09a0acf981f5da --- /dev/null +++ b/shared/package-files/6b/6b391aff978e694ae8debdefef63e6113d2863cf9a6a8264cd510aee4baa5c20/issubset.py @@ -0,0 +1,144 @@ +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.logic import fuzzy_and, fuzzy_bool, fuzzy_not, fuzzy_or +from sympy.core.relational import Eq +from sympy.sets.sets import FiniteSet, Interval, Set, Union, ProductSet +from sympy.sets.fancysets import Complexes, Reals, Range, Rationals +from sympy.multipledispatch import Dispatcher + + +_inf_sets = [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals, S.Complexes] + + +is_subset_sets = Dispatcher('is_subset_sets') + + +@is_subset_sets.register(Set, Set) +def _(a, b): + return None + +@is_subset_sets.register(Interval, Interval) +def _(a, b): + # This is correct but can be made more comprehensive... + if fuzzy_bool(a.start < b.start): + return False + if fuzzy_bool(a.end > b.end): + return False + if (b.left_open and not a.left_open and fuzzy_bool(Eq(a.start, b.start))): + return False + if (b.right_open and not a.right_open and fuzzy_bool(Eq(a.end, b.end))): + return False + +@is_subset_sets.register(Interval, FiniteSet) +def _(a_interval, b_fs): + # An Interval can only be a subset of a finite set if it is finite + # which can only happen if it has zero measure. + if fuzzy_not(a_interval.measure.is_zero): + return False + +@is_subset_sets.register(Interval, Union) +def _(a_interval, b_u): + if all(isinstance(s, (Interval, FiniteSet)) for s in b_u.args): + intervals = [s for s in b_u.args if isinstance(s, Interval)] + if all(fuzzy_bool(a_interval.start < s.start) for s in intervals): + return False + if all(fuzzy_bool(a_interval.end > s.end) for s in intervals): + return False + if a_interval.measure.is_nonzero: + no_overlap = lambda s1, s2: fuzzy_or([ + fuzzy_bool(s1.end <= s2.start), + fuzzy_bool(s1.start >= s2.end), + ]) + if all(no_overlap(s, a_interval) for s in intervals): + return False + +@is_subset_sets.register(Range, Range) +def _(a, b): + if a.step == b.step == 1: + return fuzzy_and([fuzzy_bool(a.start >= b.start), + fuzzy_bool(a.stop <= b.stop)]) + +@is_subset_sets.register(Range, Interval) +def _(a_range, b_interval): + if a_range.step.is_positive: + if b_interval.left_open and a_range.inf.is_finite: + cond_left = a_range.inf > b_interval.left + else: + cond_left = a_range.inf >= b_interval.left + if b_interval.right_open and a_range.sup.is_finite: + cond_right = a_range.sup < b_interval.right + else: + cond_right = a_range.sup <= b_interval.right + return fuzzy_and([cond_left, cond_right]) + +@is_subset_sets.register(Range, FiniteSet) +def _(a_range, b_finiteset): + try: + a_size = a_range.size + except ValueError: + # symbolic Range of unknown size + return None + if a_size > len(b_finiteset): + return False + elif any(arg.has(Symbol) for arg in a_range.args): + return fuzzy_and(b_finiteset.contains(x) for x in a_range) + else: + # Checking A \ B == EmptySet is more efficient than repeated naive + # membership checks on an arbitrary FiniteSet. + a_set = set(a_range) + b_remaining = len(b_finiteset) + # Symbolic expressions and numbers of unknown type (integer or not) are + # all counted as "candidates", i.e. *potentially* matching some a in + # a_range. + cnt_candidate = 0 + for b in b_finiteset: + if b.is_Integer: + a_set.discard(b) + elif fuzzy_not(b.is_integer): + pass + else: + cnt_candidate += 1 + b_remaining -= 1 + if len(a_set) > b_remaining + cnt_candidate: + return False + if len(a_set) == 0: + return True + return None + +@is_subset_sets.register(Interval, Range) +def _(a_interval, b_range): + if a_interval.measure.is_extended_nonzero: + return False + +@is_subset_sets.register(Interval, Rationals) +def _(a_interval, b_rationals): + if a_interval.measure.is_extended_nonzero: + return False + +@is_subset_sets.register(Range, Complexes) +def _(a, b): + return True + +@is_subset_sets.register(Complexes, Interval) +def _(a, b): + return False + +@is_subset_sets.register(Complexes, Range) +def _(a, b): + return False + +@is_subset_sets.register(Complexes, Rationals) +def _(a, b): + return False + +@is_subset_sets.register(Rationals, Reals) +def _(a, b): + return True + +@is_subset_sets.register(Rationals, Range) +def _(a, b): + return False + +@is_subset_sets.register(ProductSet, FiniteSet) +def _(a_ps, b_fs): + return fuzzy_and(b_fs.contains(x) for x in a_ps) diff --git a/shared/package-files/6b/6b394c60cd5e26a0c5081783441120a4a81b78322c58b20f116055c8b568a1c6/FunctionalInverses.h b/shared/package-files/6b/6b394c60cd5e26a0c5081783441120a4a81b78322c58b20f116055c8b568a1c6/FunctionalInverses.h new file mode 100644 index 0000000000000000000000000000000000000000..3217e097d7adf37ab7041c45f5dd413024fc33ef --- /dev/null +++ b/shared/package-files/6b/6b394c60cd5e26a0c5081783441120a4a81b78322c58b20f116055c8b568a1c6/FunctionalInverses.h @@ -0,0 +1,33 @@ +#pragma once + +// ${generated_comment} + +#include + +namespace at { +namespace functionalization { + +enum class InverseReturnMode { + /// Specifies that functional inverses should always return a view. + AlwaysView, + /// Specifies that functional inverses should always return a non-view / copy. + NeverView, + /// Specifies that functional inverses should return a view unless a (copying) scatter + /// inverse exists, in which case that will be used instead. + /// This avoids as_strided() calls that can be difficult for subclasses to handle. + ViewOrScatterInverse, +}; + +struct FunctionalInverses { + +${view_inverse_declarations} + +// NB: These are not generated! They're manually implemented in the template. +// TODO: Change codegen to generate these. See the following link: +// https://github.com/pytorch/pytorch/blob/main/torchgen/model.py#L2583-L2585 +static at::Tensor chunk_inverse(const at::Tensor & base, const at::Tensor & mutated_view, InverseReturnMode inverse_return_mode, int64_t mutated_view_idx, int chunks, int dim); +static at::Tensor narrow_inverse(const at::Tensor & base, const at::Tensor & mutated_view, InverseReturnMode inverse_return_mode, int dim, c10::SymInt start, c10::SymInt length); + +}; +} +} diff --git a/shared/package-files/6b/6b3a0ceccec15000e5da406131547a3cf7f61a104323dd267b57dc9f34f075cc/_version.py b/shared/package-files/6b/6b3a0ceccec15000e5da406131547a3cf7f61a104323dd267b57dc9f34f075cc/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..cad75fb5df82a617a82573bdcff7af579efc00e7 --- /dev/null +++ b/shared/package-files/6b/6b3a0ceccec15000e5da406131547a3cf7f61a104323dd267b57dc9f34f075cc/_version.py @@ -0,0 +1,2 @@ +# This file is protected via CODEOWNERS +__version__ = "1.26.17" diff --git a/shared/package-files/6b/6b4374843ce47be32b1e938eb21210d1de5c0edde8c0e8c8ba11f0f86377defc/_pdist_backward_cpu_dispatch.h b/shared/package-files/6b/6b4374843ce47be32b1e938eb21210d1de5c0edde8c0e8c8ba11f0f86377defc/_pdist_backward_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..bc6082fd418b063092f34f949f42844f2e89e7e8 --- /dev/null +++ b/shared/package-files/6b/6b4374843ce47be32b1e938eb21210d1de5c0edde8c0e8c8ba11f0f86377defc/_pdist_backward_cpu_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor _pdist_backward(const at::Tensor & grad, const at::Tensor & self, double p, const at::Tensor & pdist); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/6b/6b44b6a567c7fcb89dd0e0d7910867d9eb01e603ade22f5a25f9208409575a95/ansi+enq b/shared/package-files/6b/6b44b6a567c7fcb89dd0e0d7910867d9eb01e603ade22f5a25f9208409575a95/ansi+enq new file mode 100644 index 0000000000000000000000000000000000000000..8103d305a1d6dcdcf363d2b37f95c755ecc8bb72 Binary files /dev/null and b/shared/package-files/6b/6b44b6a567c7fcb89dd0e0d7910867d9eb01e603ade22f5a25f9208409575a95/ansi+enq differ diff --git a/shared/package-files/6b/6b45512d7f7c30316dae40eef6736ee6bbf5e160089e6f6fa0d2c632d8282195/G__l_a_t.py b/shared/package-files/6b/6b45512d7f7c30316dae40eef6736ee6bbf5e160089e6f6fa0d2c632d8282195/G__l_a_t.py new file mode 100644 index 0000000000000000000000000000000000000000..22c255c1c846822129c8a5b1bbdf04c88b6bd53f --- /dev/null +++ b/shared/package-files/6b/6b45512d7f7c30316dae40eef6736ee6bbf5e160089e6f6fa0d2c632d8282195/G__l_a_t.py @@ -0,0 +1,234 @@ +from fontTools.misc import sstruct +from fontTools.misc.fixedTools import floatToFixedToStr +from fontTools.misc.textTools import safeEval + +# from itertools import * +from functools import partial +from . import DefaultTable +from . import grUtils +import struct + +Glat_format_0 = """ + > # big endian + version: 16.16F +""" + +Glat_format_3 = """ + > + version: 16.16F + compression:L # compression scheme or reserved +""" + +Glat_format_1_entry = """ + > + attNum: B # Attribute number of first attribute + num: B # Number of attributes in this run +""" +Glat_format_23_entry = """ + > + attNum: H # Attribute number of first attribute + num: H # Number of attributes in this run +""" + +Glat_format_3_octabox_metrics = """ + > + subboxBitmap: H # Which subboxes exist on 4x4 grid + diagNegMin: B # Defines minimum negatively-sloped diagonal (si) + diagNegMax: B # Defines maximum negatively-sloped diagonal (sa) + diagPosMin: B # Defines minimum positively-sloped diagonal (di) + diagPosMax: B # Defines maximum positively-sloped diagonal (da) +""" + +Glat_format_3_subbox_entry = """ + > + left: B # xi + right: B # xa + bottom: B # yi + top: B # ya + diagNegMin: B # Defines minimum negatively-sloped diagonal (si) + diagNegMax: B # Defines maximum negatively-sloped diagonal (sa) + diagPosMin: B # Defines minimum positively-sloped diagonal (di) + diagPosMax: B # Defines maximum positively-sloped diagonal (da) +""" + + +class _Object: + pass + + +class _Dict(dict): + pass + + +class table_G__l_a_t(DefaultTable.DefaultTable): + """Graphite Glyph Attributes table + + See also https://graphite.sil.org/graphite_techAbout#graphite-font-tables + """ + + def __init__(self, tag=None): + DefaultTable.DefaultTable.__init__(self, tag) + self.scheme = 0 + + def decompile(self, data, ttFont): + sstruct.unpack2(Glat_format_0, data, self) + self.version = float(floatToFixedToStr(self.version, precisionBits=16)) + if self.version <= 1.9: + decoder = partial(self.decompileAttributes12, fmt=Glat_format_1_entry) + elif self.version <= 2.9: + decoder = partial(self.decompileAttributes12, fmt=Glat_format_23_entry) + elif self.version >= 3.0: + data, self.scheme = grUtils.decompress(data) + sstruct.unpack2(Glat_format_3, data, self) + self.hasOctaboxes = (self.compression & 1) == 1 + decoder = self.decompileAttributes3 + + gloc = ttFont["Gloc"] + self.attributes = {} + count = 0 + for s, e in zip(gloc, gloc[1:]): + self.attributes[ttFont.getGlyphName(count)] = decoder(data[s:e]) + count += 1 + + def decompileAttributes12(self, data, fmt): + attributes = _Dict() + while len(data) > 3: + e, data = sstruct.unpack2(fmt, data, _Object()) + keys = range(e.attNum, e.attNum + e.num) + if len(data) >= 2 * e.num: + vals = struct.unpack_from((">%dh" % e.num), data) + attributes.update(zip(keys, vals)) + data = data[2 * e.num :] + return attributes + + def decompileAttributes3(self, data): + if self.hasOctaboxes: + o, data = sstruct.unpack2(Glat_format_3_octabox_metrics, data, _Object()) + numsub = bin(o.subboxBitmap).count("1") + o.subboxes = [] + for b in range(numsub): + if len(data) >= 8: + subbox, data = sstruct.unpack2( + Glat_format_3_subbox_entry, data, _Object() + ) + o.subboxes.append(subbox) + attrs = self.decompileAttributes12(data, Glat_format_23_entry) + if self.hasOctaboxes: + attrs.octabox = o + return attrs + + def compile(self, ttFont): + data = sstruct.pack(Glat_format_0, self) + if self.version <= 1.9: + encoder = partial(self.compileAttributes12, fmt=Glat_format_1_entry) + elif self.version <= 2.9: + encoder = partial(self.compileAttributes12, fmt=Glat_format_1_entry) + elif self.version >= 3.0: + self.compression = (self.scheme << 27) + (1 if self.hasOctaboxes else 0) + data = sstruct.pack(Glat_format_3, self) + encoder = self.compileAttributes3 + + glocs = [] + for n in range(len(self.attributes)): + glocs.append(len(data)) + data += encoder(self.attributes[ttFont.getGlyphName(n)]) + glocs.append(len(data)) + ttFont["Gloc"].set(glocs) + + if self.version >= 3.0: + data = grUtils.compress(self.scheme, data) + return data + + def compileAttributes12(self, attrs, fmt): + data = b"" + for e in grUtils.entries(attrs): + data += sstruct.pack(fmt, {"attNum": e[0], "num": e[1]}) + struct.pack( + (">%dh" % len(e[2])), *e[2] + ) + return data + + def compileAttributes3(self, attrs): + if self.hasOctaboxes: + o = attrs.octabox + data = sstruct.pack(Glat_format_3_octabox_metrics, o) + numsub = bin(o.subboxBitmap).count("1") + for b in range(numsub): + data += sstruct.pack(Glat_format_3_subbox_entry, o.subboxes[b]) + else: + data = "" + return data + self.compileAttributes12(attrs, Glat_format_23_entry) + + def toXML(self, writer, ttFont): + writer.simpletag("version", version=self.version, compressionScheme=self.scheme) + writer.newline() + for n, a in sorted( + self.attributes.items(), key=lambda x: ttFont.getGlyphID(x[0]) + ): + writer.begintag("glyph", name=n) + writer.newline() + if hasattr(a, "octabox"): + o = a.octabox + formatstring, names, fixes = sstruct.getformat( + Glat_format_3_octabox_metrics + ) + vals = {} + for k in names: + if k == "subboxBitmap": + continue + vals[k] = "{:.3f}%".format(getattr(o, k) * 100.0 / 255) + vals["bitmap"] = "{:0X}".format(o.subboxBitmap) + writer.begintag("octaboxes", **vals) + writer.newline() + formatstring, names, fixes = sstruct.getformat( + Glat_format_3_subbox_entry + ) + for s in o.subboxes: + vals = {} + for k in names: + vals[k] = "{:.3f}%".format(getattr(s, k) * 100.0 / 255) + writer.simpletag("octabox", **vals) + writer.newline() + writer.endtag("octaboxes") + writer.newline() + for k, v in sorted(a.items()): + writer.simpletag("attribute", index=k, value=v) + writer.newline() + writer.endtag("glyph") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "version": + self.version = float(safeEval(attrs["version"])) + self.scheme = int(safeEval(attrs["compressionScheme"])) + if name != "glyph": + return + if not hasattr(self, "attributes"): + self.attributes = {} + gname = attrs["name"] + attributes = _Dict() + for element in content: + if not isinstance(element, tuple): + continue + tag, attrs, subcontent = element + if tag == "attribute": + k = int(safeEval(attrs["index"])) + v = int(safeEval(attrs["value"])) + attributes[k] = v + elif tag == "octaboxes": + self.hasOctaboxes = True + o = _Object() + o.subboxBitmap = int(attrs["bitmap"], 16) + o.subboxes = [] + del attrs["bitmap"] + for k, v in attrs.items(): + setattr(o, k, int(float(v[:-1]) * 255.0 / 100.0 + 0.5)) + for element in subcontent: + if not isinstance(element, tuple): + continue + tag, attrs, subcontent = element + so = _Object() + for k, v in attrs.items(): + setattr(so, k, int(float(v[:-1]) * 255.0 / 100.0 + 0.5)) + o.subboxes.append(so) + attributes.octabox = o + self.attributes[gname] = attributes diff --git a/shared/package-files/6b/6b48897f1d427706508dfda8f117ccee3892d9d68e7d74b04386b6869a05855b/_orthogonal.pyi b/shared/package-files/6b/6b48897f1d427706508dfda8f117ccee3892d9d68e7d74b04386b6869a05855b/_orthogonal.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e0ae3ce3be90187cd957fe16cc6d145a7093da5a --- /dev/null +++ b/shared/package-files/6b/6b48897f1d427706508dfda8f117ccee3892d9d68e7d74b04386b6869a05855b/_orthogonal.pyi @@ -0,0 +1,330 @@ +from typing import ( + Any, + Callable, + Literal, + Optional, + overload, +) + +import numpy as np + +_IntegerType = int | np.integer +_FloatingType = float | np.floating +_PointsAndWeights = tuple[np.ndarray, np.ndarray] +_PointsAndWeightsAndMu = tuple[np.ndarray, np.ndarray, float] + +_ArrayLike0D = bool | int | float | complex | str | bytes | np.generic + +__all__ = [ + 'legendre', + 'chebyt', + 'chebyu', + 'chebyc', + 'chebys', + 'jacobi', + 'laguerre', + 'genlaguerre', + 'hermite', + 'hermitenorm', + 'gegenbauer', + 'sh_legendre', + 'sh_chebyt', + 'sh_chebyu', + 'sh_jacobi', + 'roots_legendre', + 'roots_chebyt', + 'roots_chebyu', + 'roots_chebyc', + 'roots_chebys', + 'roots_jacobi', + 'roots_laguerre', + 'roots_genlaguerre', + 'roots_hermite', + 'roots_hermitenorm', + 'roots_gegenbauer', + 'roots_sh_legendre', + 'roots_sh_chebyt', + 'roots_sh_chebyu', + 'roots_sh_jacobi', +] + +@overload +def roots_jacobi( + n: _IntegerType, + alpha: _FloatingType, + beta: _FloatingType, +) -> _PointsAndWeights: ... +@overload +def roots_jacobi( + n: _IntegerType, + alpha: _FloatingType, + beta: _FloatingType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_jacobi( + n: _IntegerType, + alpha: _FloatingType, + beta: _FloatingType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_sh_jacobi( + n: _IntegerType, + p1: _FloatingType, + q1: _FloatingType, +) -> _PointsAndWeights: ... +@overload +def roots_sh_jacobi( + n: _IntegerType, + p1: _FloatingType, + q1: _FloatingType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_sh_jacobi( + n: _IntegerType, + p1: _FloatingType, + q1: _FloatingType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_genlaguerre( + n: _IntegerType, + alpha: _FloatingType, +) -> _PointsAndWeights: ... +@overload +def roots_genlaguerre( + n: _IntegerType, + alpha: _FloatingType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_genlaguerre( + n: _IntegerType, + alpha: _FloatingType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_laguerre(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_laguerre( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_laguerre( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_hermite(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_hermite( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_hermite( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_hermitenorm(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_hermitenorm( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_hermitenorm( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_gegenbauer( + n: _IntegerType, + alpha: _FloatingType, +) -> _PointsAndWeights: ... +@overload +def roots_gegenbauer( + n: _IntegerType, + alpha: _FloatingType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_gegenbauer( + n: _IntegerType, + alpha: _FloatingType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_chebyt(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_chebyt( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_chebyt( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_chebyu(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_chebyu( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_chebyu( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_chebyc(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_chebyc( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_chebyc( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_chebys(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_chebys( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_chebys( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_sh_chebyt(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_sh_chebyt( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_sh_chebyt( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_sh_chebyu(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_sh_chebyu( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_sh_chebyu( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_legendre(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_legendre( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_legendre( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_sh_legendre(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_sh_legendre( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_sh_legendre( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +class orthopoly1d(np.poly1d): + def __init__( + self, + roots: np.typing.ArrayLike, + weights: np.typing.ArrayLike | None, + hn: float = ..., + kn: float = ..., + wfunc = Optional[Callable[[float], float]], # noqa: UP007 + limits = tuple[float, float] | None, + monic: bool = ..., + eval_func: np.ufunc = ..., + ) -> None: ... + @property + def limits(self) -> tuple[float, float]: ... + def weight_func(self, x: float) -> float: ... + @overload + def __call__(self, x: _ArrayLike0D) -> Any: ... + @overload + def __call__(self, x: np.poly1d) -> np.poly1d: ... # type: ignore[overload-overlap] + @overload + def __call__(self, x: np.typing.ArrayLike) -> np.ndarray: ... + +def legendre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def chebyt(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def chebyu(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def chebyc(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def chebys(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def jacobi( + n: _IntegerType, + alpha: _FloatingType, + beta: _FloatingType, + monic: bool = ..., +) -> orthopoly1d: ... +def laguerre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def genlaguerre( + n: _IntegerType, + alpha: _FloatingType, + monic: bool = ..., +) -> orthopoly1d: ... +def hermite(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def hermitenorm(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def gegenbauer( + n: _IntegerType, + alpha: _FloatingType, + monic: bool = ..., +) -> orthopoly1d: ... +def sh_legendre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def sh_chebyt(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def sh_chebyu(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def sh_jacobi( + n: _IntegerType, + p: _FloatingType, + q: _FloatingType, + monic: bool = ..., +) -> orthopoly1d: ... + +# These functions are not public, but still need stubs because they +# get checked in the tests. +def _roots_hermite_asy(n: _IntegerType) -> _PointsAndWeights: ... diff --git a/shared/package-files/6b/6b4a7d9ab55f9ecf212e481fd5564228d11a83d0309ce88b03843948761126ad/crow_indices_copy_native.h b/shared/package-files/6b/6b4a7d9ab55f9ecf212e481fd5564228d11a83d0309ce88b03843948761126ad/crow_indices_copy_native.h new file mode 100644 index 0000000000000000000000000000000000000000..13af32a057d0b6bdcecf521b57314692e7ee313d --- /dev/null +++ b/shared/package-files/6b/6b4a7d9ab55f9ecf212e481fd5564228d11a83d0309ce88b03843948761126ad/crow_indices_copy_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & crow_indices_copy_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor crow_indices_copy(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/6b/6b4cc6694c33be287f6b843d0558944c5b3b359682aa097b9a5b37f8a4551e6f/SRV.py b/shared/package-files/6b/6b4cc6694c33be287f6b843d0558944c5b3b359682aa097b9a5b37f8a4551e6f/SRV.py new file mode 100644 index 0000000000000000000000000000000000000000..5adef98f9de85b8f63f9db4066c79a880bc4c783 --- /dev/null +++ b/shared/package-files/6b/6b4cc6694c33be287f6b843d0558944c5b3b359682aa097b9a5b37f8a4551e6f/SRV.py @@ -0,0 +1,75 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata +import dns.rdtypes.util + + +@dns.immutable.immutable +class SRV(dns.rdata.Rdata): + """SRV record""" + + # see: RFC 2782 + + __slots__ = ["priority", "weight", "port", "target"] + + def __init__(self, rdclass, rdtype, priority, weight, port, target): + super().__init__(rdclass, rdtype) + self.priority = self._as_uint16(priority) + self.weight = self._as_uint16(weight) + self.port = self._as_uint16(port) + self.target = self._as_name(target) + + def to_text(self, origin=None, relativize=True, **kw): + target = self.target.choose_relativity(origin, relativize) + return "%d %d %d %s" % (self.priority, self.weight, self.port, target) + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + priority = tok.get_uint16() + weight = tok.get_uint16() + port = tok.get_uint16() + target = tok.get_name(origin, relativize, relativize_to) + return cls(rdclass, rdtype, priority, weight, port, target) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + three_ints = struct.pack("!HHH", self.priority, self.weight, self.port) + file.write(three_ints) + self.target.to_wire(file, compress, origin, canonicalize) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + (priority, weight, port) = parser.get_struct("!HHH") + target = parser.get_name(origin) + return cls(rdclass, rdtype, priority, weight, port, target) + + def _processing_priority(self): + return self.priority + + def _processing_weight(self): + return self.weight + + @classmethod + def _processing_order(cls, iterable): + return dns.rdtypes.util.weighted_processing_order(iterable) diff --git a/shared/package-files/6b/6b52ed349186ba45e9ab73f4f7142fa007d4f5a0ec4d1de7674f53ec4c8538bf/hashlib.pyi b/shared/package-files/6b/6b52ed349186ba45e9ab73f4f7142fa007d4f5a0ec4d1de7674f53ec4c8538bf/hashlib.pyi new file mode 100644 index 0000000000000000000000000000000000000000..70b120d08a462f6f23317b4301b9fd23a77c154a --- /dev/null +++ b/shared/package-files/6b/6b52ed349186ba45e9ab73f4f7142fa007d4f5a0ec4d1de7674f53ec4c8538bf/hashlib.pyi @@ -0,0 +1,123 @@ +import sys +from _typeshed import ReadableBuffer +from typing import AbstractSet, Optional + +class _Hash(object): + digest_size: int + block_size: int + + # [Python documentation note] Changed in version 3.4: The name attribute has + # been present in CPython since its inception, but until Python 3.4 was not + # formally specified, so may not exist on some platforms + name: str + def __init__(self, data: ReadableBuffer = ...) -> None: ... + def copy(self) -> _Hash: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def update(self, __data: ReadableBuffer) -> None: ... + +if sys.version_info >= (3, 9): + def md5(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... + def sha1(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... + def sha224(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... + def sha256(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... + def sha384(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... + def sha512(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... + +elif sys.version_info >= (3, 8): + def md5(string: ReadableBuffer = ...) -> _Hash: ... + def sha1(string: ReadableBuffer = ...) -> _Hash: ... + def sha224(string: ReadableBuffer = ...) -> _Hash: ... + def sha256(string: ReadableBuffer = ...) -> _Hash: ... + def sha384(string: ReadableBuffer = ...) -> _Hash: ... + def sha512(string: ReadableBuffer = ...) -> _Hash: ... + +else: + def md5(__string: ReadableBuffer = ...) -> _Hash: ... + def sha1(__string: ReadableBuffer = ...) -> _Hash: ... + def sha224(__string: ReadableBuffer = ...) -> _Hash: ... + def sha256(__string: ReadableBuffer = ...) -> _Hash: ... + def sha384(__string: ReadableBuffer = ...) -> _Hash: ... + def sha512(__string: ReadableBuffer = ...) -> _Hash: ... + +def new(name: str, data: ReadableBuffer = ...) -> _Hash: ... + +algorithms_guaranteed: AbstractSet[str] +algorithms_available: AbstractSet[str] + +def pbkdf2_hmac( + hash_name: str, password: ReadableBuffer, salt: ReadableBuffer, iterations: int, dklen: Optional[int] = ... +) -> bytes: ... + +class _VarLenHash(object): + digest_size: int + block_size: int + name: str + def __init__(self, data: ReadableBuffer = ...) -> None: ... + def copy(self) -> _VarLenHash: ... + def digest(self, __length: int) -> bytes: ... + def hexdigest(self, __length: int) -> str: ... + def update(self, __data: ReadableBuffer) -> None: ... + +sha3_224 = _Hash +sha3_256 = _Hash +sha3_384 = _Hash +sha3_512 = _Hash +shake_128 = _VarLenHash +shake_256 = _VarLenHash + +def scrypt( + password: ReadableBuffer, + *, + salt: Optional[ReadableBuffer] = ..., + n: Optional[int] = ..., + r: Optional[int] = ..., + p: Optional[int] = ..., + maxmem: int = ..., + dklen: int = ..., +) -> bytes: ... + +class _BlakeHash(_Hash): + MAX_DIGEST_SIZE: int + MAX_KEY_SIZE: int + PERSON_SIZE: int + SALT_SIZE: int + + if sys.version_info >= (3, 9): + def __init__( + self, + __data: ReadableBuffer = ..., + *, + digest_size: int = ..., + key: ReadableBuffer = ..., + salt: ReadableBuffer = ..., + person: ReadableBuffer = ..., + fanout: int = ..., + depth: int = ..., + leaf_size: int = ..., + node_offset: int = ..., + node_depth: int = ..., + inner_size: int = ..., + last_node: bool = ..., + usedforsecurity: bool = ..., + ) -> None: ... + else: + def __init__( + self, + __data: ReadableBuffer = ..., + *, + digest_size: int = ..., + key: ReadableBuffer = ..., + salt: ReadableBuffer = ..., + person: ReadableBuffer = ..., + fanout: int = ..., + depth: int = ..., + leaf_size: int = ..., + node_offset: int = ..., + node_depth: int = ..., + inner_size: int = ..., + last_node: bool = ..., + ) -> None: ... + +blake2b = _BlakeHash +blake2s = _BlakeHash diff --git a/shared/package-files/6b/6b5ab8ae265db436b15d32263a8870ec55c7c0c07415b3f9baac37f73bc704e5/sw.msg b/shared/package-files/6b/6b5ab8ae265db436b15d32263a8870ec55c7c0c07415b3f9baac37f73bc704e5/sw.msg new file mode 100644 index 0000000000000000000000000000000000000000..b888b43df7009891dd34872cdce6002b961287a9 --- /dev/null +++ b/shared/package-files/6b/6b5ab8ae265db436b15d32263a8870ec55c7c0c07415b3f9baac37f73bc704e5/sw.msg @@ -0,0 +1,49 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset sw DAYS_OF_WEEK_ABBREV [list \ + "Jpi"\ + "Jtt"\ + "Jnn"\ + "Jtn"\ + "Alh"\ + "Iju"\ + "Jmo"] + ::msgcat::mcset sw DAYS_OF_WEEK_FULL [list \ + "Jumapili"\ + "Jumatatu"\ + "Jumanne"\ + "Jumatano"\ + "Alhamisi"\ + "Ijumaa"\ + "Jumamosi"] + ::msgcat::mcset sw MONTHS_ABBREV [list \ + "Jan"\ + "Feb"\ + "Mar"\ + "Apr"\ + "Mei"\ + "Jun"\ + "Jul"\ + "Ago"\ + "Sep"\ + "Okt"\ + "Nov"\ + "Des"\ + ""] + ::msgcat::mcset sw MONTHS_FULL [list \ + "Januari"\ + "Februari"\ + "Machi"\ + "Aprili"\ + "Mei"\ + "Juni"\ + "Julai"\ + "Agosti"\ + "Septemba"\ + "Oktoba"\ + "Novemba"\ + "Desemba"\ + ""] + ::msgcat::mcset sw BCE "KK" + ::msgcat::mcset sw CE "BK" +} diff --git a/shared/package-files/6b/6b61d98e6ec7b02d124ea8839e137a3892f8c8831c336f15355b4c5c323606a1/test_connected_components.py b/shared/package-files/6b/6b61d98e6ec7b02d124ea8839e137a3892f8c8831c336f15355b4c5c323606a1/test_connected_components.py new file mode 100644 index 0000000000000000000000000000000000000000..0b190a24deb9f2818893a120f8ea376fbfb8d6fe --- /dev/null +++ b/shared/package-files/6b/6b61d98e6ec7b02d124ea8839e137a3892f8c8831c336f15355b4c5c323606a1/test_connected_components.py @@ -0,0 +1,119 @@ +import numpy as np +from numpy.testing import assert_equal, assert_array_almost_equal +from scipy.sparse import csgraph, csr_array + + +def test_weak_connections(): + Xde = np.array([[0, 1, 0], + [0, 0, 0], + [0, 0, 0]]) + + Xsp = csgraph.csgraph_from_dense(Xde, null_value=0) + + for X in Xsp, Xde: + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='weak') + + assert_equal(n_components, 2) + assert_array_almost_equal(labels, [0, 0, 1]) + + +def test_strong_connections(): + X1de = np.array([[0, 1, 0], + [0, 0, 0], + [0, 0, 0]]) + X2de = X1de + X1de.T + + X1sp = csgraph.csgraph_from_dense(X1de, null_value=0) + X2sp = csgraph.csgraph_from_dense(X2de, null_value=0) + + for X in X1sp, X1de: + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='strong') + + assert_equal(n_components, 3) + labels.sort() + assert_array_almost_equal(labels, [0, 1, 2]) + + for X in X2sp, X2de: + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='strong') + + assert_equal(n_components, 2) + labels.sort() + assert_array_almost_equal(labels, [0, 0, 1]) + + +def test_strong_connections2(): + X = np.array([[0, 0, 0, 0, 0, 0], + [1, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 1, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0]]) + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='strong') + assert_equal(n_components, 5) + labels.sort() + assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4]) + + +def test_weak_connections2(): + X = np.array([[0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 1, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0]]) + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='weak') + assert_equal(n_components, 2) + labels.sort() + assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1]) + + +def test_ticket1876(): + # Regression test: this failed in the original implementation + # There should be two strongly-connected components; previously gave one + g = np.array([[0, 1, 1, 0], + [1, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 1, 0]]) + n_components, labels = csgraph.connected_components(g, connection='strong') + + assert_equal(n_components, 2) + assert_equal(labels[0], labels[1]) + assert_equal(labels[2], labels[3]) + + +def test_fully_connected_graph(): + # Fully connected dense matrices raised an exception. + # https://github.com/scipy/scipy/issues/3818 + g = np.ones((4, 4)) + n_components, labels = csgraph.connected_components(g) + assert_equal(n_components, 1) + + +def test_int64_indices_undirected(): + # See https://github.com/scipy/scipy/issues/18716 + g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2)) + assert g.indices.dtype == np.int64 + n, labels = csgraph.connected_components(g, directed=False) + assert n == 1 + assert_array_almost_equal(labels, [0, 0]) + + +def test_int64_indices_directed(): + # See https://github.com/scipy/scipy/issues/18716 + g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2)) + assert g.indices.dtype == np.int64 + n, labels = csgraph.connected_components(g, directed=True, + connection='strong') + assert n == 2 + assert_array_almost_equal(labels, [1, 0]) + diff --git a/shared/package-files/6b/6b66894c6e0571e192257b23b71a12f12e2393ff2b66c4b76b39cb91e3b6fdd6/clusterfuzz-testcase-minimized-bs4_fuzzer-6600557255327744.testcase b/shared/package-files/6b/6b66894c6e0571e192257b23b71a12f12e2393ff2b66c4b76b39cb91e3b6fdd6/clusterfuzz-testcase-minimized-bs4_fuzzer-6600557255327744.testcase new file mode 100644 index 0000000000000000000000000000000000000000..65af44d8c1bdb043fa6810902e1ce623533bd34a Binary files /dev/null and b/shared/package-files/6b/6b66894c6e0571e192257b23b71a12f12e2393ff2b66c4b76b39cb91e3b6fdd6/clusterfuzz-testcase-minimized-bs4_fuzzer-6600557255327744.testcase differ diff --git a/shared/package-files/6b/6b66f0bcdf0513790a2535cff04e5ae8bb5d38a2e651d60ff69ca202eded1815/group_by.py b/shared/package-files/6b/6b66f0bcdf0513790a2535cff04e5ae8bb5d38a2e651d60ff69ca202eded1815/group_by.py new file mode 100644 index 0000000000000000000000000000000000000000..b5cc053e3cb2c83c3794e020aaa84961220d9cfd --- /dev/null +++ b/shared/package-files/6b/6b66f0bcdf0513790a2535cff04e5ae8bb5d38a2e651d60ff69ca202eded1815/group_by.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from itertools import chain +from typing import TYPE_CHECKING + +from narwhals._duckdb.utils import join_column_names +from narwhals._sql.group_by import SQLGroupBy + +if TYPE_CHECKING: + from collections.abc import Sequence + + from duckdb import Expression # noqa: F401 + + from narwhals._duckdb.dataframe import DuckDBLazyFrame + from narwhals._duckdb.expr import DuckDBExpr + + +class DuckDBGroupBy(SQLGroupBy["DuckDBLazyFrame", "DuckDBExpr", "Expression"]): + def __init__( + self, + df: DuckDBLazyFrame, + keys: Sequence[DuckDBExpr] | Sequence[str], + /, + *, + drop_null_keys: bool, + ) -> None: + frame, self._keys, self._output_key_names = self._parse_keys(df, keys=keys) + self._compliant_frame = frame.drop_nulls(self._keys) if drop_null_keys else frame + + def agg(self, *exprs: DuckDBExpr) -> DuckDBLazyFrame: + agg_columns = tuple(self._evaluate_exprs(exprs)) + result = self.compliant.native.aggregate( + tuple(chain(self._keys, agg_columns)), join_column_names(*self._keys) + ) + + return self.compliant._with_native(result).rename( + dict(zip(self._keys, self._output_key_names, strict=False)) + ) diff --git a/shared/package-files/6b/6b683acd7097c278ab105bbe552892cd17e4db7ffe13432055ba1d2ce1df8ebd/_compile.py b/shared/package-files/6b/6b683acd7097c278ab105bbe552892cd17e4db7ffe13432055ba1d2ce1df8ebd/_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..354d64e9ff9fddc9a1dc321241ce8bea7955b58a --- /dev/null +++ b/shared/package-files/6b/6b683acd7097c278ab105bbe552892cd17e4db7ffe13432055ba1d2ce1df8ebd/_compile.py @@ -0,0 +1,30 @@ +""" +APIs related to torch.compile which lazily import torch._dynamo to avoid +circular dependencies. +""" +import functools + + +def _disable_dynamo(fn=None, recursive=True): + """ + This API should be only used inside torch, external users should still use + torch._dynamo.disable. The main goal of this API is to avoid circular + imports issues that is common while using _dynamo.disable inside torch + itself. + + This API avoids it by lazily importing torch._dynamo from the import time to + the invocation of the decorated function. + """ + if fn is not None: + + @functools.wraps(fn) + def inner(*args, **kwargs): + import torch._dynamo + + return torch._dynamo.disable(fn, recursive)(*args, **kwargs) + + return inner + else: + # decorator usage like @_disable_dynamo(recursive=False). The resulting + # object expects the original decorated function as the arg. + return functools.partial(_disable_dynamo, recursive=recursive) diff --git a/shared/package-files/6b/6b6b3195086d0d56d89fc28e287518ab073e68216deec0cf4a726c5c51b7e6e2/gh25211.f b/shared/package-files/6b/6b6b3195086d0d56d89fc28e287518ab073e68216deec0cf4a726c5c51b7e6e2/gh25211.f new file mode 100644 index 0000000000000000000000000000000000000000..ba727a10a07ebec77845f8a67746cf5d5bb3d32a --- /dev/null +++ b/shared/package-files/6b/6b6b3195086d0d56d89fc28e287518ab073e68216deec0cf4a726c5c51b7e6e2/gh25211.f @@ -0,0 +1,10 @@ + SUBROUTINE FOO(FUN,R) + EXTERNAL FUN + INTEGER I + REAL*8 R, FUN +Cf2py intent(out) r + R = 0D0 + DO I=-5,5 + R = R + FUN(I) + ENDDO + END diff --git a/shared/package-files/6b/6b70e49bf8cf3aeab336c0c0e1e7a3b8c53008404c6af33cb92ef0f358a16d16/client_auth.h b/shared/package-files/6b/6b70e49bf8cf3aeab336c0c0e1e7a3b8c53008404c6af33cb92ef0f358a16d16/client_auth.h new file mode 100644 index 0000000000000000000000000000000000000000..9dad36aa0948906ebb2447c0030cf117c8549c2c --- /dev/null +++ b/shared/package-files/6b/6b70e49bf8cf3aeab336c0c0e1e7a3b8c53008404c6af33cb92ef0f358a16d16/client_auth.h @@ -0,0 +1,62 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include "arrow/flight/visibility.h" +#include "arrow/status.h" + +namespace arrow { + +namespace flight { + +/// \brief A reader for messages from the server during an +/// authentication handshake. +class ARROW_FLIGHT_EXPORT ClientAuthReader { + public: + virtual ~ClientAuthReader() = default; + virtual Status Read(std::string* response) = 0; +}; + +/// \brief A writer for messages to the server during an +/// authentication handshake. +class ARROW_FLIGHT_EXPORT ClientAuthSender { + public: + virtual ~ClientAuthSender() = default; + virtual Status Write(const std::string& token) = 0; +}; + +/// \brief An authentication implementation for a Flight service. +/// Authentication includes both an initial negotiation and a per-call +/// token validation. Implementations may choose to use either or both +/// mechanisms. +class ARROW_FLIGHT_EXPORT ClientAuthHandler { + public: + virtual ~ClientAuthHandler() = default; + /// \brief Authenticate the client on initial connection. The client + /// can send messages to/read responses from the server at any time. + /// \return Status OK if authenticated successfully + virtual Status Authenticate(ClientAuthSender* outgoing, ClientAuthReader* incoming) = 0; + /// \brief Get a per-call token. + /// \param[out] token The token to send to the server. + virtual Status GetToken(std::string* token) = 0; +}; + +} // namespace flight +} // namespace arrow diff --git a/shared/package-files/6b/6b710718a42dfe331de31f48efbd89cfe4c6167198f9aad6a8fbd91b3f5049ed/qfunctions.py b/shared/package-files/6b/6b710718a42dfe331de31f48efbd89cfe4c6167198f9aad6a8fbd91b3f5049ed/qfunctions.py new file mode 100644 index 0000000000000000000000000000000000000000..5a20e53a8b6fa0d8fbc9ad098614d2694998f49a --- /dev/null +++ b/shared/package-files/6b/6b710718a42dfe331de31f48efbd89cfe4c6167198f9aad6a8fbd91b3f5049ed/qfunctions.py @@ -0,0 +1,280 @@ +from .functions import defun, defun_wrapped + +@defun +def qp(ctx, a, q=None, n=None, **kwargs): + r""" + Evaluates the q-Pochhammer symbol (or q-rising factorial) + + .. math :: + + (a; q)_n = \prod_{k=0}^{n-1} (1-a q^k) + + where `n = \infty` is permitted if `|q| < 1`. Called with two arguments, + ``qp(a,q)`` computes `(a;q)_{\infty}`; with a single argument, ``qp(q)`` + computes `(q;q)_{\infty}`. The special case + + .. math :: + + \phi(q) = (q; q)_{\infty} = \prod_{k=1}^{\infty} (1-q^k) = + \sum_{k=-\infty}^{\infty} (-1)^k q^{(3k^2-k)/2} + + is also known as the Euler function, or (up to a factor `q^{-1/24}`) + the Dedekind eta function. + + **Examples** + + If `n` is a positive integer, the function amounts to a finite product:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> qp(2,3,5) + -725305.0 + >>> fprod(1-2*3**k for k in range(5)) + -725305.0 + >>> qp(2,3,0) + 1.0 + + Complex arguments are allowed:: + + >>> qp(2-1j, 0.75j) + (0.4628842231660149089976379 + 4.481821753552703090628793j) + + The regular Pochhammer symbol `(a)_n` is obtained in the + following limit as `q \to 1`:: + + >>> a, n = 4, 7 + >>> limit(lambda q: qp(q**a,q,n) / (1-q)**n, 1) + 604800.0 + >>> rf(a,n) + 604800.0 + + The Taylor series of the reciprocal Euler function gives + the partition function `P(n)`, i.e. the number of ways of writing + `n` as a sum of positive integers:: + + >>> taylor(lambda q: 1/qp(q), 0, 10) + [1.0, 1.0, 2.0, 3.0, 5.0, 7.0, 11.0, 15.0, 22.0, 30.0, 42.0] + + Special values include:: + + >>> qp(0) + 1.0 + >>> findroot(diffun(qp), -0.4) # location of maximum + -0.4112484791779547734440257 + >>> qp(_) + 1.228348867038575112586878 + + The q-Pochhammer symbol is related to the Jacobi theta functions. + For example, the following identity holds:: + + >>> q = mpf(0.5) # arbitrary + >>> qp(q) + 0.2887880950866024212788997 + >>> root(3,-2)*root(q,-24)*jtheta(2,pi/6,root(q,6)) + 0.2887880950866024212788997 + + """ + a = ctx.convert(a) + if n is None: + n = ctx.inf + else: + n = ctx.convert(n) + if n < 0: + raise ValueError("n cannot be negative") + if q is None: + q = a + else: + q = ctx.convert(q) + if n == 0: + return ctx.one + 0*(a+q) + infinite = (n == ctx.inf) + same = (a == q) + if infinite: + if abs(q) >= 1: + if same and (q == -1 or q == 1): + return ctx.zero * q + raise ValueError("q-function only defined for |q| < 1") + elif q == 0: + return ctx.one - a + maxterms = kwargs.get('maxterms', 50*ctx.prec) + if infinite and same: + # Euler's pentagonal theorem + def terms(): + t = 1 + yield t + k = 1 + x1 = q + x2 = q**2 + while 1: + yield (-1)**k * x1 + yield (-1)**k * x2 + x1 *= q**(3*k+1) + x2 *= q**(3*k+2) + k += 1 + if k > maxterms: + raise ctx.NoConvergence + return ctx.sum_accurately(terms) + # return ctx.nprod(lambda k: 1-a*q**k, [0,n-1]) + def factors(): + k = 0 + r = ctx.one + while 1: + yield 1 - a*r + r *= q + k += 1 + if k >= n: + return + if k > maxterms: + raise ctx.NoConvergence + return ctx.mul_accurately(factors) + +@defun_wrapped +def qgamma(ctx, z, q, **kwargs): + r""" + Evaluates the q-gamma function + + .. math :: + + \Gamma_q(z) = \frac{(q; q)_{\infty}}{(q^z; q)_{\infty}} (1-q)^{1-z}. + + + **Examples** + + Evaluation for real and complex arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> qgamma(4,0.75) + 4.046875 + >>> qgamma(6,6) + 121226245.0 + >>> qgamma(3+4j, 0.5j) + (0.1663082382255199834630088 + 0.01952474576025952984418217j) + + The q-gamma function satisfies a functional equation similar + to that of the ordinary gamma function:: + + >>> q = mpf(0.25) + >>> z = mpf(2.5) + >>> qgamma(z+1,q) + 1.428277424823760954685912 + >>> (1-q**z)/(1-q)*qgamma(z,q) + 1.428277424823760954685912 + + """ + if abs(q) > 1: + return ctx.qgamma(z,1/q)*q**((z-2)*(z-1)*0.5) + return ctx.qp(q, q, None, **kwargs) / \ + ctx.qp(q**z, q, None, **kwargs) * (1-q)**(1-z) + +@defun_wrapped +def qfac(ctx, z, q, **kwargs): + r""" + Evaluates the q-factorial, + + .. math :: + + [n]_q! = (1+q)(1+q+q^2)\cdots(1+q+\cdots+q^{n-1}) + + or more generally + + .. math :: + + [z]_q! = \frac{(q;q)_z}{(1-q)^z}. + + **Examples** + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> qfac(0,0) + 1.0 + >>> qfac(4,3) + 2080.0 + >>> qfac(5,6) + 121226245.0 + >>> qfac(1+1j, 2+1j) + (0.4370556551322672478613695 + 0.2609739839216039203708921j) + + """ + if ctx.isint(z) and ctx._re(z) > 0: + n = int(ctx._re(z)) + return ctx.qp(q, q, n, **kwargs) / (1-q)**n + return ctx.qgamma(z+1, q, **kwargs) + +@defun +def qhyper(ctx, a_s, b_s, q, z, **kwargs): + r""" + Evaluates the basic hypergeometric series or hypergeometric q-series + + .. math :: + + \,_r\phi_s \left[\begin{matrix} + a_1 & a_2 & \ldots & a_r \\ + b_1 & b_2 & \ldots & b_s + \end{matrix} ; q,z \right] = + \sum_{n=0}^\infty + \frac{(a_1;q)_n, \ldots, (a_r;q)_n} + {(b_1;q)_n, \ldots, (b_s;q)_n} + \left((-1)^n q^{n\choose 2}\right)^{1+s-r} + \frac{z^n}{(q;q)_n} + + where `(a;q)_n` denotes the q-Pochhammer symbol (see :func:`~mpmath.qp`). + + **Examples** + + Evaluation works for real and complex arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> qhyper([0.5], [2.25], 0.25, 4) + -0.1975849091263356009534385 + >>> qhyper([0.5], [2.25], 0.25-0.25j, 4) + (2.806330244925716649839237 + 3.568997623337943121769938j) + >>> qhyper([1+j], [2,3+0.5j], 0.25, 3+4j) + (9.112885171773400017270226 - 1.272756997166375050700388j) + + Comparing with a summation of the defining series, using + :func:`~mpmath.nsum`:: + + >>> b, q, z = 3, 0.25, 0.5 + >>> qhyper([], [b], q, z) + 0.6221136748254495583228324 + >>> nsum(lambda n: z**n / qp(q,q,n)/qp(b,q,n) * q**(n*(n-1)), [0,inf]) + 0.6221136748254495583228324 + + """ + #a_s = [ctx._convert_param(a)[0] for a in a_s] + #b_s = [ctx._convert_param(b)[0] for b in b_s] + #q = ctx._convert_param(q)[0] + a_s = [ctx.convert(a) for a in a_s] + b_s = [ctx.convert(b) for b in b_s] + q = ctx.convert(q) + z = ctx.convert(z) + r = len(a_s) + s = len(b_s) + d = 1+s-r + maxterms = kwargs.get('maxterms', 50*ctx.prec) + def terms(): + t = ctx.one + yield t + qk = 1 + k = 0 + x = 1 + while 1: + for a in a_s: + p = 1 - a*qk + t *= p + for b in b_s: + p = 1 - b*qk + if not p: + raise ValueError + t /= p + t *= z + x *= (-1)**d * qk ** d + qk *= q + t /= (1 - qk) + k += 1 + yield t * x + if k > maxterms: + raise ctx.NoConvergence + return ctx.sum_accurately(terms) diff --git a/shared/package-files/6b/6b7292969b1b6b4346dcceeae898077f5df75a8c57321cbf51277fbffc784ea5/att610+cvis b/shared/package-files/6b/6b7292969b1b6b4346dcceeae898077f5df75a8c57321cbf51277fbffc784ea5/att610+cvis new file mode 100644 index 0000000000000000000000000000000000000000..5f94bfb59d8eecaaa1a08b74c49d99ab347fccd8 Binary files /dev/null and b/shared/package-files/6b/6b7292969b1b6b4346dcceeae898077f5df75a8c57321cbf51277fbffc784ea5/att610+cvis differ diff --git a/shared/package-files/6b/6b73d255fa8a2c5a9c94837365acd3ed3df6e51cdebd37a0b335494fc0039c99/tcolor b/shared/package-files/6b/6b73d255fa8a2c5a9c94837365acd3ed3df6e51cdebd37a0b335494fc0039c99/tcolor new file mode 100644 index 0000000000000000000000000000000000000000..aae858b305b473f8df01793c1ddf2fc21a90a243 --- /dev/null +++ b/shared/package-files/6b/6b73d255fa8a2c5a9c94837365acd3ed3df6e51cdebd37a0b335494fc0039c99/tcolor @@ -0,0 +1,358 @@ +#!/bin/sh +# the next line restarts using wish \ +exec wish8.6 "$0" ${1+"$@"} + +# tcolor -- +# This script implements a simple color editor, where you can +# create colors using either the RGB, HSB, or CYM color spaces +# and apply the color to existing applications. + +package require Tk +wm title . "Color Editor" + +# Global variables that control the program: +# +# colorSpace - Color space currently being used for +# editing. Must be "rgb", "cmy", or "hsb". +# label1, label2, label3 - Labels for the scales. +# red, green, blue - Current color intensities in decimal +# on a scale of 0-65535. +# color - A string giving the current color value +# in the proper form for x: +# #RRRRGGGGBBBB +# updating - Non-zero means that we're in the middle of +# updating the scales to load a new color,so +# information shouldn't be propagating back +# from the scales to other elements of the +# program: this would make an infinite loop. +# command - Holds the command that has been typed +# into the "Command" entry. +# autoUpdate - 1 means execute the update command +# automatically whenever the color changes. +# name - Name for new color, typed into entry. + +set colorSpace hsb +set red 65535 +set green 0 +set blue 0 +set color #ffff00000000 +set updating 0 +set autoUpdate 1 +set name "" + +# Create the menu bar at the top of the window. + +. configure -menu [menu .menu] +menu .menu.file +.menu add cascade -menu .menu.file -label File -underline 0 +.menu.file add radio -label "RGB color space" -variable colorSpace \ + -value rgb -underline 0 -command {changeColorSpace rgb} +.menu.file add radio -label "CMY color space" -variable colorSpace \ + -value cmy -underline 0 -command {changeColorSpace cmy} +.menu.file add radio -label "HSB color space" -variable colorSpace \ + -value hsb -underline 0 -command {changeColorSpace hsb} +.menu.file add separator +.menu.file add radio -label "Automatic updates" -variable autoUpdate \ + -value 1 -underline 0 +.menu.file add radio -label "Manual updates" -variable autoUpdate \ + -value 0 -underline 0 +.menu.file add separator +.menu.file add command -label "Exit program" -underline 0 -command {exit} + +# Create the command entry window at the bottom of the window, along +# with the update button. + +labelframe .command -text "Command:" -padx {1m 0} +entry .command.e -textvariable command +button .command.update -text Update -command doUpdate +pack .command.update -side right -pady .1c -padx {.25c 0} +pack .command.e -expand yes -fill x -ipadx 0.25c + + +# Create the listbox that holds all of the color names in rgb.txt, +# if an rgb.txt file can be found. + +grid .command -sticky nsew -row 2 -columnspan 3 -padx 1m -pady {0 1m} + +grid columnconfigure . {1 2} -weight 1 +grid rowconfigure . 0 -weight 1 +foreach i { + /usr/local/lib/X11/rgb.txt /usr/lib/X11/rgb.txt + /X11/R5/lib/X11/rgb.txt /X11/R4/lib/rgb/rgb.txt + /usr/openwin/lib/X11/rgb.txt +} { + if {![file readable $i]} { + continue; + } + set f [open $i] + labelframe .names -text "Select:" -padx .1c -pady .1c + grid .names -row 0 -column 0 -sticky nsew -padx .15c -pady .15c -rowspan 2 + grid columnconfigure . 0 -weight 1 + listbox .names.lb -width 20 -height 12 -yscrollcommand ".names.s set" \ + -exportselection false + bind .names.lb { + tc_loadNamedColor [.names.lb get [.names.lb curselection]] + } + scrollbar .names.s -orient vertical -command ".names.lb yview" + pack .names.lb .names.s -side left -fill y -expand 1 + while {[gets $f line] >= 0} { + if {[regexp {^\s*\d+\s+\d+\s+\d+\s+(\S+)$} $line -> col]} { + .names.lb insert end $col + } + } + close $f + break +} + +# Create the three scales for editing the color, and the entry for +# typing in a color value. + +frame .adjust +foreach i {1 2 3} { + label .adjust.l$i -textvariable label$i -pady 0 + labelframe .adjust.$i -labelwidget .adjust.l$i -padx 1m -pady 1m + scale .scale$i -from 0 -to 1000 -length 6c -orient horizontal \ + -command tc_scaleChanged + pack .scale$i -in .adjust.$i + pack .adjust.$i +} +grid .adjust -row 0 -column 1 -sticky nsew -padx .15c -pady .15c + +labelframe .name -text "Name:" -padx 1m -pady 1m +entry .name.e -textvariable name -width 10 +pack .name.e -side right -expand 1 -fill x +bind .name.e {tc_loadNamedColor $name} +grid .name -column 1 -row 1 -sticky nsew -padx .15c -pady .15c + +# Create the color display swatch on the right side of the window. + +labelframe .sample -text "Color:" -padx 1m -pady 1m +frame .sample.swatch -width 2c -height 5c -background $color +label .sample.value -textvariable color -width 13 -font {Courier 12} +pack .sample.swatch -side top -expand yes -fill both +pack .sample.value -side bottom -pady .25c +grid .sample -row 0 -column 2 -sticky nsew -padx .15c -pady .15c -rowspan 2 + + +# The procedure below is invoked when one of the scales is adjusted. +# It propagates color information from the current scale readings +# to everywhere else that it is used. + +proc tc_scaleChanged args { + global red green blue colorSpace color updating autoUpdate + if {$updating} { + return + } + switch $colorSpace { + rgb { + set red [format %.0f [expr {[.scale1 get]*65.535}]] + set green [format %.0f [expr {[.scale2 get]*65.535}]] + set blue [format %.0f [expr {[.scale3 get]*65.535}]] + } + cmy { + set red [format %.0f [expr {65535 - [.scale1 get]*65.535}]] + set green [format %.0f [expr {65535 - [.scale2 get]*65.535}]] + set blue [format %.0f [expr {65535 - [.scale3 get]*65.535}]] + } + hsb { + set list [hsbToRgb [expr {[.scale1 get]/1000.0}] \ + [expr {[.scale2 get]/1000.0}] \ + [expr {[.scale3 get]/1000.0}]] + set red [lindex $list 0] + set green [lindex $list 1] + set blue [lindex $list 2] + } + } + set color [format "#%04x%04x%04x" $red $green $blue] + .sample.swatch config -bg $color + if {$autoUpdate} doUpdate + update idletasks +} + +# The procedure below is invoked to update the scales from the +# current red, green, and blue intensities. It's invoked after +# a change in the color space and after a named color value has +# been loaded. + +proc tc_setScales {} { + global red green blue colorSpace updating + set updating 1 + switch $colorSpace { + rgb { + .scale1 set [format %.0f [expr {$red/65.535}]] + .scale2 set [format %.0f [expr {$green/65.535}]] + .scale3 set [format %.0f [expr {$blue/65.535}]] + } + cmy { + .scale1 set [format %.0f [expr {(65535-$red)/65.535}]] + .scale2 set [format %.0f [expr {(65535-$green)/65.535}]] + .scale3 set [format %.0f [expr {(65535-$blue)/65.535}]] + } + hsb { + set list [rgbToHsv $red $green $blue] + .scale1 set [format %.0f [expr {[lindex $list 0] * 1000.0}]] + .scale2 set [format %.0f [expr {[lindex $list 1] * 1000.0}]] + .scale3 set [format %.0f [expr {[lindex $list 2] * 1000.0}]] + } + } + set updating 0 +} + +# The procedure below is invoked when a named color has been +# selected from the listbox or typed into the entry. It loads +# the color into the editor. + +proc tc_loadNamedColor name { + global red green blue color autoUpdate + + if {[string index $name 0] != "#"} { + set list [winfo rgb .sample.swatch $name] + set red [lindex $list 0] + set green [lindex $list 1] + set blue [lindex $list 2] + } else { + switch [string length $name] { + 4 {set format "#%1x%1x%1x"; set shift 12} + 7 {set format "#%2x%2x%2x"; set shift 8} + 10 {set format "#%3x%3x%3x"; set shift 4} + 13 {set format "#%4x%4x%4x"; set shift 0} + default {error "syntax error in color name \"$name\""} + } + if {[scan $name $format red green blue] != 3} { + error "syntax error in color name \"$name\"" + } + set red [expr {$red<<$shift}] + set green [expr {$green<<$shift}] + set blue [expr {$blue<<$shift}] + } + tc_setScales + set color [format "#%04x%04x%04x" $red $green $blue] + .sample.swatch config -bg $color + if {$autoUpdate} doUpdate +} + +# The procedure below is invoked when a new color space is selected. +# It changes the labels on the scales and re-loads the scales with +# the appropriate values for the current color in the new color space + +proc changeColorSpace space { + global label1 label2 label3 + switch $space { + rgb { + set label1 "Adjust Red:" + set label2 "Adjust Green:" + set label3 "Adjust Blue:" + tc_setScales + return + } + cmy { + set label1 "Adjust Cyan:" + set label2 "Adjust Magenta:" + set label3 "Adjust Yellow:" + tc_setScales + return + } + hsb { + set label1 "Adjust Hue:" + set label2 "Adjust Saturation:" + set label3 "Adjust Brightness:" + tc_setScales + return + } + } +} + +# The procedure below converts an RGB value to HSB. It takes red, green, +# and blue components (0-65535) as arguments, and returns a list containing +# HSB components (floating-point, 0-1) as result. The code here is a copy +# of the code on page 615 of "Fundamentals of Interactive Computer Graphics" +# by Foley and Van Dam. + +proc rgbToHsv {red green blue} { + if {$red > $green} { + set max [expr {double($red)}] + set min [expr {double($green)}] + } else { + set max [expr {double($green)}] + set min [expr {double($red)}] + } + if {$blue > $max} { + set max [expr {double($blue)}] + } elseif {$blue < $min} { + set min [expr {double($blue)}] + } + set range [expr {$max-$min}] + if {$max == 0} { + set sat 0 + } else { + set sat [expr {($max-$min)/$max}] + } + if {$sat == 0} { + set hue 0 + } else { + set rc [expr {($max - $red)/$range}] + set gc [expr {($max - $green)/$range}] + set bc [expr {($max - $blue)/$range}] + if {$red == $max} { + set hue [expr {($bc - $gc)/6.0}] + } elseif {$green == $max} { + set hue [expr {(2 + $rc - $bc)/6.0}] + } else { + set hue [expr {(4 + $gc - $rc)/6.0}] + } + if {$hue < 0.0} { + set hue [expr {$hue + 1.0}] + } + } + return [list $hue $sat [expr {$max/65535}]] +} + +# The procedure below converts an HSB value to RGB. It takes hue, saturation, +# and value components (floating-point, 0-1.0) as arguments, and returns a +# list containing RGB components (integers, 0-65535) as result. The code +# here is a copy of the code on page 616 of "Fundamentals of Interactive +# Computer Graphics" by Foley and Van Dam. + +proc hsbToRgb {hue sat value} { + set v [format %.0f [expr {65535.0*$value}]] + if {$sat == 0} { + return "$v $v $v" + } else { + set hue [expr {$hue*6.0}] + if {$hue >= 6.0} { + set hue 0.0 + } + scan $hue. %d i + set f [expr {$hue-$i}] + set p [format %.0f [expr {65535.0*$value*(1 - $sat)}]] + set q [format %.0f [expr {65535.0*$value*(1 - ($sat*$f))}]] + set t [format %.0f [expr {65535.0*$value*(1 - ($sat*(1 - $f)))}]] + switch $i { + 0 {return "$v $t $p"} + 1 {return "$q $v $p"} + 2 {return "$p $v $t"} + 3 {return "$p $q $v"} + 4 {return "$t $p $v"} + 5 {return "$v $p $q"} + default {error "i value $i is out of range"} + } + } +} + +# The procedure below is invoked when the "Update" button is pressed, +# and whenever the color changes if update mode is enabled. It +# propagates color information as determined by the command in the +# Command entry. + +proc doUpdate {} { + global color command + set newCmd $command + regsub -all %% $command $color newCmd + eval $newCmd +} + +changeColorSpace hsb + +# Local Variables: +# mode: tcl +# End: diff --git a/shared/package-files/6b/6b75e7a9cabf8ced24733666866b812a4982b0a1ce3ae7f2f61eb23423c794c9/test_dtypes.py b/shared/package-files/6b/6b75e7a9cabf8ced24733666866b812a4982b0a1ce3ae7f2f61eb23423c794c9/test_dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..4007320b5de332ee4aef40b1ad1be9092eeb3347 --- /dev/null +++ b/shared/package-files/6b/6b75e7a9cabf8ced24733666866b812a4982b0a1ce3ae7f2f61eb23423c794c9/test_dtypes.py @@ -0,0 +1,173 @@ +import numpy as np +import pytest + +from pandas.errors import DataError + +from pandas.core.dtypes.common import pandas_dtype + +from pandas import ( + NA, + DataFrame, + Series, +) +import pandas._testing as tm + +# gh-12373 : rolling functions error on float32 data +# make sure rolling functions works for different dtypes +# +# further note that we are only checking rolling for fully dtype +# compliance (though both expanding and ewm inherit) + + +def get_dtype(dtype, coerce_int=None): + if coerce_int is False and "int" in dtype: + return None + return pandas_dtype(dtype) + + +@pytest.fixture( + params=[ + "object", + "category", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "float16", + "float32", + "float64", + "m8[ns]", + "M8[ns]", + "datetime64[ns, UTC]", + ] +) +def dtypes(request): + """Dtypes for window tests""" + return request.param + + +@pytest.mark.parametrize( + "method, data, expected_data, coerce_int, min_periods", + [ + ("count", np.arange(5), [1, 2, 2, 2, 2], True, 0), + ("count", np.arange(10, 0, -2), [1, 2, 2, 2, 2], True, 0), + ("count", [0, 1, 2, np.nan, 4], [1, 2, 2, 1, 1], False, 0), + ("max", np.arange(5), [np.nan, 1, 2, 3, 4], True, None), + ("max", np.arange(10, 0, -2), [np.nan, 10, 8, 6, 4], True, None), + ("max", [0, 1, 2, np.nan, 4], [np.nan, 1, 2, np.nan, np.nan], False, None), + ("min", np.arange(5), [np.nan, 0, 1, 2, 3], True, None), + ("min", np.arange(10, 0, -2), [np.nan, 8, 6, 4, 2], True, None), + ("min", [0, 1, 2, np.nan, 4], [np.nan, 0, 1, np.nan, np.nan], False, None), + ("sum", np.arange(5), [np.nan, 1, 3, 5, 7], True, None), + ("sum", np.arange(10, 0, -2), [np.nan, 18, 14, 10, 6], True, None), + ("sum", [0, 1, 2, np.nan, 4], [np.nan, 1, 3, np.nan, np.nan], False, None), + ("mean", np.arange(5), [np.nan, 0.5, 1.5, 2.5, 3.5], True, None), + ("mean", np.arange(10, 0, -2), [np.nan, 9, 7, 5, 3], True, None), + ("mean", [0, 1, 2, np.nan, 4], [np.nan, 0.5, 1.5, np.nan, np.nan], False, None), + ("std", np.arange(5), [np.nan] + [np.sqrt(0.5)] * 4, True, None), + ("std", np.arange(10, 0, -2), [np.nan] + [np.sqrt(2)] * 4, True, None), + ( + "std", + [0, 1, 2, np.nan, 4], + [np.nan] + [np.sqrt(0.5)] * 2 + [np.nan] * 2, + False, + None, + ), + ("var", np.arange(5), [np.nan, 0.5, 0.5, 0.5, 0.5], True, None), + ("var", np.arange(10, 0, -2), [np.nan, 2, 2, 2, 2], True, None), + ("var", [0, 1, 2, np.nan, 4], [np.nan, 0.5, 0.5, np.nan, np.nan], False, None), + ("median", np.arange(5), [np.nan, 0.5, 1.5, 2.5, 3.5], True, None), + ("median", np.arange(10, 0, -2), [np.nan, 9, 7, 5, 3], True, None), + ( + "median", + [0, 1, 2, np.nan, 4], + [np.nan, 0.5, 1.5, np.nan, np.nan], + False, + None, + ), + ], +) +def test_series_dtypes( + method, data, expected_data, coerce_int, dtypes, min_periods, step +): + ser = Series(data, dtype=get_dtype(dtypes, coerce_int=coerce_int)) + rolled = ser.rolling(2, min_periods=min_periods, step=step) + + if dtypes in ("m8[ns]", "M8[ns]", "datetime64[ns, UTC]") and method != "count": + msg = "No numeric types to aggregate" + with pytest.raises(DataError, match=msg): + getattr(rolled, method)() + else: + result = getattr(rolled, method)() + expected = Series(expected_data, dtype="float64")[::step] + tm.assert_almost_equal(result, expected) + + +def test_series_nullable_int(any_signed_int_ea_dtype, step): + # GH 43016 + ser = Series([0, 1, NA], dtype=any_signed_int_ea_dtype) + result = ser.rolling(2, step=step).mean() + expected = Series([np.nan, 0.5, np.nan])[::step] + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "method, expected_data, min_periods", + [ + ("count", {0: Series([1, 2, 2, 2, 2]), 1: Series([1, 2, 2, 2, 2])}, 0), + ( + "max", + {0: Series([np.nan, 2, 4, 6, 8]), 1: Series([np.nan, 3, 5, 7, 9])}, + None, + ), + ( + "min", + {0: Series([np.nan, 0, 2, 4, 6]), 1: Series([np.nan, 1, 3, 5, 7])}, + None, + ), + ( + "sum", + {0: Series([np.nan, 2, 6, 10, 14]), 1: Series([np.nan, 4, 8, 12, 16])}, + None, + ), + ( + "mean", + {0: Series([np.nan, 1, 3, 5, 7]), 1: Series([np.nan, 2, 4, 6, 8])}, + None, + ), + ( + "std", + { + 0: Series([np.nan] + [np.sqrt(2)] * 4), + 1: Series([np.nan] + [np.sqrt(2)] * 4), + }, + None, + ), + ( + "var", + {0: Series([np.nan, 2, 2, 2, 2]), 1: Series([np.nan, 2, 2, 2, 2])}, + None, + ), + ( + "median", + {0: Series([np.nan, 1, 3, 5, 7]), 1: Series([np.nan, 2, 4, 6, 8])}, + None, + ), + ], +) +def test_dataframe_dtypes(method, expected_data, dtypes, min_periods, step): + df = DataFrame(np.arange(10).reshape((5, 2)), dtype=get_dtype(dtypes)) + rolled = df.rolling(2, min_periods=min_periods, step=step) + + if dtypes in ("m8[ns]", "M8[ns]", "datetime64[ns, UTC]") and method != "count": + msg = "Cannot aggregate non-numeric type" + with pytest.raises(DataError, match=msg): + getattr(rolled, method)() + else: + result = getattr(rolled, method)() + expected = DataFrame(expected_data, dtype="float64")[::step] + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/6b/6b75f15b545c3403f0115688da0d758699c9bd21f119416c1a60c059f0e72cff/__init__.py b/shared/package-files/6b/6b75f15b545c3403f0115688da0d758699c9bd21f119416c1a60c059f0e72cff/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10a55772ab58b21573a6eba0356ddd3080164ac7 --- /dev/null +++ b/shared/package-files/6b/6b75f15b545c3403f0115688da0d758699c9bd21f119416c1a60c059f0e72cff/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. diff --git a/shared/package-files/6b/6b7a9e6082077b5ea379c0dcefe21455a21c57f69e51e9f16d1efe25176d0663/py3_test_grammar.py b/shared/package-files/6b/6b7a9e6082077b5ea379c0dcefe21455a21c57f69e51e9f16d1efe25176d0663/py3_test_grammar.py new file mode 100644 index 0000000000000000000000000000000000000000..a4a3f7eac0dded281bc70018d603e3cea6c42b99 --- /dev/null +++ b/shared/package-files/6b/6b7a9e6082077b5ea379c0dcefe21455a21c57f69e51e9f16d1efe25176d0663/py3_test_grammar.py @@ -0,0 +1,956 @@ +# Python test set -- part 1, grammar. +# This just tests whether the parser accepts them all. + +# NOTE: When you run this test as a script from the command line, you +# get warnings about certain hex/oct constants. Since those are +# issued by the parser, you can't suppress them by adding a +# filterwarnings() call to this module. Therefore, to shut up the +# regression test, the filterwarnings() call has been added to +# regrtest.py. + +from test.support import check_syntax_error +import unittest +import sys +# testing import * +from sys import * + +class TokenTests(unittest.TestCase): + + def testBackslash(self): + # Backslash means line continuation: + x = 1 \ + + 1 + self.assertEquals(x, 2, 'backslash for line continuation') + + # Backslash does not means continuation in comments :\ + x = 0 + self.assertEquals(x, 0, 'backslash ending comment') + + def testPlainIntegers(self): + self.assertEquals(type(000), type(0)) + self.assertEquals(0xff, 255) + self.assertEquals(0o377, 255) + self.assertEquals(2147483647, 0o17777777777) + self.assertEquals(0b1001, 9) + # "0x" is not a valid literal + self.assertRaises(SyntaxError, eval, "0x") + from sys import maxsize + if maxsize == 2147483647: + self.assertEquals(-2147483647-1, -0o20000000000) + # XXX -2147483648 + self.assert_(0o37777777777 > 0) + self.assert_(0xffffffff > 0) + self.assert_(0b1111111111111111111111111111111 > 0) + for s in ('2147483648', '0o40000000000', '0x100000000', + '0b10000000000000000000000000000000'): + try: + x = eval(s) + except OverflowError: + self.fail("OverflowError on huge integer literal %r" % s) + elif maxsize == 9223372036854775807: + self.assertEquals(-9223372036854775807-1, -0o1000000000000000000000) + self.assert_(0o1777777777777777777777 > 0) + self.assert_(0xffffffffffffffff > 0) + self.assert_(0b11111111111111111111111111111111111111111111111111111111111111 > 0) + for s in '9223372036854775808', '0o2000000000000000000000', \ + '0x10000000000000000', \ + '0b100000000000000000000000000000000000000000000000000000000000000': + try: + x = eval(s) + except OverflowError: + self.fail("OverflowError on huge integer literal %r" % s) + else: + self.fail('Weird maxsize value %r' % maxsize) + + def testLongIntegers(self): + x = 0 + x = 0xffffffffffffffff + x = 0Xffffffffffffffff + x = 0o77777777777777777 + x = 0O77777777777777777 + x = 123456789012345678901234567890 + x = 0b100000000000000000000000000000000000000000000000000000000000000000000 + x = 0B111111111111111111111111111111111111111111111111111111111111111111111 + + def testUnderscoresInNumbers(self): + # Integers + x = 1_0 + x = 123_456_7_89 + x = 0xabc_123_4_5 + x = 0X_abc_123 + x = 0B11_01 + x = 0b_11_01 + x = 0o45_67 + x = 0O_45_67 + + # Floats + x = 3_1.4 + x = 03_1.4 + x = 3_1. + x = .3_1 + x = 3.1_4 + x = 0_3.1_4 + x = 3e1_4 + x = 3_1e+4_1 + x = 3_1E-4_1 + + def testFloats(self): + x = 3.14 + x = 314. + x = 0.314 + # XXX x = 000.314 + x = .314 + x = 3e14 + x = 3E14 + x = 3e-14 + x = 3e+14 + x = 3.e14 + x = .3e14 + x = 3.1e4 + + def testStringLiterals(self): + x = ''; y = ""; self.assert_(len(x) == 0 and x == y) + x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39) + x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34) + x = "doesn't \"shrink\" does it" + y = 'doesn\'t "shrink" does it' + self.assert_(len(x) == 24 and x == y) + x = "does \"shrink\" doesn't it" + y = 'does "shrink" doesn\'t it' + self.assert_(len(x) == 24 and x == y) + x = """ +The "quick" +brown fox +jumps over +the 'lazy' dog. +""" + y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' + self.assertEquals(x, y) + y = ''' +The "quick" +brown fox +jumps over +the 'lazy' dog. +''' + self.assertEquals(x, y) + y = "\n\ +The \"quick\"\n\ +brown fox\n\ +jumps over\n\ +the 'lazy' dog.\n\ +" + self.assertEquals(x, y) + y = '\n\ +The \"quick\"\n\ +brown fox\n\ +jumps over\n\ +the \'lazy\' dog.\n\ +' + self.assertEquals(x, y) + x = rf"hello \{True}"; y = f"hello \\{True}" + self.assertEquals(x, y) + + def testEllipsis(self): + x = ... + self.assert_(x is Ellipsis) + self.assertRaises(SyntaxError, eval, ".. .") + +class GrammarTests(unittest.TestCase): + + # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE + # XXX can't test in a script -- this rule is only used when interactive + + # file_input: (NEWLINE | stmt)* ENDMARKER + # Being tested as this very moment this very module + + # expr_input: testlist NEWLINE + # XXX Hard to test -- used only in calls to input() + + def testEvalInput(self): + # testlist ENDMARKER + x = eval('1, 0 or 1') + + def testFuncdef(self): + ### [decorators] 'def' NAME parameters ['->' test] ':' suite + ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE + ### decorators: decorator+ + ### parameters: '(' [typedargslist] ')' + ### typedargslist: ((tfpdef ['=' test] ',')* + ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef) + ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [',']) + ### tfpdef: NAME [':' test] + ### varargslist: ((vfpdef ['=' test] ',')* + ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef) + ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [',']) + ### vfpdef: NAME + def f1(): pass + f1() + f1(*()) + f1(*(), **{}) + def f2(one_argument): pass + def f3(two, arguments): pass + self.assertEquals(f2.__code__.co_varnames, ('one_argument',)) + self.assertEquals(f3.__code__.co_varnames, ('two', 'arguments')) + def a1(one_arg,): pass + def a2(two, args,): pass + def v0(*rest): pass + def v1(a, *rest): pass + def v2(a, b, *rest): pass + + f1() + f2(1) + f2(1,) + f3(1, 2) + f3(1, 2,) + v0() + v0(1) + v0(1,) + v0(1,2) + v0(1,2,3,4,5,6,7,8,9,0) + v1(1) + v1(1,) + v1(1,2) + v1(1,2,3) + v1(1,2,3,4,5,6,7,8,9,0) + v2(1,2) + v2(1,2,3) + v2(1,2,3,4) + v2(1,2,3,4,5,6,7,8,9,0) + + def d01(a=1): pass + d01() + d01(1) + d01(*(1,)) + d01(**{'a':2}) + def d11(a, b=1): pass + d11(1) + d11(1, 2) + d11(1, **{'b':2}) + def d21(a, b, c=1): pass + d21(1, 2) + d21(1, 2, 3) + d21(*(1, 2, 3)) + d21(1, *(2, 3)) + d21(1, 2, *(3,)) + d21(1, 2, **{'c':3}) + def d02(a=1, b=2): pass + d02() + d02(1) + d02(1, 2) + d02(*(1, 2)) + d02(1, *(2,)) + d02(1, **{'b':2}) + d02(**{'a': 1, 'b': 2}) + def d12(a, b=1, c=2): pass + d12(1) + d12(1, 2) + d12(1, 2, 3) + def d22(a, b, c=1, d=2): pass + d22(1, 2) + d22(1, 2, 3) + d22(1, 2, 3, 4) + def d01v(a=1, *rest): pass + d01v() + d01v(1) + d01v(1, 2) + d01v(*(1, 2, 3, 4)) + d01v(*(1,)) + d01v(**{'a':2}) + def d11v(a, b=1, *rest): pass + d11v(1) + d11v(1, 2) + d11v(1, 2, 3) + def d21v(a, b, c=1, *rest): pass + d21v(1, 2) + d21v(1, 2, 3) + d21v(1, 2, 3, 4) + d21v(*(1, 2, 3, 4)) + d21v(1, 2, **{'c': 3}) + def d02v(a=1, b=2, *rest): pass + d02v() + d02v(1) + d02v(1, 2) + d02v(1, 2, 3) + d02v(1, *(2, 3, 4)) + d02v(**{'a': 1, 'b': 2}) + def d12v(a, b=1, c=2, *rest): pass + d12v(1) + d12v(1, 2) + d12v(1, 2, 3) + d12v(1, 2, 3, 4) + d12v(*(1, 2, 3, 4)) + d12v(1, 2, *(3, 4, 5)) + d12v(1, *(2,), **{'c': 3}) + def d22v(a, b, c=1, d=2, *rest): pass + d22v(1, 2) + d22v(1, 2, 3) + d22v(1, 2, 3, 4) + d22v(1, 2, 3, 4, 5) + d22v(*(1, 2, 3, 4)) + d22v(1, 2, *(3, 4, 5)) + d22v(1, *(2, 3), **{'d': 4}) + + # keyword argument type tests + try: + str('x', **{b'foo':1 }) + except TypeError: + pass + else: + self.fail('Bytes should not work as keyword argument names') + # keyword only argument tests + def pos0key1(*, key): return key + pos0key1(key=100) + def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2 + pos2key2(1, 2, k1=100) + pos2key2(1, 2, k1=100, k2=200) + pos2key2(1, 2, k2=100, k1=200) + def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg + pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200) + pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100) + + # keyword arguments after *arglist + def f(*args, **kwargs): + return args, kwargs + self.assertEquals(f(1, x=2, *[3, 4], y=5), ((1, 3, 4), + {'x':2, 'y':5})) + self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)") + self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)") + + # argument annotation tests + def f(x) -> list: pass + self.assertEquals(f.__annotations__, {'return': list}) + def f(x:int): pass + self.assertEquals(f.__annotations__, {'x': int}) + def f(*x:str): pass + self.assertEquals(f.__annotations__, {'x': str}) + def f(**x:float): pass + self.assertEquals(f.__annotations__, {'x': float}) + def f(x, y:1+2): pass + self.assertEquals(f.__annotations__, {'y': 3}) + def f(a, b:1, c:2, d): pass + self.assertEquals(f.__annotations__, {'b': 1, 'c': 2}) + def f(a, b:1, c:2, d, e:3=4, f=5, *g:6): pass + self.assertEquals(f.__annotations__, + {'b': 1, 'c': 2, 'e': 3, 'g': 6}) + def f(a, b:1, c:2, d, e:3=4, f=5, *g:6, h:7, i=8, j:9=10, + **k:11) -> 12: pass + self.assertEquals(f.__annotations__, + {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9, + 'k': 11, 'return': 12}) + # Check for SF Bug #1697248 - mixing decorators and a return annotation + def null(x): return x + @null + def f(x) -> list: pass + self.assertEquals(f.__annotations__, {'return': list}) + + # test closures with a variety of oparg's + closure = 1 + def f(): return closure + def f(x=1): return closure + def f(*, k=1): return closure + def f() -> int: return closure + + # Check ast errors in *args and *kwargs + check_syntax_error(self, "f(*g(1=2))") + check_syntax_error(self, "f(**g(1=2))") + + def testLambdef(self): + ### lambdef: 'lambda' [varargslist] ':' test + l1 = lambda : 0 + self.assertEquals(l1(), 0) + l2 = lambda : a[d] # XXX just testing the expression + l3 = lambda : [2 < x for x in [-1, 3, 0]] + self.assertEquals(l3(), [0, 1, 0]) + l4 = lambda x = lambda y = lambda z=1 : z : y() : x() + self.assertEquals(l4(), 1) + l5 = lambda x, y, z=2: x + y + z + self.assertEquals(l5(1, 2), 5) + self.assertEquals(l5(1, 2, 3), 6) + check_syntax_error(self, "lambda x: x = 2") + check_syntax_error(self, "lambda (None,): None") + l6 = lambda x, y, *, k=20: x+y+k + self.assertEquals(l6(1,2), 1+2+20) + self.assertEquals(l6(1,2,k=10), 1+2+10) + + + ### stmt: simple_stmt | compound_stmt + # Tested below + + def testSimpleStmt(self): + ### simple_stmt: small_stmt (';' small_stmt)* [';'] + x = 1; pass; del x + def foo(): + # verify statements that end with semi-colons + x = 1; pass; del x; + foo() + + ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt + # Tested below + + def testExprStmt(self): + # (exprlist '=')* exprlist + 1 + 1, 2, 3 + x = 1 + x = 1, 2, 3 + x = y = z = 1, 2, 3 + x, y, z = 1, 2, 3 + abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4) + + check_syntax_error(self, "x + 1 = 1") + check_syntax_error(self, "a + 1 = b + 2") + + def testDelStmt(self): + # 'del' exprlist + abc = [1,2,3] + x, y, z = abc + xyz = x, y, z + + del abc + del x, y, (z, xyz) + + def testPassStmt(self): + # 'pass' + pass + + # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt + # Tested below + + def testBreakStmt(self): + # 'break' + while 1: break + + def testContinueStmt(self): + # 'continue' + i = 1 + while i: i = 0; continue + + msg = "" + while not msg: + msg = "ok" + try: + continue + msg = "continue failed to continue inside try" + except: + msg = "continue inside try called except block" + if msg != "ok": + self.fail(msg) + + msg = "" + while not msg: + msg = "finally block not called" + try: + continue + finally: + msg = "ok" + if msg != "ok": + self.fail(msg) + + def test_break_continue_loop(self): + # This test warrants an explanation. It is a test specifically for SF bugs + # #463359 and #462937. The bug is that a 'break' statement executed or + # exception raised inside a try/except inside a loop, *after* a continue + # statement has been executed in that loop, will cause the wrong number of + # arguments to be popped off the stack and the instruction pointer reset to + # a very small number (usually 0.) Because of this, the following test + # *must* written as a function, and the tracking vars *must* be function + # arguments with default values. Otherwise, the test will loop and loop. + + def test_inner(extra_burning_oil = 1, count=0): + big_hippo = 2 + while big_hippo: + count += 1 + try: + if extra_burning_oil and big_hippo == 1: + extra_burning_oil -= 1 + break + big_hippo -= 1 + continue + except: + raise + if count > 2 or big_hippo != 1: + self.fail("continue then break in try/except in loop broken!") + test_inner() + + def testReturn(self): + # 'return' [testlist_star_expr] + def g1(): return + def g2(): return 1 + return_list = [2, 3] + def g3(): return 1, *return_list + g1() + x = g2() + x3 = g3() + check_syntax_error(self, "class foo:return 1") + + def testYield(self): + # 'yield' [yield_arg] + def g1(): yield 1 + yield_list = [2, 3] + def g2(): yield 1, *yield_list + def g3(): yield from iter(yield_list) + x1 = g1() + x2 = g2() + x3 = g3() + check_syntax_error(self, "class foo:yield 1") + check_syntax_error(self, "def g4(): yield from *a") + + def testRaise(self): + # 'raise' test [',' test] + try: raise RuntimeError('just testing') + except RuntimeError: pass + try: raise KeyboardInterrupt + except KeyboardInterrupt: pass + + def testImport(self): + # 'import' dotted_as_names + import sys + import time, sys + # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names) + from time import time + from time import (time) + # not testable inside a function, but already done at top of the module + # from sys import * + from sys import path, argv + from sys import (path, argv) + from sys import (path, argv,) + + def testGlobal(self): + # 'global' NAME (',' NAME)* + global a + global a, b + global one, two, three, four, five, six, seven, eight, nine, ten + + def testNonlocal(self): + # 'nonlocal' NAME (',' NAME)* + x = 0 + y = 0 + def f(): + nonlocal x + nonlocal x, y + + def testAssert(self): + # assert_stmt: 'assert' test [',' test] + assert 1 + assert 1, 1 + assert lambda x:x + assert 1, lambda x:x+1 + try: + assert 0, "msg" + except AssertionError as e: + self.assertEquals(e.args[0], "msg") + else: + if __debug__: + self.fail("AssertionError not raised by assert 0") + + ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef + # Tested below + + def testIf(self): + # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] + if 1: pass + if 1: pass + else: pass + if 0: pass + elif 0: pass + if 0: pass + elif 0: pass + elif 0: pass + elif 0: pass + else: pass + + def testWhile(self): + # 'while' test ':' suite ['else' ':' suite] + while 0: pass + while 0: pass + else: pass + + # Issue1920: "while 0" is optimized away, + # ensure that the "else" clause is still present. + x = 0 + while 0: + x = 1 + else: + x = 2 + self.assertEquals(x, 2) + + def testFor(self): + # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] + for i in 1, 2, 3: pass + for i, j, k in (): pass + else: pass + class Squares: + def __init__(self, max): + self.max = max + self.sofar = [] + def __len__(self): return len(self.sofar) + def __getitem__(self, i): + if not 0 <= i < self.max: raise IndexError + n = len(self.sofar) + while n <= i: + self.sofar.append(n*n) + n = n+1 + return self.sofar[i] + n = 0 + for x in Squares(10): n = n+x + if n != 285: + self.fail('for over growing sequence') + + result = [] + for x, in [(1,), (2,), (3,)]: + result.append(x) + self.assertEqual(result, [1, 2, 3]) + + def testTry(self): + ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] + ### | 'try' ':' suite 'finally' ':' suite + ### except_clause: 'except' [expr ['as' expr]] + try: + 1/0 + except ZeroDivisionError: + pass + else: + pass + try: 1/0 + except EOFError: pass + except TypeError as msg: pass + except RuntimeError as msg: pass + except: pass + else: pass + try: 1/0 + except (EOFError, TypeError, ZeroDivisionError): pass + try: 1/0 + except (EOFError, TypeError, ZeroDivisionError) as msg: pass + try: pass + finally: pass + + def testSuite(self): + # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT + if 1: pass + if 1: + pass + if 1: + # + # + # + pass + pass + # + pass + # + + def testTest(self): + ### and_test ('or' and_test)* + ### and_test: not_test ('and' not_test)* + ### not_test: 'not' not_test | comparison + if not 1: pass + if 1 and 1: pass + if 1 or 1: pass + if not not not 1: pass + if not 1 and 1 and 1: pass + if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass + + def testComparison(self): + ### comparison: expr (comp_op expr)* + ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not' + if 1: pass + x = (1 == 1) + if 1 == 1: pass + if 1 != 1: pass + if 1 < 1: pass + if 1 > 1: pass + if 1 <= 1: pass + if 1 >= 1: pass + if 1 is 1: pass + if 1 is not 1: pass + if 1 in (): pass + if 1 not in (): pass + if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass + + def testBinaryMaskOps(self): + x = 1 & 1 + x = 1 ^ 1 + x = 1 | 1 + + def testShiftOps(self): + x = 1 << 1 + x = 1 >> 1 + x = 1 << 1 >> 1 + + def testAdditiveOps(self): + x = 1 + x = 1 + 1 + x = 1 - 1 - 1 + x = 1 - 1 + 1 - 1 + 1 + + def testMultiplicativeOps(self): + x = 1 * 1 + x = 1 / 1 + x = 1 % 1 + x = 1 / 1 * 1 % 1 + + def testUnaryOps(self): + x = +1 + x = -1 + x = ~1 + x = ~1 ^ 1 & 1 | 1 & 1 ^ -1 + x = -1*1/1 + 1*1 - ---1*1 + + def testSelectors(self): + ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME + ### subscript: expr | [expr] ':' [expr] + + import sys, time + c = sys.path[0] + x = time.time() + x = sys.modules['time'].time() + a = '01234' + c = a[0] + c = a[-1] + s = a[0:5] + s = a[:5] + s = a[0:] + s = a[:] + s = a[-5:] + s = a[:-1] + s = a[-4:-3] + # A rough test of SF bug 1333982. https://python.org/sf/1333982 + # The testing here is fairly incomplete. + # Test cases should include: commas with 1 and 2 colons + d = {} + d[1] = 1 + d[1,] = 2 + d[1,2] = 3 + d[1,2,3] = 4 + L = list(d) + L.sort(key=lambda x: x if isinstance(x, tuple) else ()) + self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]') + + def testAtoms(self): + ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING + ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [',']) + + x = (1) + x = (1 or 2 or 3) + x = (1 or 2 or 3, 2, 3) + + x = [] + x = [1] + x = [1 or 2 or 3] + x = [1 or 2 or 3, 2, 3] + x = [] + + x = {} + x = {'one': 1} + x = {'one': 1,} + x = {'one' or 'two': 1 or 2} + x = {'one': 1, 'two': 2} + x = {'one': 1, 'two': 2,} + x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} + + x = {'one'} + x = {'one', 1,} + x = {'one', 'two', 'three'} + x = {2, 3, 4,} + + x = x + x = 'x' + x = 123 + + ### exprlist: expr (',' expr)* [','] + ### testlist: test (',' test)* [','] + # These have been exercised enough above + + def testClassdef(self): + # 'class' NAME ['(' [testlist] ')'] ':' suite + class B: pass + class B2(): pass + class C1(B): pass + class C2(B): pass + class D(C1, C2, B): pass + class C: + def meth1(self): pass + def meth2(self, arg): pass + def meth3(self, a1, a2): pass + + # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE + # decorators: decorator+ + # decorated: decorators (classdef | funcdef) + def class_decorator(x): return x + @class_decorator + class G: pass + + def testDictcomps(self): + # dictorsetmaker: ( (test ':' test (comp_for | + # (',' test ':' test)* [','])) | + # (test (comp_for | (',' test)* [','])) ) + nums = [1, 2, 3] + self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4}) + + def testListcomps(self): + # list comprehension tests + nums = [1, 2, 3, 4, 5] + strs = ["Apple", "Banana", "Coconut"] + spcs = [" Apple", " Banana ", "Coco nut "] + + self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut']) + self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15]) + self.assertEqual([x for x in nums if x > 2], [3, 4, 5]) + self.assertEqual([(i, s) for i in nums for s in strs], + [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'), + (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'), + (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'), + (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'), + (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')]) + self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]], + [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'), + (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'), + (5, 'Banana'), (5, 'Coconut')]) + self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)], + [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]]) + + def test_in_func(l): + return [0 < x < 3 for x in l if x > 2] + + self.assertEqual(test_in_func(nums), [False, False, False]) + + def test_nested_front(): + self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]], + [[1, 2], [3, 4], [5, 6]]) + + test_nested_front() + + check_syntax_error(self, "[i, s for i in nums for s in strs]") + check_syntax_error(self, "[x if y]") + + suppliers = [ + (1, "Boeing"), + (2, "Ford"), + (3, "Macdonalds") + ] + + parts = [ + (10, "Airliner"), + (20, "Engine"), + (30, "Cheeseburger") + ] + + suppart = [ + (1, 10), (1, 20), (2, 20), (3, 30) + ] + + x = [ + (sname, pname) + for (sno, sname) in suppliers + for (pno, pname) in parts + for (sp_sno, sp_pno) in suppart + if sno == sp_sno and pno == sp_pno + ] + + self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'), + ('Macdonalds', 'Cheeseburger')]) + + def testGenexps(self): + # generator expression tests + g = ([x for x in range(10)] for x in range(1)) + self.assertEqual(next(g), [x for x in range(10)]) + try: + next(g) + self.fail('should produce StopIteration exception') + except StopIteration: + pass + + a = 1 + try: + g = (a for d in a) + next(g) + self.fail('should produce TypeError') + except TypeError: + pass + + self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd']) + self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy']) + + a = [x for x in range(10)] + b = (x for x in (y for y in a)) + self.assertEqual(sum(b), sum([x for x in range(10)])) + + self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)])) + self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2])) + self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)])) + self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)])) + self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)])) + self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True)) if True), sum([x for x in range(10)])) + self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0) + check_syntax_error(self, "foo(x for x in range(10), 100)") + check_syntax_error(self, "foo(100, x for x in range(10))") + + def testComprehensionSpecials(self): + # test for outmost iterable precomputation + x = 10; g = (i for i in range(x)); x = 5 + self.assertEqual(len(list(g)), 10) + + # This should hold, since we're only precomputing outmost iterable. + x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x)) + x = 5; t = True; + self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g)) + + # Grammar allows multiple adjacent 'if's in listcomps and genexps, + # even though it's silly. Make sure it works (ifelse broke this.) + self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7]) + self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7]) + + # verify unpacking single element tuples in listcomp/genexp. + self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6]) + self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9]) + + def test_with_statement(self): + class manager(object): + def __enter__(self): + return (1, 2) + def __exit__(self, *args): + pass + + with manager(): + pass + with manager() as x: + pass + with manager() as (x, y): + pass + with manager(), manager(): + pass + with manager() as x, manager() as y: + pass + with manager() as x, manager(): + pass + + def testIfElseExpr(self): + # Test ifelse expressions in various cases + def _checkeval(msg, ret): + "helper to check that evaluation of expressions is done correctly" + print(x) + return ret + + # the next line is not allowed anymore + #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True]) + self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True]) + self.assertEqual([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ], [True]) + self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5) + self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5) + self.assertEqual((5 and 6 if 0 else 1), 1) + self.assertEqual(((5 and 6) if 0 else 1), 1) + self.assertEqual((5 and (6 if 1 else 1)), 6) + self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3) + self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1) + self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5) + self.assertEqual((not 5 if 1 else 1), False) + self.assertEqual((not 5 if 0 else 1), 1) + self.assertEqual((6 + 1 if 1 else 2), 7) + self.assertEqual((6 - 1 if 1 else 2), 5) + self.assertEqual((6 * 2 if 1 else 4), 12) + self.assertEqual((6 / 2 if 1 else 3), 3) + self.assertEqual((6 < 4 if 0 else 2), 2) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/6b/6b7c36fa64e4eaa99e98eb6fe282e59f6b71b4845ad2f33ddbcb4b4a674fc924/hypot_meta_dispatch.h b/shared/package-files/6b/6b7c36fa64e4eaa99e98eb6fe282e59f6b71b4845ad2f33ddbcb4b4a674fc924/hypot_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..36fe940f953a313521b36625dc28c3f5eaef62ca --- /dev/null +++ b/shared/package-files/6b/6b7c36fa64e4eaa99e98eb6fe282e59f6b71b4845ad2f33ddbcb4b4a674fc924/hypot_meta_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor hypot(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & hypot_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & hypot_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor & hypot_(at::Tensor & self, const at::Tensor & other); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/6b/6b7d6e0ae966b767ae06bc149205fbfd54f6a2b19ec83a2f3529ec247c6ce1b4/glu_backward_native.h b/shared/package-files/6b/6b7d6e0ae966b767ae06bc149205fbfd54f6a2b19ec83a2f3529ec247c6ce1b4/glu_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..ea620c6449484f5a7e4697f2e4837579a8011434 --- /dev/null +++ b/shared/package-files/6b/6b7d6e0ae966b767ae06bc149205fbfd54f6a2b19ec83a2f3529ec247c6ce1b4/glu_backward_native.h @@ -0,0 +1,24 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor glu_backward_cpu(const at::Tensor & grad_output, const at::Tensor & self, int64_t dim); +TORCH_API at::Tensor & glu_backward_cpu_out(const at::Tensor & grad_output, const at::Tensor & self, int64_t dim, at::Tensor & grad_input); +TORCH_API at::Tensor glu_backward_cuda(const at::Tensor & grad_output, const at::Tensor & self, int64_t dim); +TORCH_API at::Tensor & glu_backward_cuda_out(const at::Tensor & grad_output, const at::Tensor & self, int64_t dim, at::Tensor & grad_input); +} // namespace native +} // namespace at diff --git a/shared/package-files/6b/6b83c8026f243e49fcbf5bdfc74d1b7e841f929e79d62972084278b4c2e95861/ttProgram.py b/shared/package-files/6b/6b83c8026f243e49fcbf5bdfc74d1b7e841f929e79d62972084278b4c2e95861/ttProgram.py new file mode 100644 index 0000000000000000000000000000000000000000..4b3f9dfe0538cd12875fd3a5f209efe5cc31b64f --- /dev/null +++ b/shared/package-files/6b/6b83c8026f243e49fcbf5bdfc74d1b7e841f929e79d62972084278b4c2e95861/ttProgram.py @@ -0,0 +1,595 @@ +"""ttLib.tables.ttProgram.py -- Assembler/disassembler for TrueType bytecode programs.""" + +from __future__ import annotations + +from fontTools.misc.textTools import num2binary, binary2num, readHex, strjoin +import array +from io import StringIO +from typing import List +import re +import logging + +log = logging.getLogger(__name__) + +# fmt: off + +# first, the list of instructions that eat bytes or words from the instruction stream + +streamInstructions = [ +# +# opcode mnemonic argBits descriptive name pops pushes eats from instruction stream pushes +# + (0x40, 'NPUSHB', 0, 'PushNBytes', 0, -1), # n, b1, b2,...bn b1,b2...bn + (0x41, 'NPUSHW', 0, 'PushNWords', 0, -1), # n, w1, w2,...w w1,w2...wn + (0xb0, 'PUSHB', 3, 'PushBytes', 0, -1), # b0, b1,..bn b0, b1, ...,bn + (0xb8, 'PUSHW', 3, 'PushWords', 0, -1), # w0,w1,..wn w0 ,w1, ...wn +] + + +# next, the list of "normal" instructions + +instructions = [ +# +# opcode mnemonic argBits descriptive name pops pushes eats from instruction stream pushes +# + (0x7f, 'AA', 0, 'AdjustAngle', 1, 0), # p - + (0x64, 'ABS', 0, 'Absolute', 1, 1), # n |n| + (0x60, 'ADD', 0, 'Add', 2, 1), # n2, n1 (n1 + n2) + (0x27, 'ALIGNPTS', 0, 'AlignPts', 2, 0), # p2, p1 - + (0x3c, 'ALIGNRP', 0, 'AlignRelativePt', -1, 0), # p1, p2, ... , ploopvalue - + (0x5a, 'AND', 0, 'LogicalAnd', 2, 1), # e2, e1 b + (0x2b, 'CALL', 0, 'CallFunction', 1, 0), # f - + (0x67, 'CEILING', 0, 'Ceiling', 1, 1), # n ceil(n) + (0x25, 'CINDEX', 0, 'CopyXToTopStack', 1, 1), # k ek + (0x22, 'CLEAR', 0, 'ClearStack', -1, 0), # all items on the stack - + (0x4f, 'DEBUG', 0, 'DebugCall', 1, 0), # n - + (0x73, 'DELTAC1', 0, 'DeltaExceptionC1', -1, 0), # argn, cn, argn-1,cn-1, , arg1, c1 - + (0x74, 'DELTAC2', 0, 'DeltaExceptionC2', -1, 0), # argn, cn, argn-1,cn-1, , arg1, c1 - + (0x75, 'DELTAC3', 0, 'DeltaExceptionC3', -1, 0), # argn, cn, argn-1,cn-1, , arg1, c1 - + (0x5d, 'DELTAP1', 0, 'DeltaExceptionP1', -1, 0), # argn, pn, argn-1, pn-1, , arg1, p1 - + (0x71, 'DELTAP2', 0, 'DeltaExceptionP2', -1, 0), # argn, pn, argn-1, pn-1, , arg1, p1 - + (0x72, 'DELTAP3', 0, 'DeltaExceptionP3', -1, 0), # argn, pn, argn-1, pn-1, , arg1, p1 - + (0x24, 'DEPTH', 0, 'GetDepthStack', 0, 1), # - n + (0x62, 'DIV', 0, 'Divide', 2, 1), # n2, n1 (n1 * 64)/ n2 + (0x20, 'DUP', 0, 'DuplicateTopStack', 1, 2), # e e, e + (0x59, 'EIF', 0, 'EndIf', 0, 0), # - - + (0x1b, 'ELSE', 0, 'Else', 0, 0), # - - + (0x2d, 'ENDF', 0, 'EndFunctionDefinition', 0, 0), # - - + (0x54, 'EQ', 0, 'Equal', 2, 1), # e2, e1 b + (0x57, 'EVEN', 0, 'Even', 1, 1), # e b + (0x2c, 'FDEF', 0, 'FunctionDefinition', 1, 0), # f - + (0x4e, 'FLIPOFF', 0, 'SetAutoFlipOff', 0, 0), # - - + (0x4d, 'FLIPON', 0, 'SetAutoFlipOn', 0, 0), # - - + (0x80, 'FLIPPT', 0, 'FlipPoint', -1, 0), # p1, p2, ..., ploopvalue - + (0x82, 'FLIPRGOFF', 0, 'FlipRangeOff', 2, 0), # h, l - + (0x81, 'FLIPRGON', 0, 'FlipRangeOn', 2, 0), # h, l - + (0x66, 'FLOOR', 0, 'Floor', 1, 1), # n floor(n) + (0x46, 'GC', 1, 'GetCoordOnPVector', 1, 1), # p c + (0x88, 'GETINFO', 0, 'GetInfo', 1, 1), # selector result + (0x91, 'GETVARIATION', 0, 'GetVariation', 0, -1), # - a1,..,an + (0x0d, 'GFV', 0, 'GetFVector', 0, 2), # - px, py + (0x0c, 'GPV', 0, 'GetPVector', 0, 2), # - px, py + (0x52, 'GT', 0, 'GreaterThan', 2, 1), # e2, e1 b + (0x53, 'GTEQ', 0, 'GreaterThanOrEqual', 2, 1), # e2, e1 b + (0x89, 'IDEF', 0, 'InstructionDefinition', 1, 0), # f - + (0x58, 'IF', 0, 'If', 1, 0), # e - + (0x8e, 'INSTCTRL', 0, 'SetInstrExecControl', 2, 0), # s, v - + (0x39, 'IP', 0, 'InterpolatePts', -1, 0), # p1, p2, ... , ploopvalue - + (0x0f, 'ISECT', 0, 'MovePtToIntersect', 5, 0), # a1, a0, b1, b0, p - + (0x30, 'IUP', 1, 'InterpolateUntPts', 0, 0), # - - + (0x1c, 'JMPR', 0, 'Jump', 1, 0), # offset - + (0x79, 'JROF', 0, 'JumpRelativeOnFalse', 2, 0), # e, offset - + (0x78, 'JROT', 0, 'JumpRelativeOnTrue', 2, 0), # e, offset - + (0x2a, 'LOOPCALL', 0, 'LoopAndCallFunction', 2, 0), # f, count - + (0x50, 'LT', 0, 'LessThan', 2, 1), # e2, e1 b + (0x51, 'LTEQ', 0, 'LessThenOrEqual', 2, 1), # e2, e1 b + (0x8b, 'MAX', 0, 'Maximum', 2, 1), # e2, e1 max(e1, e2) + (0x49, 'MD', 1, 'MeasureDistance', 2, 1), # p2,p1 d + (0x2e, 'MDAP', 1, 'MoveDirectAbsPt', 1, 0), # p - + (0xc0, 'MDRP', 5, 'MoveDirectRelPt', 1, 0), # p - + (0x3e, 'MIAP', 1, 'MoveIndirectAbsPt', 2, 0), # n, p - + (0x8c, 'MIN', 0, 'Minimum', 2, 1), # e2, e1 min(e1, e2) + (0x26, 'MINDEX', 0, 'MoveXToTopStack', 1, 1), # k ek + (0xe0, 'MIRP', 5, 'MoveIndirectRelPt', 2, 0), # n, p - + (0x4b, 'MPPEM', 0, 'MeasurePixelPerEm', 0, 1), # - ppem + (0x4c, 'MPS', 0, 'MeasurePointSize', 0, 1), # - pointSize + (0x3a, 'MSIRP', 1, 'MoveStackIndirRelPt', 2, 0), # d, p - + (0x63, 'MUL', 0, 'Multiply', 2, 1), # n2, n1 (n1 * n2)/64 + (0x65, 'NEG', 0, 'Negate', 1, 1), # n -n + (0x55, 'NEQ', 0, 'NotEqual', 2, 1), # e2, e1 b + (0x5c, 'NOT', 0, 'LogicalNot', 1, 1), # e ( not e ) + (0x6c, 'NROUND', 2, 'NoRound', 1, 1), # n1 n2 + (0x56, 'ODD', 0, 'Odd', 1, 1), # e b + (0x5b, 'OR', 0, 'LogicalOr', 2, 1), # e2, e1 b + (0x21, 'POP', 0, 'PopTopStack', 1, 0), # e - + (0x45, 'RCVT', 0, 'ReadCVT', 1, 1), # location value + (0x7d, 'RDTG', 0, 'RoundDownToGrid', 0, 0), # - - + (0x7a, 'ROFF', 0, 'RoundOff', 0, 0), # - - + (0x8a, 'ROLL', 0, 'RollTopThreeStack', 3, 3), # a,b,c b,a,c + (0x68, 'ROUND', 2, 'Round', 1, 1), # n1 n2 + (0x43, 'RS', 0, 'ReadStore', 1, 1), # n v + (0x3d, 'RTDG', 0, 'RoundToDoubleGrid', 0, 0), # - - + (0x18, 'RTG', 0, 'RoundToGrid', 0, 0), # - - + (0x19, 'RTHG', 0, 'RoundToHalfGrid', 0, 0), # - - + (0x7c, 'RUTG', 0, 'RoundUpToGrid', 0, 0), # - - + (0x77, 'S45ROUND', 0, 'SuperRound45Degrees', 1, 0), # n - + (0x7e, 'SANGW', 0, 'SetAngleWeight', 1, 0), # weight - + (0x85, 'SCANCTRL', 0, 'ScanConversionControl', 1, 0), # n - + (0x8d, 'SCANTYPE', 0, 'ScanType', 1, 0), # n - + (0x48, 'SCFS', 0, 'SetCoordFromStackFP', 2, 0), # c, p - + (0x1d, 'SCVTCI', 0, 'SetCVTCutIn', 1, 0), # n - + (0x5e, 'SDB', 0, 'SetDeltaBaseInGState', 1, 0), # n - + (0x86, 'SDPVTL', 1, 'SetDualPVectorToLine', 2, 0), # p2, p1 - + (0x5f, 'SDS', 0, 'SetDeltaShiftInGState', 1, 0), # n - + (0x0b, 'SFVFS', 0, 'SetFVectorFromStack', 2, 0), # y, x - + (0x04, 'SFVTCA', 1, 'SetFVectorToAxis', 0, 0), # - - + (0x08, 'SFVTL', 1, 'SetFVectorToLine', 2, 0), # p2, p1 - + (0x0e, 'SFVTPV', 0, 'SetFVectorToPVector', 0, 0), # - - + (0x34, 'SHC', 1, 'ShiftContourByLastPt', 1, 0), # c - + (0x32, 'SHP', 1, 'ShiftPointByLastPoint', -1, 0), # p1, p2, ..., ploopvalue - + (0x38, 'SHPIX', 0, 'ShiftZoneByPixel', -1, 0), # d, p1, p2, ..., ploopvalue - + (0x36, 'SHZ', 1, 'ShiftZoneByLastPoint', 1, 0), # e - + (0x17, 'SLOOP', 0, 'SetLoopVariable', 1, 0), # n - + (0x1a, 'SMD', 0, 'SetMinimumDistance', 1, 0), # distance - + (0x0a, 'SPVFS', 0, 'SetPVectorFromStack', 2, 0), # y, x - + (0x02, 'SPVTCA', 1, 'SetPVectorToAxis', 0, 0), # - - + (0x06, 'SPVTL', 1, 'SetPVectorToLine', 2, 0), # p2, p1 - + (0x76, 'SROUND', 0, 'SuperRound', 1, 0), # n - + (0x10, 'SRP0', 0, 'SetRefPoint0', 1, 0), # p - + (0x11, 'SRP1', 0, 'SetRefPoint1', 1, 0), # p - + (0x12, 'SRP2', 0, 'SetRefPoint2', 1, 0), # p - + (0x1f, 'SSW', 0, 'SetSingleWidth', 1, 0), # n - + (0x1e, 'SSWCI', 0, 'SetSingleWidthCutIn', 1, 0), # n - + (0x61, 'SUB', 0, 'Subtract', 2, 1), # n2, n1 (n1 - n2) + (0x00, 'SVTCA', 1, 'SetFPVectorToAxis', 0, 0), # - - + (0x23, 'SWAP', 0, 'SwapTopStack', 2, 2), # e2, e1 e1, e2 + (0x13, 'SZP0', 0, 'SetZonePointer0', 1, 0), # n - + (0x14, 'SZP1', 0, 'SetZonePointer1', 1, 0), # n - + (0x15, 'SZP2', 0, 'SetZonePointer2', 1, 0), # n - + (0x16, 'SZPS', 0, 'SetZonePointerS', 1, 0), # n - + (0x29, 'UTP', 0, 'UnTouchPt', 1, 0), # p - + (0x70, 'WCVTF', 0, 'WriteCVTInFUnits', 2, 0), # n, l - + (0x44, 'WCVTP', 0, 'WriteCVTInPixels', 2, 0), # v, l - + (0x42, 'WS', 0, 'WriteStore', 2, 0), # v, l - +] + +# fmt: on + + +def bitRepr(value: int, bits: int) -> str: + s = "" + for i in range(bits): + s = "01"[value & 0x1] + s + value = value >> 1 + return s + + +_mnemonicPat = re.compile(r"[A-Z][A-Z0-9]*$") + + +def _makeDict( + instructionList: list[tuple[int, str, int, str, int, int]], +) -> tuple[dict, dict]: + opcodeDict = {} + mnemonicDict = {} + for op, mnemonic, argBits, name, pops, pushes in instructionList: + assert _mnemonicPat.match(mnemonic) + mnemonicDict[mnemonic] = op, argBits, name + if argBits: + argoffset = op + for i in range(1 << argBits): + opcodeDict[op + i] = mnemonic, argBits, argoffset, name + else: + opcodeDict[op] = mnemonic, 0, 0, name + return opcodeDict, mnemonicDict + + +streamOpcodeDict, streamMnemonicDict = _makeDict(streamInstructions) +opcodeDict, mnemonicDict = _makeDict(instructions) + + +class tt_instructions_error(Exception): + def __init__(self, error: str) -> None: + self.error = error + + def __str__(self) -> str: + return "TT instructions error: %s" % repr(self.error) + + +_comment = r"/\*.*?\*/" +_instruction = r"([A-Z][A-Z0-9]*)\s*\[(.*?)\]" +_number = r"-?[0-9]+" +_token = "(%s)|(%s)|(%s)" % (_instruction, _number, _comment) + +_tokenRE = re.compile(_token) +_whiteRE = re.compile(r"\s*") + +_pushCountPat = re.compile(r"[A-Z][A-Z0-9]*\s*\[.*?\]\s*/\* ([0-9]+).*?\*/") + +_indentRE = re.compile(r"^FDEF|IDEF|IF|ELSE\[ \]\t.+") +_unindentRE = re.compile(r"^ELSE|ENDF|EIF\[ \]\t.+") + + +def _skipWhite(data: str, pos: int) -> int: + m = _whiteRE.match(data, pos) + newPos = m.regs[0][1] + assert newPos >= pos + return newPos + + +class Program: + def __init__(self) -> None: + pass + + def fromBytecode(self, bytecode: bytes) -> None: + self.bytecode = array.array("B", bytecode) + if hasattr(self, "assembly"): + del self.assembly + + def fromAssembly(self, assembly: list[str] | str) -> None: + if isinstance(assembly, list): + self.assembly = assembly + elif isinstance(assembly, str): + self.assembly = assembly.splitlines() + else: + raise TypeError(f"expected str or List[str], got {type(assembly).__name__}") + if hasattr(self, "bytecode"): + del self.bytecode + + def getBytecode(self) -> bytes: + if not hasattr(self, "bytecode"): + self._assemble() + return self.bytecode.tobytes() + + def getAssembly(self, preserve=True) -> List[str]: + if not hasattr(self, "assembly"): + self._disassemble(preserve=preserve) + return self.assembly + + def toXML(self, writer, ttFont) -> None: + if ( + not hasattr(ttFont, "disassembleInstructions") + or ttFont.disassembleInstructions + ): + try: + assembly = self.getAssembly() + except: + import traceback + + tmp = StringIO() + traceback.print_exc(file=tmp) + msg = "An exception occurred during the decompilation of glyph program:\n\n" + msg += tmp.getvalue() + log.error(msg) + writer.begintag("bytecode") + writer.newline() + writer.comment(msg.strip()) + writer.newline() + writer.dumphex(self.getBytecode()) + writer.endtag("bytecode") + writer.newline() + else: + if not assembly: + return + writer.begintag("assembly") + writer.newline() + i = 0 + indent = 0 + nInstr = len(assembly) + while i < nInstr: + instr = assembly[i] + if _unindentRE.match(instr): + indent -= 1 + writer.write(writer.indentwhite * indent) + writer.write(instr) + writer.newline() + m = _pushCountPat.match(instr) + i = i + 1 + if m: + nValues = int(m.group(1)) + line: List[str] = [] + j = 0 + for j in range(nValues): + if j and not (j % 25): + writer.write(writer.indentwhite * indent) + writer.write(" ".join(line)) + writer.newline() + line = [] + line.append(assembly[i + j]) + writer.write(writer.indentwhite * indent) + writer.write(" ".join(line)) + writer.newline() + i = i + j + 1 + if _indentRE.match(instr): + indent += 1 + writer.endtag("assembly") + writer.newline() + else: + bytecode = self.getBytecode() + if not bytecode: + return + writer.begintag("bytecode") + writer.newline() + writer.dumphex(bytecode) + writer.endtag("bytecode") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont) -> None: + if name == "assembly": + self.fromAssembly(strjoin(content)) + self._assemble() + del self.assembly + else: + assert name == "bytecode" + self.fromBytecode(readHex(content)) + + def _assemble(self) -> None: + assembly = " ".join(getattr(self, "assembly", [])) + bytecode: List[int] = [] + push = bytecode.append + lenAssembly = len(assembly) + pos = _skipWhite(assembly, 0) + while pos < lenAssembly: + m = _tokenRE.match(assembly, pos) + if m is None: + raise tt_instructions_error( + "Syntax error in TT program (%s)" % assembly[pos - 5 : pos + 15] + ) + dummy, mnemonic, arg, number, comment = m.groups() + pos = m.regs[0][1] + if comment: + pos = _skipWhite(assembly, pos) + continue + + arg = arg.strip() + if mnemonic.startswith("INSTR"): + # Unknown instruction + op = int(mnemonic[5:]) + push(op) + elif mnemonic not in ("PUSH", "NPUSHB", "NPUSHW", "PUSHB", "PUSHW"): + op, argBits, name = mnemonicDict[mnemonic] + if len(arg) != argBits: + raise tt_instructions_error( + "Incorrect number of argument bits (%s[%s])" % (mnemonic, arg) + ) + if arg: + arg = binary2num(arg) + push(op + arg) + else: + push(op) + else: + args = [] + pos = _skipWhite(assembly, pos) + while pos < lenAssembly: + m = _tokenRE.match(assembly, pos) + if m is None: + raise tt_instructions_error( + "Syntax error in TT program (%s)" % assembly[pos : pos + 15] + ) + dummy, _mnemonic, arg, number, comment = m.groups() + if number is None and comment is None: + break + pos = m.regs[0][1] + pos = _skipWhite(assembly, pos) + if comment is not None: + continue + args.append(int(number)) + nArgs = len(args) + if mnemonic == "PUSH": + # Automatically choose the most compact representation + nWords = 0 + while nArgs: + while ( + nWords < nArgs + and nWords < 255 + and not (0 <= args[nWords] <= 255) + ): + nWords += 1 + nBytes = 0 + while ( + nWords + nBytes < nArgs + and nBytes < 255 + and 0 <= args[nWords + nBytes] <= 255 + ): + nBytes += 1 + if ( + nBytes < 2 + and nWords + nBytes < 255 + and nWords + nBytes != nArgs + ): + # Will write bytes as words + nWords += nBytes + continue + + # Write words + if nWords: + if nWords <= 8: + op, argBits, name = streamMnemonicDict["PUSHW"] + op = op + nWords - 1 + push(op) + else: + op, argBits, name = streamMnemonicDict["NPUSHW"] + push(op) + push(nWords) + for value in args[:nWords]: + assert -32768 <= value < 32768, ( + "PUSH value out of range %d" % value + ) + push((value >> 8) & 0xFF) + push(value & 0xFF) + + # Write bytes + if nBytes: + pass + if nBytes <= 8: + op, argBits, name = streamMnemonicDict["PUSHB"] + op = op + nBytes - 1 + push(op) + else: + op, argBits, name = streamMnemonicDict["NPUSHB"] + push(op) + push(nBytes) + for value in args[nWords : nWords + nBytes]: + push(value) + + nTotal = nWords + nBytes + args = args[nTotal:] + nArgs -= nTotal + nWords = 0 + else: + # Write exactly what we've been asked to + words = mnemonic[-1] == "W" + op, argBits, name = streamMnemonicDict[mnemonic] + if mnemonic[0] != "N": + assert nArgs <= 8, nArgs + op = op + nArgs - 1 + push(op) + else: + assert nArgs < 256 + push(op) + push(nArgs) + if words: + for value in args: + assert -32768 <= value < 32768, ( + "PUSHW value out of range %d" % value + ) + push((value >> 8) & 0xFF) + push(value & 0xFF) + else: + for value in args: + assert 0 <= value < 256, ( + "PUSHB value out of range %d" % value + ) + push(value) + + pos = _skipWhite(assembly, pos) + + if bytecode: + assert max(bytecode) < 256 and min(bytecode) >= 0 + self.bytecode = array.array("B", bytecode) + + def _disassemble(self, preserve=False) -> None: + assembly = [] + i = 0 + bytecode = getattr(self, "bytecode", []) + numBytecode = len(bytecode) + while i < numBytecode: + op = bytecode[i] + try: + mnemonic, argBits, argoffset, name = opcodeDict[op] + except KeyError: + if op in streamOpcodeDict: + values = [] + + # Merge consecutive PUSH operations + while bytecode[i] in streamOpcodeDict: + op = bytecode[i] + mnemonic, argBits, argoffset, name = streamOpcodeDict[op] + words = mnemonic[-1] == "W" + if argBits: + nValues = op - argoffset + 1 + else: + i = i + 1 + nValues = bytecode[i] + i = i + 1 + assert nValues > 0 + if not words: + for j in range(nValues): + value = bytecode[i] + values.append(repr(value)) + i = i + 1 + else: + for j in range(nValues): + # cast to signed int16 + value = (bytecode[i] << 8) | bytecode[i + 1] + if value >= 0x8000: + value = value - 0x10000 + values.append(repr(value)) + i = i + 2 + if preserve: + break + + if not preserve: + mnemonic = "PUSH" + nValues = len(values) + if nValues == 1: + assembly.append("%s[ ] /* 1 value pushed */" % mnemonic) + else: + assembly.append( + "%s[ ] /* %s values pushed */" % (mnemonic, nValues) + ) + assembly.extend(values) + else: + assembly.append("INSTR%d[ ]" % op) + i = i + 1 + else: + if argBits: + assembly.append( + mnemonic + + "[%s] /* %s */" % (num2binary(op - argoffset, argBits), name) + ) + else: + assembly.append(mnemonic + "[ ] /* %s */" % name) + i = i + 1 + self.assembly = assembly + + def __bool__(self) -> bool: + """ + >>> p = Program() + >>> bool(p) + False + >>> bc = array.array("B", [0]) + >>> p.fromBytecode(bc) + >>> bool(p) + True + >>> p.bytecode.pop() + 0 + >>> bool(p) + False + + >>> p = Program() + >>> asm = ['SVTCA[0]'] + >>> p.fromAssembly(asm) + >>> bool(p) + True + >>> p.assembly.pop() + 'SVTCA[0]' + >>> bool(p) + False + """ + return (hasattr(self, "assembly") and len(self.assembly) > 0) or ( + hasattr(self, "bytecode") and len(self.bytecode) > 0 + ) + + __nonzero__ = __bool__ + + def __eq__(self, other) -> bool: + if type(self) != type(other): + return NotImplemented + return self.__dict__ == other.__dict__ + + def __ne__(self, other) -> bool: + result = self.__eq__(other) + return result if result is NotImplemented else not result + + +def _test(): + """ + >>> _test() + True + """ + + bc = b"""@;:9876543210/.-,+*)(\'&%$#"! \037\036\035\034\033\032\031\030\027\026\025\024\023\022\021\020\017\016\015\014\013\012\011\010\007\006\005\004\003\002\001\000,\001\260\030CXEj\260\031C`\260F#D#\020 \260FN\360M/\260\000\022\033!#\0213Y-,\001\260\030CX\260\005+\260\000\023K\260\024PX\261\000@8Y\260\006+\033!#\0213Y-,\001\260\030CXN\260\003%\020\362!\260\000\022M\033 E\260\004%\260\004%#Jad\260(RX!#\020\326\033\260\003%\020\362!\260\000\022YY-,\260\032CX!!\033\260\002%\260\002%I\260\003%\260\003%Ja d\260\020PX!!!\033\260\003%\260\003%I\260\000PX\260\000PX\270\377\3428!\033\260\0208!Y\033\260\000RX\260\0368!\033\270\377\3608!YYYY-,\001\260\030CX\260\005+\260\000\023K\260\024PX\271\000\000\377\3008Y\260\006+\033!#\0213Y-,N\001\212\020\261F\031CD\260\000\024\261\000F\342\260\000\025\271\000\000\377\3608\000\260\000<\260(+\260\002%\020\260\000<-,\001\030\260\000/\260\001\024\362\260\001\023\260\001\025M\260\000\022-,\001\260\030CX\260\005+\260\000\023\271\000\000\377\3408\260\006+\033!#\0213Y-,\001\260\030CXEdj#Edi\260\031Cd``\260F#D#\020 \260F\360/\260\000\022\033!! \212 \212RX\0213\033!!YY-,\001\261\013\012C#Ce\012-,\000\261\012\013C#C\013-,\000\260F#p\261\001F>\001\260F#p\261\002FE:\261\002\000\010\015-,\260\022+\260\002%E\260\002%Ej\260@\213`\260\002%#D!!!-,\260\023+\260\002%E\260\002%Ej\270\377\300\214`\260\002%#D!!!-,\260\000\260\022+!!!-,\260\000\260\023+!!!-,\001\260\006C\260\007Ce\012-, i\260@a\260\000\213 \261,\300\212\214\270\020\000b`+\014d#da\\X\260\003aY-,\261\000\003%EhT\260\034KPZX\260\003%E\260\003%E`h \260\004%#D\260\004%#D\033\260\003% Eh \212#D\260\003%Eh`\260\003%#DY-,\260\003% Eh \212#D\260\003%Edhe`\260\004%\260\001`#D-,\260\011CX\207!\300\033\260\022CX\207E\260\021+\260G#D\260Gz\344\033\003\212E\030i \260G#D\212\212\207 \260\240QX\260\021+\260G#D\260Gz\344\033!\260Gz\344YYY\030-, \212E#Eh`D-,EjB-,\001\030/-,\001\260\030CX\260\004%\260\004%Id#Edi\260@\213a \260\200bj\260\002%\260\002%a\214\260\031C`\260F#D!\212\020\260F\366!\033!!!!Y-,\001\260\030CX\260\002%E\260\002%Ed`j\260\003%Eja \260\004%Ej \212\213e\260\004%#D\214\260\003%#D!!\033 EjD EjDY-,\001 E\260\000U\260\030CZXEh#Ei\260@\213a \260\200bj \212#a \260\003%\213e\260\004%#D\214\260\003%#D!!\033!!\260\031+Y-,\001\212\212Ed#EdadB-,\260\004%\260\004%\260\031+\260\030CX\260\004%\260\004%\260\003%\260\033+\001\260\002%C\260@T\260\002%C\260\000TZX\260\003% E\260@aDY\260\002%C\260\000T\260\002%C\260@TZX\260\004% E\260@`DYY!!!!-,\001KRXC\260\002%E#aD\033!!Y-,\001KRXC\260\002%E#`D\033!!Y-,KRXED\033!!Y-,\001 \260\003%#I\260@`\260 c \260\000RX#\260\002%8#\260\002%e8\000\212c8\033!!!!!Y\001-,KPXED\033!!Y-,\001\260\005%\020# \212\365\000\260\001`#\355\354-,\001\260\005%\020# \212\365\000\260\001a#\355\354-,\001\260\006%\020\365\000\355\354-,F#F`\212\212F# F\212`\212a\270\377\200b# \020#\212\261KK\212pE` \260\000PX\260\001a\270\377\272\213\033\260F\214Y\260\020`h\001:-, E\260\003%FRX\260\002%F ha\260\003%\260\003%?#!8\033!\021Y-, E\260\003%FPX\260\002%F ha\260\003%\260\003%?#!8\033!\021Y-,\000\260\007C\260\006C\013-,\212\020\354-,\260\014CX!\033 F\260\000RX\270\377\3608\033\260\0208YY-, \260\000UX\270\020\000c\260\003%Ed\260\003%Eda\260\000SX\260\002\033\260@a\260\003Y%EiSXED\033!!Y\033!\260\002%E\260\002%Ead\260(QXED\033!!YY-,!!\014d#d\213\270@\000b-,!\260\200QX\014d#d\213\270 \000b\033\262\000@/+Y\260\002`-,!\260\300QX\014d#d\213\270\025Ub\033\262\000\200/+Y\260\002`-,\014d#d\213\270@\000b`#!-,KSX\260\004%\260\004%Id#Edi\260@\213a \260\200bj\260\002%\260\002%a\214\260F#D!\212\020\260F\366!\033!\212\021#\022 9/Y-,\260\002%\260\002%Id\260\300TX\270\377\3708\260\0108\033!!Y-,\260\023CX\003\033\002Y-,\260\023CX\002\033\003Y-,\260\012+#\020 <\260\027+-,\260\002%\270\377\3608\260(+\212\020# \320#\260\020+\260\005CX\300\033 +#include + +#include "arrow/util/bit_util.h" +#include "arrow/util/endian.h" +#include "arrow/util/macros.h" + +namespace arrow { +namespace internal { + +class BitmapWriter { + // A sequential bitwise writer that preserves surrounding bit values. + + public: + BitmapWriter(uint8_t* bitmap, int64_t start_offset, int64_t length) + : bitmap_(bitmap), position_(0), length_(length) { + byte_offset_ = start_offset / 8; + bit_mask_ = bit_util::kBitmask[start_offset % 8]; + if (length > 0) { + current_byte_ = bitmap[byte_offset_]; + } else { + current_byte_ = 0; + } + } + + void Set() { current_byte_ |= bit_mask_; } + + void Clear() { current_byte_ &= bit_mask_ ^ 0xFF; } + + void Next() { + bit_mask_ = static_cast(bit_mask_ << 1); + ++position_; + if (bit_mask_ == 0) { + // Finished this byte, need advancing + bit_mask_ = 0x01; + bitmap_[byte_offset_++] = current_byte_; + if (ARROW_PREDICT_TRUE(position_ < length_)) { + current_byte_ = bitmap_[byte_offset_]; + } + } + } + + void Finish() { + // Store current byte if we didn't went past bitmap storage + if (length_ > 0 && (bit_mask_ != 0x01 || position_ < length_)) { + bitmap_[byte_offset_] = current_byte_; + } + } + + int64_t position() const { return position_; } + + private: + uint8_t* bitmap_; + int64_t position_; + int64_t length_; + + uint8_t current_byte_; + uint8_t bit_mask_; + int64_t byte_offset_; +}; + +class FirstTimeBitmapWriter { + // Like BitmapWriter, but any bit values *following* the bits written + // might be clobbered. It is hence faster than BitmapWriter, and can + // also avoid false positives with Valgrind. + + public: + FirstTimeBitmapWriter(uint8_t* bitmap, int64_t start_offset, int64_t length) + : bitmap_(bitmap), position_(0), length_(length) { + current_byte_ = 0; + byte_offset_ = start_offset / 8; + bit_mask_ = bit_util::kBitmask[start_offset % 8]; + if (length > 0) { + current_byte_ = + bitmap[byte_offset_] & bit_util::kPrecedingBitmask[start_offset % 8]; + } else { + current_byte_ = 0; + } + } + + /// Appends number_of_bits from word to valid_bits and valid_bits_offset. + /// + /// \param[in] word The LSB bitmap to append. Any bits past number_of_bits are assumed + /// to be unset (i.e. 0). + /// \param[in] number_of_bits The number of bits to append from word. + void AppendWord(uint64_t word, int64_t number_of_bits) { + if (ARROW_PREDICT_FALSE(number_of_bits == 0)) { + return; + } + + // Location that the first byte needs to be written to. + uint8_t* append_position = bitmap_ + byte_offset_; + + // Update state variables except for current_byte_ here. + position_ += number_of_bits; + int64_t bit_offset = bit_util::CountTrailingZeros(static_cast(bit_mask_)); + bit_mask_ = bit_util::kBitmask[(bit_offset + number_of_bits) % 8]; + byte_offset_ += (bit_offset + number_of_bits) / 8; + + if (bit_offset != 0) { + // We are in the middle of the byte. This code updates the byte and shifts + // bits appropriately within word so it can be memcpy'd below. + int64_t bits_to_carry = 8 - bit_offset; + // Carry over bits from word to current_byte_. We assume any extra bits in word + // unset so no additional accounting is needed for when number_of_bits < + // bits_to_carry. + current_byte_ |= (word & bit_util::kPrecedingBitmask[bits_to_carry]) << bit_offset; + // Check if everything is transferred into current_byte_. + if (ARROW_PREDICT_FALSE(number_of_bits < bits_to_carry)) { + return; + } + *append_position = current_byte_; + append_position++; + // Move the carry bits off of word. + word = word >> bits_to_carry; + number_of_bits -= bits_to_carry; + } + word = bit_util::ToLittleEndian(word); + int64_t bytes_for_word = ::arrow::bit_util::BytesForBits(number_of_bits); + std::memcpy(append_position, &word, bytes_for_word); + // At this point, the previous current_byte_ has been written to bitmap_. + // The new current_byte_ is either the last relevant byte in 'word' + // or cleared if the new position is byte aligned (i.e. a fresh byte). + if (bit_mask_ == 0x1) { + current_byte_ = 0; + } else { + current_byte_ = *(append_position + bytes_for_word - 1); + } + } + + void Set() { current_byte_ |= bit_mask_; } + + void Clear() {} + + void Next() { + bit_mask_ = static_cast(bit_mask_ << 1); + ++position_; + if (bit_mask_ == 0) { + // Finished this byte, need advancing + bit_mask_ = 0x01; + bitmap_[byte_offset_++] = current_byte_; + current_byte_ = 0; + } + } + + void Finish() { + // Store current byte if we didn't went go bitmap storage + if (length_ > 0 && (bit_mask_ != 0x01 || position_ < length_)) { + bitmap_[byte_offset_] = current_byte_; + } + } + + int64_t position() const { return position_; } + + private: + uint8_t* bitmap_; + int64_t position_; + int64_t length_; + + uint8_t current_byte_; + uint8_t bit_mask_; + int64_t byte_offset_; +}; + +template +class BitmapWordWriter { + public: + BitmapWordWriter() = default; + BitmapWordWriter(uint8_t* bitmap, int64_t offset, int64_t length) + : offset_(static_cast(may_have_byte_offset) * (offset % 8)), + bitmap_(bitmap + offset / 8), + bitmap_end_(bitmap_ + bit_util::BytesForBits(offset_ + length)), + mask_((1U << offset_) - 1) { + if (offset_) { + if (length >= static_cast(sizeof(Word) * 8)) { + current_data.word_ = load(bitmap_); + } else if (length > 0) { + current_data.epi.byte_ = load(bitmap_); + } + } + } + + void PutNextWord(Word word) { + if (may_have_byte_offset && offset_) { + // split one word into two adjacent words, don't touch unused bits + // |<------ word ----->| + // +-----+-------------+ + // | A | B | + // +-----+-------------+ + // | | + // v v offset + // +-------------+-----+-------------+-----+ + // | --- | A | B | --- | + // +-------------+-----+-------------+-----+ + // |<------ next ----->|<---- current ---->| + word = (word << offset_) | (word >> (sizeof(Word) * 8 - offset_)); + Word next_word = load(bitmap_ + sizeof(Word)); + current_data.word_ = (current_data.word_ & mask_) | (word & ~mask_); + next_word = (next_word & ~mask_) | (word & mask_); + store(bitmap_, current_data.word_); + store(bitmap_ + sizeof(Word), next_word); + current_data.word_ = next_word; + } else { + store(bitmap_, word); + } + bitmap_ += sizeof(Word); + } + + void PutNextTrailingByte(uint8_t byte, int valid_bits) { + if (valid_bits == 8) { + if (may_have_byte_offset && offset_) { + byte = (byte << offset_) | (byte >> (8 - offset_)); + uint8_t next_byte = load(bitmap_ + 1); + current_data.epi.byte_ = (current_data.epi.byte_ & mask_) | (byte & ~mask_); + next_byte = (next_byte & ~mask_) | (byte & mask_); + store(bitmap_, current_data.epi.byte_); + store(bitmap_ + 1, next_byte); + current_data.epi.byte_ = next_byte; + } else { + store(bitmap_, byte); + } + ++bitmap_; + } else { + assert(valid_bits > 0); + assert(valid_bits < 8); + assert(bitmap_ + bit_util::BytesForBits(offset_ + valid_bits) <= bitmap_end_); + internal::BitmapWriter writer(bitmap_, offset_, valid_bits); + for (int i = 0; i < valid_bits; ++i) { + (byte & 0x01) ? writer.Set() : writer.Clear(); + writer.Next(); + byte >>= 1; + } + writer.Finish(); + } + } + + private: + int64_t offset_; + uint8_t* bitmap_; + + const uint8_t* bitmap_end_; + uint64_t mask_; + union { + Word word_; + struct { +#if ARROW_LITTLE_ENDIAN == 0 + uint8_t padding_bytes_[sizeof(Word) - 1]; +#endif + uint8_t byte_; + } epi; + } current_data; + + template + DType load(const uint8_t* bitmap) { + assert(bitmap + sizeof(DType) <= bitmap_end_); + return bit_util::ToLittleEndian(util::SafeLoadAs(bitmap)); + } + + template + void store(uint8_t* bitmap, DType data) { + assert(bitmap + sizeof(DType) <= bitmap_end_); + util::SafeStore(bitmap, bit_util::FromLittleEndian(data)); + } +}; + +} // namespace internal +} // namespace arrow diff --git a/shared/package-files/6b/6b8aafa843892b5769d793e5e3fcecfd2a339678227d0aa51cab5bb4eab2733a/ibm3151 b/shared/package-files/6b/6b8aafa843892b5769d793e5e3fcecfd2a339678227d0aa51cab5bb4eab2733a/ibm3151 new file mode 100644 index 0000000000000000000000000000000000000000..b6c078e5a4801d9398b91148eb297eeafe18f20d Binary files /dev/null and b/shared/package-files/6b/6b8aafa843892b5769d793e5e3fcecfd2a339678227d0aa51cab5bb4eab2733a/ibm3151 differ diff --git a/shared/package-files/6b/6b8c3c7260473925303091ef2c950eb3aa5252538712cc7437c1c61007f1b315/backend_inline.py b/shared/package-files/6b/6b8c3c7260473925303091ef2c950eb3aa5252538712cc7437c1c61007f1b315/backend_inline.py new file mode 100644 index 0000000000000000000000000000000000000000..6bcc1d4a013957a4015ef9d66e5fc4e29d80f201 --- /dev/null +++ b/shared/package-files/6b/6b8c3c7260473925303091ef2c950eb3aa5252538712cc7437c1c61007f1b315/backend_inline.py @@ -0,0 +1,311 @@ +"""A matplotlib backend for publishing figures via display_data""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the BSD 3-Clause License. + +import matplotlib +from matplotlib import colors +from matplotlib.backends import backend_agg +from matplotlib.backends.backend_agg import FigureCanvasAgg +from matplotlib._pylab_helpers import Gcf +from matplotlib.figure import Figure + +from IPython.core.interactiveshell import InteractiveShell +from IPython.core.getipython import get_ipython +from IPython.core.pylabtools import select_figure_formats +from IPython.display import display + +from .config import InlineBackend + + +def new_figure_manager(num, *args, FigureClass=Figure, **kwargs): + """ + Return a new figure manager for a new figure instance. + + This function is part of the API expected by Matplotlib backends. + """ + return new_figure_manager_given_figure(num, FigureClass(*args, **kwargs)) + + +def new_figure_manager_given_figure(num, figure): + """ + Return a new figure manager for a given figure instance. + + This function is part of the API expected by Matplotlib backends. + """ + manager = backend_agg.new_figure_manager_given_figure(num, figure) + + # Hack: matplotlib FigureManager objects in interacive backends (at least + # in some of them) monkeypatch the figure object and add a .show() method + # to it. This applies the same monkeypatch in order to support user code + # that might expect `.show()` to be part of the official API of figure + # objects. For further reference: + # https://github.com/ipython/ipython/issues/1612 + # https://github.com/matplotlib/matplotlib/issues/835 + + if not hasattr(figure, 'show'): + # Queue up `figure` for display + figure.show = lambda *a: display( + figure, metadata=_fetch_figure_metadata(figure)) + + # If matplotlib was manually set to non-interactive mode, this function + # should be a no-op (otherwise we'll generate duplicate plots, since a user + # who set ioff() manually expects to make separate draw/show calls). + if not matplotlib.is_interactive(): + return manager + + # ensure current figure will be drawn, and each subsequent call + # of draw_if_interactive() moves the active figure to ensure it is + # drawn last + try: + show._to_draw.remove(figure) + except ValueError: + # ensure it only appears in the draw list once + pass + # Queue up the figure for drawing in next show() call + show._to_draw.append(figure) + show._draw_called = True + + return manager + + +def show(close=None, block=None): + """Show all figures as SVG/PNG payloads sent to the IPython clients. + + Parameters + ---------- + close : bool, optional + If true, a ``plt.close('all')`` call is automatically issued after + sending all the figures. If this is set, the figures will entirely + removed from the internal list of figures. + block : Not used. + The `block` parameter is a Matplotlib experimental parameter. + We accept it in the function signature for compatibility with other + backends. + """ + if close is None: + close = InlineBackend.instance().close_figures + try: + for figure_manager in Gcf.get_all_fig_managers(): + display( + figure_manager.canvas.figure, + metadata=_fetch_figure_metadata(figure_manager.canvas.figure) + ) + finally: + show._to_draw = [] + # only call close('all') if any to close + # close triggers gc.collect, which can be slow + if close and Gcf.get_all_fig_managers(): + matplotlib.pyplot.close('all') + + +# This flag will be reset by draw_if_interactive when called +show._draw_called = False +# list of figures to draw when flush_figures is called +show._to_draw = [] + + +def flush_figures(): + """Send all figures that changed + + This is meant to be called automatically and will call show() if, during + prior code execution, there had been any calls to draw_if_interactive. + + This function is meant to be used as a post_execute callback in IPython, + so user-caused errors are handled with showtraceback() instead of being + allowed to raise. If this function is not called from within IPython, + then these exceptions will raise. + """ + if not show._draw_called: + return + + try: + if InlineBackend.instance().close_figures: + # ignore the tracking, just draw and close all figures + try: + return show(True) + except Exception as e: + # safely show traceback if in IPython, else raise + ip = get_ipython() + if ip is None: + raise e + else: + ip.showtraceback() + return + + # exclude any figures that were closed: + active = set([fm.canvas.figure for fm in Gcf.get_all_fig_managers()]) + for fig in [fig for fig in show._to_draw if fig in active]: + try: + display(fig, metadata=_fetch_figure_metadata(fig)) + except Exception as e: + # safely show traceback if in IPython, else raise + ip = get_ipython() + if ip is None: + raise e + else: + ip.showtraceback() + return + finally: + # clear flags for next round + show._to_draw = [] + show._draw_called = False + + +# Changes to matplotlib in version 1.2 requires a mpl backend to supply a default +# figurecanvas. This is set here to a Agg canvas +# See https://github.com/matplotlib/matplotlib/pull/1125 +FigureCanvas = FigureCanvasAgg + + +def configure_inline_support(shell, backend): + """Configure an IPython shell object for matplotlib use. + + Parameters + ---------- + shell : InteractiveShell instance + + backend : matplotlib backend + """ + # If using our svg payload backend, register the post-execution + # function that will pick up the results for display. This can only be + # done with access to the real shell object. + + cfg = InlineBackend.instance(parent=shell) + cfg.shell = shell + if cfg not in shell.configurables: + shell.configurables.append(cfg) + + if backend == 'module://matplotlib_inline.backend_inline': + shell.events.register('post_execute', flush_figures) + + # Save rcParams that will be overwrittern + shell._saved_rcParams = {} + for k in cfg.rc: + shell._saved_rcParams[k] = matplotlib.rcParams[k] + # load inline_rc + matplotlib.rcParams.update(cfg.rc) + new_backend_name = "inline" + else: + try: + shell.events.unregister('post_execute', flush_figures) + except ValueError: + pass + if hasattr(shell, '_saved_rcParams'): + matplotlib.rcParams.update(shell._saved_rcParams) + del shell._saved_rcParams + new_backend_name = "other" + + # only enable the formats once -> don't change the enabled formats (which the user may + # has changed) when getting another "%matplotlib inline" call. + # See https://github.com/ipython/ipykernel/issues/29 + cur_backend = getattr(configure_inline_support, "current_backend", "unset") + if new_backend_name != cur_backend: + # Setup the default figure format + select_figure_formats(shell, cfg.figure_formats, **cfg.print_figure_kwargs) + configure_inline_support.current_backend = new_backend_name + + +def _enable_matplotlib_integration(): + """Enable extra IPython matplotlib integration when we are loaded as the matplotlib backend.""" + from matplotlib import get_backend + ip = get_ipython() + backend = get_backend() + if ip and backend == 'module://%s' % __name__: + from IPython.core.pylabtools import activate_matplotlib + try: + activate_matplotlib(backend) + configure_inline_support(ip, backend) + except (ImportError, AttributeError): + # bugs may cause a circular import on Python 2 + def configure_once(*args): + activate_matplotlib(backend) + configure_inline_support(ip, backend) + ip.events.unregister('post_run_cell', configure_once) + ip.events.register('post_run_cell', configure_once) + + +_enable_matplotlib_integration() + + +def _fetch_figure_metadata(fig): + """Get some metadata to help with displaying a figure.""" + # determine if a background is needed for legibility + if _is_transparent(fig.get_facecolor()): + # the background is transparent + ticksLight = _is_light([label.get_color() + for axes in fig.axes + for axis in (axes.xaxis, axes.yaxis) + for label in axis.get_ticklabels()]) + if ticksLight.size and (ticksLight == ticksLight[0]).all(): + # there are one or more tick labels, all with the same lightness + return {'needs_background': 'dark' if ticksLight[0] else 'light'} + + return None + + +def _is_light(color): + """Determines if a color (or each of a sequence of colors) is light (as + opposed to dark). Based on ITU BT.601 luminance formula (see + https://stackoverflow.com/a/596241).""" + rgbaArr = colors.to_rgba_array(color) + return rgbaArr[:, :3].dot((.299, .587, .114)) > .5 + + +def _is_transparent(color): + """Determine transparency from alpha.""" + rgba = colors.to_rgba(color) + return rgba[3] < .5 + + +def set_matplotlib_formats(*formats, **kwargs): + """Select figure formats for the inline backend. Optionally pass quality for JPEG. + + For example, this enables PNG and JPEG output with a JPEG quality of 90%:: + + In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) + + To set this in your config files use the following:: + + c.InlineBackend.figure_formats = {'png', 'jpeg'} + c.InlineBackend.print_figure_kwargs.update({'quality' : 90}) + + Parameters + ---------- + *formats : strs + One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. + **kwargs + Keyword args will be relayed to ``figure.canvas.print_figure``. + """ + # build kwargs, starting with InlineBackend config + cfg = InlineBackend.instance() + kw = {} + kw.update(cfg.print_figure_kwargs) + kw.update(**kwargs) + shell = InteractiveShell.instance() + select_figure_formats(shell, formats, **kw) + + +def set_matplotlib_close(close=True): + """Set whether the inline backend closes all figures automatically or not. + + By default, the inline backend used in the IPython Notebook will close all + matplotlib figures automatically after each cell is run. This means that + plots in different cells won't interfere. Sometimes, you may want to make + a plot in one cell and then refine it in later cells. This can be accomplished + by:: + + In [1]: set_matplotlib_close(False) + + To set this in your config files use the following:: + + c.InlineBackend.close_figures = False + + Parameters + ---------- + close : bool + Should all matplotlib figures be automatically closed after each cell is + run? + """ + cfg = InlineBackend.instance() + cfg.close_figures = close diff --git a/shared/package-files/6b/6b8c8a2bf3372d76abf81e25d31011bbbfa1017aeeaf8765f73d52e3211bd24d/_penalties.py b/shared/package-files/6b/6b8c8a2bf3372d76abf81e25d31011bbbfa1017aeeaf8765f73d52e3211bd24d/_penalties.py new file mode 100644 index 0000000000000000000000000000000000000000..e7d09488795919b1a8c3efb73323de6b567645ed --- /dev/null +++ b/shared/package-files/6b/6b8c8a2bf3372d76abf81e25d31011bbbfa1017aeeaf8765f73d52e3211bd24d/_penalties.py @@ -0,0 +1,601 @@ +""" +A collection of smooth penalty functions. + +Penalties on vectors take a vector argument and return a scalar +penalty. The gradient of the penalty is a vector with the same shape +as the input value. + +Penalties on covariance matrices take two arguments: the matrix and +its inverse, both in unpacked (square) form. The returned penalty is +a scalar, and the gradient is returned as a vector that contains the +gradient with respect to the free elements in the lower triangle of +the covariance matrix. + +All penalties are subtracted from the log-likelihood, so greater +penalty values correspond to a greater degree of penalization. + +The penalties should be smooth so that they can be subtracted from log +likelihood functions and optimized using standard methods (i.e., L1 +penalties do not belong here). +""" + +import numpy as np + + +class Penalty: + """ + A class for representing a scalar-value penalty. + + Parameters + ---------- + weights : array_like, optional + A vector of weights that determines the weight of the penalty + for each parameter. + + Notes + ----- + The class has a member called `alpha` that scales the weights. + """ + + def __init__(self, weights=1.0): + self.weights = weights + self.alpha = 1.0 + + def func(self, params): + """ + A penalty function on a vector of parameters. + + Parameters + ---------- + params : array_like + A vector of parameters. + + Returns + ------- + float + A scalar penalty value; greater values imply greater + penalization. + """ + raise NotImplementedError + + def deriv(self, params): + """ + The gradient of a penalty function. + + Parameters + ---------- + params : array_like + A vector of parameters. + + Returns + ------- + ndarray + The gradient of the penalty with respect to each element in + `params`. + """ + raise NotImplementedError + + def _null_weights(self, params): + """Work around for Null model + + This will not be needed anymore when we can use `self._null_drop_keys` + as in DiscreteModels. + TODO: check other models + """ + if np.size(self.weights) > 1: + if len(params) == 1: + # raise to identify models where this would be needed + raise NotImplementedError + + return self.weights + + +class NonePenalty(Penalty): + """ + A penalty that does not penalize. + """ + + def __init__(self, **kwds): + super().__init__() + if kwds: + import warnings + + warnings.warn("keyword arguments are be ignored", stacklevel=2) + + def func(self, params): + if params.ndim == 2: + return np.zeros(params.shape[1:]) + else: + return 0 + + def deriv(self, params): + return np.zeros(params.shape) + + def deriv2(self, params): + # returns diagonal of hessian + return np.zeros(params.shape[0]) + + +class L2(Penalty): + """ + The L2 (ridge) penalty. + """ + + def __init__(self, weights=1.0): + super().__init__(weights) + + def func(self, params): + return np.sum(self.weights * self.alpha * params**2) + + def deriv(self, params): + return 2 * self.weights * self.alpha * params + + def deriv2(self, params): + return 2 * self.weights * self.alpha * np.ones(len(params)) + + +class L2Univariate(Penalty): + """ + The L2 (ridge) penalty applied to each parameter. + """ + + def __init__(self, weights=None): + if weights is None: + self.weights = 1.0 + else: + self.weights = weights + + def func(self, params): + return self.weights * params**2 + + def deriv(self, params): + return 2 * self.weights * params + + def deriv2(self, params): + return 2 * self.weights * np.ones(len(params)) + + +class PseudoHuber(Penalty): + """ + The pseudo-Huber penalty. + """ + + def __init__(self, dlt, weights=1.0): + super().__init__(weights) + self.dlt = dlt + + def func(self, params): + v = np.sqrt(1 + (params / self.dlt) ** 2) + v -= 1 + v *= self.dlt**2 + return np.sum(self.weights * self.alpha * v, 0) + + def deriv(self, params): + v = np.sqrt(1 + (params / self.dlt) ** 2) + return params * self.weights * self.alpha / v + + def deriv2(self, params): + v = np.power(1 + (params / self.dlt) ** 2, -3 / 2) + return self.weights * self.alpha * v + + +class SCAD(Penalty): + """ + The SCAD penalty of Fan and Li. + + The SCAD penalty is linear around zero as a L1 penalty up to threshold tau. + The SCAD penalty is constant for values larger than c*tau. + The middle segment is quadratic and connect the two segments with a continuous + derivative. + The penalty is symmetric around zero. + + Parameterization follows Boo, Johnson, Li and Tan 2011. + Fan and Li use lambda instead of tau, and a instead of c. Fan and Li + recommend setting c=3.7. + + f(x) = { tau |x| if 0 <= |x| < tau + { -(|x|^2 - 2 c tau |x| + tau^2) / (2 (c - 1)) if tau <= |x| < c tau + { (c + 1) tau^2 / 2 if c tau <= |x| + + Parameters + ---------- + tau : float + Slope and threshold for linear segment. + c : float, optional + Factor for second threshold which is c * tau. + weights : array_like, optional + Weights for penalty of each parameter. If an entry is zero, then the + corresponding parameter will not be penalized. + + References + ---------- + Buu, Anne, Norman J. Johnson, Runze Li, and Xianming Tan. "New variable + selection methods for zero-inflated count data with applications to the + substance abuse field." + *Statistics in Medicine* 30, no. 18 (2011): 2326-2340. + + Fan, Jianqing, and Runze Li. "Variable selection via nonconcave penalized + likelihood and its oracle properties." + *Journal of the American Statistical Association* 96, no. 456 (2001): + 1348-1360. + """ + + def __init__(self, tau, c=3.7, weights=1.0): + super().__init__(weights) + self.tau = tau + self.c = c + + def func(self, params): + + # 3 segments in absolute value + tau = self.tau + p_abs = np.atleast_1d(np.abs(params)) + res = np.empty(p_abs.shape, p_abs.dtype) + res.fill(np.nan) + mask1 = p_abs < tau + mask3 = p_abs >= self.c * tau + res[mask1] = tau * p_abs[mask1] + mask2 = ~mask1 & ~mask3 + p_abs2 = p_abs[mask2] + tmp = p_abs2**2 - 2 * self.c * tau * p_abs2 + tau**2 + res[mask2] = -tmp / (2 * (self.c - 1)) + res[mask3] = (self.c + 1) * tau**2 / 2.0 + + return (self.weights * res).sum(0) + + def deriv(self, params): + + # 3 segments in absolute value + tau = self.tau + p = np.atleast_1d(params) + p_abs = np.abs(p) + p_sign = np.sign(p) + res = np.empty(p_abs.shape) + res.fill(np.nan) + + mask1 = p_abs < tau + mask3 = p_abs >= self.c * tau + mask2 = ~mask1 & ~mask3 + res[mask1] = p_sign[mask1] * tau + tmp = p_sign[mask2] * (p_abs[mask2] - self.c * tau) + res[mask2] = -tmp / (self.c - 1) + res[mask3] = 0 + + return self.weights * res + + def deriv2(self, params): + """Second derivative of function + + This returns scalar or vector in same shape as params, not a square + Hessian. If the return is 1 dimensional, then it is the diagonal of + the Hessian. + """ + + # 3 segments in absolute value + tau = self.tau + p = np.atleast_1d(params) + p_abs = np.abs(p) + res = np.zeros(p_abs.shape) + + mask1 = p_abs < tau + mask3 = p_abs >= self.c * tau + mask2 = ~mask1 & ~mask3 + res[mask2] = -1 / (self.c - 1) + + return self.weights * res + + +class SCADSmoothed(SCAD): + """ + The SCAD penalty of Fan and Li, quadratically smoothed around zero. + + This follows Fan and Li 2001 equation (3.7). + + Parameterization follows Boo, Johnson, Li and Tan 2011 + see docstring of SCAD + + Parameters + ---------- + tau : float + Slope and threshold for linear segment. + c : float, optional + Factor for second threshold. + c0 : float, optional + Threshold for quadratically smoothed segment. + weights : array_like, optional + Weights for penalty of each parameter. If an entry is zero, then the + corresponding parameter will not be penalized. + restriction : None or ndarray, optional + Linear transformation of the parameters. If it is not None, then + the penalty function is applied to each transformed parameter + independently. + + Notes + ----- + TODO: Use delegation instead of subclassing, so smoothing can be added to + all penalty classes. + """ + + def __init__(self, tau, c=3.7, c0=None, weights=1.0, restriction=None): + super().__init__(tau, c=c, weights=weights) + self.tau = tau + self.c = c + self.c0 = c0 if c0 is not None else tau * 0.1 + if self.c0 > tau: + raise ValueError("c0 cannot be larger than tau") + + # get coefficients for quadratic approximation + c0 = self.c0 + # need to temporarily override weights for call to super + weights = self.weights + self.weights = 1.0 + deriv_c0 = super().deriv(c0) + value_c0 = super().func(c0) + self.weights = weights + + self.aq1 = value_c0 - 0.5 * deriv_c0 * c0 + self.aq2 = 0.5 * deriv_c0 / c0 + self.restriction = restriction + + def func(self, params): + # workaround for Null model + weights = self._null_weights(params) + # TODO: `and np.size(params) > 1` is hack for llnull, need better solution + if self.restriction is not None and np.size(params) > 1: + params = self.restriction.dot(params) + # need to temporarily override weights for call to super + # Note: we have the same problem with `restriction` + self_weights = self.weights + self.weights = 1.0 + value = super().func(params[None, ...]) + self.weights = self_weights + + # shift down so func(0) == 0 + value -= self.aq1 + # change the segment corresponding to quadratic approximation + p_abs = np.atleast_1d(np.abs(params)) + mask = p_abs < self.c0 + p_abs_masked = p_abs[mask] + value[mask] = self.aq2 * p_abs_masked**2 + + return (weights * value).sum(0) + + def deriv(self, params): + # workaround for Null model + weights = self._null_weights(params) + if self.restriction is not None and np.size(params) > 1: + params = self.restriction.dot(params) + # need to temporarily override weights for call to super + self_weights = self.weights + self.weights = 1.0 + value = super().deriv(params) + self.weights = self_weights + + # change the segment corresponding to quadratic approximation + p = np.atleast_1d(params) + mask = np.abs(p) < self.c0 + value[mask] = 2 * self.aq2 * p[mask] + + if self.restriction is not None and np.size(params) > 1: + return weights * value.dot(self.restriction) + else: + return weights * value + + def deriv2(self, params): + # workaround for Null model + weights = self._null_weights(params) + if self.restriction is not None and np.size(params) > 1: + params = self.restriction.dot(params) + # need to temporarily override weights for call to super + self_weights = self.weights + self.weights = 1.0 + value = super().deriv2(params) + self.weights = self_weights + + # change the segment corresponding to quadratic approximation + p = np.atleast_1d(params) + mask = np.abs(p) < self.c0 + value[mask] = 2 * self.aq2 + + if self.restriction is not None and np.size(params) > 1: + # note: super returns 1d array for diag, i.e., hessian_diag + # TODO: weights are missing + return (self.restriction.T * (weights * value)).dot(self.restriction) + else: + return weights * value + + +class ConstraintsPenalty: + """ + Penalty applied to linear transformation of parameters + + Parameters + ---------- + penalty : instance of penalty function + Currently this requires an instance of a univariate, vectorized + penalty class. + weights : array_like, optional + Weights for adding penalties of transformed params. + restriction : None or array_like, optional + If it is not None, then restriction defines a linear transformation + of the parameters. The penalty function is applied to each transformed + parameter independently. + + Notes + ----- + `restrictions` allows us to impose penalization on contrasts or stochastic + constraints of the original parameters. + Examples for these contrast are difference penalities or all pairs + penalties. + """ + + def __init__(self, penalty, weights=None, restriction=None): + + self.penalty = penalty + if weights is None: + self.weights = 1.0 + else: + self.weights = weights + + if restriction is not None: + restriction = np.asarray(restriction) + + self.restriction = restriction + + def func(self, params): + """Evaluate penalty function at params + + Parameters + ---------- + params : ndarray + Array of parameters at which the penalty is evaluated. + + Returns + ------- + value : ndarray + Value(s) of penalty function. + """ + # TODO: `and np.size(params) > 1` is hack for llnull, need better solution + # Is this still needed? it seems to work without + if self.restriction is not None: + params = self.restriction.dot(params) + + value = self.penalty.func(params) + + return (self.weights * value.T).T.sum(0) + + def deriv(self, params): + """First derivative of penalty function w.r.t. params + + Parameters + ---------- + params : ndarray + Array of parameters at which the derivative is evaluated. + + Returns + ------- + deriv : ndarray + Array of first partial derivatives. + """ + if self.restriction is not None: + params = self.restriction.dot(params) + + value = self.penalty.deriv(params) + + if self.restriction is not None: + return self.weights * value.T.dot(self.restriction) + else: + return self.weights * value.T + + grad = deriv + + def deriv2(self, params): + """Second derivative of penalty function w.r.t. params + + Parameters + ---------- + params : ndarray + Array of parameters at which the derivative is evaluated. + + Returns + ------- + deriv2 : ndarray, 2-D + Second derivative matrix. + """ + + if self.restriction is not None: + params = self.restriction.dot(params) + + value = self.penalty.deriv2(params) + + if self.restriction is not None: + # note: univariate penalty returns 1d array for diag, + # i.e., hessian_diag + v = self.restriction.T * value * self.weights + value = v.dot(self.restriction) + else: + value = np.diag(self.weights * value) + + return value + + +class L2ConstraintsPenalty(ConstraintsPenalty): + """Convenience class of ConstraintsPenalty with L2 penalization""" + + def __init__(self, weights=None, restriction=None, sigma_prior=None): + + if sigma_prior is not None: + raise NotImplementedError("sigma_prior is not implemented yet") + + penalty = L2Univariate() + + super().__init__(penalty, weights=weights, restriction=restriction) + + +class CovariancePenalty: + """Base class for a penalty applied to a covariance matrix + + Parameters + ---------- + weight : float + The weight (scalar) applied to the penalty. + """ + + def __init__(self, weight): + # weight should be scalar + self.weight = weight + + def func(self, mat, mat_inv): + """ + Parameters + ---------- + mat : square matrix + The matrix to be penalized. + mat_inv : square matrix + The inverse of `mat`. + + Returns + ------- + float + A scalar penalty value. + """ + raise NotImplementedError + + def deriv(self, mat, mat_inv): + """ + Parameters + ---------- + mat : square matrix + The matrix to be penalized. + mat_inv : square matrix + The inverse of `mat`. + + Returns + ------- + ndarray + A vector containing the gradient of the penalty + with respect to each element in the lower triangle + of `mat`. + """ + raise NotImplementedError + + +class PSD(CovariancePenalty): + """ + A penalty that converges to +infinity as the argument matrix + approaches the boundary of the domain of symmetric, positive + definite matrices. + """ + + def func(self, mat, mat_inv): + try: + cy = np.linalg.cholesky(mat) + except np.linalg.LinAlgError: + return np.inf + return -2 * self.weight * np.sum(np.log(np.diag(cy))) + + def deriv(self, mat, mat_inv): + cy = mat_inv.copy() + cy = 2 * cy - np.diag(np.diag(cy)) + i, j = np.tril_indices(mat.shape[0]) + return -self.weight * cy[i, j] diff --git a/shared/package-files/6b/6b8eb761926210d4c1e10198c1fcee600a96e8b07770c3129373960101d9b1b4/xterm-p370 b/shared/package-files/6b/6b8eb761926210d4c1e10198c1fcee600a96e8b07770c3129373960101d9b1b4/xterm-p370 new file mode 100644 index 0000000000000000000000000000000000000000..915c17a4caa3ad1a1edf16debe59ccaacff4cdf7 Binary files /dev/null and b/shared/package-files/6b/6b8eb761926210d4c1e10198c1fcee600a96e8b07770c3129373960101d9b1b4/xterm-p370 differ diff --git a/shared/package-files/6b/6b92a782e27db90468ec892ae182449e8d1f165b57625b9dfb40e9463df32ebd/wheel.py b/shared/package-files/6b/6b92a782e27db90468ec892ae182449e8d1f165b57625b9dfb40e9463df32ebd/wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..58a7730597b3ad3f6552478d9bd5425a9ec4c66a --- /dev/null +++ b/shared/package-files/6b/6b92a782e27db90468ec892ae182449e8d1f165b57625b9dfb40e9463df32ebd/wheel.py @@ -0,0 +1,740 @@ +"""Support for installing and building the "wheel" binary package format. +""" + +import collections +import compileall +import contextlib +import csv +import importlib +import logging +import os.path +import re +import shutil +import sys +import warnings +from base64 import urlsafe_b64encode +from email.message import Message +from itertools import chain, filterfalse, starmap +from typing import ( + IO, + TYPE_CHECKING, + Any, + BinaryIO, + Callable, + Dict, + Generator, + Iterable, + Iterator, + List, + NewType, + Optional, + Sequence, + Set, + Tuple, + Union, + cast, +) +from zipfile import ZipFile, ZipInfo + +from pip._vendor.distlib.scripts import ScriptMaker +from pip._vendor.distlib.util import get_export_entry +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.exceptions import InstallationError +from pip._internal.locations import get_major_minor_version +from pip._internal.metadata import ( + BaseDistribution, + FilesystemWheel, + get_wheel_distribution, +) +from pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME, DirectUrl +from pip._internal.models.scheme import SCHEME_KEYS, Scheme +from pip._internal.utils.filesystem import adjacent_tmp_file, replace +from pip._internal.utils.misc import captured_stdout, ensure_dir, hash_file, partition +from pip._internal.utils.unpacking import ( + current_umask, + is_within_directory, + set_extracted_file_to_default_mode_plus_executable, + zip_item_is_executable, +) +from pip._internal.utils.wheel import parse_wheel + +if TYPE_CHECKING: + from typing import Protocol + + class File(Protocol): + src_record_path: "RecordPath" + dest_path: str + changed: bool + + def save(self) -> None: + pass + + +logger = logging.getLogger(__name__) + +RecordPath = NewType("RecordPath", str) +InstalledCSVRow = Tuple[RecordPath, str, Union[int, str]] + + +def rehash(path: str, blocksize: int = 1 << 20) -> Tuple[str, str]: + """Return (encoded_digest, length) for path using hashlib.sha256()""" + h, length = hash_file(path, blocksize) + digest = "sha256=" + urlsafe_b64encode(h.digest()).decode("latin1").rstrip("=") + return (digest, str(length)) + + +def csv_io_kwargs(mode: str) -> Dict[str, Any]: + """Return keyword arguments to properly open a CSV file + in the given mode. + """ + return {"mode": mode, "newline": "", "encoding": "utf-8"} + + +def fix_script(path: str) -> bool: + """Replace #!python with #!/path/to/python + Return True if file was changed. + """ + # XXX RECORD hashes will need to be updated + assert os.path.isfile(path) + + with open(path, "rb") as script: + firstline = script.readline() + if not firstline.startswith(b"#!python"): + return False + exename = sys.executable.encode(sys.getfilesystemencoding()) + firstline = b"#!" + exename + os.linesep.encode("ascii") + rest = script.read() + with open(path, "wb") as script: + script.write(firstline) + script.write(rest) + return True + + +def wheel_root_is_purelib(metadata: Message) -> bool: + return metadata.get("Root-Is-Purelib", "").lower() == "true" + + +def get_entrypoints(dist: BaseDistribution) -> Tuple[Dict[str, str], Dict[str, str]]: + console_scripts = {} + gui_scripts = {} + for entry_point in dist.iter_entry_points(): + if entry_point.group == "console_scripts": + console_scripts[entry_point.name] = entry_point.value + elif entry_point.group == "gui_scripts": + gui_scripts[entry_point.name] = entry_point.value + return console_scripts, gui_scripts + + +def message_about_scripts_not_on_PATH(scripts: Sequence[str]) -> Optional[str]: + """Determine if any scripts are not on PATH and format a warning. + Returns a warning message if one or more scripts are not on PATH, + otherwise None. + """ + if not scripts: + return None + + # Group scripts by the path they were installed in + grouped_by_dir: Dict[str, Set[str]] = collections.defaultdict(set) + for destfile in scripts: + parent_dir = os.path.dirname(destfile) + script_name = os.path.basename(destfile) + grouped_by_dir[parent_dir].add(script_name) + + # We don't want to warn for directories that are on PATH. + not_warn_dirs = [ + os.path.normcase(os.path.normpath(i)).rstrip(os.sep) + for i in os.environ.get("PATH", "").split(os.pathsep) + ] + # If an executable sits with sys.executable, we don't warn for it. + # This covers the case of venv invocations without activating the venv. + not_warn_dirs.append( + os.path.normcase(os.path.normpath(os.path.dirname(sys.executable))) + ) + warn_for: Dict[str, Set[str]] = { + parent_dir: scripts + for parent_dir, scripts in grouped_by_dir.items() + if os.path.normcase(os.path.normpath(parent_dir)) not in not_warn_dirs + } + if not warn_for: + return None + + # Format a message + msg_lines = [] + for parent_dir, dir_scripts in warn_for.items(): + sorted_scripts: List[str] = sorted(dir_scripts) + if len(sorted_scripts) == 1: + start_text = "script {} is".format(sorted_scripts[0]) + else: + start_text = "scripts {} are".format( + ", ".join(sorted_scripts[:-1]) + " and " + sorted_scripts[-1] + ) + + msg_lines.append( + "The {} installed in '{}' which is not on PATH.".format( + start_text, parent_dir + ) + ) + + last_line_fmt = ( + "Consider adding {} to PATH or, if you prefer " + "to suppress this warning, use --no-warn-script-location." + ) + if len(msg_lines) == 1: + msg_lines.append(last_line_fmt.format("this directory")) + else: + msg_lines.append(last_line_fmt.format("these directories")) + + # Add a note if any directory starts with ~ + warn_for_tilde = any( + i[0] == "~" for i in os.environ.get("PATH", "").split(os.pathsep) if i + ) + if warn_for_tilde: + tilde_warning_msg = ( + "NOTE: The current PATH contains path(s) starting with `~`, " + "which may not be expanded by all applications." + ) + msg_lines.append(tilde_warning_msg) + + # Returns the formatted multiline message + return "\n".join(msg_lines) + + +def _normalized_outrows( + outrows: Iterable[InstalledCSVRow], +) -> List[Tuple[str, str, str]]: + """Normalize the given rows of a RECORD file. + + Items in each row are converted into str. Rows are then sorted to make + the value more predictable for tests. + + Each row is a 3-tuple (path, hash, size) and corresponds to a record of + a RECORD file (see PEP 376 and PEP 427 for details). For the rows + passed to this function, the size can be an integer as an int or string, + or the empty string. + """ + # Normally, there should only be one row per path, in which case the + # second and third elements don't come into play when sorting. + # However, in cases in the wild where a path might happen to occur twice, + # we don't want the sort operation to trigger an error (but still want + # determinism). Since the third element can be an int or string, we + # coerce each element to a string to avoid a TypeError in this case. + # For additional background, see-- + # https://github.com/pypa/pip/issues/5868 + return sorted( + (record_path, hash_, str(size)) for record_path, hash_, size in outrows + ) + + +def _record_to_fs_path(record_path: RecordPath, lib_dir: str) -> str: + return os.path.join(lib_dir, record_path) + + +def _fs_to_record_path(path: str, lib_dir: str) -> RecordPath: + # On Windows, do not handle relative paths if they belong to different + # logical disks + if os.path.splitdrive(path)[0].lower() == os.path.splitdrive(lib_dir)[0].lower(): + path = os.path.relpath(path, lib_dir) + + path = path.replace(os.path.sep, "/") + return cast("RecordPath", path) + + +def get_csv_rows_for_installed( + old_csv_rows: List[List[str]], + installed: Dict[RecordPath, RecordPath], + changed: Set[RecordPath], + generated: List[str], + lib_dir: str, +) -> List[InstalledCSVRow]: + """ + :param installed: A map from archive RECORD path to installation RECORD + path. + """ + installed_rows: List[InstalledCSVRow] = [] + for row in old_csv_rows: + if len(row) > 3: + logger.warning("RECORD line has more than three elements: %s", row) + old_record_path = cast("RecordPath", row[0]) + new_record_path = installed.pop(old_record_path, old_record_path) + if new_record_path in changed: + digest, length = rehash(_record_to_fs_path(new_record_path, lib_dir)) + else: + digest = row[1] if len(row) > 1 else "" + length = row[2] if len(row) > 2 else "" + installed_rows.append((new_record_path, digest, length)) + for f in generated: + path = _fs_to_record_path(f, lib_dir) + digest, length = rehash(f) + installed_rows.append((path, digest, length)) + return installed_rows + [ + (installed_record_path, "", "") for installed_record_path in installed.values() + ] + + +def get_console_script_specs(console: Dict[str, str]) -> List[str]: + """ + Given the mapping from entrypoint name to callable, return the relevant + console script specs. + """ + # Don't mutate caller's version + console = console.copy() + + scripts_to_generate = [] + + # Special case pip and setuptools to generate versioned wrappers + # + # The issue is that some projects (specifically, pip and setuptools) use + # code in setup.py to create "versioned" entry points - pip2.7 on Python + # 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into + # the wheel metadata at build time, and so if the wheel is installed with + # a *different* version of Python the entry points will be wrong. The + # correct fix for this is to enhance the metadata to be able to describe + # such versioned entry points, but that won't happen till Metadata 2.0 is + # available. + # In the meantime, projects using versioned entry points will either have + # incorrect versioned entry points, or they will not be able to distribute + # "universal" wheels (i.e., they will need a wheel per Python version). + # + # Because setuptools and pip are bundled with _ensurepip and virtualenv, + # we need to use universal wheels. So, as a stopgap until Metadata 2.0, we + # override the versioned entry points in the wheel and generate the + # correct ones. This code is purely a short-term measure until Metadata 2.0 + # is available. + # + # To add the level of hack in this section of code, in order to support + # ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment + # variable which will control which version scripts get installed. + # + # ENSUREPIP_OPTIONS=altinstall + # - Only pipX.Y and easy_install-X.Y will be generated and installed + # ENSUREPIP_OPTIONS=install + # - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note + # that this option is technically if ENSUREPIP_OPTIONS is set and is + # not altinstall + # DEFAULT + # - The default behavior is to install pip, pipX, pipX.Y, easy_install + # and easy_install-X.Y. + pip_script = console.pop("pip", None) + if pip_script: + if "ENSUREPIP_OPTIONS" not in os.environ: + scripts_to_generate.append("pip = " + pip_script) + + if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall": + scripts_to_generate.append( + "pip{} = {}".format(sys.version_info[0], pip_script) + ) + + scripts_to_generate.append(f"pip{get_major_minor_version()} = {pip_script}") + # Delete any other versioned pip entry points + pip_ep = [k for k in console if re.match(r"pip(\d+(\.\d+)?)?$", k)] + for k in pip_ep: + del console[k] + easy_install_script = console.pop("easy_install", None) + if easy_install_script: + if "ENSUREPIP_OPTIONS" not in os.environ: + scripts_to_generate.append("easy_install = " + easy_install_script) + + scripts_to_generate.append( + "easy_install-{} = {}".format( + get_major_minor_version(), easy_install_script + ) + ) + # Delete any other versioned easy_install entry points + easy_install_ep = [ + k for k in console if re.match(r"easy_install(-\d+\.\d+)?$", k) + ] + for k in easy_install_ep: + del console[k] + + # Generate the console entry points specified in the wheel + scripts_to_generate.extend(starmap("{} = {}".format, console.items())) + + return scripts_to_generate + + +class ZipBackedFile: + def __init__( + self, src_record_path: RecordPath, dest_path: str, zip_file: ZipFile + ) -> None: + self.src_record_path = src_record_path + self.dest_path = dest_path + self._zip_file = zip_file + self.changed = False + + def _getinfo(self) -> ZipInfo: + return self._zip_file.getinfo(self.src_record_path) + + def save(self) -> None: + # directory creation is lazy and after file filtering + # to ensure we don't install empty dirs; empty dirs can't be + # uninstalled. + parent_dir = os.path.dirname(self.dest_path) + ensure_dir(parent_dir) + + # When we open the output file below, any existing file is truncated + # before we start writing the new contents. This is fine in most + # cases, but can cause a segfault if pip has loaded a shared + # object (e.g. from pyopenssl through its vendored urllib3) + # Since the shared object is mmap'd an attempt to call a + # symbol in it will then cause a segfault. Unlinking the file + # allows writing of new contents while allowing the process to + # continue to use the old copy. + if os.path.exists(self.dest_path): + os.unlink(self.dest_path) + + zipinfo = self._getinfo() + + with self._zip_file.open(zipinfo) as f: + with open(self.dest_path, "wb") as dest: + shutil.copyfileobj(f, dest) + + if zip_item_is_executable(zipinfo): + set_extracted_file_to_default_mode_plus_executable(self.dest_path) + + +class ScriptFile: + def __init__(self, file: "File") -> None: + self._file = file + self.src_record_path = self._file.src_record_path + self.dest_path = self._file.dest_path + self.changed = False + + def save(self) -> None: + self._file.save() + self.changed = fix_script(self.dest_path) + + +class MissingCallableSuffix(InstallationError): + def __init__(self, entry_point: str) -> None: + super().__init__( + "Invalid script entry point: {} - A callable " + "suffix is required. Cf https://packaging.python.org/" + "specifications/entry-points/#use-for-scripts for more " + "information.".format(entry_point) + ) + + +def _raise_for_invalid_entrypoint(specification: str) -> None: + entry = get_export_entry(specification) + if entry is not None and entry.suffix is None: + raise MissingCallableSuffix(str(entry)) + + +class PipScriptMaker(ScriptMaker): + def make( + self, specification: str, options: Optional[Dict[str, Any]] = None + ) -> List[str]: + _raise_for_invalid_entrypoint(specification) + return super().make(specification, options) + + +def _install_wheel( + name: str, + wheel_zip: ZipFile, + wheel_path: str, + scheme: Scheme, + pycompile: bool = True, + warn_script_location: bool = True, + direct_url: Optional[DirectUrl] = None, + requested: bool = False, +) -> None: + """Install a wheel. + + :param name: Name of the project to install + :param wheel_zip: open ZipFile for wheel being installed + :param scheme: Distutils scheme dictating the install directories + :param req_description: String used in place of the requirement, for + logging + :param pycompile: Whether to byte-compile installed Python files + :param warn_script_location: Whether to check that scripts are installed + into a directory on PATH + :raises UnsupportedWheel: + * when the directory holds an unpacked wheel with incompatible + Wheel-Version + * when the .dist-info dir does not match the wheel + """ + info_dir, metadata = parse_wheel(wheel_zip, name) + + if wheel_root_is_purelib(metadata): + lib_dir = scheme.purelib + else: + lib_dir = scheme.platlib + + # Record details of the files moved + # installed = files copied from the wheel to the destination + # changed = files changed while installing (scripts #! line typically) + # generated = files newly generated during the install (script wrappers) + installed: Dict[RecordPath, RecordPath] = {} + changed: Set[RecordPath] = set() + generated: List[str] = [] + + def record_installed( + srcfile: RecordPath, destfile: str, modified: bool = False + ) -> None: + """Map archive RECORD paths to installation RECORD paths.""" + newpath = _fs_to_record_path(destfile, lib_dir) + installed[srcfile] = newpath + if modified: + changed.add(newpath) + + def is_dir_path(path: RecordPath) -> bool: + return path.endswith("/") + + def assert_no_path_traversal(dest_dir_path: str, target_path: str) -> None: + if not is_within_directory(dest_dir_path, target_path): + message = ( + "The wheel {!r} has a file {!r} trying to install" + " outside the target directory {!r}" + ) + raise InstallationError( + message.format(wheel_path, target_path, dest_dir_path) + ) + + def root_scheme_file_maker( + zip_file: ZipFile, dest: str + ) -> Callable[[RecordPath], "File"]: + def make_root_scheme_file(record_path: RecordPath) -> "File": + normed_path = os.path.normpath(record_path) + dest_path = os.path.join(dest, normed_path) + assert_no_path_traversal(dest, dest_path) + return ZipBackedFile(record_path, dest_path, zip_file) + + return make_root_scheme_file + + def data_scheme_file_maker( + zip_file: ZipFile, scheme: Scheme + ) -> Callable[[RecordPath], "File"]: + scheme_paths = {key: getattr(scheme, key) for key in SCHEME_KEYS} + + def make_data_scheme_file(record_path: RecordPath) -> "File": + normed_path = os.path.normpath(record_path) + try: + _, scheme_key, dest_subpath = normed_path.split(os.path.sep, 2) + except ValueError: + message = ( + "Unexpected file in {}: {!r}. .data directory contents" + " should be named like: '/'." + ).format(wheel_path, record_path) + raise InstallationError(message) + + try: + scheme_path = scheme_paths[scheme_key] + except KeyError: + valid_scheme_keys = ", ".join(sorted(scheme_paths)) + message = ( + "Unknown scheme key used in {}: {} (for file {!r}). .data" + " directory contents should be in subdirectories named" + " with a valid scheme key ({})" + ).format(wheel_path, scheme_key, record_path, valid_scheme_keys) + raise InstallationError(message) + + dest_path = os.path.join(scheme_path, dest_subpath) + assert_no_path_traversal(scheme_path, dest_path) + return ZipBackedFile(record_path, dest_path, zip_file) + + return make_data_scheme_file + + def is_data_scheme_path(path: RecordPath) -> bool: + return path.split("/", 1)[0].endswith(".data") + + paths = cast(List[RecordPath], wheel_zip.namelist()) + file_paths = filterfalse(is_dir_path, paths) + root_scheme_paths, data_scheme_paths = partition(is_data_scheme_path, file_paths) + + make_root_scheme_file = root_scheme_file_maker(wheel_zip, lib_dir) + files: Iterator[File] = map(make_root_scheme_file, root_scheme_paths) + + def is_script_scheme_path(path: RecordPath) -> bool: + parts = path.split("/", 2) + return len(parts) > 2 and parts[0].endswith(".data") and parts[1] == "scripts" + + other_scheme_paths, script_scheme_paths = partition( + is_script_scheme_path, data_scheme_paths + ) + + make_data_scheme_file = data_scheme_file_maker(wheel_zip, scheme) + other_scheme_files = map(make_data_scheme_file, other_scheme_paths) + files = chain(files, other_scheme_files) + + # Get the defined entry points + distribution = get_wheel_distribution( + FilesystemWheel(wheel_path), + canonicalize_name(name), + ) + console, gui = get_entrypoints(distribution) + + def is_entrypoint_wrapper(file: "File") -> bool: + # EP, EP.exe and EP-script.py are scripts generated for + # entry point EP by setuptools + path = file.dest_path + name = os.path.basename(path) + if name.lower().endswith(".exe"): + matchname = name[:-4] + elif name.lower().endswith("-script.py"): + matchname = name[:-10] + elif name.lower().endswith(".pya"): + matchname = name[:-4] + else: + matchname = name + # Ignore setuptools-generated scripts + return matchname in console or matchname in gui + + script_scheme_files: Iterator[File] = map( + make_data_scheme_file, script_scheme_paths + ) + script_scheme_files = filterfalse(is_entrypoint_wrapper, script_scheme_files) + script_scheme_files = map(ScriptFile, script_scheme_files) + files = chain(files, script_scheme_files) + + for file in files: + file.save() + record_installed(file.src_record_path, file.dest_path, file.changed) + + def pyc_source_file_paths() -> Generator[str, None, None]: + # We de-duplicate installation paths, since there can be overlap (e.g. + # file in .data maps to same location as file in wheel root). + # Sorting installation paths makes it easier to reproduce and debug + # issues related to permissions on existing files. + for installed_path in sorted(set(installed.values())): + full_installed_path = os.path.join(lib_dir, installed_path) + if not os.path.isfile(full_installed_path): + continue + if not full_installed_path.endswith(".py"): + continue + yield full_installed_path + + def pyc_output_path(path: str) -> str: + """Return the path the pyc file would have been written to.""" + return importlib.util.cache_from_source(path) + + # Compile all of the pyc files for the installed files + if pycompile: + with captured_stdout() as stdout: + with warnings.catch_warnings(): + warnings.filterwarnings("ignore") + for path in pyc_source_file_paths(): + success = compileall.compile_file(path, force=True, quiet=True) + if success: + pyc_path = pyc_output_path(path) + assert os.path.exists(pyc_path) + pyc_record_path = cast( + "RecordPath", pyc_path.replace(os.path.sep, "/") + ) + record_installed(pyc_record_path, pyc_path) + logger.debug(stdout.getvalue()) + + maker = PipScriptMaker(None, scheme.scripts) + + # Ensure old scripts are overwritten. + # See https://github.com/pypa/pip/issues/1800 + maker.clobber = True + + # Ensure we don't generate any variants for scripts because this is almost + # never what somebody wants. + # See https://bitbucket.org/pypa/distlib/issue/35/ + maker.variants = {""} + + # This is required because otherwise distlib creates scripts that are not + # executable. + # See https://bitbucket.org/pypa/distlib/issue/32/ + maker.set_mode = True + + # Generate the console and GUI entry points specified in the wheel + scripts_to_generate = get_console_script_specs(console) + + gui_scripts_to_generate = list(starmap("{} = {}".format, gui.items())) + + generated_console_scripts = maker.make_multiple(scripts_to_generate) + generated.extend(generated_console_scripts) + + generated.extend(maker.make_multiple(gui_scripts_to_generate, {"gui": True})) + + if warn_script_location: + msg = message_about_scripts_not_on_PATH(generated_console_scripts) + if msg is not None: + logger.warning(msg) + + generated_file_mode = 0o666 & ~current_umask() + + @contextlib.contextmanager + def _generate_file(path: str, **kwargs: Any) -> Generator[BinaryIO, None, None]: + with adjacent_tmp_file(path, **kwargs) as f: + yield f + os.chmod(f.name, generated_file_mode) + replace(f.name, path) + + dest_info_dir = os.path.join(lib_dir, info_dir) + + # Record pip as the installer + installer_path = os.path.join(dest_info_dir, "INSTALLER") + with _generate_file(installer_path) as installer_file: + installer_file.write(b"pip\n") + generated.append(installer_path) + + # Record the PEP 610 direct URL reference + if direct_url is not None: + direct_url_path = os.path.join(dest_info_dir, DIRECT_URL_METADATA_NAME) + with _generate_file(direct_url_path) as direct_url_file: + direct_url_file.write(direct_url.to_json().encode("utf-8")) + generated.append(direct_url_path) + + # Record the REQUESTED file + if requested: + requested_path = os.path.join(dest_info_dir, "REQUESTED") + with open(requested_path, "wb"): + pass + generated.append(requested_path) + + record_text = distribution.read_text("RECORD") + record_rows = list(csv.reader(record_text.splitlines())) + + rows = get_csv_rows_for_installed( + record_rows, + installed=installed, + changed=changed, + generated=generated, + lib_dir=lib_dir, + ) + + # Record details of all files installed + record_path = os.path.join(dest_info_dir, "RECORD") + + with _generate_file(record_path, **csv_io_kwargs("w")) as record_file: + # Explicitly cast to typing.IO[str] as a workaround for the mypy error: + # "writer" has incompatible type "BinaryIO"; expected "_Writer" + writer = csv.writer(cast("IO[str]", record_file)) + writer.writerows(_normalized_outrows(rows)) + + +@contextlib.contextmanager +def req_error_context(req_description: str) -> Generator[None, None, None]: + try: + yield + except InstallationError as e: + message = "For req: {}. {}".format(req_description, e.args[0]) + raise InstallationError(message) from e + + +def install_wheel( + name: str, + wheel_path: str, + scheme: Scheme, + req_description: str, + pycompile: bool = True, + warn_script_location: bool = True, + direct_url: Optional[DirectUrl] = None, + requested: bool = False, +) -> None: + with ZipFile(wheel_path, allowZip64=True) as z: + with req_error_context(req_description): + _install_wheel( + name=name, + wheel_zip=z, + wheel_path=wheel_path, + scheme=scheme, + pycompile=pycompile, + warn_script_location=warn_script_location, + direct_url=direct_url, + requested=requested, + ) diff --git a/shared/package-files/6b/6b93155d285091bd94521e612625f54bf51a2c9dd1ceaa7620a07d65fb94d924/indexes.pyi b/shared/package-files/6b/6b93155d285091bd94521e612625f54bf51a2c9dd1ceaa7620a07d65fb94d924/indexes.pyi new file mode 100644 index 0000000000000000000000000000000000000000..99db1146bdcdb42356c03e35b08fd096189e7454 --- /dev/null +++ b/shared/package-files/6b/6b93155d285091bd94521e612625f54bf51a2c9dd1ceaa7620a07d65fb94d924/indexes.pyi @@ -0,0 +1,39 @@ +from typing import Any, Optional + +class IndexMeta(type): + def __init__(self, name, bases, attrs) -> None: ... + +class Index(metaclass=IndexMeta): + Meta: Any + def __init__(self) -> None: ... + @classmethod + def count(cls, hash_key, consistent_read: bool = ..., **filters) -> int: ... + @classmethod + def query( + cls, + hash_key, + scan_index_forward: Optional[Any] = ..., + consistent_read: bool = ..., + limit: Optional[Any] = ..., + last_evaluated_key: Optional[Any] = ..., + attributes_to_get: Optional[Any] = ..., + **filters, + ): ... + +class GlobalSecondaryIndex(Index): ... +class LocalSecondaryIndex(Index): ... + +class Projection(object): + projection_type: Any + non_key_attributes: Any + +class KeysOnlyProjection(Projection): + projection_type: Any + +class IncludeProjection(Projection): + projection_type: Any + non_key_attributes: Any + def __init__(self, non_attr_keys: Optional[Any] = ...) -> None: ... + +class AllProjection(Projection): + projection_type: Any diff --git a/shared/package-files/6b/6b94824c2074c073c902e66d823d3838c2a8c9cdd2283c239e37c338d21b619a/iterator.h b/shared/package-files/6b/6b94824c2074c073c902e66d823d3838c2a8c9cdd2283c239e37c338d21b619a/iterator.h new file mode 100644 index 0000000000000000000000000000000000000000..82091b59e046a72b5906301ab0835379de9bdee5 --- /dev/null +++ b/shared/package-files/6b/6b94824c2074c073c902e66d823d3838c2a8c9cdd2283c239e37c338d21b619a/iterator.h @@ -0,0 +1,178 @@ +#pragma once + +#include +#include + +#include + +#include +#include +#include +#include +#include + +namespace torch { +namespace data { +namespace detail { +// For increased safety and more separated logic, this implementation of +// `Iterator` consists of a `ValidIterator` and a `SentinelIterator`. A +// `ValidIterator` yields new batches until the `DataLoader` is exhausted. While +// the `DataLoader` is not exhausted, `ValidIterator`s compare equal if they are +// the same object. When the `ValidIterator` becomes exhausted, it compares +// equal to the `SentinelIterator`, but not before. Half the code here is to +// implement double dispatch for the comparison. Got damnit, C++. + +template +struct ValidIterator; + +template +struct SentinelIterator; + +/// Base class for the `ValidIterator` and `SentinelIterator` +template +struct IteratorImpl { + virtual ~IteratorImpl() = default; + virtual void next() = 0; + virtual Batch& get() = 0; + virtual bool operator==(const IteratorImpl& other) const = 0; + virtual bool operator==(const ValidIterator& other) const = 0; + virtual bool operator==(const SentinelIterator& other) const = 0; +}; + +template +struct ValidIterator : public IteratorImpl { + using BatchProducer = std::function()>; + + explicit ValidIterator(BatchProducer next_batch) + : next_batch_(std::move(next_batch)) {} + + /// Fetches the next batch. + void next() override { + // If we didn't get the very first batch yet, get it now. + lazy_initialize(); + TORCH_CHECK( + batch_.has_value(), "Attempted to increment iterator past the end"); + // Increment to the next batch. + batch_ = next_batch_(); + } + + /// Returns the current batch. The precondition for this operation to not + /// throw an exception is that it has been compared to the `SentinelIterator` + /// and did not compare equal. + Batch& get() override { + // If we didn't get the very first batch yet, get it now. + lazy_initialize(); + TORCH_CHECK( + batch_.has_value(), + "Attempted to dereference iterator that was past the end"); + return batch_.value(); + } + + /// Does double dispatch. + bool operator==(const IteratorImpl& other) const override { + return other == *this; + } + + /// A `ValidIterator` is equal to the `SentinelIterator` iff. the + /// `ValidIterator` has reached the end of the dataloader. + bool operator==(const SentinelIterator& /* unused */) const override { + lazy_initialize(); + return !batch_; + } + + /// Returns true if the memory address of `other` equals that of `this`. + bool operator==(const ValidIterator& other) const override { + return &other == this; + } + + /// Gets the very first batch if it has not yet been fetched. + void lazy_initialize() const { + if (!initialized_) { + batch_ = next_batch_(); + initialized_ = true; + } + } + + BatchProducer next_batch_; + mutable optional batch_; + mutable bool initialized_ = false; +}; + +template +struct SentinelIterator : public IteratorImpl { + void next() override { + AT_ERROR( + "Incrementing the DataLoader's past-the-end iterator is not allowed"); + } + + Batch& get() override { + AT_ERROR( + "Dereferencing the DataLoader's past-the-end iterator is not allowed"); + } + + /// Does double dispatch. + bool operator==(const IteratorImpl& other) const override { + return other == *this; + } + + /// Calls the comparison operator between `ValidIterator` and + /// `SentinelIterator`. + bool operator==(const ValidIterator& other) const override { + return other == *this; + } + + /// Sentinel iterators always compare equal. + bool operator==(const SentinelIterator& other) const override { + return true; + } +}; +} // namespace detail + +template +class Iterator { + public: + // Type aliases to make the class recognized as a proper iterator. + using difference_type = std::ptrdiff_t; + using value_type = Batch; + using pointer = Batch*; + using reference = Batch&; + using iterator_category = std::input_iterator_tag; + + explicit Iterator(std::unique_ptr> impl) + : impl_(std::move(impl)) {} + + /// Increments the iterator. + /// Only permitted for valid iterators (not past the end). + Iterator& operator++() { + impl_->next(); + return *this; + } + + /// Returns the current batch. + /// Only permitted for valid iterators (not past the end). + Batch& operator*() { + return impl_->get(); + } + + /// Returns a pointer to the current batch. + /// Only permitted for valid iterators (not past the end). + Batch* operator->() { + return &impl_->get(); + } + + /// Compares two iterators for equality. + bool operator==(const Iterator& other) const { + return *impl_ == *other.impl_; + } + + /// Compares two iterators for inequality. + bool operator!=(const Iterator& other) const { + return !(*this == other); + } + + private: + /// Points either to a `ValidIterator` or to a `SentinelIterator`. + std::shared_ptr> impl_; +}; +} // namespace data +} // namespace torch diff --git a/shared/package-files/6b/6b96d9bf75892b570003ead72f3d96460bd646bfcaacd4a1cf5868dfb67bde70/dist.pyi b/shared/package-files/6b/6b96d9bf75892b570003ead72f3d96460bd646bfcaacd4a1cf5868dfb67bde70/dist.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d3acdafbd5b19f94ccc5b01410fa0d82133cd099 --- /dev/null +++ b/shared/package-files/6b/6b96d9bf75892b570003ead72f3d96460bd646bfcaacd4a1cf5868dfb67bde70/dist.pyi @@ -0,0 +1,58 @@ +from _typeshed import AnyPath, SupportsWrite +from distutils.cmd import Command +from typing import IO, Any, Dict, Iterable, List, Mapping, Optional, Tuple, Type, Union + +class DistributionMetadata: + def __init__(self, path: Optional[Union[int, AnyPath]] = ...) -> None: ... + name: Optional[str] + version: Optional[str] + author: Optional[str] + author_email: Optional[str] + maintainer: Optional[str] + maintainer_email: Optional[str] + url: Optional[str] + license: Optional[str] + description: Optional[str] + long_description: Optional[str] + keywords: Optional[Union[str, List[str]]] + platforms: Optional[Union[str, List[str]]] + classifiers: Optional[Union[str, List[str]]] + download_url: Optional[str] + provides: Optional[List[str]] + requires: Optional[List[str]] + obsoletes: Optional[List[str]] + def read_pkg_file(self, file: IO[str]) -> None: ... + def write_pkg_info(self, base_dir: str) -> None: ... + def write_pkg_file(self, file: SupportsWrite[str]) -> None: ... + def get_name(self) -> str: ... + def get_version(self) -> str: ... + def get_fullname(self) -> str: ... + def get_author(self) -> str: ... + def get_author_email(self) -> str: ... + def get_maintainer(self) -> str: ... + def get_maintainer_email(self) -> str: ... + def get_contact(self) -> str: ... + def get_contact_email(self) -> str: ... + def get_url(self) -> str: ... + def get_license(self) -> str: ... + def get_licence(self) -> str: ... + def get_description(self) -> str: ... + def get_long_description(self) -> str: ... + def get_keywords(self) -> Union[str, List[str]]: ... + def get_platforms(self) -> Union[str, List[str]]: ... + def get_classifiers(self) -> Union[str, List[str]]: ... + def get_download_url(self) -> str: ... + def get_requires(self) -> List[str]: ... + def set_requires(self, value: Iterable[str]) -> None: ... + def get_provides(self) -> List[str]: ... + def set_provides(self, value: Iterable[str]) -> None: ... + def get_obsoletes(self) -> List[str]: ... + def set_obsoletes(self, value: Iterable[str]) -> None: ... + +class Distribution: + cmdclass: Dict[str, Type[Command]] + metadata: DistributionMetadata + def __init__(self, attrs: Optional[Mapping[str, Any]] = ...) -> None: ... + def get_option_dict(self, command: str) -> Dict[str, Tuple[str, str]]: ... + def parse_config_files(self, filenames: Optional[Iterable[str]] = ...) -> None: ... + def get_command_obj(self, command: str, create: bool = ...) -> Optional[Command]: ... diff --git a/shared/package-files/6b/6b97320c201207413566e04a2b7ddd648ed905caf6ac84a48965396a586325b0/utils.pyi b/shared/package-files/6b/6b97320c201207413566e04a2b7ddd648ed905caf6ac84a48965396a586325b0/utils.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9559abbced7bcdcd518dfed38ef1916fccda55e4 --- /dev/null +++ b/shared/package-files/6b/6b97320c201207413566e04a2b7ddd648ed905caf6ac84a48965396a586325b0/utils.pyi @@ -0,0 +1,8 @@ +from typing import Any + +HIREDIS_AVAILABLE: Any + +def from_url(url, db=..., **kwargs): ... +def pipeline(redis_obj): ... + +class dummy: ... diff --git a/shared/package-files/6b/6b9fcd6e73a76f6cf83182ccde65d2464d28307f827e4ace6bb9733492a3372d/macros.h b/shared/package-files/6b/6b9fcd6e73a76f6cf83182ccde65d2464d28307f827e4ace6bb9733492a3372d/macros.h new file mode 100644 index 0000000000000000000000000000000000000000..55bc1eeb1d2d5c6f93e94fadb5bc1c03cbce34b7 --- /dev/null +++ b/shared/package-files/6b/6b9fcd6e73a76f6cf83182ccde65d2464d28307f827e4ace6bb9733492a3372d/macros.h @@ -0,0 +1,252 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#define ARROW_EXPAND(x) x +#define ARROW_STRINGIFY(x) #x +#define ARROW_CONCAT(x, y) x##y + +// From Google gutil +#ifndef ARROW_DISALLOW_COPY_AND_ASSIGN +# define ARROW_DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName&) = delete; \ + void operator=(const TypeName&) = delete +#endif + +#ifndef ARROW_DEFAULT_MOVE_AND_ASSIGN +# define ARROW_DEFAULT_MOVE_AND_ASSIGN(TypeName) \ + TypeName(TypeName&&) = default; \ + TypeName& operator=(TypeName&&) = default +#endif + +// With ARROW_PREDICT_FALSE, GCC and clang can be told that a certain branch is +// not likely to be taken (for instance, a CHECK failure), and use that information in +// static analysis. Giving the compiler this information can affect the generated code +// layout in the absence of better information (i.e. -fprofile-arcs). [1] explains how +// this feature can be used to improve code generation. It was written as a positive +// comment to a negative article about the use of these annotations. +// +// ARROW_COMPILER_ASSUME allows the compiler to assume that a given expression is +// true, without evaluating it, and to optimise based on this assumption [2]. If this +// condition is violated at runtime, the behavior is undefined. This can be useful to +// generate both faster and smaller code in compute kernels. +// +// IMPORTANT: Different optimisers are likely to react differently to this annotation! +// It should be used with care when we can prove by some means that the assumption +// is (1) guaranteed to always hold and (2) is useful for optimization [3]. If the +// assumption is pessimistic, it might even block the compiler from decisions that +// could lead to better code [4]. If you have a good intuition for what the compiler +// can do with assumptions [5], you can use this macro to guide it and end up with +// results you would only get with more complex code transformations. +// `clang -S -emit-llvm` can be used to check how the generated code changes with +// your specific use of this macro. +// +// [1] https://lobste.rs/s/uwgtkt/don_t_use_likely_unlikely_attributes#c_xi3wmc +// [2] "Portable assumptions" +// https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p1774r4.pdf +// [3] "Assertions Are Pessimistic, Assumptions Are Optimistic" +// https://blog.regehr.org/archives/1096 +// [4] https://discourse.llvm.org/t/llvm-assume-blocks-optimization/71609 +// [5] J. Doerfert et al. 2019. "Performance Exploration Through Optimistic Static +// Program Annotations". https://github.com/jdoerfert/PETOSPA/blob/master/ISC19.pdf +#define ARROW_UNUSED(x) (void)(x) +#ifdef ARROW_WARN_DOCUMENTATION +# define ARROW_ARG_UNUSED(x) x +#else +# define ARROW_ARG_UNUSED(x) +#endif +#if defined(__GNUC__) // GCC and compatible compilers (clang, Intel ICC) +# define ARROW_NORETURN __attribute__((noreturn)) +# define ARROW_NOINLINE __attribute__((noinline)) +# define ARROW_FORCE_INLINE __attribute__((always_inline)) +# define ARROW_PREDICT_FALSE(x) (__builtin_expect(!!(x), 0)) +# define ARROW_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1)) +# define ARROW_RESTRICT __restrict +# if defined(__clang__) // clang-specific +# define ARROW_COMPILER_ASSUME(expr) __builtin_assume(expr) +# else // GCC-specific +# if __GNUC__ >= 13 +# define ARROW_COMPILER_ASSUME(expr) __attribute__((assume(expr))) +# else +// GCC does not have a built-in assume intrinsic before GCC 13, so we use an +// if statement and __builtin_unreachable() to achieve the same effect [2]. +// Unlike clang's __builtin_assume and C++23's [[assume(expr)]], using this +// on GCC won't warn about side-effects in the expression, so make sure expr +// is side-effect free when working with GCC versions before 13 (Jan-2024), +// otherwise clang/MSVC builds will fail in CI. +# define ARROW_COMPILER_ASSUME(expr) \ + if (expr) { \ + } else { \ + __builtin_unreachable(); \ + } +# endif // __GNUC__ >= 13 +# endif +#elif defined(_MSC_VER) // MSVC +# define ARROW_NORETURN __declspec(noreturn) +# define ARROW_NOINLINE __declspec(noinline) +# define ARROW_FORCE_INLINE __forceinline +# define ARROW_PREDICT_FALSE(x) (x) +# define ARROW_PREDICT_TRUE(x) (x) +# define ARROW_RESTRICT __restrict +# define ARROW_COMPILER_ASSUME(expr) __assume(expr) +#else +# define ARROW_NORETURN +# define ARROW_NOINLINE +# define ARROW_FORCE_INLINE +# define ARROW_PREDICT_FALSE(x) (x) +# define ARROW_PREDICT_TRUE(x) (x) +# define ARROW_RESTRICT +# define ARROW_COMPILER_ASSUME(expr) +#endif + +// ---------------------------------------------------------------------- +// C++/CLI support macros (see ARROW-1134) + +#ifndef NULLPTR + +# ifdef __cplusplus_cli +# define NULLPTR __nullptr +# else +# define NULLPTR nullptr +# endif + +#endif // ifndef NULLPTR + +// ---------------------------------------------------------------------- + +// clang-format off +// [[deprecated]] is only available in C++14, use this for the time being +// This macro takes an optional deprecation message +#ifdef __COVERITY__ +# define ARROW_DEPRECATED(...) +#else +# define ARROW_DEPRECATED(...) [[deprecated(__VA_ARGS__)]] +#endif + +#ifdef __COVERITY__ +# define ARROW_DEPRECATED_ENUM_VALUE(...) +#else +# define ARROW_DEPRECATED_ENUM_VALUE(...) [[deprecated(__VA_ARGS__)]] +#endif + +// clang-format on + +// Macros to disable deprecation warnings + +#ifdef __clang__ +# define ARROW_SUPPRESS_DEPRECATION_WARNING \ + _Pragma("clang diagnostic push"); \ + _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") +# define ARROW_UNSUPPRESS_DEPRECATION_WARNING _Pragma("clang diagnostic pop") +#elif defined(__GNUC__) +# define ARROW_SUPPRESS_DEPRECATION_WARNING \ + _Pragma("GCC diagnostic push"); \ + _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +# define ARROW_UNSUPPRESS_DEPRECATION_WARNING _Pragma("GCC diagnostic pop") +#elif defined(_MSC_VER) +# define ARROW_SUPPRESS_DEPRECATION_WARNING \ + __pragma(warning(push)) __pragma(warning(disable : 4996)) +# define ARROW_UNSUPPRESS_DEPRECATION_WARNING __pragma(warning(pop)) +#else +# define ARROW_SUPPRESS_DEPRECATION_WARNING +# define ARROW_UNSUPPRESS_DEPRECATION_WARNING +#endif + +// ---------------------------------------------------------------------- + +// Macros to disable warnings about undeclared global functions +#if defined(__GNUC__) +# define ARROW_SUPPRESS_MISSING_DECLARATIONS_WARNING \ + _Pragma("GCC diagnostic push"); \ + _Pragma("GCC diagnostic ignored \"-Wmissing-declarations\"") +# define ARROW_UNSUPPRESS_MISSING_DECLARATIONS_WARNING _Pragma("GCC diagnostic pop") +#else +# define ARROW_SUPPRESS_MISSING_DECLARATIONS_WARNING +# define ARROW_UNSUPPRESS_MISSING_DECLARATIONS_WARNING +#endif + +// ---------------------------------------------------------------------- + +// macros to disable padding +// these macros are portable across different compilers and platforms +//[https://github.com/google/flatbuffers/blob/master/include/flatbuffers/flatbuffers.h#L1355] +#if !defined(MANUALLY_ALIGNED_STRUCT) +# if defined(_MSC_VER) +# define MANUALLY_ALIGNED_STRUCT(alignment) \ + __pragma(pack(1)); \ + struct __declspec(align(alignment)) +# define STRUCT_END(name, size) \ + __pragma(pack()); \ + static_assert(sizeof(name) == size, "compiler breaks packing rules") +# elif defined(__GNUC__) || defined(__clang__) +# define MANUALLY_ALIGNED_STRUCT(alignment) \ + _Pragma("pack(1)") struct __attribute__((aligned(alignment))) +# define STRUCT_END(name, size) \ + _Pragma("pack()") static_assert(sizeof(name) == size, \ + "compiler breaks packing rules") +# else +# error Unknown compiler, please define structure alignment macros +# endif +#endif // !defined(MANUALLY_ALIGNED_STRUCT) + +// ---------------------------------------------------------------------- +// Convenience macro disabling a particular UBSan check in a function + +#if defined(__clang__) +# define ARROW_DISABLE_UBSAN(feature) __attribute__((no_sanitize(feature))) +#else +# define ARROW_DISABLE_UBSAN(feature) +#endif + +// ---------------------------------------------------------------------- +// Machine information + +#if INTPTR_MAX == INT64_MAX +# define ARROW_BITNESS 64 +#elif INTPTR_MAX == INT32_MAX +# define ARROW_BITNESS 32 +#else +# error Unexpected INTPTR_MAX +#endif + +// ---------------------------------------------------------------------- +// From googletest +// (also in parquet-cpp) + +// When you need to test the private or protected members of a class, +// use the FRIEND_TEST macro to declare your tests as friends of the +// class. For example: +// +// class MyClass { +// private: +// void MyMethod(); +// FRIEND_TEST(MyClassTest, MyMethod); +// }; +// +// class MyClassTest : public testing::Test { +// // ... +// }; +// +// TEST_F(MyClassTest, MyMethod) { +// // Can call MyClass::MyMethod() here. +// } + +#define FRIEND_TEST(test_case_name, test_name) \ + friend class test_case_name##_##test_name##_Test diff --git a/shared/package-files/6b/6ba21402e8c38c6a5a16a893cc6afce5e0c3f25e9b6962cfacce5836f6fa83d2/stackplot.py b/shared/package-files/6b/6ba21402e8c38c6a5a16a893cc6afce5e0c3f25e9b6962cfacce5836f6fa83d2/stackplot.py new file mode 100644 index 0000000000000000000000000000000000000000..bd11558b0da99ad0774ea85b2996e699c6e15717 --- /dev/null +++ b/shared/package-files/6b/6ba21402e8c38c6a5a16a893cc6afce5e0c3f25e9b6962cfacce5836f6fa83d2/stackplot.py @@ -0,0 +1,147 @@ +""" +Stacked area plot for 1D arrays inspired by Douglas Y'barbo's stackoverflow +answer: +https://stackoverflow.com/q/2225995/ + +(https://stackoverflow.com/users/66549/doug) +""" + +import itertools + +import numpy as np + +from matplotlib import _api + +__all__ = ['stackplot'] + + +def stackplot(axes, x, *args, + labels=(), colors=None, hatch=None, baseline='zero', + **kwargs): + """ + Draw a stacked area plot or a streamgraph. + + Parameters + ---------- + x : (N,) array-like + + y : (M, N) array-like + The data can be either stacked or unstacked. Each of the following + calls is legal:: + + stackplot(x, y) # where y has shape (M, N) e.g. y = [y1, y2, y3, y4] + stackplot(x, y1, y2, y3, y4) # where y1, y2, y3, y4 have length N + + baseline : {'zero', 'sym', 'wiggle', 'weighted_wiggle'} + Method used to calculate the baseline: + + - ``'zero'``: Constant zero baseline, i.e. a simple stacked plot. + - ``'sym'``: Symmetric around zero and is sometimes called + 'ThemeRiver'. + - ``'wiggle'``: Minimizes the sum of the squared slopes. + - ``'weighted_wiggle'``: Does the same but weights to account for + size of each layer. It is also called 'Streamgraph'-layout. More + details can be found at http://leebyron.com/streamgraph/. + + labels : list of str, optional + A sequence of labels to assign to each data series. If unspecified, + then no labels will be applied to artists. + + colors : list of :mpltype:`color`, optional + A sequence of colors to be cycled through and used to color the stacked + areas. The sequence need not be exactly the same length as the number + of provided *y*, in which case the colors will repeat from the + beginning. + + If not specified, the colors from the Axes property cycle will be used. + + hatch : list of str, default: None + A sequence of hatching styles. See + :doc:`/gallery/shapes_and_collections/hatch_style_reference`. + The sequence will be cycled through for filling the + stacked areas from bottom to top. + It need not be exactly the same length as the number + of provided *y*, in which case the styles will repeat from the + beginning. + + .. versionadded:: 3.9 + Support for list input + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + All other keyword arguments are passed to `.Axes.fill_between`. + + Returns + ------- + list of `.PolyCollection` + A list of `.PolyCollection` instances, one for each element in the + stacked area plot. + """ + + y = np.vstack(args) + + labels = iter(labels) + if colors is not None: + colors = itertools.cycle(colors) + else: + colors = (axes._get_lines.get_next_color() for _ in y) + + if hatch is None or isinstance(hatch, str): + hatch = itertools.cycle([hatch]) + else: + hatch = itertools.cycle(hatch) + + # Assume data passed has not been 'stacked', so stack it here. + # We'll need a float buffer for the upcoming calculations. + stack = np.cumsum(y, axis=0, dtype=np.promote_types(y.dtype, np.float32)) + + _api.check_in_list(['zero', 'sym', 'wiggle', 'weighted_wiggle'], + baseline=baseline) + if baseline == 'zero': + first_line = 0. + + elif baseline == 'sym': + first_line = -np.sum(y, 0) * 0.5 + stack += first_line[None, :] + + elif baseline == 'wiggle': + m = y.shape[0] + first_line = (y * (m - 0.5 - np.arange(m)[:, None])).sum(0) + first_line /= -m + stack += first_line + + elif baseline == 'weighted_wiggle': + total = np.sum(y, 0) + # multiply by 1/total (or zero) to avoid infinities in the division: + inv_total = np.zeros_like(total) + mask = total > 0 + inv_total[mask] = 1.0 / total[mask] + increase = np.hstack((y[:, 0:1], np.diff(y))) + below_size = total - stack + below_size += 0.5 * y + move_up = below_size * inv_total + move_up[:, 0] = 0.5 + center = (move_up - 0.5) * increase + center = np.cumsum(center.sum(0)) + first_line = center - 0.5 * total + stack += first_line + + # Color between x = 0 and the first array. + coll = axes.fill_between(x, first_line, stack[0, :], + facecolor=next(colors), + hatch=next(hatch), + label=next(labels, None), + **kwargs) + coll.sticky_edges.y[:] = [0] + r = [coll] + + # Color between array i-1 and array i + for i in range(len(y) - 1): + r.append(axes.fill_between(x, stack[i, :], stack[i + 1, :], + facecolor=next(colors), + hatch=next(hatch), + label=next(labels, None), + **kwargs)) + return r diff --git a/shared/package-files/6b/6ba241a80ac5d78010046d1c95d12e7f30285854b7eb78493644a503efcdcb83/_cast_Byte_ops.h b/shared/package-files/6b/6ba241a80ac5d78010046d1c95d12e7f30285854b7eb78493644a503efcdcb83/_cast_Byte_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..641a371ea186c40cf734240bcbf12c598d562c45 --- /dev/null +++ b/shared/package-files/6b/6ba241a80ac5d78010046d1c95d12e7f30285854b7eb78493644a503efcdcb83/_cast_Byte_ops.h @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _cast_Byte { + using schema = at::Tensor (const at::Tensor &, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_cast_Byte") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_cast_Byte(Tensor self, bool non_blocking=False) -> Tensor") + static at::Tensor call(const at::Tensor & self, bool non_blocking); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, bool non_blocking); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/6b/6ba3e960d02855be0ab40725251f18f09e08d5570d6752c8c7f48021d4368699/__init__.py b/shared/package-files/6b/6ba3e960d02855be0ab40725251f18f09e08d5570d6752c8c7f48021d4368699/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3e2f9a431b45c7ff1b0357dcb0e24a508a38a87 --- /dev/null +++ b/shared/package-files/6b/6ba3e960d02855be0ab40725251f18f09e08d5570d6752c8c7f48021d4368699/__init__.py @@ -0,0 +1,3 @@ +from .types import * +from .types_base import * +from .signatures import * # isort:skip diff --git a/shared/package-files/6b/6bafa95a3292a2fecfd3fad8d8be990164de5a80176d6c7c3da058ee0416c7ab/communicability_alg.py b/shared/package-files/6b/6bafa95a3292a2fecfd3fad8d8be990164de5a80176d6c7c3da058ee0416c7ab/communicability_alg.py new file mode 100644 index 0000000000000000000000000000000000000000..1d2161dee5d086d53743512c4d02c6c16a71cdd1 --- /dev/null +++ b/shared/package-files/6b/6bafa95a3292a2fecfd3fad8d8be990164de5a80176d6c7c3da058ee0416c7ab/communicability_alg.py @@ -0,0 +1,161 @@ +""" +Communicability. +""" +import networkx as nx +from networkx.utils import not_implemented_for + +__all__ = ["communicability", "communicability_exp"] + + +@not_implemented_for("directed") +@not_implemented_for("multigraph") +def communicability(G): + r"""Returns communicability between all pairs of nodes in G. + + The communicability between pairs of nodes in G is the sum of + walks of different lengths starting at node u and ending at node v. + + Parameters + ---------- + G: graph + + Returns + ------- + comm: dictionary of dictionaries + Dictionary of dictionaries keyed by nodes with communicability + as the value. + + Raises + ------ + NetworkXError + If the graph is not undirected and simple. + + See Also + -------- + communicability_exp: + Communicability between all pairs of nodes in G using spectral + decomposition. + communicability_betweenness_centrality: + Communicability betweenness centrality for each node in G. + + Notes + ----- + This algorithm uses a spectral decomposition of the adjacency matrix. + Let G=(V,E) be a simple undirected graph. Using the connection between + the powers of the adjacency matrix and the number of walks in the graph, + the communicability between nodes `u` and `v` based on the graph spectrum + is [1]_ + + .. math:: + C(u,v)=\sum_{j=1}^{n}\phi_{j}(u)\phi_{j}(v)e^{\lambda_{j}}, + + where `\phi_{j}(u)` is the `u\rm{th}` element of the `j\rm{th}` orthonormal + eigenvector of the adjacency matrix associated with the eigenvalue + `\lambda_{j}`. + + References + ---------- + .. [1] Ernesto Estrada, Naomichi Hatano, + "Communicability in complex networks", + Phys. Rev. E 77, 036111 (2008). + https://arxiv.org/abs/0707.0756 + + Examples + -------- + >>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)]) + >>> c = nx.communicability(G) + """ + import numpy as np + + nodelist = list(G) # ordering of nodes in matrix + A = nx.to_numpy_array(G, nodelist) + # convert to 0-1 matrix + A[A != 0.0] = 1 + w, vec = np.linalg.eigh(A) + expw = np.exp(w) + mapping = dict(zip(nodelist, range(len(nodelist)))) + c = {} + # computing communicabilities + for u in G: + c[u] = {} + for v in G: + s = 0 + p = mapping[u] + q = mapping[v] + for j in range(len(nodelist)): + s += vec[:, j][p] * vec[:, j][q] * expw[j] + c[u][v] = float(s) + return c + + +@not_implemented_for("directed") +@not_implemented_for("multigraph") +def communicability_exp(G): + r"""Returns communicability between all pairs of nodes in G. + + Communicability between pair of node (u,v) of node in G is the sum of + walks of different lengths starting at node u and ending at node v. + + Parameters + ---------- + G: graph + + Returns + ------- + comm: dictionary of dictionaries + Dictionary of dictionaries keyed by nodes with communicability + as the value. + + Raises + ------ + NetworkXError + If the graph is not undirected and simple. + + See Also + -------- + communicability: + Communicability between pairs of nodes in G. + communicability_betweenness_centrality: + Communicability betweenness centrality for each node in G. + + Notes + ----- + This algorithm uses matrix exponentiation of the adjacency matrix. + + Let G=(V,E) be a simple undirected graph. Using the connection between + the powers of the adjacency matrix and the number of walks in the graph, + the communicability between nodes u and v is [1]_, + + .. math:: + C(u,v) = (e^A)_{uv}, + + where `A` is the adjacency matrix of G. + + References + ---------- + .. [1] Ernesto Estrada, Naomichi Hatano, + "Communicability in complex networks", + Phys. Rev. E 77, 036111 (2008). + https://arxiv.org/abs/0707.0756 + + Examples + -------- + >>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)]) + >>> c = nx.communicability_exp(G) + """ + import scipy as sp + import scipy.linalg # call as sp.linalg + + nodelist = list(G) # ordering of nodes in matrix + A = nx.to_numpy_array(G, nodelist) + # convert to 0-1 matrix + A[A != 0.0] = 1 + # communicability matrix + expA = sp.linalg.expm(A) + mapping = dict(zip(nodelist, range(len(nodelist)))) + c = {} + for u in G: + c[u] = {} + for v in G: + c[u][v] = float(expA[mapping[u], mapping[v]]) + return c diff --git a/shared/package-files/6b/6bb0859a7cfe3056d06dfa29fed02145400793b0496447daf4f95c5f62bc6346/test_kane4.py b/shared/package-files/6b/6bb0859a7cfe3056d06dfa29fed02145400793b0496447daf4f95c5f62bc6346/test_kane4.py new file mode 100644 index 0000000000000000000000000000000000000000..cce7ca5040524c4dc7a5a6be55e90afb139f552e --- /dev/null +++ b/shared/package-files/6b/6bb0859a7cfe3056d06dfa29fed02145400793b0496447daf4f95c5f62bc6346/test_kane4.py @@ -0,0 +1,115 @@ +from sympy.core.backend import (cos, sin, Matrix, symbols) +from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Point, + KanesMethod, Particle) + +def test_replace_qdots_in_force(): + # Test PR 16700 "Replaces qdots with us in force-list in kanes.py" + # The new functionality allows one to specify forces in qdots which will + # automatically be replaced with u:s which are defined by the kde supplied + # to KanesMethod. The test case is the double pendulum with interacting + # forces in the example of chapter 4.7 "CONTRIBUTING INTERACTION FORCES" + # in Ref. [1]. Reference list at end test function. + + q1, q2 = dynamicsymbols('q1, q2') + qd1, qd2 = dynamicsymbols('q1, q2', level=1) + u1, u2 = dynamicsymbols('u1, u2') + + l, m = symbols('l, m') + + N = ReferenceFrame('N') # Inertial frame + A = N.orientnew('A', 'Axis', (q1, N.z)) # Rod A frame + B = A.orientnew('B', 'Axis', (q2, N.z)) # Rod B frame + + O = Point('O') # Origo + O.set_vel(N, 0) + + P = O.locatenew('P', ( l * A.x )) # Point @ end of rod A + P.v2pt_theory(O, N, A) + + Q = P.locatenew('Q', ( l * B.x )) # Point @ end of rod B + Q.v2pt_theory(P, N, B) + + Ap = Particle('Ap', P, m) + Bp = Particle('Bp', Q, m) + + # The forces are specified below. sigma is the torsional spring stiffness + # and delta is the viscous damping coefficient acting between the two + # bodies. Here, we specify the viscous damper as function of qdots prior + # forming the kde. In more complex systems it not might be obvious which + # kde is most efficient, why it is convenient to specify viscous forces in + # qdots independently of the kde. + sig, delta = symbols('sigma, delta') + Ta = (sig * q2 + delta * qd2) * N.z + forces = [(A, Ta), (B, -Ta)] + + # Try different kdes. + kde1 = [u1 - qd1, u2 - qd2] + kde2 = [u1 - qd1, u2 - (qd1 + qd2)] + + KM1 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde1) + fr1, fstar1 = KM1.kanes_equations([Ap, Bp], forces) + + KM2 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde2) + fr2, fstar2 = KM2.kanes_equations([Ap, Bp], forces) + + # Check EOM for KM2: + # Mass and force matrix from p.6 in Ref. [2] with added forces from + # example of chapter 4.7 in [1] and without gravity. + forcing_matrix_expected = Matrix( [ [ m * l**2 * sin(q2) * u2**2 + sig * q2 + + delta * (u2 - u1)], + [ m * l**2 * sin(q2) * -u1**2 - sig * q2 + - delta * (u2 - u1)] ] ) + mass_matrix_expected = Matrix( [ [ 2 * m * l**2, m * l**2 * cos(q2) ], + [ m * l**2 * cos(q2), m * l**2 ] ] ) + + assert (KM2.mass_matrix.expand() == mass_matrix_expected.expand()) + assert (KM2.forcing.expand() == forcing_matrix_expected.expand()) + + # Check fr1 with reference fr_expected from [1] with u:s instead of qdots. + fr1_expected = Matrix([ 0, -(sig*q2 + delta * u2) ]) + assert fr1.expand() == fr1_expected.expand() + + # Check fr2 + fr2_expected = Matrix([sig * q2 + delta * (u2 - u1), + - sig * q2 - delta * (u2 - u1)]) + assert fr2.expand() == fr2_expected.expand() + + # Specifying forces in u:s should stay the same: + Ta = (sig * q2 + delta * u2) * N.z + forces = [(A, Ta), (B, -Ta)] + KM1 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde1) + fr1, fstar1 = KM1.kanes_equations([Ap, Bp], forces) + + assert fr1.expand() == fr1_expected.expand() + + Ta = (sig * q2 + delta * (u2-u1)) * N.z + forces = [(A, Ta), (B, -Ta)] + KM2 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde2) + fr2, fstar2 = KM2.kanes_equations([Ap, Bp], forces) + + assert fr2.expand() == fr2_expected.expand() + + # Test if we have a qubic qdot force: + Ta = (sig * q2 + delta * qd2**3) * N.z + forces = [(A, Ta), (B, -Ta)] + + KM1 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde1) + fr1, fstar1 = KM1.kanes_equations([Ap, Bp], forces) + + fr1_cubic_expected = Matrix([ 0, -(sig*q2 + delta * u2**3) ]) + + assert fr1.expand() == fr1_cubic_expected.expand() + + KM2 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde2) + fr2, fstar2 = KM2.kanes_equations([Ap, Bp], forces) + + fr2_cubic_expected = Matrix([sig * q2 + delta * (u2 - u1)**3, + - sig * q2 - delta * (u2 - u1)**3]) + + assert fr2.expand() == fr2_cubic_expected.expand() + + # References: + # [1] T.R. Kane, D. a Levinson, Dynamics Theory and Applications, 2005. + # [2] Arun K Banerjee, Flexible Multibody Dynamics:Efficient Formulations + # and Applications, John Wiley and Sons, Ltd, 2016. + # doi:http://dx.doi.org/10.1002/9781119015635. diff --git a/shared/package-files/6b/6bb180ff084b6ce892e16c5476d0eba8a39486c7eaab74cbd27921a8f71cbacb/test_equals.py b/shared/package-files/6b/6bb180ff084b6ce892e16c5476d0eba8a39486c7eaab74cbd27921a8f71cbacb/test_equals.py new file mode 100644 index 0000000000000000000000000000000000000000..87e2348e5fdb331d80061d184f41e1ab11bedcc3 --- /dev/null +++ b/shared/package-files/6b/6bb180ff084b6ce892e16c5476d0eba8a39486c7eaab74cbd27921a8f71cbacb/test_equals.py @@ -0,0 +1,36 @@ +import numpy as np + +from pandas import ( + IntervalIndex, + date_range, +) + + +class TestEquals: + def test_equals(self, closed): + expected = IntervalIndex.from_breaks(np.arange(5), closed=closed) + assert expected.equals(expected) + assert expected.equals(expected.copy()) + + assert not expected.equals(expected.astype(object)) + assert not expected.equals(np.array(expected)) + assert not expected.equals(list(expected)) + + assert not expected.equals([1, 2]) + assert not expected.equals(np.array([1, 2])) + assert not expected.equals(date_range("20130101", periods=2)) + + expected_name1 = IntervalIndex.from_breaks( + np.arange(5), closed=closed, name="foo" + ) + expected_name2 = IntervalIndex.from_breaks( + np.arange(5), closed=closed, name="bar" + ) + assert expected.equals(expected_name1) + assert expected_name1.equals(expected_name2) + + for other_closed in {"left", "right", "both", "neither"} - {closed}: + expected_other_closed = IntervalIndex.from_breaks( + np.arange(5), closed=other_closed + ) + assert not expected.equals(expected_other_closed) diff --git a/shared/package-files/6b/6bb370c0ed1ffd3ae1ed84572c86e0a0e0055884e0edda8786227ccb76aad7ef/dku7103-sna b/shared/package-files/6b/6bb370c0ed1ffd3ae1ed84572c86e0a0e0055884e0edda8786227ccb76aad7ef/dku7103-sna new file mode 100644 index 0000000000000000000000000000000000000000..17cfc916e65ab4842180396ee9710ecea7a47a29 Binary files /dev/null and b/shared/package-files/6b/6bb370c0ed1ffd3ae1ed84572c86e0a0e0055884e0edda8786227ccb76aad7ef/dku7103-sna differ diff --git a/shared/package-files/6b/6bb370c0ed1ffd3ae1ed84572c86e0a0e0055884e0edda8786227ccb76aad7ef/tws2103-sna b/shared/package-files/6b/6bb370c0ed1ffd3ae1ed84572c86e0a0e0055884e0edda8786227ccb76aad7ef/tws2103-sna new file mode 100644 index 0000000000000000000000000000000000000000..17cfc916e65ab4842180396ee9710ecea7a47a29 Binary files /dev/null and b/shared/package-files/6b/6bb370c0ed1ffd3ae1ed84572c86e0a0e0055884e0edda8786227ccb76aad7ef/tws2103-sna differ diff --git a/shared/package-files/6b/6bb3872b315e8cd54d82c99ccfc5e1dfa7d31633951a9f698f1cca483c685e79/_fake_quantize_learnable_per_channel_affine_cuda_dispatch.h b/shared/package-files/6b/6bb3872b315e8cd54d82c99ccfc5e1dfa7d31633951a9f698f1cca483c685e79/_fake_quantize_learnable_per_channel_affine_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..c3b7af9484fd7f48a4cb60df71b3f8aa6a3e3994 --- /dev/null +++ b/shared/package-files/6b/6bb3872b315e8cd54d82c99ccfc5e1dfa7d31633951a9f698f1cca483c685e79/_fake_quantize_learnable_per_channel_affine_cuda_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor _fake_quantize_learnable_per_channel_affine(const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, int64_t axis, int64_t quant_min, int64_t quant_max, double grad_factor=1.0); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/6b/6bb503df4dc171c442ac48468df304969bf94456088a7680840baa62a854be6c/bar.py b/shared/package-files/6b/6bb503df4dc171c442ac48468df304969bf94456088a7680840baa62a854be6c/bar.py new file mode 100644 index 0000000000000000000000000000000000000000..ed86a552d1ca6baa0cfd48ec73a7a5c952d047c9 --- /dev/null +++ b/shared/package-files/6b/6bb503df4dc171c442ac48468df304969bf94456088a7680840baa62a854be6c/bar.py @@ -0,0 +1,94 @@ +from typing import Optional, Union + +from .color import Color +from .console import Console, ConsoleOptions, RenderResult +from .jupyter import JupyterMixin +from .measure import Measurement +from .segment import Segment +from .style import Style + +# There are left-aligned characters for 1/8 to 7/8, but +# the right-aligned characters exist only for 1/8 and 4/8. +BEGIN_BLOCK_ELEMENTS = ["█", "█", "█", "▐", "▐", "▐", "▕", "▕"] +END_BLOCK_ELEMENTS = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"] +FULL_BLOCK = "█" + + +class Bar(JupyterMixin): + """Renders a solid block bar. + + Args: + size (float): Value for the end of the bar. + begin (float): Begin point (between 0 and size, inclusive). + end (float): End point (between 0 and size, inclusive). + width (int, optional): Width of the bar, or ``None`` for maximum width. Defaults to None. + color (Union[Color, str], optional): Color of the bar. Defaults to "default". + bgcolor (Union[Color, str], optional): Color of bar background. Defaults to "default". + """ + + def __init__( + self, + size: float, + begin: float, + end: float, + *, + width: Optional[int] = None, + color: Union[Color, str] = "default", + bgcolor: Union[Color, str] = "default", + ): + self.size = size + self.begin = max(begin, 0) + self.end = min(end, size) + self.width = width + self.style = Style(color=color, bgcolor=bgcolor) + + def __repr__(self) -> str: + return f"Bar({self.size}, {self.begin}, {self.end})" + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + + width = min( + self.width if self.width is not None else options.max_width, + options.max_width, + ) + + if self.begin >= self.end: + yield Segment(" " * width, self.style) + yield Segment.line() + return + + prefix_complete_eights = int(width * 8 * self.begin / self.size) + prefix_bar_count = prefix_complete_eights // 8 + prefix_eights_count = prefix_complete_eights % 8 + + body_complete_eights = int(width * 8 * self.end / self.size) + body_bar_count = body_complete_eights // 8 + body_eights_count = body_complete_eights % 8 + + # When start and end fall into the same cell, we ideally should render + # a symbol that's "center-aligned", but there is no good symbol in Unicode. + # In this case, we fall back to right-aligned block symbol for simplicity. + + prefix = " " * prefix_bar_count + if prefix_eights_count: + prefix += BEGIN_BLOCK_ELEMENTS[prefix_eights_count] + + body = FULL_BLOCK * body_bar_count + if body_eights_count: + body += END_BLOCK_ELEMENTS[body_eights_count] + + suffix = " " * (width - len(body)) + + yield Segment(prefix + body[len(prefix) :] + suffix, self.style) + yield Segment.line() + + def __rich_measure__( + self, console: Console, options: ConsoleOptions + ) -> Measurement: + return ( + Measurement(self.width, self.width) + if self.width is not None + else Measurement(4, options.max_width) + ) diff --git a/shared/package-files/6b/6bb58c8142aacd2ab5d05140d99a3e0112e8248a6ab966e696c13b56827323b4/wrapper_benchmark.py b/shared/package-files/6b/6bb58c8142aacd2ab5d05140d99a3e0112e8248a6ab966e696c13b56827323b4/wrapper_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..c0205659ef72bd43641339b7de73749ddfc9bc8e --- /dev/null +++ b/shared/package-files/6b/6bb58c8142aacd2ab5d05140d99a3e0112e8248a6ab966e696c13b56827323b4/wrapper_benchmark.py @@ -0,0 +1,299 @@ +import dataclasses +import tempfile +from collections import defaultdict + +import torch +from torch.autograd import DeviceType +from .utils import create_bandwidth_info_str, do_bench, get_num_bytes + +_kernel_category_choices = [ + "foreach", + "persistent_reduction", + "pointwise", + "reduction", + "split_scan", + "template", +] + + +def get_kernel_category_by_source_code(src_code): + """ + Similar to get_kernel_category but use the source code. Call this API + if we have not compile the src_code to module yet. + """ + choices = [ + ch for ch in _kernel_category_choices if f"@triton_heuristics.{ch}" in src_code + ] + if len(choices) == 1: + return choices[0] + else: + return "unknown" + + +def get_kernel_category(kernel_mod): + """ + Given the module defining a triton kernel, return the category of the kernel. + Category can be one of: + - pointwise + - reduction + - persistent_reduction + + Currently we simply decide the category depending on what decorator is imported + by the kernel. + """ + choices = [ch for ch in _kernel_category_choices if ch in kernel_mod.__dict__] + if len(choices) == 1: + return choices[0] + else: + return "unknown" + + +def get_triton_kernel(mod): + from torch._inductor.triton_heuristics import CachingAutotuner + + cand_list = [ + v + for k, v in mod.__dict__.items() + if k.startswith("triton_") and isinstance(v, CachingAutotuner) + ] + assert len(cand_list) == 1 + return cand_list[0] + + +def benchmark_all_kernels(benchmark_name, benchmark_all_configs): + """ + An experimental API used only when config.benchmark_kernel is true. + + Run the kernel benchmarks for all the kernels cached in PyCodeCache. + Used in the compiled modules. + + Put this method here rather than codegen it for convenience since its implementation + does not change based on different graph modules being compiled. + """ + from torch._inductor.codecache import PyCodeCache + + nfound = 0 + for kernel_key, kernel_mod in PyCodeCache.cache.items(): + if not hasattr(kernel_mod, "get_args") or not hasattr(kernel_mod, "call"): + continue + + triton_kernel = get_triton_kernel(kernel_mod) + kernel_category = get_kernel_category(kernel_mod) + args = kernel_mod.get_args() + num_in_out_ptrs = len( + [ + arg_name + for arg_name in triton_kernel.fn.arg_names + if arg_name.startswith("in_out_ptr") + ] + ) + num_gb = triton_kernel.inductor_meta.get("kernel_num_gb", None) + if num_gb is None: + num_gb = get_num_bytes(*args, num_in_out_args=num_in_out_ptrs) / 1e9 + + def get_info_str(ms, n_regs, n_spills, shared, prefix=""): + if not any(x is None for x in [n_regs, n_spills, shared]): + kernel_detail_str = ( + f" {n_regs:3} regs {n_spills:3} spills {shared:8} shared mem" + ) + else: + kernel_detail_str = "" + + gb_per_s = num_gb / (ms / 1e3) + return create_bandwidth_info_str( + ms, num_gb, gb_per_s, prefix=prefix, suffix=kernel_detail_str + ) + + kernel_desc = ( + f"{benchmark_name:20} {kernel_category[:3].upper()} {kernel_key[:10]}" + ) + if benchmark_all_configs: + assert hasattr(kernel_mod, "benchmark_all_configs") + bench_result = kernel_mod.benchmark_all_configs(args) + print(kernel_desc) + for launcher, ms in bench_result.items(): + print( + f" {get_info_str(ms, launcher.n_regs, launcher.n_spills, launcher.shared)} @ {launcher.config}" + ) + else: + ms = do_bench(lambda: kernel_mod.call(args), rep=40, fast_flush=True) + assert ( + len(triton_kernel.launchers) == 1 + ), "Autotuner should have selected the best config" + launcher = triton_kernel.launchers[0] + print( + get_info_str( + ms, + launcher.n_regs, + launcher.n_spills, + launcher.shared, + prefix=f"{kernel_desc} ", + ) + ) + + nfound += 1 + if nfound == 0: + print( + "No kernel with benchmark functionality found. Make sure you run inductor with config.benchmark_kernel being True" + ) + + +@dataclasses.dataclass +class ProfileEvent: + category: str + key: str + self_cuda_time_ms: float + # the benchmark is run multiple times and we average the count across all the + # runs. It should be an integer but define a float just in case. + count: float + + +def parse_profile_event_list(benchmark_name, event_list, wall_time_ms, nruns): + def get_self_cuda_time(ev): + """ + ev.self_cuda_time_total is in microsecond. Convert to millisecond. + """ + return ev.self_cuda_time_total / 1000 / nruns + + all_events = defaultdict(list) + + def add_event(ev, category): + profile_ev = ProfileEvent( + category=category, + key=ev.key, + self_cuda_time_ms=get_self_cuda_time(ev), + count=ev.count / nruns, # average across all runs + ) + all_events[category].append(profile_ev) + + for ev in event_list: + assert not ev.is_legacy, "Don't support the legacy profiler" + if ev.device_type == DeviceType.CPU: + # ignore the event on CPU side + continue + + category = "unknown" + if ev.key.startswith("triton_"): + if ev.key.startswith("triton_poi"): + category = "triton_pointwise" + elif ev.key.startswith("triton_red"): + category = "triton_reduction" + elif ev.key.startswith("triton_per"): + category = "triton_persistent_reduction" + else: + category = "triton_unknown" + + add_event(ev, category) + + def report_category(category, profile_events): + from tabulate import tabulate + + profile_events.sort(key=lambda ev: ev.self_cuda_time_ms, reverse=True) + + rows = [] + total_time = 0.0 + print(f"\n == {category} category kernels == ") + for ev in profile_events: + total_time += ev.self_cuda_time_ms + percent = f"{ev.self_cuda_time_ms / wall_time_ms * 100:.2f}%" + rows.append([ev.key[:120], ev.self_cuda_time_ms, ev.count, percent]) + rows.append( + ["Total", total_time, "", f"{total_time / wall_time_ms * 100:.2f}%"] + ) + print( + tabulate( + rows, headers=["Kernel", "Self CUDA TIME (ms)", "Count", "Percent"] + ) + ) + return total_time + + def report(): + category_list = [ + "triton_pointwise", + "triton_reduction", + "triton_persistent_reduction", + "triton_unknown", + "unknown", + ] + assert set(all_events.keys()).issubset( + set(category_list) + ), f"{list(all_events.keys())}" + + per_category_wall_time = {} + total_cuda_ms = 0.0 + for category in category_list: + if category in all_events: + _time = report_category(category, all_events[category]) + per_category_wall_time[category] = _time + total_cuda_ms += _time + + gpu_busy_percent = f"{total_cuda_ms / wall_time_ms * 100:.2f}%" + print(f"\nPercent of time when GPU is busy: {gpu_busy_percent}") + print(f"Total wall time {wall_time_ms:.3f} ms") + + # output such a line so we can gather such line from all compiled modules from all + # benchmarks and tabulate it! + # Columns: benchmark_name, pointwise_percent, reduction_percent, persistent_reduction_percent, + # unknown_category_percent, GPU_busy_percent, wall_time_ms + tabulate_line = f"Output for tabulate: {benchmark_name}" + for category in category_list: + percent = ( + f"{per_category_wall_time.get(category, 0.0) / wall_time_ms * 100:.2f}%" + ) + tabulate_line += f", {percent}" + tabulate_line += f", {gpu_busy_percent}, {wall_time_ms:.3f}ms" + + print(tabulate_line) + + report() + + +def compiled_module_main(benchmark_name, benchmark_compiled_module_fn): + """ + This is the function called in __main__ block of a compiled module. + """ + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--benchmark-kernels", + "-k", + action="store_true", + help="Whether to benchmark each individual kernels", + ) + parser.add_argument( + "--benchmark-all-configs", + "-c", + action="store_true", + help="Whether to benchmark each individual config for a kernel", + ) + parser.add_argument( + "--profile", + "-p", + action="store_true", + help="Whether to profile the compiled module", + ) + args = parser.parse_args() + + if args.benchmark_kernels: + benchmark_all_kernels(benchmark_name, args.benchmark_all_configs) + else: + times = 10 + repeat = 10 + wall_time_ms = benchmark_compiled_module_fn(times=times, repeat=repeat) * 1000 + + if not args.profile: + return + + with torch.profiler.profile(record_shapes=True) as p: + benchmark_compiled_module_fn(times=times, repeat=repeat) + + path = f"{tempfile.gettempdir()}/compiled_module_profile.json" + p.export_chrome_trace(path) + print(f"Profiling result for a compiled module of benchmark {benchmark_name}:") + print(f"Chrome trace for the profile is written to {path}") + event_list = p.key_averages(group_by_input_shape=True) + print(event_list.table(sort_by="self_cuda_time_total", row_limit=10)) + parse_profile_event_list( + benchmark_name, event_list, wall_time_ms, times * repeat + ) diff --git a/shared/package-files/6b/6bb5cfe1c4bde2524e20a2e1c1d19ae7850de60707e4584b67b2de2df5469cb5/bmm_meta_dispatch.h b/shared/package-files/6b/6bb5cfe1c4bde2524e20a2e1c1d19ae7850de60707e4584b67b2de2df5469cb5/bmm_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..3abf2e8d9d832f19026e66aa85d8a2d7de40c8d3 --- /dev/null +++ b/shared/package-files/6b/6bb5cfe1c4bde2524e20a2e1c1d19ae7850de60707e4584b67b2de2df5469cb5/bmm_meta_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor bmm(const at::Tensor & self, const at::Tensor & mat2); +TORCH_API at::Tensor & bmm_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & mat2); +TORCH_API at::Tensor & bmm_outf(const at::Tensor & self, const at::Tensor & mat2, at::Tensor & out); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/6b/6bb6db52f210d29605c6982ce188c89eef1e2d0338356dba473f98b2b3432f3b/vt300-nam b/shared/package-files/6b/6bb6db52f210d29605c6982ce188c89eef1e2d0338356dba473f98b2b3432f3b/vt300-nam new file mode 100644 index 0000000000000000000000000000000000000000..bee83f5db8fcdd177ac212d8c7fc21787e09a564 Binary files /dev/null and b/shared/package-files/6b/6bb6db52f210d29605c6982ce188c89eef1e2d0338356dba473f98b2b3432f3b/vt300-nam differ diff --git a/shared/package-files/6b/6bb6db52f210d29605c6982ce188c89eef1e2d0338356dba473f98b2b3432f3b/vt320-nam b/shared/package-files/6b/6bb6db52f210d29605c6982ce188c89eef1e2d0338356dba473f98b2b3432f3b/vt320-nam new file mode 100644 index 0000000000000000000000000000000000000000..bee83f5db8fcdd177ac212d8c7fc21787e09a564 Binary files /dev/null and b/shared/package-files/6b/6bb6db52f210d29605c6982ce188c89eef1e2d0338356dba473f98b2b3432f3b/vt320-nam differ diff --git a/shared/package-files/6b/6bb889b93736ae4f5f46b69e5977c15a7e31776a5151d8fabe184ecace0115ac/backends.py b/shared/package-files/6b/6bb889b93736ae4f5f46b69e5977c15a7e31776a5151d8fabe184ecace0115ac/backends.py new file mode 100644 index 0000000000000000000000000000000000000000..b48798d8023659ba9bbc241bdb4df84d6bb68dc1 --- /dev/null +++ b/shared/package-files/6b/6bb889b93736ae4f5f46b69e5977c15a7e31776a5151d8fabe184ecace0115ac/backends.py @@ -0,0 +1,1553 @@ +""" +NetworkX utilizes a plugin-dispatch architecture, which means we can plug in and +out of backends with minimal code changes. A valid NetworkX backend specifies +`entry points `_, +named ``networkx.backends`` and an optional ``networkx.backend_info`` when it is +installed (not imported). This allows NetworkX to dispatch (redirect) function calls +to the backend so the execution flows to the designated backend +implementation, similar to how plugging a charger into a socket redirects the +electricity to your phone. This design enhances flexibility and integration, making +NetworkX more adaptable and efficient. + +There are three main ways to use a backend after the package is installed. +You can set environment variables and run the exact same code you run for +NetworkX. You can use a keyword argument ``backend=...`` with the NetworkX +function. Or, you can convert the NetworkX Graph to a backend graph type and +call a NetworkX function supported by that backend. Environment variables +and backend keywords automatically convert your NetworkX Graph to the +backend type. Manually converting it yourself allows you to use that same +backend graph for more than one function call, reducing conversion time. + +For example, you can set an environment variable before starting python to request +all dispatchable functions automatically dispatch to the given backend:: + + bash> NETWORKX_AUTOMATIC_BACKENDS=cugraph python my_networkx_script.py + +or you can specify the backend as a kwarg:: + + nx.betweenness_centrality(G, k=10, backend="parallel") + +or you can convert the NetworkX Graph object ``G`` into a Graph-like +object specific to the backend and then pass that in the NetworkX function:: + + H = nx_parallel.ParallelGraph(G) + nx.betweenness_centrality(H, k=10) + +How it works: You might have seen the ``@nx._dispatchable`` decorator on +many of the NetworkX functions in the codebase. It decorates the function +with code that redirects execution to the function's backend implementation. +The code also manages any ``backend_kwargs`` you provide to the backend +version of the function. The code looks for the environment variable or +a ``backend`` keyword argument and if found, converts the input NetworkX +graph to the backend format before calling the backend's version of the +function. If no environment variable or backend keyword are found, the +dispatching code checks the input graph object for an attribute +called ``__networkx_backend__`` which tells it which backend provides this +graph type. That backend's version of the function is then called. +The backend system relies on Python ``entry_point`` system to signal +NetworkX that a backend is installed (even if not imported yet). Thus no +code needs to be changed between running with NetworkX and running with +a backend to NetworkX. The attribute ``__networkx_backend__`` holds a +string with the name of the ``entry_point``. If none of these options +are being used, the decorator code simply calls the NetworkX function +on the NetworkX graph as usual. + +The NetworkX library does not need to know that a backend exists for it +to work. So long as the backend package creates the entry_point, and +provides the correct interface, it will be called when the user requests +it using one of the three approaches described above. Some backends have +been working with the NetworkX developers to ensure smooth operation. +They are the following:: + +- `graphblas `_ +- `cugraph `_ +- `parallel `_ +- ``loopback`` is for testing purposes only and is not a real backend. + +Note that the ``backend_name`` is e.g. ``parallel``, the package installed +is ``nx-parallel``, and we use ``nx_parallel`` while importing the package. + +Creating a Custom backend +------------------------- + +1. To be a valid backend that is discoverable by NetworkX, your package must + register an `entry-point `_ + ``networkx.backends`` in the package's metadata, with a `key pointing to your + dispatch object `_ . + For example, if you are using ``setuptools`` to manage your backend package, + you can `add the following to your pyproject.toml file `_:: + + [project.entry-points."networkx.backends"] + backend_name = "your_dispatcher_class" + + You can also add the ``backend_info`` entry-point. It points towards the ``get_info`` + function that returns all the backend information, which is then used to build the + "Additional Backend Implementation" box at the end of algorithm's documentation + page (e.g. `nx-cugraph's get_info function `_):: + + [project.entry-points."networkx.backend_info"] + backend_name = "your_get_info_function" + + Note that this would only work if your backend is a trusted backend of NetworkX, + and is present in the `.circleci/config.yml` and + `.github/workflows/deploy-docs.yml` files in the NetworkX repository. + +2. The backend must create an ``nx.Graph``-like object which contains an attribute + ``__networkx_backend__`` with a value of the entry point name:: + + class BackendGraph: + __networkx_backend__ = "backend_name" + ... + + +Testing the Custom backend +-------------------------- + +To test your custom backend, you can run the NetworkX test suite with your backend. +This also ensures that the custom backend is compatible with NetworkX's API. + +Testing Environment Setup +~~~~~~~~~~~~~~~~~~~~~~~~~ + +To enable automatic testing with your custom backend, follow these steps: + +1. Set Backend Environment Variables: + - ``NETWORKX_TEST_BACKEND`` : Setting this to your registered backend key will let + the NetworkX's dispatch machinery automatically convert a regular NetworkX + ``Graph``, ``DiGraph``, ``MultiGraph``, etc. to their backend equivalents, using + ``your_dispatcher_class.convert_from_nx(G, ...)`` function. + - ``NETWORKX_FALLBACK_TO_NX`` (default=False) : Setting this variable to `True` will + instruct tests to use a NetworkX ``Graph`` for algorithms not implemented by your + custom backend. Setting this to `False` will only run the tests for algorithms + implemented by your custom backend and tests for other algorithms will ``xfail``. + +2. Defining ``convert_from_nx`` and ``convert_to_nx`` methods: + The arguments to ``convert_from_nx`` are: + + - ``G`` : NetworkX Graph + - ``edge_attrs`` : dict, optional + Dictionary mapping edge attributes to default values if missing in ``G``. + If None, then no edge attributes will be converted and default may be 1. + - ``node_attrs``: dict, optional + Dictionary mapping node attributes to default values if missing in ``G``. + If None, then no node attributes will be converted. + - ``preserve_edge_attrs`` : bool + Whether to preserve all edge attributes. + - ``preserve_node_attrs`` : bool + Whether to preserve all node attributes. + - ``preserve_graph_attrs`` : bool + Whether to preserve all graph attributes. + - ``preserve_all_attrs`` : bool + Whether to preserve all graph, node, and edge attributes. + - ``name`` : str + The name of the algorithm. + - ``graph_name`` : str + The name of the graph argument being converted. + +Running Tests +~~~~~~~~~~~~~ + +You can invoke NetworkX tests for your custom backend with the following commands:: + + NETWORKX_TEST_BACKEND= + NETWORKX_FALLBACK_TO_NX=True # or False + pytest --pyargs networkx + +Conversions while running tests : + +- Convert NetworkX graphs using ``.convert_from_nx(G, ...)`` into + the backend graph. +- Pass the backend graph objects to the backend implementation of the algorithm. +- Convert the result back to a form expected by NetworkX tests using + ``.convert_to_nx(result, ...)``. + +Notes +~~~~~ + +- Dispatchable algorithms that are not implemented by the backend + will cause a ``pytest.xfail``, giving some indication that not all + tests are running, while avoiding causing an explicit failure. + +- If a backend only partially implements some algorithms, it can define + a ``can_run(name, args, kwargs)`` function that returns True or False + indicating whether it can run the algorithm with the given arguments. + It may also return a string indicating why the algorithm can't be run; + this string may be used in the future to give helpful info to the user. + +- A backend may also define ``should_run(name, args, kwargs)`` that is similar + to ``can_run``, but answers whether the backend *should* be run (converting + if necessary). Like ``can_run``, it receives the original arguments so it + can decide whether it should be run by inspecting the arguments. ``can_run`` + runs before ``should_run``, so ``should_run`` may assume ``can_run`` is True. + If not implemented by the backend, ``can_run`` and ``should_run`` are + assumed to always return True if the backend implements the algorithm. + +- A special ``on_start_tests(items)`` function may be defined by the backend. + It will be called with the list of NetworkX tests discovered. Each item + is a test object that can be marked as xfail if the backend does not support + the test using ``item.add_marker(pytest.mark.xfail(reason=...))``. + +- A backend graph instance may have a ``G.__networkx_cache__`` dict to enable + caching, and care should be taken to clear the cache when appropriate. +""" + +import inspect +import itertools +import os +import warnings +from functools import partial +from importlib.metadata import entry_points + +import networkx as nx + +from .decorators import argmap + +__all__ = ["_dispatchable"] + + +def _do_nothing(): + """This does nothing at all, yet it helps turn `_dispatchable` into functions.""" + + +def _get_backends(group, *, load_and_call=False): + """ + Retrieve NetworkX ``backends`` and ``backend_info`` from the entry points. + + Parameters + ----------- + group : str + The entry_point to be retrieved. + load_and_call : bool, optional + If True, load and call the backend. Defaults to False. + + Returns + -------- + dict + A dictionary mapping backend names to their respective backend objects. + + Notes + ------ + If a backend is defined more than once, a warning is issued. + The `nx-loopback` backend is removed if it exists, as it is only available during testing. + A warning is displayed if an error occurs while loading a backend. + """ + items = entry_points(group=group) + rv = {} + for ep in items: + if ep.name in rv: + warnings.warn( + f"networkx backend defined more than once: {ep.name}", + RuntimeWarning, + stacklevel=2, + ) + elif load_and_call: + try: + rv[ep.name] = ep.load()() + except Exception as exc: + warnings.warn( + f"Error encountered when loading info for backend {ep.name}: {exc}", + RuntimeWarning, + stacklevel=2, + ) + else: + rv[ep.name] = ep + rv.pop("nx-loopback", None) + return rv + + +backends = _get_backends("networkx.backends") +backend_info = _get_backends("networkx.backend_info", load_and_call=True) + +# We must import from config after defining `backends` above +from .configs import Config, config + +# Get default configuration from environment variables at import time +config.backend_priority = [ + x.strip() + for x in os.environ.get( + "NETWORKX_BACKEND_PRIORITY", + os.environ.get("NETWORKX_AUTOMATIC_BACKENDS", ""), + ).split(",") + if x.strip() +] +# Initialize default configuration for backends +config.backends = Config( + **{ + backend: ( + cfg if isinstance(cfg := info["default_config"], Config) else Config(**cfg) + ) + if "default_config" in info + else Config() + for backend, info in backend_info.items() + } +) +type(config.backends).__doc__ = "All installed NetworkX backends and their configs." + +# Load and cache backends on-demand +_loaded_backends = {} # type: ignore[var-annotated] + + +def _always_run(name, args, kwargs): + return True + + +def _load_backend(backend_name): + if backend_name in _loaded_backends: + return _loaded_backends[backend_name] + rv = _loaded_backends[backend_name] = backends[backend_name].load() + if not hasattr(rv, "can_run"): + rv.can_run = _always_run + if not hasattr(rv, "should_run"): + rv.should_run = _always_run + return rv + + +_registered_algorithms = {} + + +class _dispatchable: + """Allow any of the following decorator forms: + - @_dispatchable + - @_dispatchable() + - @_dispatchable(name="override_name") + - @_dispatchable(graphs="graph") + - @_dispatchable(edge_attrs="weight") + - @_dispatchable(graphs={"G": 0, "H": 1}, edge_attrs={"weight": "default"}) + + These class attributes are currently used to allow backends to run networkx tests. + For example: `PYTHONPATH=. pytest --backend graphblas --fallback-to-nx` + Future work: add configuration to control these. + """ + + _is_testing = False + _fallback_to_nx = ( + os.environ.get("NETWORKX_FALLBACK_TO_NX", "true").strip().lower() == "true" + ) + + def __new__( + cls, + func=None, + *, + name=None, + graphs="G", + edge_attrs=None, + node_attrs=None, + preserve_edge_attrs=False, + preserve_node_attrs=False, + preserve_graph_attrs=False, + preserve_all_attrs=False, + mutates_input=False, + returns_graph=False, + ): + """A decorator that makes certain input graph types dispatch to ``func``'s + backend implementation. + + Usage can be any of the following decorator forms: + - @_dispatchable + - @_dispatchable() + - @_dispatchable(name="override_name") + - @_dispatchable(graphs="graph_var_name") + - @_dispatchable(edge_attrs="weight") + - @_dispatchable(graphs={"G": 0, "H": 1}, edge_attrs={"weight": "default"}) + with 0 and 1 giving the position in the signature function for graph objects. + When edge_attrs is a dict, keys are keyword names and values are defaults. + + The class attributes are used to allow backends to run networkx tests. + For example: `PYTHONPATH=. pytest --backend graphblas --fallback-to-nx` + Future work: add configuration to control these. + + Parameters + ---------- + func : callable, optional + The function to be decorated. If ``func`` is not provided, returns a + partial object that can be used to decorate a function later. If ``func`` + is provided, returns a new callable object that dispatches to a backend + algorithm based on input graph types. + + name : str, optional + The name of the algorithm to use for dispatching. If not provided, + the name of ``func`` will be used. ``name`` is useful to avoid name + conflicts, as all dispatched algorithms live in a single namespace. + For example, ``tournament.is_strongly_connected`` had a name conflict + with the standard ``nx.is_strongly_connected``, so we used + ``@_dispatchable(name="tournament_is_strongly_connected")``. + + graphs : str or dict or None, default "G" + If a string, the parameter name of the graph, which must be the first + argument of the wrapped function. If more than one graph is required + for the algorithm (or if the graph is not the first argument), provide + a dict of parameter name to argument position for each graph argument. + For example, ``@_dispatchable(graphs={"G": 0, "auxiliary?": 4})`` + indicates the 0th parameter ``G`` of the function is a required graph, + and the 4th parameter ``auxiliary`` is an optional graph. + To indicate an argument is a list of graphs, do e.g. ``"[graphs]"``. + Use ``graphs=None`` if *no* arguments are NetworkX graphs such as for + graph generators, readers, and conversion functions. + + edge_attrs : str or dict, optional + ``edge_attrs`` holds information about edge attribute arguments + and default values for those edge attributes. + If a string, ``edge_attrs`` holds the function argument name that + indicates a single edge attribute to include in the converted graph. + The default value for this attribute is 1. To indicate that an argument + is a list of attributes (all with default value 1), use e.g. ``"[attrs]"``. + If a dict, ``edge_attrs`` holds a dict keyed by argument names, with + values that are either the default value or, if a string, the argument + name that indicates the default value. + + node_attrs : str or dict, optional + Like ``edge_attrs``, but for node attributes. + + preserve_edge_attrs : bool or str or dict, optional + For bool, whether to preserve all edge attributes. + For str, the parameter name that may indicate (with ``True`` or a + callable argument) whether all edge attributes should be preserved + when converting. + For dict of ``{graph_name: {attr: default}}``, indicate pre-determined + edge attributes (and defaults) to preserve for input graphs. + + preserve_node_attrs : bool or str or dict, optional + Like ``preserve_edge_attrs``, but for node attributes. + + preserve_graph_attrs : bool or set + For bool, whether to preserve all graph attributes. + For set, which input graph arguments to preserve graph attributes. + + preserve_all_attrs : bool + Whether to preserve all edge, node and graph attributes. + This overrides all the other preserve_*_attrs. + + mutates_input : bool or dict, default False + For bool, whether the functions mutates an input graph argument. + For dict of ``{arg_name: arg_pos}``, arguments that indicates whether an + input graph will be mutated, and ``arg_name`` may begin with ``"not "`` + to negate the logic (for example, this is used by ``copy=`` arguments). + By default, dispatching doesn't convert input graphs to a different + backend for functions that mutate input graphs. + + returns_graph : bool, default False + Whether the function can return or yield a graph object. By default, + dispatching doesn't convert input graphs to a different backend for + functions that return graphs. + """ + if func is None: + return partial( + _dispatchable, + name=name, + graphs=graphs, + edge_attrs=edge_attrs, + node_attrs=node_attrs, + preserve_edge_attrs=preserve_edge_attrs, + preserve_node_attrs=preserve_node_attrs, + preserve_graph_attrs=preserve_graph_attrs, + preserve_all_attrs=preserve_all_attrs, + mutates_input=mutates_input, + returns_graph=returns_graph, + ) + if isinstance(func, str): + raise TypeError("'name' and 'graphs' must be passed by keyword") from None + # If name not provided, use the name of the function + if name is None: + name = func.__name__ + + self = object.__new__(cls) + + # standard function-wrapping stuff + # __annotations__ not used + self.__name__ = func.__name__ + # self.__doc__ = func.__doc__ # __doc__ handled as cached property + self.__defaults__ = func.__defaults__ + # We "magically" add `backend=` keyword argument to allow backend to be specified + if func.__kwdefaults__: + self.__kwdefaults__ = {**func.__kwdefaults__, "backend": None} + else: + self.__kwdefaults__ = {"backend": None} + self.__module__ = func.__module__ + self.__qualname__ = func.__qualname__ + self.__dict__.update(func.__dict__) + self.__wrapped__ = func + + # Supplement docstring with backend info; compute and cache when needed + self._orig_doc = func.__doc__ + self._cached_doc = None + + self.orig_func = func + self.name = name + self.edge_attrs = edge_attrs + self.node_attrs = node_attrs + self.preserve_edge_attrs = preserve_edge_attrs or preserve_all_attrs + self.preserve_node_attrs = preserve_node_attrs or preserve_all_attrs + self.preserve_graph_attrs = preserve_graph_attrs or preserve_all_attrs + self.mutates_input = mutates_input + # Keep `returns_graph` private for now, b/c we may extend info on return types + self._returns_graph = returns_graph + + if edge_attrs is not None and not isinstance(edge_attrs, str | dict): + raise TypeError( + f"Bad type for edge_attrs: {type(edge_attrs)}. Expected str or dict." + ) from None + if node_attrs is not None and not isinstance(node_attrs, str | dict): + raise TypeError( + f"Bad type for node_attrs: {type(node_attrs)}. Expected str or dict." + ) from None + if not isinstance(self.preserve_edge_attrs, bool | str | dict): + raise TypeError( + f"Bad type for preserve_edge_attrs: {type(self.preserve_edge_attrs)}." + " Expected bool, str, or dict." + ) from None + if not isinstance(self.preserve_node_attrs, bool | str | dict): + raise TypeError( + f"Bad type for preserve_node_attrs: {type(self.preserve_node_attrs)}." + " Expected bool, str, or dict." + ) from None + if not isinstance(self.preserve_graph_attrs, bool | set): + raise TypeError( + f"Bad type for preserve_graph_attrs: {type(self.preserve_graph_attrs)}." + " Expected bool or set." + ) from None + if not isinstance(self.mutates_input, bool | dict): + raise TypeError( + f"Bad type for mutates_input: {type(self.mutates_input)}." + " Expected bool or dict." + ) from None + if not isinstance(self._returns_graph, bool): + raise TypeError( + f"Bad type for returns_graph: {type(self._returns_graph)}." + " Expected bool." + ) from None + + if isinstance(graphs, str): + graphs = {graphs: 0} + elif graphs is None: + pass + elif not isinstance(graphs, dict): + raise TypeError( + f"Bad type for graphs: {type(graphs)}. Expected str or dict." + ) from None + elif len(graphs) == 0: + raise KeyError("'graphs' must contain at least one variable name") from None + + # This dict comprehension is complicated for better performance; equivalent shown below. + self.optional_graphs = set() + self.list_graphs = set() + if graphs is None: + self.graphs = {} + else: + self.graphs = { + self.optional_graphs.add(val := k[:-1]) or val + if (last := k[-1]) == "?" + else self.list_graphs.add(val := k[1:-1]) or val + if last == "]" + else k: v + for k, v in graphs.items() + } + # The above is equivalent to: + # self.optional_graphs = {k[:-1] for k in graphs if k[-1] == "?"} + # self.list_graphs = {k[1:-1] for k in graphs if k[-1] == "]"} + # self.graphs = {k[:-1] if k[-1] == "?" else k: v for k, v in graphs.items()} + + # Compute and cache the signature on-demand + self._sig = None + + # Which backends implement this function? + self.backends = { + backend + for backend, info in backend_info.items() + if "functions" in info and name in info["functions"] + } + + if name in _registered_algorithms: + raise KeyError( + f"Algorithm already exists in dispatch registry: {name}" + ) from None + # Use the magic of `argmap` to turn `self` into a function. This does result + # in small additional overhead compared to calling `_dispatchable` directly, + # but `argmap` has the magical property that it can stack with other `argmap` + # decorators "for free". Being a function is better for REPRs and type-checkers. + self = argmap(_do_nothing)(self) + _registered_algorithms[name] = self + return self + + @property + def __doc__(self): + """If the cached documentation exists, it is returned. + Otherwise, the documentation is generated using _make_doc() method, + cached, and then returned.""" + + if (rv := self._cached_doc) is not None: + return rv + rv = self._cached_doc = self._make_doc() + return rv + + @__doc__.setter + def __doc__(self, val): + """Sets the original documentation to the given value and resets the + cached documentation.""" + + self._orig_doc = val + self._cached_doc = None + + @property + def __signature__(self): + """Return the signature of the original function, with the addition of + the `backend` and `backend_kwargs` parameters.""" + + if self._sig is None: + sig = inspect.signature(self.orig_func) + # `backend` is now a reserved argument used by dispatching. + # assert "backend" not in sig.parameters + if not any( + p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values() + ): + sig = sig.replace( + parameters=[ + *sig.parameters.values(), + inspect.Parameter( + "backend", inspect.Parameter.KEYWORD_ONLY, default=None + ), + inspect.Parameter( + "backend_kwargs", inspect.Parameter.VAR_KEYWORD + ), + ] + ) + else: + *parameters, var_keyword = sig.parameters.values() + sig = sig.replace( + parameters=[ + *parameters, + inspect.Parameter( + "backend", inspect.Parameter.KEYWORD_ONLY, default=None + ), + var_keyword, + ] + ) + self._sig = sig + return self._sig + + def __call__(self, /, *args, backend=None, **kwargs): + """Returns the result of the original function, or the backend function if + the backend is specified and that backend implements `func`.""" + + if not backends: + # Fast path if no backends are installed + return self.orig_func(*args, **kwargs) + + # Use `backend_name` in this function instead of `backend` + backend_name = backend + if backend_name is not None and backend_name not in backends: + raise ImportError(f"Unable to load backend: {backend_name}") + + graphs_resolved = {} + for gname, pos in self.graphs.items(): + if pos < len(args): + if gname in kwargs: + raise TypeError(f"{self.name}() got multiple values for {gname!r}") + val = args[pos] + elif gname in kwargs: + val = kwargs[gname] + elif gname not in self.optional_graphs: + raise TypeError( + f"{self.name}() missing required graph argument: {gname}" + ) + else: + continue + if val is None: + if gname not in self.optional_graphs: + raise TypeError( + f"{self.name}() required graph argument {gname!r} is None; must be a graph" + ) + else: + graphs_resolved[gname] = val + + # Alternative to the above that does not check duplicated args or missing required graphs. + # graphs_resolved = { + # val + # for gname, pos in self.graphs.items() + # if (val := args[pos] if pos < len(args) else kwargs.get(gname)) is not None + # } + + # Check if any graph comes from a backend + if self.list_graphs: + # Make sure we don't lose values by consuming an iterator + args = list(args) + for gname in self.list_graphs & graphs_resolved.keys(): + val = list(graphs_resolved[gname]) + graphs_resolved[gname] = val + if gname in kwargs: + kwargs[gname] = val + else: + args[self.graphs[gname]] = val + + has_backends = any( + hasattr(g, "__networkx_backend__") + if gname not in self.list_graphs + else any(hasattr(g2, "__networkx_backend__") for g2 in g) + for gname, g in graphs_resolved.items() + ) + if has_backends: + graph_backend_names = { + getattr(g, "__networkx_backend__", "networkx") + for gname, g in graphs_resolved.items() + if gname not in self.list_graphs + } + for gname in self.list_graphs & graphs_resolved.keys(): + graph_backend_names.update( + getattr(g, "__networkx_backend__", "networkx") + for g in graphs_resolved[gname] + ) + else: + has_backends = any( + hasattr(g, "__networkx_backend__") for g in graphs_resolved.values() + ) + if has_backends: + graph_backend_names = { + getattr(g, "__networkx_backend__", "networkx") + for g in graphs_resolved.values() + } + + backend_priority = config.backend_priority + if self._is_testing and backend_priority and backend_name is None: + # Special path if we are running networkx tests with a backend. + # This even runs for (and handles) functions that mutate input graphs. + return self._convert_and_call_for_tests( + backend_priority[0], + args, + kwargs, + fallback_to_nx=self._fallback_to_nx, + ) + + if has_backends: + # Dispatchable graphs found! Dispatch to backend function. + # We don't handle calls with different backend graphs yet, + # but we may be able to convert additional networkx graphs. + backend_names = graph_backend_names - {"networkx"} + if len(backend_names) != 1: + # Future work: convert between backends and run if multiple backends found + raise TypeError( + f"{self.name}() graphs must all be from the same backend, found {backend_names}" + ) + [graph_backend_name] = backend_names + if backend_name is not None and backend_name != graph_backend_name: + # Future work: convert between backends to `backend_name` backend + raise TypeError( + f"{self.name}() is unable to convert graph from backend {graph_backend_name!r} " + f"to the specified backend {backend_name!r}." + ) + if graph_backend_name not in backends: + raise ImportError(f"Unable to load backend: {graph_backend_name}") + if ( + "networkx" in graph_backend_names + and graph_backend_name not in backend_priority + ): + # Not configured to convert networkx graphs to this backend + raise TypeError( + f"Unable to convert inputs and run {self.name}. " + f"{self.name}() has networkx and {graph_backend_name} graphs, but NetworkX is not " + f"configured to automatically convert graphs from networkx to {graph_backend_name}." + ) + backend = _load_backend(graph_backend_name) + if hasattr(backend, self.name): + if "networkx" in graph_backend_names: + # We need to convert networkx graphs to backend graphs. + # There is currently no need to check `self.mutates_input` here. + return self._convert_and_call( + graph_backend_name, + args, + kwargs, + fallback_to_nx=self._fallback_to_nx, + ) + # All graphs are backend graphs--no need to convert! + return getattr(backend, self.name)(*args, **kwargs) + # Future work: try to convert and run with other backends in backend_priority + raise nx.NetworkXNotImplemented( + f"'{self.name}' not implemented by {graph_backend_name}" + ) + + # If backend was explicitly given by the user, so we need to use it no matter what + if backend_name is not None: + return self._convert_and_call( + backend_name, args, kwargs, fallback_to_nx=False + ) + + # Only networkx graphs; try to convert and run with a backend with automatic + # conversion, but don't do this by default for graph generators or loaders, + # or if the functions mutates an input graph or returns a graph. + # Only convert and run if `backend.should_run(...)` returns True. + if ( + not self._returns_graph + and ( + not self.mutates_input + or isinstance(self.mutates_input, dict) + # If `mutates_input` begins with "not ", then assume the argument is boolean, + # otherwise treat it as a node or edge attribute if it's not None. + and any( + not ( + args[arg_pos] + if len(args) > arg_pos + else kwargs.get(arg_name[4:], True) + ) + if arg_name.startswith("not ") + else ( + args[arg_pos] if len(args) > arg_pos else kwargs.get(arg_name) + ) + is not None + for arg_name, arg_pos in self.mutates_input.items() + ) + ) + ): + # Should we warn or log if we don't convert b/c the input will be mutated? + for backend_name in backend_priority: + if self._should_backend_run(backend_name, *args, **kwargs): + return self._convert_and_call( + backend_name, + args, + kwargs, + fallback_to_nx=self._fallback_to_nx, + ) + # Default: run with networkx on networkx inputs + return self.orig_func(*args, **kwargs) + + def _can_backend_run(self, backend_name, /, *args, **kwargs): + """Can the specified backend run this algorithm with these arguments?""" + backend = _load_backend(backend_name) + # `backend.can_run` and `backend.should_run` may return strings that describe + # why they can't or shouldn't be run. We plan to use the strings in the future. + return ( + hasattr(backend, self.name) + and (can_run := backend.can_run(self.name, args, kwargs)) + and not isinstance(can_run, str) + ) + + def _should_backend_run(self, backend_name, /, *args, **kwargs): + """Can/should the specified backend run this algorithm with these arguments?""" + backend = _load_backend(backend_name) + # `backend.can_run` and `backend.should_run` may return strings that describe + # why they can't or shouldn't be run. We plan to use the strings in the future. + return ( + hasattr(backend, self.name) + and (can_run := backend.can_run(self.name, args, kwargs)) + and not isinstance(can_run, str) + and (should_run := backend.should_run(self.name, args, kwargs)) + and not isinstance(should_run, str) + ) + + def _convert_arguments(self, backend_name, args, kwargs, *, use_cache): + """Convert graph arguments to the specified backend. + + Returns + ------- + args tuple and kwargs dict + """ + bound = self.__signature__.bind(*args, **kwargs) + bound.apply_defaults() + if not self.graphs: + bound_kwargs = bound.kwargs + del bound_kwargs["backend"] + return bound.args, bound_kwargs + # Convert graphs into backend graph-like object + # Include the edge and/or node labels if provided to the algorithm + preserve_edge_attrs = self.preserve_edge_attrs + edge_attrs = self.edge_attrs + if preserve_edge_attrs is False: + # e.g. `preserve_edge_attrs=False` + pass + elif preserve_edge_attrs is True: + # e.g. `preserve_edge_attrs=True` + edge_attrs = None + elif isinstance(preserve_edge_attrs, str): + if bound.arguments[preserve_edge_attrs] is True or callable( + bound.arguments[preserve_edge_attrs] + ): + # e.g. `preserve_edge_attrs="attr"` and `func(attr=True)` + # e.g. `preserve_edge_attrs="attr"` and `func(attr=myfunc)` + preserve_edge_attrs = True + edge_attrs = None + elif bound.arguments[preserve_edge_attrs] is False and ( + isinstance(edge_attrs, str) + and edge_attrs == preserve_edge_attrs + or isinstance(edge_attrs, dict) + and preserve_edge_attrs in edge_attrs + ): + # e.g. `preserve_edge_attrs="attr"` and `func(attr=False)` + # Treat `False` argument as meaning "preserve_edge_data=False" + # and not `False` as the edge attribute to use. + preserve_edge_attrs = False + edge_attrs = None + else: + # e.g. `preserve_edge_attrs="attr"` and `func(attr="weight")` + preserve_edge_attrs = False + # Else: e.g. `preserve_edge_attrs={"G": {"weight": 1}}` + + if edge_attrs is None: + # May have been set to None above b/c all attributes are preserved + pass + elif isinstance(edge_attrs, str): + if edge_attrs[0] == "[": + # e.g. `edge_attrs="[edge_attributes]"` (argument of list of attributes) + # e.g. `func(edge_attributes=["foo", "bar"])` + edge_attrs = { + edge_attr: 1 for edge_attr in bound.arguments[edge_attrs[1:-1]] + } + elif callable(bound.arguments[edge_attrs]): + # e.g. `edge_attrs="weight"` and `func(weight=myfunc)` + preserve_edge_attrs = True + edge_attrs = None + elif bound.arguments[edge_attrs] is not None: + # e.g. `edge_attrs="weight"` and `func(weight="foo")` (default of 1) + edge_attrs = {bound.arguments[edge_attrs]: 1} + elif self.name == "to_numpy_array" and hasattr( + bound.arguments["dtype"], "names" + ): + # Custom handling: attributes may be obtained from `dtype` + edge_attrs = { + edge_attr: 1 for edge_attr in bound.arguments["dtype"].names + } + else: + # e.g. `edge_attrs="weight"` and `func(weight=None)` + edge_attrs = None + else: + # e.g. `edge_attrs={"attr": "default"}` and `func(attr="foo", default=7)` + # e.g. `edge_attrs={"attr": 0}` and `func(attr="foo")` + edge_attrs = { + edge_attr: bound.arguments.get(val, 1) if isinstance(val, str) else val + for key, val in edge_attrs.items() + if (edge_attr := bound.arguments[key]) is not None + } + + preserve_node_attrs = self.preserve_node_attrs + node_attrs = self.node_attrs + if preserve_node_attrs is False: + # e.g. `preserve_node_attrs=False` + pass + elif preserve_node_attrs is True: + # e.g. `preserve_node_attrs=True` + node_attrs = None + elif isinstance(preserve_node_attrs, str): + if bound.arguments[preserve_node_attrs] is True or callable( + bound.arguments[preserve_node_attrs] + ): + # e.g. `preserve_node_attrs="attr"` and `func(attr=True)` + # e.g. `preserve_node_attrs="attr"` and `func(attr=myfunc)` + preserve_node_attrs = True + node_attrs = None + elif bound.arguments[preserve_node_attrs] is False and ( + isinstance(node_attrs, str) + and node_attrs == preserve_node_attrs + or isinstance(node_attrs, dict) + and preserve_node_attrs in node_attrs + ): + # e.g. `preserve_node_attrs="attr"` and `func(attr=False)` + # Treat `False` argument as meaning "preserve_node_data=False" + # and not `False` as the node attribute to use. Is this used? + preserve_node_attrs = False + node_attrs = None + else: + # e.g. `preserve_node_attrs="attr"` and `func(attr="weight")` + preserve_node_attrs = False + # Else: e.g. `preserve_node_attrs={"G": {"pos": None}}` + + if node_attrs is None: + # May have been set to None above b/c all attributes are preserved + pass + elif isinstance(node_attrs, str): + if node_attrs[0] == "[": + # e.g. `node_attrs="[node_attributes]"` (argument of list of attributes) + # e.g. `func(node_attributes=["foo", "bar"])` + node_attrs = { + node_attr: None for node_attr in bound.arguments[node_attrs[1:-1]] + } + elif callable(bound.arguments[node_attrs]): + # e.g. `node_attrs="weight"` and `func(weight=myfunc)` + preserve_node_attrs = True + node_attrs = None + elif bound.arguments[node_attrs] is not None: + # e.g. `node_attrs="weight"` and `func(weight="foo")` + node_attrs = {bound.arguments[node_attrs]: None} + else: + # e.g. `node_attrs="weight"` and `func(weight=None)` + node_attrs = None + else: + # e.g. `node_attrs={"attr": "default"}` and `func(attr="foo", default=7)` + # e.g. `node_attrs={"attr": 0}` and `func(attr="foo")` + node_attrs = { + node_attr: bound.arguments.get(val) if isinstance(val, str) else val + for key, val in node_attrs.items() + if (node_attr := bound.arguments[key]) is not None + } + + preserve_graph_attrs = self.preserve_graph_attrs + + # It should be safe to assume that we either have networkx graphs or backend graphs. + # Future work: allow conversions between backends. + for gname in self.graphs: + if gname in self.list_graphs: + bound.arguments[gname] = [ + self._convert_graph( + backend_name, + g, + edge_attrs=edge_attrs, + node_attrs=node_attrs, + preserve_edge_attrs=preserve_edge_attrs, + preserve_node_attrs=preserve_node_attrs, + preserve_graph_attrs=preserve_graph_attrs, + graph_name=gname, + use_cache=use_cache, + ) + if getattr(g, "__networkx_backend__", "networkx") == "networkx" + else g + for g in bound.arguments[gname] + ] + else: + graph = bound.arguments[gname] + if graph is None: + if gname in self.optional_graphs: + continue + raise TypeError( + f"Missing required graph argument `{gname}` in {self.name} function" + ) + if isinstance(preserve_edge_attrs, dict): + preserve_edges = False + edges = preserve_edge_attrs.get(gname, edge_attrs) + else: + preserve_edges = preserve_edge_attrs + edges = edge_attrs + if isinstance(preserve_node_attrs, dict): + preserve_nodes = False + nodes = preserve_node_attrs.get(gname, node_attrs) + else: + preserve_nodes = preserve_node_attrs + nodes = node_attrs + if isinstance(preserve_graph_attrs, set): + preserve_graph = gname in preserve_graph_attrs + else: + preserve_graph = preserve_graph_attrs + if getattr(graph, "__networkx_backend__", "networkx") == "networkx": + bound.arguments[gname] = self._convert_graph( + backend_name, + graph, + edge_attrs=edges, + node_attrs=nodes, + preserve_edge_attrs=preserve_edges, + preserve_node_attrs=preserve_nodes, + preserve_graph_attrs=preserve_graph, + graph_name=gname, + use_cache=use_cache, + ) + bound_kwargs = bound.kwargs + del bound_kwargs["backend"] + return bound.args, bound_kwargs + + def _convert_graph( + self, + backend_name, + graph, + *, + edge_attrs, + node_attrs, + preserve_edge_attrs, + preserve_node_attrs, + preserve_graph_attrs, + graph_name, + use_cache, + ): + if ( + use_cache + and (nx_cache := getattr(graph, "__networkx_cache__", None)) is not None + ): + cache = nx_cache.setdefault("backends", {}).setdefault(backend_name, {}) + # edge_attrs: dict | None + # node_attrs: dict | None + # preserve_edge_attrs: bool (False if edge_attrs is not None) + # preserve_node_attrs: bool (False if node_attrs is not None) + # preserve_graph_attrs: bool + key = edge_key, node_key, graph_key = ( + frozenset(edge_attrs.items()) + if edge_attrs is not None + else preserve_edge_attrs, + frozenset(node_attrs.items()) + if node_attrs is not None + else preserve_node_attrs, + preserve_graph_attrs, + ) + if cache: + warning_message = ( + f"Using cached graph for {backend_name!r} backend in " + f"call to {self.name}.\n\nFor the cache to be consistent " + "(i.e., correct), the input graph must not have been " + "manually mutated since the cached graph was created. " + "Examples of manually mutating the graph data structures " + "resulting in an inconsistent cache include:\n\n" + " >>> G[u][v][key] = val\n\n" + "and\n\n" + " >>> for u, v, d in G.edges(data=True):\n" + " ... d[key] = val\n\n" + "Using methods such as `G.add_edge(u, v, weight=val)` " + "will correctly clear the cache to keep it consistent. " + "You may also use `G.__networkx_cache__.clear()` to " + "manually clear the cache, or set `G.__networkx_cache__` " + "to None to disable caching for G. Enable or disable " + "caching via `nx.config.cache_converted_graphs` config." + ) + # Do a simple search for a cached graph with compatible data. + # For example, if we need a single attribute, then it's okay + # to use a cached graph that preserved all attributes. + # This looks for an exact match first. + for compat_key in itertools.product( + (edge_key, True) if edge_key is not True else (True,), + (node_key, True) if node_key is not True else (True,), + (graph_key, True) if graph_key is not True else (True,), + ): + if (rv := cache.get(compat_key)) is not None: + warnings.warn(warning_message) + return rv + if edge_key is not True and node_key is not True: + # Iterate over the items in `cache` to see if any are compatible. + # For example, if no edge attributes are needed, then a graph + # with any edge attribute will suffice. We use the same logic + # below (but switched) to clear unnecessary items from the cache. + # Use `list(cache.items())` to be thread-safe. + for (ekey, nkey, gkey), val in list(cache.items()): + if edge_key is False or ekey is True: + pass + elif ( + edge_key is True + or ekey is False + or not edge_key.issubset(ekey) + ): + continue + if node_key is False or nkey is True: + pass + elif ( + node_key is True + or nkey is False + or not node_key.issubset(nkey) + ): + continue + if graph_key and not gkey: + continue + warnings.warn(warning_message) + return val + + backend = _load_backend(backend_name) + rv = backend.convert_from_nx( + graph, + edge_attrs=edge_attrs, + node_attrs=node_attrs, + preserve_edge_attrs=preserve_edge_attrs, + preserve_node_attrs=preserve_node_attrs, + preserve_graph_attrs=preserve_graph_attrs, + name=self.name, + graph_name=graph_name, + ) + if use_cache and nx_cache is not None: + # Remove old cached items that are no longer necessary since they + # are dominated/subsumed/outdated by what was just calculated. + # This uses the same logic as above, but with keys switched. + cache[key] = rv # Set at beginning to be thread-safe + for cur_key in list(cache): + if cur_key == key: + continue + ekey, nkey, gkey = cur_key + if ekey is False or edge_key is True: + pass + elif ekey is True or edge_key is False or not ekey.issubset(edge_key): + continue + if nkey is False or node_key is True: + pass + elif nkey is True or node_key is False or not nkey.issubset(node_key): + continue + if gkey and not graph_key: + continue + cache.pop(cur_key, None) # Use pop instead of del to be thread-safe + + return rv + + def _convert_and_call(self, backend_name, args, kwargs, *, fallback_to_nx=False): + """Call this dispatchable function with a backend, converting graphs if necessary.""" + backend = _load_backend(backend_name) + if not self._can_backend_run(backend_name, *args, **kwargs): + if fallback_to_nx: + return self.orig_func(*args, **kwargs) + msg = f"'{self.name}' not implemented by {backend_name}" + if hasattr(backend, self.name): + msg += " with the given arguments" + raise RuntimeError(msg) + + try: + converted_args, converted_kwargs = self._convert_arguments( + backend_name, args, kwargs, use_cache=config.cache_converted_graphs + ) + result = getattr(backend, self.name)(*converted_args, **converted_kwargs) + except (NotImplementedError, nx.NetworkXNotImplemented) as exc: + if fallback_to_nx: + return self.orig_func(*args, **kwargs) + raise + + return result + + def _convert_and_call_for_tests( + self, backend_name, args, kwargs, *, fallback_to_nx=False + ): + """Call this dispatchable function with a backend; for use with testing.""" + backend = _load_backend(backend_name) + if not self._can_backend_run(backend_name, *args, **kwargs): + if fallback_to_nx or not self.graphs: + return self.orig_func(*args, **kwargs) + + import pytest + + msg = f"'{self.name}' not implemented by {backend_name}" + if hasattr(backend, self.name): + msg += " with the given arguments" + pytest.xfail(msg) + + from collections.abc import Iterable, Iterator, Mapping + from copy import copy + from io import BufferedReader, BytesIO, StringIO, TextIOWrapper + from itertools import tee + from random import Random + + import numpy as np + from numpy.random import Generator, RandomState + from scipy.sparse import sparray + + # We sometimes compare the backend result to the original result, + # so we need two sets of arguments. We tee iterators and copy + # random state so that they may be used twice. + if not args: + args1 = args2 = args + else: + args1, args2 = zip( + *( + (arg, copy(arg)) + if isinstance( + arg, BytesIO | StringIO | Random | Generator | RandomState + ) + else tee(arg) + if isinstance(arg, Iterator) + and not isinstance(arg, BufferedReader | TextIOWrapper) + else (arg, arg) + for arg in args + ) + ) + if not kwargs: + kwargs1 = kwargs2 = kwargs + else: + kwargs1, kwargs2 = zip( + *( + ((k, v), (k, copy(v))) + if isinstance( + v, BytesIO | StringIO | Random | Generator | RandomState + ) + else ((k, (teed := tee(v))[0]), (k, teed[1])) + if isinstance(v, Iterator) + and not isinstance(v, BufferedReader | TextIOWrapper) + else ((k, v), (k, v)) + for k, v in kwargs.items() + ) + ) + kwargs1 = dict(kwargs1) + kwargs2 = dict(kwargs2) + try: + converted_args, converted_kwargs = self._convert_arguments( + backend_name, args1, kwargs1, use_cache=False + ) + result = getattr(backend, self.name)(*converted_args, **converted_kwargs) + except (NotImplementedError, nx.NetworkXNotImplemented) as exc: + if fallback_to_nx: + return self.orig_func(*args2, **kwargs2) + import pytest + + pytest.xfail( + exc.args[0] if exc.args else f"{self.name} raised {type(exc).__name__}" + ) + # Verify that `self._returns_graph` is correct. This compares the return type + # to the type expected from `self._returns_graph`. This handles tuple and list + # return types, but *does not* catch functions that yield graphs. + if ( + self._returns_graph + != ( + isinstance(result, nx.Graph) + or hasattr(result, "__networkx_backend__") + or isinstance(result, tuple | list) + and any( + isinstance(x, nx.Graph) or hasattr(x, "__networkx_backend__") + for x in result + ) + ) + and not ( + # May return Graph or None + self.name in {"check_planarity", "check_planarity_recursive"} + and any(x is None for x in result) + ) + and not ( + # May return Graph or dict + self.name in {"held_karp_ascent"} + and any(isinstance(x, dict) for x in result) + ) + and self.name + not in { + # yields graphs + "all_triads", + "general_k_edge_subgraphs", + # yields graphs or arrays + "nonisomorphic_trees", + } + ): + raise RuntimeError(f"`returns_graph` is incorrect for {self.name}") + + def check_result(val, depth=0): + if isinstance(val, np.number): + raise RuntimeError( + f"{self.name} returned a numpy scalar {val} ({type(val)}, depth={depth})" + ) + if isinstance(val, np.ndarray | sparray): + return + if isinstance(val, nx.Graph): + check_result(val._node, depth=depth + 1) + check_result(val._adj, depth=depth + 1) + return + if isinstance(val, Iterator): + raise NotImplementedError + if isinstance(val, Iterable) and not isinstance(val, str): + for x in val: + check_result(x, depth=depth + 1) + if isinstance(val, Mapping): + for x in val.values(): + check_result(x, depth=depth + 1) + + def check_iterator(it): + for val in it: + try: + check_result(val) + except RuntimeError as exc: + raise RuntimeError( + f"{self.name} returned a numpy scalar {val} ({type(val)})" + ) from exc + yield val + + if self.name in {"from_edgelist"}: + # numpy scalars are explicitly given as values in some tests + pass + elif isinstance(result, Iterator): + result = check_iterator(result) + else: + try: + check_result(result) + except RuntimeError as exc: + raise RuntimeError( + f"{self.name} returned a numpy scalar {result} ({type(result)})" + ) from exc + check_result(result) + + if self.name in { + "edmonds_karp", + "barycenter", + "contracted_edge", + "contracted_nodes", + "stochastic_graph", + "relabel_nodes", + "maximum_branching", + "incremental_closeness_centrality", + "minimal_branching", + "minimum_spanning_arborescence", + "recursive_simple_cycles", + "connected_double_edge_swap", + }: + # Special-case algorithms that mutate input graphs + bound = self.__signature__.bind(*converted_args, **converted_kwargs) + bound.apply_defaults() + bound2 = self.__signature__.bind(*args2, **kwargs2) + bound2.apply_defaults() + if self.name in { + "minimal_branching", + "minimum_spanning_arborescence", + "recursive_simple_cycles", + "connected_double_edge_swap", + }: + G1 = backend.convert_to_nx(bound.arguments["G"]) + G2 = bound2.arguments["G"] + G2._adj = G1._adj + nx._clear_cache(G2) + elif self.name == "edmonds_karp": + R1 = backend.convert_to_nx(bound.arguments["residual"]) + R2 = bound2.arguments["residual"] + if R1 is not None and R2 is not None: + for k, v in R1.edges.items(): + R2.edges[k]["flow"] = v["flow"] + R2.graph.update(R1.graph) + nx._clear_cache(R2) + elif self.name == "barycenter" and bound.arguments["attr"] is not None: + G1 = backend.convert_to_nx(bound.arguments["G"]) + G2 = bound2.arguments["G"] + attr = bound.arguments["attr"] + for k, v in G1.nodes.items(): + G2.nodes[k][attr] = v[attr] + nx._clear_cache(G2) + elif ( + self.name in {"contracted_nodes", "contracted_edge"} + and not bound.arguments["copy"] + ): + # Edges and nodes changed; node "contraction" and edge "weight" attrs + G1 = backend.convert_to_nx(bound.arguments["G"]) + G2 = bound2.arguments["G"] + G2.__dict__.update(G1.__dict__) + nx._clear_cache(G2) + elif self.name == "stochastic_graph" and not bound.arguments["copy"]: + G1 = backend.convert_to_nx(bound.arguments["G"]) + G2 = bound2.arguments["G"] + for k, v in G1.edges.items(): + G2.edges[k]["weight"] = v["weight"] + nx._clear_cache(G2) + elif ( + self.name == "relabel_nodes" + and not bound.arguments["copy"] + or self.name in {"incremental_closeness_centrality"} + ): + G1 = backend.convert_to_nx(bound.arguments["G"]) + G2 = bound2.arguments["G"] + if G1 is G2: + return G2 + G2._node.clear() + G2._node.update(G1._node) + G2._adj.clear() + G2._adj.update(G1._adj) + if hasattr(G1, "_pred") and hasattr(G2, "_pred"): + G2._pred.clear() + G2._pred.update(G1._pred) + if hasattr(G1, "_succ") and hasattr(G2, "_succ"): + G2._succ.clear() + G2._succ.update(G1._succ) + nx._clear_cache(G2) + if self.name == "relabel_nodes": + return G2 + return backend.convert_to_nx(result) + + converted_result = backend.convert_to_nx(result) + if isinstance(converted_result, nx.Graph) and self.name not in { + "boykov_kolmogorov", + "preflow_push", + "quotient_graph", + "shortest_augmenting_path", + "spectral_graph_forge", + # We don't handle tempfile.NamedTemporaryFile arguments + "read_gml", + "read_graph6", + "read_sparse6", + # We don't handle io.BufferedReader or io.TextIOWrapper arguments + "bipartite_read_edgelist", + "read_adjlist", + "read_edgelist", + "read_graphml", + "read_multiline_adjlist", + "read_pajek", + "from_pydot", + "pydot_read_dot", + "agraph_read_dot", + # graph comparison fails b/c of nan values + "read_gexf", + }: + # For graph return types (e.g. generators), we compare that results are + # the same between the backend and networkx, then return the original + # networkx result so the iteration order will be consistent in tests. + G = self.orig_func(*args2, **kwargs2) + if not nx.utils.graphs_equal(G, converted_result): + assert G.number_of_nodes() == converted_result.number_of_nodes() + assert G.number_of_edges() == converted_result.number_of_edges() + assert G.graph == converted_result.graph + assert G.nodes == converted_result.nodes + assert G.adj == converted_result.adj + assert type(G) is type(converted_result) + raise AssertionError("Graphs are not equal") + return G + return converted_result + + def _make_doc(self): + """Generate the backends section at the end for functions having an alternate + backend implementation(s) using the `backend_info` entry-point.""" + + if not self.backends: + return self._orig_doc + lines = [ + "Backends", + "--------", + ] + for backend in sorted(self.backends): + info = backend_info[backend] + if "short_summary" in info: + lines.append(f"{backend} : {info['short_summary']}") + else: + lines.append(backend) + if "functions" not in info or self.name not in info["functions"]: + lines.append("") + continue + + func_info = info["functions"][self.name] + + # Renaming extra_docstring to additional_docs + if func_docs := ( + func_info.get("additional_docs") or func_info.get("extra_docstring") + ): + lines.extend( + f" {line}" if line else line for line in func_docs.split("\n") + ) + add_gap = True + else: + add_gap = False + + # Renaming extra_parameters to additional_parameters + if extra_parameters := ( + func_info.get("extra_parameters") + or func_info.get("additional_parameters") + ): + if add_gap: + lines.append("") + lines.append(" Additional parameters:") + for param in sorted(extra_parameters): + lines.append(f" {param}") + if desc := extra_parameters[param]: + lines.append(f" {desc}") + lines.append("") + else: + lines.append("") + + if func_url := func_info.get("url"): + lines.append(f"[`Source <{func_url}>`_]") + lines.append("") + + lines.pop() # Remove last empty line + to_add = "\n ".join(lines) + return f"{self._orig_doc.rstrip()}\n\n {to_add}" + + def __reduce__(self): + """Allow this object to be serialized with pickle. + + This uses the global registry `_registered_algorithms` to deserialize. + """ + return _restore_dispatchable, (self.name,) + + +def _restore_dispatchable(name): + return _registered_algorithms[name] + + +if os.environ.get("_NETWORKX_BUILDING_DOCS_"): + # When building docs with Sphinx, use the original function with the + # dispatched __doc__, b/c Sphinx renders normal Python functions better. + # This doesn't show e.g. `*, backend=None, **backend_kwargs` in the + # signatures, which is probably okay. It does allow the docstring to be + # updated based on the installed backends. + _orig_dispatchable = _dispatchable + + def _dispatchable(func=None, **kwargs): # type: ignore[no-redef] + if func is None: + return partial(_dispatchable, **kwargs) + dispatched_func = _orig_dispatchable(func, **kwargs) + func.__doc__ = dispatched_func.__doc__ + return func + + _dispatchable.__doc__ = _orig_dispatchable.__new__.__doc__ # type: ignore[method-assign,assignment] + _sig = inspect.signature(_orig_dispatchable.__new__) + _dispatchable.__signature__ = _sig.replace( # type: ignore[method-assign,assignment] + parameters=[v for k, v in _sig.parameters.items() if k != "cls"] + ) diff --git a/shared/package-files/6b/6bb99359d62bc8707095462dc9f7500fc7b4487298371f4edb6e791ea23f00d4/upsample_bicubic2d_backward_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/6b/6bb99359d62bc8707095462dc9f7500fc7b4487298371f4edb6e791ea23f00d4/upsample_bicubic2d_backward_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..15de400f78b921372783b0036cf5ba0b30f697cd --- /dev/null +++ b/shared/package-files/6b/6bb99359d62bc8707095462dc9f7500fc7b4487298371f4edb6e791ea23f00d4/upsample_bicubic2d_backward_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor upsample_bicubic2d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor upsample_bicubic2d_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/6b/6bbad9518cdb8e4b6851f650daa4a06699177ab1bba29e567a3141ecf96651db/compat.py b/shared/package-files/6b/6bbad9518cdb8e4b6851f650daa4a06699177ab1bba29e567a3141ecf96651db/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..96fbd25091787be47f76ff674bdf9a455d09ca52 --- /dev/null +++ b/shared/package-files/6b/6bbad9518cdb8e4b6851f650daa4a06699177ab1bba29e567a3141ecf96651db/compat.py @@ -0,0 +1,160 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +# Try to keep compat small because it's imported by everything +# What is compat, and what isn't? +# If a piece of code is "general" and used in multiple modules, it goes here. +# If it's only used in one module, keep it in that module, preferably near the top. +# This module should contain ONLY stdlib imports. + +import sys + +on_win = bool(sys.platform == "win32") +on_mac = bool(sys.platform == "darwin") +on_linux = bool(sys.platform == "linux") + +FILESYSTEM_ENCODING = sys.getfilesystemencoding() + +# Control some tweakables that will be removed finally. +ENCODE_ENVIRONMENT = True +ENCODE_ARGS = False + + +def encode_for_env_var(value) -> str: + """Environment names and values need to be string.""" + if isinstance(value, str): + return value + elif isinstance(value, bytes): + return value.decode() + return str(value) + + +def encode_environment(env): + if ENCODE_ENVIRONMENT: + env = {encode_for_env_var(k): encode_for_env_var(v) for k, v in env.items()} + return env + + +def encode_arguments(arguments): + if ENCODE_ARGS: + arguments = {encode_for_env_var(arg) for arg in arguments} + return arguments + + +from collections.abc import Iterable + + +def isiterable(obj): + return not isinstance(obj, str) and isinstance(obj, Iterable) + + +# ############################# +# other +# ############################# + +from collections import OrderedDict as odict # noqa: F401 +from io import open as io_open # NOQA + + +def open( + file, mode="r", buffering=-1, encoding=None, errors=None, newline=None, closefd=True +): + if "b" in mode: + return io_open( + file, + str(mode), + buffering=buffering, + errors=errors, + newline=newline, + closefd=closefd, + ) + else: + return io_open( + file, + str(mode), + buffering=buffering, + encoding=encoding or "utf-8", + errors=errors, + newline=newline, + closefd=closefd, + ) + + +def six_with_metaclass(meta, *bases): + """Create a base class with a metaclass.""" + + # This requires a bit of explanation: the basic idea is to make a dummy + # metaclass for one level of class instantiation that replaces itself with + # the actual metaclass. + class metaclass(type): + def __new__(cls, name, this_bases, d): + return meta(name, bases, d) + + @classmethod + def __prepare__(cls, name, this_bases): + return meta.__prepare__(name, bases) + + return type.__new__(metaclass, "temporary_class", (), {}) + + +NoneType = type(None) +primitive_types = (str, int, float, complex, bool, NoneType) + + +def ensure_binary(value): + try: + return value.encode("utf-8") + except AttributeError: # pragma: no cover + # AttributeError: '<>' object has no attribute 'encode' + # In this case assume already binary type and do nothing + return value + + +def ensure_text_type(value) -> str: + try: + return value.decode("utf-8") + except AttributeError: # pragma: no cover + # AttributeError: '<>' object has no attribute 'decode' + # In this case assume already text_type and do nothing + return value + except UnicodeDecodeError: # pragma: no cover + try: + from chardet import detect + except ImportError: + try: + from requests.packages.chardet import detect + except ImportError: # pragma: no cover + from pip._vendor.requests.packages.chardet import detect + encoding = detect(value).get("encoding") or "utf-8" + return value.decode(encoding, errors="replace") + except UnicodeEncodeError: # pragma: no cover + # it's already str, so ignore? + # not sure, surfaced with tests/models/test_match_spec.py test_tarball_match_specs + # using py27 + return value + + +def ensure_unicode(value): + try: + return value.decode("unicode_escape") + except AttributeError: # pragma: no cover + # AttributeError: '<>' object has no attribute 'decode' + # In this case assume already unicode and do nothing + return value + + +def ensure_fs_path_encoding(value): + try: + return value.encode(FILESYSTEM_ENCODING) + except AttributeError: + return value + except UnicodeEncodeError: + return value + + +def ensure_utf8_encoding(value): + try: + return value.encode("utf-8") + except AttributeError: + return value + except UnicodeEncodeError: + return value diff --git a/shared/package-files/6b/6bbb95eb64ab4a0197ea547380db5f1eb272d737bd5904ca5e6c7fd5d5848a0b/masked_scatter_ops.h b/shared/package-files/6b/6bbb95eb64ab4a0197ea547380db5f1eb272d737bd5904ca5e6c7fd5d5848a0b/masked_scatter_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..d9ea382ff78ccc5770288d1b949cc464cb3a3db6 --- /dev/null +++ b/shared/package-files/6b/6bbb95eb64ab4a0197ea547380db5f1eb272d737bd5904ca5e6c7fd5d5848a0b/masked_scatter_ops.h @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API masked_scatter_ { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::masked_scatter_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "masked_scatter_(Tensor(a!) self, Tensor mask, Tensor source) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & mask, const at::Tensor & source); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & mask, const at::Tensor & source); +}; + +struct TORCH_API masked_scatter { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::masked_scatter") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "masked_scatter(Tensor self, Tensor mask, Tensor source) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & mask, const at::Tensor & source); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mask, const at::Tensor & source); +}; + +struct TORCH_API masked_scatter_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::masked_scatter") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "masked_scatter.out(Tensor self, Tensor mask, Tensor source, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & mask, const at::Tensor & source, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mask, const at::Tensor & source, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/6b/6bbb9dd3aeee3083337c7aa8d8e61e5a28134b18cf5df5513eb4c3efef1b2432/_adaptive_avg_pool2d_native.h b/shared/package-files/6b/6bbb9dd3aeee3083337c7aa8d8e61e5a28134b18cf5df5513eb4c3efef1b2432/_adaptive_avg_pool2d_native.h new file mode 100644 index 0000000000000000000000000000000000000000..769ba38dc3770fc2d98e307b466f17cc4615fad2 --- /dev/null +++ b/shared/package-files/6b/6bbb9dd3aeee3083337c7aa8d8e61e5a28134b18cf5df5513eb4c3efef1b2432/_adaptive_avg_pool2d_native.h @@ -0,0 +1,25 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & _adaptive_avg_pool2d_out_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, at::Tensor & out); +TORCH_API at::Tensor adaptive_avg_pool2d_cpu(const at::Tensor & self, at::IntArrayRef output_size); +TORCH_API at::Tensor adaptive_avg_pool2d_cuda(const at::Tensor & self, at::IntArrayRef output_size); +TORCH_API at::Tensor adaptive_avg_pool2d_quantized_cpu(const at::Tensor & self, at::IntArrayRef output_size); +TORCH_API at::Tensor adaptive_avg_pool2d_quantized_cuda(const at::Tensor & self, at::IntArrayRef output_size); +} // namespace native +} // namespace at diff --git a/shared/package-files/6b/6bbc15f0ec644738f41752fb074da0719aef322e54cfcee0db01b4a47bd6b4d2/sre_compile.pyi b/shared/package-files/6b/6bbc15f0ec644738f41752fb074da0719aef322e54cfcee0db01b4a47bd6b4d2/sre_compile.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9b50b75d8c312446ffa62f34d7f5e360791235c5 --- /dev/null +++ b/shared/package-files/6b/6bbc15f0ec644738f41752fb074da0719aef322e54cfcee0db01b4a47bd6b4d2/sre_compile.pyi @@ -0,0 +1,31 @@ +import sys +from sre_constants import ( + SRE_FLAG_DEBUG as SRE_FLAG_DEBUG, + SRE_FLAG_DOTALL as SRE_FLAG_DOTALL, + SRE_FLAG_IGNORECASE as SRE_FLAG_IGNORECASE, + SRE_FLAG_LOCALE as SRE_FLAG_LOCALE, + SRE_FLAG_MULTILINE as SRE_FLAG_MULTILINE, + SRE_FLAG_TEMPLATE as SRE_FLAG_TEMPLATE, + SRE_FLAG_UNICODE as SRE_FLAG_UNICODE, + SRE_FLAG_VERBOSE as SRE_FLAG_VERBOSE, + SRE_INFO_CHARSET as SRE_INFO_CHARSET, + SRE_INFO_LITERAL as SRE_INFO_LITERAL, + SRE_INFO_PREFIX as SRE_INFO_PREFIX, +) +from sre_parse import SubPattern +from typing import Any, List, Pattern, Tuple, Type, Union + +if sys.version_info >= (3,): + from sre_constants import SRE_FLAG_ASCII as SRE_FLAG_ASCII + +MAXCODE: int +if sys.version_info < (3, 0): + STRING_TYPES: Tuple[Type[str], Type[unicode]] + _IsStringType = int +else: + from sre_constants import _NamedIntConstant + def dis(code: List[_NamedIntConstant]) -> None: ... + _IsStringType = bool + +def isstring(obj: Any) -> _IsStringType: ... +def compile(p: Union[str, bytes, SubPattern], flags: int = ...) -> Pattern[Any]: ... diff --git a/shared/package-files/6b/6bbc9fe7cf6be5bd2602b62e96a2df6ef996f0d7493539c75d987dadc9574d54/unittest.pyi b/shared/package-files/6b/6bbc9fe7cf6be5bd2602b62e96a2df6ef996f0d7493539c75d987dadc9574d54/unittest.pyi new file mode 100644 index 0000000000000000000000000000000000000000..57b73a762cfa8cffefe878f46220b3732ce3d525 --- /dev/null +++ b/shared/package-files/6b/6bbc9fe7cf6be5bd2602b62e96a2df6ef996f0d7493539c75d987dadc9574d54/unittest.pyi @@ -0,0 +1,280 @@ +import datetime +import types +from abc import ABCMeta, abstractmethod +from typing import ( + Any, + Callable, + Dict, + FrozenSet, + Iterable, + Iterator, + List, + Mapping, + NoReturn, + Optional, + Pattern, + Sequence, + Set, + Text, + TextIO, + Tuple, + Type, + TypeVar, + Union, + overload, +) + +_T = TypeVar("_T") +_FT = TypeVar("_FT") + +_ExceptionType = Union[Type[BaseException], Tuple[Type[BaseException], ...]] +_Regexp = Union[Text, Pattern[Text]] + +_SysExcInfoType = Union[Tuple[Type[BaseException], BaseException, types.TracebackType], Tuple[None, None, None]] + +class Testable(metaclass=ABCMeta): + @abstractmethod + def run(self, result: TestResult) -> None: ... + @abstractmethod + def debug(self) -> None: ... + @abstractmethod + def countTestCases(self) -> int: ... + +# TODO ABC for test runners? + +class TestResult: + errors: List[Tuple[TestCase, str]] + failures: List[Tuple[TestCase, str]] + skipped: List[Tuple[TestCase, str]] + expectedFailures: List[Tuple[TestCase, str]] + unexpectedSuccesses: List[TestCase] + shouldStop: bool + testsRun: int + buffer: bool + failfast: bool + def wasSuccessful(self) -> bool: ... + def stop(self) -> None: ... + def startTest(self, test: TestCase) -> None: ... + def stopTest(self, test: TestCase) -> None: ... + def startTestRun(self) -> None: ... + def stopTestRun(self) -> None: ... + def addError(self, test: TestCase, err: _SysExcInfoType) -> None: ... + def addFailure(self, test: TestCase, err: _SysExcInfoType) -> None: ... + def addSuccess(self, test: TestCase) -> None: ... + def addSkip(self, test: TestCase, reason: str) -> None: ... + def addExpectedFailure(self, test: TestCase, err: str) -> None: ... + def addUnexpectedSuccess(self, test: TestCase) -> None: ... + +class _AssertRaisesBaseContext: + expected: Any + failureException: Type[BaseException] + obj_name: str + expected_regex: Pattern[str] + +class _AssertRaisesContext(_AssertRaisesBaseContext): + exception: Any + def __enter__(self) -> _AssertRaisesContext: ... + def __exit__(self, exc_type, exc_value, tb) -> bool: ... + +class TestCase(Testable): + failureException: Type[BaseException] + longMessage: bool + maxDiff: Optional[int] + # undocumented + _testMethodName: str + def __init__(self, methodName: str = ...) -> None: ... + def setUp(self) -> None: ... + def tearDown(self) -> None: ... + @classmethod + def setUpClass(cls) -> None: ... + @classmethod + def tearDownClass(cls) -> None: ... + def run(self, result: TestResult = ...) -> None: ... + def debug(self) -> None: ... + def assert_(self, expr: Any, msg: object = ...) -> None: ... + def failUnless(self, expr: Any, msg: object = ...) -> None: ... + def assertTrue(self, expr: Any, msg: object = ...) -> None: ... + def assertEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... + def assertEquals(self, first: Any, second: Any, msg: object = ...) -> None: ... + def failUnlessEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... + def assertNotEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... + def assertNotEquals(self, first: Any, second: Any, msg: object = ...) -> None: ... + def failIfEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... + @overload + def assertAlmostEqual(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... + @overload + def assertAlmostEqual(self, first: float, second: float, *, msg: Any = ..., delta: float = ...) -> None: ... + @overload + def assertAlmostEqual( + self, first: datetime.datetime, second: datetime.datetime, *, msg: Any = ..., delta: datetime.timedelta = ... + ) -> None: ... + @overload + def assertAlmostEquals(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... + @overload + def assertAlmostEquals(self, first: float, second: float, *, msg: Any = ..., delta: float = ...) -> None: ... + @overload + def assertAlmostEquals( + self, first: datetime.datetime, second: datetime.datetime, *, msg: Any = ..., delta: datetime.timedelta = ... + ) -> None: ... + def failUnlessAlmostEqual(self, first: float, second: float, places: int = ..., msg: object = ...) -> None: ... + @overload + def assertNotAlmostEqual(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... + @overload + def assertNotAlmostEqual(self, first: float, second: float, *, msg: Any = ..., delta: float = ...) -> None: ... + @overload + def assertNotAlmostEqual( + self, first: datetime.datetime, second: datetime.datetime, *, msg: Any = ..., delta: datetime.timedelta = ... + ) -> None: ... + @overload + def assertNotAlmostEquals(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... + @overload + def assertNotAlmostEquals(self, first: float, second: float, *, msg: Any = ..., delta: float = ...) -> None: ... + @overload + def assertNotAlmostEquals( + self, first: datetime.datetime, second: datetime.datetime, *, msg: Any = ..., delta: datetime.timedelta = ... + ) -> None: ... + def failIfAlmostEqual( + self, first: float, second: float, places: int = ..., msg: object = ..., delta: float = ... + ) -> None: ... + def assertGreater(self, first: Any, second: Any, msg: object = ...) -> None: ... + def assertGreaterEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... + def assertMultiLineEqual(self, first: str, second: str, msg: object = ...) -> None: ... + def assertSequenceEqual( + self, first: Sequence[Any], second: Sequence[Any], msg: object = ..., seq_type: type = ... + ) -> None: ... + def assertListEqual(self, first: List[Any], second: List[Any], msg: object = ...) -> None: ... + def assertTupleEqual(self, first: Tuple[Any, ...], second: Tuple[Any, ...], msg: object = ...) -> None: ... + def assertSetEqual( + self, first: Union[Set[Any], FrozenSet[Any]], second: Union[Set[Any], FrozenSet[Any]], msg: object = ... + ) -> None: ... + def assertDictEqual(self, first: Dict[Any, Any], second: Dict[Any, Any], msg: object = ...) -> None: ... + def assertLess(self, first: Any, second: Any, msg: object = ...) -> None: ... + def assertLessEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... + @overload + def assertRaises(self, exception: _ExceptionType, callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + @overload + def assertRaises(self, exception: _ExceptionType) -> _AssertRaisesContext: ... + @overload + def assertRaisesRegexp( + self, exception: _ExceptionType, regexp: _Regexp, callable: Callable[..., Any], *args: Any, **kwargs: Any + ) -> None: ... + @overload + def assertRaisesRegexp(self, exception: _ExceptionType, regexp: _Regexp) -> _AssertRaisesContext: ... + def assertRegexpMatches(self, text: Text, regexp: _Regexp, msg: object = ...) -> None: ... + def assertNotRegexpMatches(self, text: Text, regexp: _Regexp, msg: object = ...) -> None: ... + def assertItemsEqual(self, first: Iterable[Any], second: Iterable[Any], msg: object = ...) -> None: ... + def assertDictContainsSubset(self, expected: Mapping[Any, Any], actual: Mapping[Any, Any], msg: object = ...) -> None: ... + def addTypeEqualityFunc(self, typeobj: type, function: Callable[..., None]) -> None: ... + @overload + def failUnlessRaises(self, exception: _ExceptionType, callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + @overload + def failUnlessRaises(self, exception: _ExceptionType) -> _AssertRaisesContext: ... + def failIf(self, expr: Any, msg: object = ...) -> None: ... + def assertFalse(self, expr: Any, msg: object = ...) -> None: ... + def assertIs(self, first: object, second: object, msg: object = ...) -> None: ... + def assertIsNot(self, first: object, second: object, msg: object = ...) -> None: ... + def assertIsNone(self, expr: Any, msg: object = ...) -> None: ... + def assertIsNotNone(self, expr: Any, msg: object = ...) -> None: ... + def assertIn(self, first: _T, second: Iterable[_T], msg: object = ...) -> None: ... + def assertNotIn(self, first: _T, second: Iterable[_T], msg: object = ...) -> None: ... + def assertIsInstance(self, obj: Any, cls: Union[type, Tuple[type, ...]], msg: object = ...) -> None: ... + def assertNotIsInstance(self, obj: Any, cls: Union[type, Tuple[type, ...]], msg: object = ...) -> None: ... + def fail(self, msg: object = ...) -> NoReturn: ... + def countTestCases(self) -> int: ... + def defaultTestResult(self) -> TestResult: ... + def id(self) -> str: ... + def shortDescription(self) -> str: ... # May return None + def addCleanup(self, function: Any, *args: Any, **kwargs: Any) -> None: ... + def doCleanups(self) -> bool: ... + def skipTest(self, reason: Any) -> None: ... + def _formatMessage(self, msg: Optional[Text], standardMsg: Text) -> str: ... # undocumented + def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ... # undocumented + +class FunctionTestCase(TestCase): + def __init__( + self, + testFunc: Callable[[], None], + setUp: Optional[Callable[[], None]] = ..., + tearDown: Optional[Callable[[], None]] = ..., + description: Optional[str] = ..., + ) -> None: ... + def debug(self) -> None: ... + def countTestCases(self) -> int: ... + +class TestSuite(Testable): + def __init__(self, tests: Iterable[Testable] = ...) -> None: ... + def addTest(self, test: Testable) -> None: ... + def addTests(self, tests: Iterable[Testable]) -> None: ... + def run(self, result: TestResult) -> None: ... + def debug(self) -> None: ... + def countTestCases(self) -> int: ... + def __iter__(self) -> Iterator[Testable]: ... + +class TestLoader: + testMethodPrefix: str + sortTestMethodsUsing: Optional[Callable[[str, str], int]] + suiteClass: Callable[[List[TestCase]], TestSuite] + def loadTestsFromTestCase(self, testCaseClass: Type[TestCase]) -> TestSuite: ... + def loadTestsFromModule(self, module: types.ModuleType = ..., use_load_tests: bool = ...) -> TestSuite: ... + def loadTestsFromName(self, name: str = ..., module: Optional[types.ModuleType] = ...) -> TestSuite: ... + def loadTestsFromNames(self, names: List[str] = ..., module: Optional[types.ModuleType] = ...) -> TestSuite: ... + def discover(self, start_dir: str, pattern: str = ..., top_level_dir: Optional[str] = ...) -> TestSuite: ... + def getTestCaseNames(self, testCaseClass: Type[TestCase] = ...) -> List[str]: ... + +defaultTestLoader: TestLoader + +class TextTestResult(TestResult): + def __init__(self, stream: TextIO, descriptions: bool, verbosity: int) -> None: ... + def getDescription(self, test: TestCase) -> str: ... # undocumented + def printErrors(self) -> None: ... # undocumented + def printErrorList(self, flavour: str, errors: List[Tuple[TestCase, str]]) -> None: ... # undocumented + +class TextTestRunner: + def __init__( + self, + stream: Optional[TextIO] = ..., + descriptions: bool = ..., + verbosity: int = ..., + failfast: bool = ..., + buffer: bool = ..., + resultclass: Optional[Type[TestResult]] = ..., + ) -> None: ... + def _makeResult(self) -> TestResult: ... + def run(self, test: Testable) -> TestResult: ... # undocumented + +class SkipTest(Exception): ... + +# TODO precise types +def skipUnless(condition: Any, reason: Union[str, unicode]) -> Any: ... +def skipIf(condition: Any, reason: Union[str, unicode]) -> Any: ... +def expectedFailure(func: _FT) -> _FT: ... +def skip(reason: Union[str, unicode]) -> Any: ... + +# not really documented +class TestProgram: + result: TestResult + def runTests(self) -> None: ... # undocumented + +def main( + module: Union[None, Text, types.ModuleType] = ..., + defaultTest: Optional[str] = ..., + argv: Optional[Sequence[str]] = ..., + testRunner: Union[Type[TextTestRunner], TextTestRunner, None] = ..., + testLoader: TestLoader = ..., + exit: bool = ..., + verbosity: int = ..., + failfast: Optional[bool] = ..., + catchbreak: Optional[bool] = ..., + buffer: Optional[bool] = ..., +) -> TestProgram: ... +def load_tests(loader: TestLoader, tests: TestSuite, pattern: Optional[Text]) -> TestSuite: ... +def installHandler() -> None: ... +def registerResult(result: TestResult) -> None: ... +def removeResult(result: TestResult) -> bool: ... +@overload +def removeHandler() -> None: ... +@overload +def removeHandler(function: Callable[..., Any]) -> Callable[..., Any]: ... + +# private but occasionally used +util: types.ModuleType diff --git a/shared/package-files/6b/6bbf08ad0e95898d3e4d0db890d678e117bbdc321b9e61b501ae703b83dc73d5/_numeric_suite_fx.py b/shared/package-files/6b/6bbf08ad0e95898d3e4d0db890d678e117bbdc321b9e61b501ae703b83dc73d5/_numeric_suite_fx.py new file mode 100644 index 0000000000000000000000000000000000000000..b26dbadc006823cdbb2fb9f9cfce537336abf842 --- /dev/null +++ b/shared/package-files/6b/6bbf08ad0e95898d3e4d0db890d678e117bbdc321b9e61b501ae703b83dc73d5/_numeric_suite_fx.py @@ -0,0 +1,1025 @@ +""" +This module contains tooling to compare weights and activations +across models. Example usage:: + + import copy + import torch + import torch.ao.quantization.quantize_fx as quantize_fx + import torch.ao.ns._numeric_suite_fx as ns + + m = torch.nn.Sequential(torch.nn.Conv2d(1, 1, 1)).eval() + mp = quantize_fx.prepare_fx(m, {'': torch.ao.quantization.default_qconfig}) + # We convert a copy because we need the original prepared model + # to be available for comparisons, and `quantize_fx.convert_fx` is inplace. + mq = quantize_fx.convert_fx(copy.deepcopy(mp)) + + # + # Comparing weights + # + + # extract weight pairs + weight_comparison = ns.extract_weights('a', mp, 'b', mq) + + # add SQNR for each comparison, inplace + ns.extend_logger_results_with_comparison( + weight_comparison, 'a', 'b', torch.ao.ns.fx.utils.compute_sqnr, + 'sqnr') + + # weight_comparison contains the weights from `mp` and `mq` stored + # in pairs, and can be used for further analysis. + + + # + # Comparing activations, with error propagation + # + + # add loggers + mp_ns, mq_ns = ns.add_loggers( + 'a', copy.deepcopy(mp), + 'b', copy.deepcopy(mq), + ns.OutputLogger) + + # send an example datum to capture intermediate activations + datum = torch.randn(1, 1, 1, 1) + mp_ns(datum) + mq_ns(datum) + + # extract intermediate activations + act_comparison = ns.extract_logger_info( + mp_ns, mq_ns, ns.OutputLogger, 'b') + + # add SQNR for each comparison, inplace + ns.extend_logger_results_with_comparison( + act_comparison, 'a', 'b', torch.ao.ns.fx.utils.compute_sqnr, + 'sqnr') + + # act_comparison contains the activations from `mp_ns` and `mq_ns` stored + # in pairs, and can be used for further analysis. + + # + # Comparing activations, without error propagation + # + + # create shadow model + mp_shadows_mq = ns.add_shadow_loggers( + 'a', copy.deepcopy(mp), + 'b', copy.deepcopy(mq), + ns.OutputLogger) + + # send an example datum to capture intermediate activations + datum = torch.randn(1, 1, 1, 1) + mp_shadows_mq(datum) + + # extract intermediate activations + shadow_act_comparison = ns.extract_shadow_logger_info( + mp_shadows_mq, ns.OutputLogger, 'b') + + # add SQNR for each comparison, inplace + ns.extend_logger_results_with_comparison( + shadow_act_comparison, 'a', 'b', torch.ao.ns.fx.utils.compute_sqnr, + 'sqnr') + + # shadow_act_comparison contains the activations from `mp_ns` and `mq_ns` stored + # in pairs, and can be used for further analysis. + +""" + +import collections + +import torch +import torch.nn as nn +import torch.ao.quantization.quantize_fx as quantize_fx +from torch.fx import GraphModule +from torch.fx.graph import Node +from torch.ao.ns.fx.mappings import ( + get_base_name_to_sets_of_related_ops, +) +from torch.ao.ns.fx.graph_matcher import ( + get_matching_subgraph_pairs, + get_type_a_related_to_b, +) + +from .fx.weight_utils import ( + extract_weight_from_node, +) + +from .fx.graph_passes import ( + add_loggers_to_model, + create_a_shadows_b, +) + +from .fx.utils import ( + rekey_logger_info_on_node_name_of_model, + maybe_add_missing_fqns, + get_target_type_str, +) + +from .fx.ns_types import ( + NSSingleResultValuesType, + NSResultsType, + NSNodeTargetType, +) +from torch.ao.quantization.backend_config.utils import get_fusion_pattern_to_root_node_getter +from torch.ao.quantization.backend_config import BackendConfig +from torch.ao.quantization.fx.match_utils import _find_matches +from torch.ao.quantization.fx.graph_module import _get_observed_graph_module_attr +from torch.ao.quantization.fx.qconfig_mapping_utils import _generate_node_name_to_qconfig +from torch.ao.quantization.fx.quantize_handler import _get_pattern_to_quantize_handlers +from torch.ao.quantization.qconfig import QConfigAny +from torch.ao.quantization import QConfigMapping +from torch.ao.ns.fx.n_shadows_utils import ( + OutputProp, + _get_dedup_subgraphs, + SHADOW_WRAPPER_NODE_NAME_PREFIX, + group_results_by_subgraph, + create_results_comparison, + print_n_shadows_summary, + create_n_transformed_and_logged_copies_of_subgraph, + create_add_loggers_graph, + extract_weight_comparison, +) +from torch.ao.ns.fx.qconfig_multi_mapping import QConfigMultiMapping + +from typing import Dict, Tuple, Callable, List, Optional, Set, Any, Type + +RNNReturnType = Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]] + +class OutputLogger(nn.Module): + """ + Base class for capturing intermediate values. + """ + stats: List[torch.Tensor] + stats_rnn: List[RNNReturnType] + + # Mark as impure so that calls to it will not be removed during DCE. + _is_impure = True + + def __init__( + self, + ref_node_name: str, + prev_node_name: str, + model_name: str, + ref_name: str, + prev_node_target_type: str, + ref_node_target_type: str, + results_type: str, + index_within_arg: int, + index_of_arg: int, + fqn: Optional[str], + qconfig_str: Optional[str] = '', + ): + super().__init__() + self.stats: List[torch.Tensor] = [] + self.stats_rnn: List[RNNReturnType] = [] + + # name of the node which was responsible for adding this logger + # Note: + # - if we are logging node outputs, this is the same as prev_node_name + # - if we are logging node inputs, this is the name of the node + # whose input this logger is logging. + # + # example, where logger1 is logging input of op1 and logger2 is logging + # the output of op1: + # + # x1 -> logger1 -> op1 -> logger2 -> x2 + # + # in this example, + # - logger1's prev_node_name is x1 and ref_node_name is op1 + # - logger2's prev_node_name is op1 and ref_node_name is op1 + self.ref_node_name = ref_node_name + # name of the node whose output this Logger is capturing + self.prev_node_name = prev_node_name + + # name of the model from which the node originated from + self.model_name = model_name + # reference name, used to match loggers from separate models + # to each other + self.ref_name = ref_name + # type of the target of the node whose output this logger is logging + self.prev_node_target_type = prev_node_target_type + # type of the target of the node which was responsible for adding this + # logger + self.ref_node_target_type = ref_node_target_type + # what kind of values are inside of stats + self.results_type = results_type + # index of this node within the arg of the input/output node + # for example, in cat([x1, x2, x3], dim=0), x2 would have index_within_arg == 1 + self.index_within_arg = index_within_arg + # index of this node within the args of the input/output node + # for example, in add(x1, x2), x2 would have index_of_arg == 1 + self.index_of_arg = index_of_arg + # fully qualified name + self.fqn = fqn + # if loggers are added before prepare_fx, but we do not want + # collect results of calibration, only results after convert_fx + # so, we add a flag to control whether this logger collects data + self.enabled = True + # string representation of qconfig + self.qconfig_str = qconfig_str + # this can be turned off to reduce memory usage during calibration + self.save_activations = True + + # Note: cannot annotate the type of x because TorchScript does not support + # the Union type. + def forward(self, x): + """ + """ # blank docblock to make autodoc happy + # TODO(future PR): consider designing this better, as the difference + # between these two flags is subtle and not obvious. + if not self.enabled: + return x + if not self.save_activations: + return x + # TODO(future PR): consider refactoring this to better reuse the parent + # class + if isinstance(x, torch.Tensor): + self.stats.append(x.detach()) + elif isinstance(x, tuple) and len(x) == 2 and len(x[1]) == 2: + new_res = (x[0].detach(), (x[1][0].detach(), x[1][1].detach())) + self.stats_rnn.append(new_res) + return x + + def __repr__(self): + clean_dict = { + k: v + for k, v in self.__dict__.items() + # skip nn.Module keys + if (k != 'training') and not k.startswith('_') + } + return f"OutputLogger({clean_dict})" + + +class OutputComparisonLogger(OutputLogger): + """ + Same as OutputLogger, but also requires the original activation + in order to calculate the comparison at calibration time + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # TODO(future PR): make the comparison function configurable + self.comparison_fn = torch.ao.ns.fx.utils.compute_sqnr + self.comparison_fn_name = 'sqnr' + # precalculated comparisons of logger output versus reference + self.comparisons = [] + # precalculated comparisons function + + def forward(self, x, x_ref): + """ + """ # blank docblock to make autodoc happy + if not self.enabled: + return x + assert isinstance(x, torch.Tensor), 'non-tensor inputs not yet supported' + if self.save_activations: + # save the activation, for debugging + self.stats.append(x.detach()) + # save the comparison + self.comparisons.append(self.comparison_fn(x, x_ref)) + return x + + def __repr__(self): + clean_dict = { + k: v + for k, v in self.__dict__.items() + # skip nn.Module keys + if (k != 'training') and not k.startswith('_') + } + return f"OutputComparisonLogger({clean_dict})" + + +class NSTracer(quantize_fx.QuantizationTracer): + """ + Just like a regular FX quantization tracer, but treats observers and fake_quantize + modules as leaf modules. + """ + def is_leaf_module(self, m: torch.nn.Module, module_qualified_name : str) -> bool: + """ + """ # blank docblock to make autodoc happy + if isinstance(m, torch.ao.quantization.ObserverBase): + return True + elif isinstance(m, torch.ao.quantization.FakeQuantizeBase): + return True + return super().is_leaf_module(m, module_qualified_name) + + +def _extract_weights_one_model( + model_name: str, + model: GraphModule, + nodes_and_names_to_instrument: List[Tuple[Node, str]], + results: NSResultsType, + op_to_type_to_weight_extraction_fn: Optional[Dict[str, Dict[Callable, Callable]]] = None, +) -> None: + torch._C._log_api_usage_once("quantization_api._numeric_suite_fx._extract_weights_one_model") + for node, ref_name in nodes_and_names_to_instrument: + res_type = NSSingleResultValuesType.WEIGHT.value + extracted_weight = extract_weight_from_node( + node, model, op_to_type_to_weight_extraction_fn) + if extracted_weight: + if ref_name not in results: + results[ref_name] = {res_type: {}} + results[ref_name][res_type][model_name] = [extracted_weight] + + +def _extract_weights_impl( + model_name_a: str, + gm_a: GraphModule, + model_name_b: str, + gm_b: GraphModule, + base_name_to_sets_of_related_ops: Optional[Dict[str, Set[NSNodeTargetType]]] = None, + unmatchable_types_map: Optional[Dict[str, Set[NSNodeTargetType]]] = None, + op_to_type_to_weight_extraction_fn: Optional[Dict[str, Dict[Callable, Callable]]] = None, +) -> NSResultsType: + torch._C._log_api_usage_once("quantization_api._numeric_suite_fx._extract_weights_impl") + matched_subgraph_pairs = get_matching_subgraph_pairs( + gm_a, gm_b, base_name_to_sets_of_related_ops, + unmatchable_types_map) + + # split the subgraph pairs into one data structure for each model + nodes_and_names_to_instrument_a: List[Tuple[Node, str]] = [] + nodes_and_names_to_instrument_b: List[Tuple[Node, str]] = [] + for match_name, match in matched_subgraph_pairs.items(): + subgraph_a, subgraph_b = match + nodes_and_names_to_instrument_a.append((subgraph_a.base_op_node, match_name)) + nodes_and_names_to_instrument_b.append((subgraph_b.base_op_node, match_name)) + + # populate the results, one model at a time + results: NSResultsType = {} + _extract_weights_one_model( + model_name_a, gm_a, nodes_and_names_to_instrument_a, results, + op_to_type_to_weight_extraction_fn) + _extract_weights_one_model( + model_name_b, gm_b, nodes_and_names_to_instrument_b, results, + op_to_type_to_weight_extraction_fn) + + # fill in missing fqn entries + maybe_add_missing_fqns(results) + + # rekey on names of nodes in gm_b + results = rekey_logger_info_on_node_name_of_model(results, model_name_b) + + return results + + +def extract_weights( + model_name_a: str, + model_a: nn.Module, + model_name_b: str, + model_b: nn.Module, + base_name_to_sets_of_related_ops: Optional[Dict[str, Set[NSNodeTargetType]]] = None, + unmatchable_types_map: Optional[Dict[str, Set[NSNodeTargetType]]] = None, + op_to_type_to_weight_extraction_fn: Optional[Dict[str, Dict[Callable, Callable]]] = None, +) -> NSResultsType: + """ + Extract weights from model A and model B, and return a comparison. + + Args: + model_name_a: string name of model A to use in results + model_a: model A + model_name_b: string name of model B to use in results + model_b: model B + base_name_to_sets_of_related_ops: optional override of subgraph base nodes, subject to change + unmatchable_types_map: optional override of unmatchable types, subject to change + op_to_type_to_weight_extraction_fn: optional override of function which extracts weight + from a type, subject to change + + Return: + NSResultsType, containing the weight comparisons + """ + + torch._C._log_api_usage_once("quantization_api._numeric_suite_fx.extract_weights") + if base_name_to_sets_of_related_ops is None: + base_name_to_sets_of_related_ops = \ + get_base_name_to_sets_of_related_ops() + type_a_related_to_b = \ + get_type_a_related_to_b(base_name_to_sets_of_related_ops) + + # TODO(future PR): expose these + skipped_module_names: List[str] = [] + skipped_module_classes: List[Callable] = [] + tracer_a = NSTracer(skipped_module_names, skipped_module_classes) + tracer_b = NSTracer(skipped_module_names, skipped_module_classes) + gm_a = GraphModule(model_a, tracer_a.trace(model_a)) + maybe_model_a_node_name_to_scope = _get_observed_graph_module_attr(model_a, 'node_name_to_scope') + if maybe_model_a_node_name_to_scope is not None: + gm_a._node_name_to_scope = maybe_model_a_node_name_to_scope + gm_b = GraphModule(model_b, tracer_b.trace(model_b)) + maybe_model_b_node_name_to_scope = _get_observed_graph_module_attr(model_b, 'node_name_to_scope') + if maybe_model_b_node_name_to_scope is not None: + gm_b._node_name_to_scope = maybe_model_b_node_name_to_scope + return _extract_weights_impl( + model_name_a, gm_a, model_name_b, gm_b, base_name_to_sets_of_related_ops, + unmatchable_types_map, op_to_type_to_weight_extraction_fn) + + +def _add_loggers_one_model( + model_name: str, + model: GraphModule, + nodes_and_names_to_instrument_inputs: List[Tuple[Node, str, str]], + nodes_and_names_to_instrument_outputs: List[Tuple[Node, str, str]], + logger_cls: Callable, +) -> nn.Module: + torch._C._log_api_usage_once("quantization_api._numeric_suite_fx._add_loggers_one_model") + + # TODO(future PR): do not observe nodes we do not care + # about (both fp32, denylist, etc) + node_to_instrument_inputs_to_ref_name: Dict[Node, Tuple[str, str]] = {} + node_to_instrument_outputs_to_ref_name: Dict[Node, Tuple[str, str]] = {} + for node, ref_name, ref_node_type in nodes_and_names_to_instrument_inputs: + node_to_instrument_inputs_to_ref_name[node] = (ref_name, ref_node_type) + for node, ref_name, ref_node_type in nodes_and_names_to_instrument_outputs: + node_to_instrument_outputs_to_ref_name[node] = (ref_name, ref_node_type) + + model = add_loggers_to_model( + model, node_to_instrument_inputs_to_ref_name, + node_to_instrument_outputs_to_ref_name, logger_cls, model_name) + return model + + +def _add_loggers_impl( + name_a: str, + gm_a: GraphModule, + name_b: str, + gm_b: GraphModule, + logger_cls: Callable, + should_log_inputs: bool, + base_name_to_sets_of_related_ops: Optional[Dict[str, Set[NSNodeTargetType]]] = None, + unmatchable_types_map: Optional[Dict[str, Set[NSNodeTargetType]]] = None, +) -> Tuple[nn.Module, nn.Module]: + torch._C._log_api_usage_once("quantization_api._numeric_suite_fx._add_loggers_impl") + matched_subgraph_pairs = get_matching_subgraph_pairs( + gm_a, gm_b, + base_name_to_sets_of_related_ops, unmatchable_types_map) + nodes_and_names_to_instrument_inputs_a = [] + nodes_and_names_to_instrument_inputs_b = [] + nodes_and_names_to_instrument_outputs_a = [] + nodes_and_names_to_instrument_outputs_b = [] + for match_name, (subgraph_a, subgraph_b) in matched_subgraph_pairs.items(): + ref_node_type_a = get_target_type_str(subgraph_a.base_op_node, gm_a) + ref_node_type_b = get_target_type_str(subgraph_b.base_op_node, gm_b) + # Note: for matching inputs we use start_node, such as observing + # the input of linear in linear-relu + if should_log_inputs: + nodes_and_names_to_instrument_inputs_a.append( + (subgraph_a.start_node, match_name, ref_node_type_a)) + nodes_and_names_to_instrument_inputs_b.append( + (subgraph_b.start_node, match_name, ref_node_type_b)) + # Note: for matching activations we always use end_node, + # such as observing the output of relu in linear-relu + nodes_and_names_to_instrument_outputs_a.append( + (subgraph_a.end_node, match_name, ref_node_type_a)) + nodes_and_names_to_instrument_outputs_b.append( + (subgraph_b.end_node, match_name, ref_node_type_b)) + + new_model_a = _add_loggers_one_model( + name_a, gm_a, nodes_and_names_to_instrument_inputs_a, + nodes_and_names_to_instrument_outputs_a, logger_cls) + new_model_b = _add_loggers_one_model( + name_b, gm_b, nodes_and_names_to_instrument_inputs_b, + nodes_and_names_to_instrument_outputs_b, logger_cls) + return (new_model_a, new_model_b) + + +def add_loggers( + name_a: str, + model_a: nn.Module, + name_b: str, + model_b: nn.Module, + logger_cls: Callable, + should_log_inputs : bool = False, + base_name_to_sets_of_related_ops: Optional[Dict[str, Set[NSNodeTargetType]]] = None, + unmatchable_types_map: Optional[Dict[str, Set[NSNodeTargetType]]] = None, +) -> Tuple[nn.Module, nn.Module]: + """ + Instrument model A and model B with loggers. + + Args: + name_a: string name of model A to use in results + model_a: model A + name_b: string name of model B to use in results + model_b: model B + logger_cls: class of Logger to use + base_name_to_sets_of_related_ops: optional override of subgraph base nodes, subject to change + unmatchable_types_map: optional override of unmatchable types, subject to change + + Return: + Returns a tuple of (model_a_with_loggers, model_b_with_loggers). Modifies both models inplace. + """ + + torch._C._log_api_usage_once("quantization_api._numeric_suite_fx.add_loggers") + # TODO(future PR): expose these + skipped_module_names: List[str] = [] + skipped_module_classes: List[Callable] = [] + tracer_a = NSTracer(skipped_module_names, skipped_module_classes) + tracer_b = NSTracer(skipped_module_names, skipped_module_classes) + gm_a = GraphModule(model_a, tracer_a.trace(model_a)) + maybe_model_a_node_name_to_scope = _get_observed_graph_module_attr(model_a, 'node_name_to_scope') + if maybe_model_a_node_name_to_scope is not None: + gm_a._node_name_to_scope = maybe_model_a_node_name_to_scope + gm_b = GraphModule(model_b, tracer_b.trace(model_b)) + maybe_model_b_node_name_to_scope = _get_observed_graph_module_attr(model_b, 'node_name_to_scope') + if maybe_model_b_node_name_to_scope is not None: + gm_b._node_name_to_scope = maybe_model_b_node_name_to_scope + return _add_loggers_impl( + name_a, gm_a, name_b, gm_b, logger_cls, + should_log_inputs=should_log_inputs, + base_name_to_sets_of_related_ops=base_name_to_sets_of_related_ops, + unmatchable_types_map=unmatchable_types_map) + + +def _extract_logger_info_one_model( + model: nn.Module, + results: NSResultsType, + logger_cls: Callable, +) -> None: + torch._C._log_api_usage_once("quantization_api._numeric_suite_fx._extract_logger_info_one_model") + for gm_name, mod in model.named_modules(): + # TODO(future PR): better check when scripted + is_logger = ( + isinstance(mod, logger_cls) # type: ignore[arg-type] + or ( + isinstance(mod, torch.jit.RecursiveScriptModule) + and mod.original_name == 'OutputLogger' + ) + ) + if is_logger: + key = mod.ref_name + if key not in results: + results[key] = {} + assert mod.model_name not in results[key], \ + f"{mod.model_name} is already present in results" + if mod.results_type not in results[key]: + results[key][mod.results_type] = {} + if mod.model_name not in results[key][mod.results_type]: + results[key][mod.results_type][mod.model_name] = [] + stats_to_use = mod.stats + if len(mod.stats_rnn) > 0: + stats_to_use = mod.stats_rnn + data = { + 'type': mod.results_type, + 'values': stats_to_use, + 'ref_node_name': mod.ref_node_name, + 'ref_node_target_type': mod.ref_node_target_type, + 'prev_node_name': mod.prev_node_name, + 'prev_node_target_type': mod.prev_node_target_type, + 'index_within_arg': mod.index_within_arg, + 'index_of_arg': mod.index_of_arg, + 'fqn': mod.fqn, + 'qconfig_str': mod.qconfig_str, + } + if hasattr(mod, 'comparisons'): + data['comparisons'] = mod.comparisons + data['comparison_fn_name'] = mod.comparison_fn_name + else: + data['comparisons'] = [] + data['comparison_fn_name'] = '' + results[key][mod.results_type][mod.model_name].append(data) + # ensure the list stays sorted + results[key][mod.results_type][mod.model_name].sort( + key=lambda res: + f"{res['index_of_arg']}:{res['index_within_arg']}" + ) + + +# TODO(future PR): align on naming +# this is equivalent of just the comparison extraction part of `ns.compare_model_outputs` +def extract_logger_info( + model_a: nn.Module, + model_b: nn.Module, + logger_cls: Callable, + model_name_to_use_for_layer_names: str, +) -> NSResultsType: + """ + Traverse all loggers in `model_a` and `model_b`, and extract the logged + information. + + Args: + model_a: model A + model_b: model B + logger_cls: class of Logger to use + model_name_to_use_for_layer_names: string name of model to use for + layer names in the output + + Return: + NSResultsType, containing the logged comparisons + """ + torch._C._log_api_usage_once("quantization_api._numeric_suite_fx.extract_logger_info") + results: NSResultsType = {} + for model in (model_a, model_b): + _extract_logger_info_one_model(model, results, logger_cls) + # fill in missing fqn entries + maybe_add_missing_fqns(results) + # rekey on the name of model b + results = rekey_logger_info_on_node_name_of_model( + results, model_name_to_use_for_layer_names) + return results + + +def _add_shadow_loggers_impl( + name_a: str, + gm_a: GraphModule, + name_b: str, + gm_b: GraphModule, + logger_cls: Callable, + should_log_inputs: bool, + base_name_to_sets_of_related_ops: Optional[Dict[str, Set[NSNodeTargetType]]] = None, + node_type_to_io_type_map: Optional[Dict[str, Set[NSNodeTargetType]]] = None, + unmatchable_types_map: Optional[Dict[str, Set[NSNodeTargetType]]] = None, +) -> nn.Module: + torch._C._log_api_usage_once("quantization_api._numeric_suite_fx._add_shadow_loggers_impl") + matched_subgraph_pairs = get_matching_subgraph_pairs( + gm_a, gm_b, base_name_to_sets_of_related_ops, + unmatchable_types_map) + gm_a_shadows_b = create_a_shadows_b( + name_a, gm_a, name_b, gm_b, matched_subgraph_pairs, logger_cls, + should_log_inputs=should_log_inputs, + node_type_to_io_type_map=node_type_to_io_type_map) + return gm_a_shadows_b + + +def add_shadow_loggers( + name_a: str, + model_a: nn.Module, + name_b: str, + model_b: nn.Module, + logger_cls: Callable, + should_log_inputs: bool = False, + base_name_to_sets_of_related_ops: Optional[Dict[str, Set[NSNodeTargetType]]] = None, + node_type_to_io_type_map: Optional[Dict[str, Set[NSNodeTargetType]]] = None, + unmatchable_types_map: Optional[Dict[str, Set[NSNodeTargetType]]] = None, +) -> nn.Module: + """ + Instrument model A and model B with shadow loggers. + + Args: + name_a: string name of model A to use in results + model_a: model A + name_b: string name of model B to use in results + model_b: model B + logger_cls: class of Logger to use + should_log_inputs: whether to log inputs + base_name_to_sets_of_related_ops: optional override of subgraph base nodes, subject to change + unmatchable_types_map: optional override of unmatchable types, subject to change + """ + torch._C._log_api_usage_once("quantization_api._numeric_suite_fx.add_shadow_loggers") + # TODO(future PR): expose these + skipped_module_names: List[str] = [] + skipped_module_classes: List[Callable] = [] + tracer_a = NSTracer(skipped_module_names, skipped_module_classes) + tracer_b = NSTracer(skipped_module_names, skipped_module_classes) + gm_a = GraphModule(model_a, tracer_a.trace(model_a)) + maybe_model_a_node_name_to_scope = _get_observed_graph_module_attr(model_a, 'node_name_to_scope') + if maybe_model_a_node_name_to_scope is not None: + gm_a._node_name_to_scope = maybe_model_a_node_name_to_scope + gm_b = GraphModule(model_b, tracer_b.trace(model_b)) + maybe_model_b_node_name_to_scope = _get_observed_graph_module_attr(model_b, 'node_name_to_scope') + if maybe_model_b_node_name_to_scope is not None: + gm_b._node_name_to_scope = maybe_model_b_node_name_to_scope + return _add_shadow_loggers_impl( + name_a, gm_a, name_b, gm_b, logger_cls, + should_log_inputs=should_log_inputs, + base_name_to_sets_of_related_ops=base_name_to_sets_of_related_ops, + node_type_to_io_type_map=node_type_to_io_type_map, + unmatchable_types_map=unmatchable_types_map) + + +def extract_shadow_logger_info( + model_a_shadows_b: nn.Module, + logger_cls: Callable, + model_name_to_use_for_layer_names: str, +) -> NSResultsType: + """ + Traverse all loggers in a shadow model, and extract the logged + information. + + Args: + model_a_shadows_b: shadow model + logger_cls: class of Logger to use + model_name_to_use_for_layer_names: string name of model to use for + layer names in the output + + Return: + NSResultsType, containing the logged comparisons + """ + torch._C._log_api_usage_once("quantization_api._numeric_suite_fx.extract_shadow_logger_info") + results: NSResultsType = collections.defaultdict(dict) + _extract_logger_info_one_model(model_a_shadows_b, results, logger_cls) + # fill in missing fqn entries + maybe_add_missing_fqns(results) + # rekey on the name of model b + results = rekey_logger_info_on_node_name_of_model( + results, model_name_to_use_for_layer_names) + return dict(results) + + +def extend_logger_results_with_comparison( + results: NSResultsType, + model_name_1: str, + model_name_2: str, + comparison_fn: Callable[[torch.Tensor, torch.Tensor], torch.Tensor], + comparison_name: str, +) -> None: + """ + Compares the logged values from `model_name_2` against the corresponding + values in `model_name_1`, using `comparison_fn`. Records the result + in `model_name_2`'s results under `comparison_name`. Modifies `results` inplace. + + Args: + results: the result data structure from `extract_logger_info` or + `extract_shadow_logger_info`. + model_name_1: string name of model 1 + model_name_2: string name of model 2 + comparison_fn: function to compare two Tensors + comparison_name: string name of model to use for + layer names in the output + """ + for results_type_to_results in results.values(): + for model_name_to_results in results_type_to_results.values(): + assert model_name_1 in model_name_to_results, \ + f"{model_name_1} not found in results" + assert model_name_2 in model_name_to_results, \ + f"{model_name_2} not found in results" + + results_1 = model_name_to_results[model_name_1] + results_2 = model_name_to_results[model_name_2] + + for result_2 in results_2: + index_within_arg_2 = result_2['index_within_arg'] + index_of_arg_2 = result_2['index_of_arg'] + # find corresponding result_1 + result_1 = None + for cur_result_1 in results_1: + index_within_arg_1 = cur_result_1['index_within_arg'] + index_of_arg_1 = cur_result_1['index_of_arg'] + if ( + (index_within_arg_1 == index_within_arg_2) and + (index_of_arg_1 == index_of_arg_2) + ): + result_1 = cur_result_1 + break + assert result_1 is not None + + values_1 = result_1['values'] + values_2 = result_2['values'] + result_2[comparison_name] = [] + for value_1, value_2 in zip(values_1, values_2): + comparison_result = comparison_fn(value_1, value_2) + result_2[comparison_name].append(comparison_result) + +def prepare_n_shadows_model( + model: torch.nn.Module, + example_inputs: Any, + qconfig_multi_mapping: QConfigMultiMapping, + backend_config: BackendConfig, + custom_prepare_fn: Optional[Callable] = None, + custom_prepare_kwargs: Optional[Dict[str, Any]] = None, + custom_tracer: Any = None, +) -> GraphModule: + """ + Given a model with a graph with M ops such as + + + args_kwargs_m -> op_m -> output_m + + + And a set of N qconfigs for each op, creates a new model, with + each of the subgraph of `op_m` transformed into + + .. code:: + + |---------> op_m_n -> log_m_n + | / + args_kwargs_m ---------> op_m -> log_m_0 + + Where op_m_n is op_m wrapped in a submodule and transformed with + qconfig_n, and its inner graph looks like + + .. code:: + + args_m -------- op_m_prepared_with_qconfig_n -> out_m_n + / + kwargs_m --- + + This is useful for testing different quantization of multiple layers in + a single pass through the model. + + High level TODOs for future PRs: + * figure out a better way to name the output structure + * return a results data structure instead of printing it out + * add examples to docblocks + """ + + if custom_tracer is None: + tracer = quantize_fx.QuantizationTracer([], []) + else: + tracer = custom_tracer + mt = torch.fx.GraphModule(model, tracer.trace(model)) + # this is necessary to ensure logger FQNs get populated + mt._node_name_to_scope = tracer.node_name_to_scope + + # run example input propagation, we need this to call prepare_fx on + # individual subgraphs + output_prop = OutputProp(mt) + output_prop.propagate(*example_inputs) + + # Find the set of subgraphs in the original graph which we need to + # consider. + modules = dict(mt.named_modules(remove_duplicate=False)) + patterns = _get_pattern_to_quantize_handlers(backend_config) + root_node_getter_mapping = \ + get_fusion_pattern_to_root_node_getter(backend_config) + standalone_module_names: List[str] = [] + standalone_module_classes: List[Type] = [] + custom_module_classes: List[Type] = [] + matches = _find_matches( + mt.graph, modules, patterns, root_node_getter_mapping, + standalone_module_names, standalone_module_classes, custom_module_classes) + subgraphs_dedup: Dict[str, List[Node]] = \ + _get_dedup_subgraphs(matches) + + # generate node to qconfig for each subgraph + # TODO(future PR): deduplicate repeating entries + list_of_node_name_to_qconfig: List[Dict[str, QConfigAny]] = [] + for qconfig_mapping in qconfig_multi_mapping.qconfig_mappings_list: + node_name_to_qconfig = _generate_node_name_to_qconfig( + mt, modules, mt.graph, qconfig_mapping, tracer.node_name_to_scope) + list_of_node_name_to_qconfig.append(node_name_to_qconfig) + + # For each region in the model, do the following: + # For each qconfig for that region, do the following: + # 1. create a copy of the region wrapped in a module + # 2. pass original args, original kwargs, and expected output to module + # 3. add an output comparison logger and hook it up to compare + # actual output to expected output + # 4. run `prepare_fx` on the module + for (subgraph_idx, (match_name, nodes_in_this_subgraph)) in \ + enumerate(subgraphs_dedup.items()): + create_n_transformed_and_logged_copies_of_subgraph( + mt, subgraph_idx, match_name, nodes_in_this_subgraph, + qconfig_multi_mapping.qconfig_mappings_list, list_of_node_name_to_qconfig, + custom_prepare_fn, custom_prepare_kwargs # type: ignore[arg-type] + ) + + return mt + +# TODO(future PR): we should rethink the names of all the PNP APIs +def _prepare_n_shadows_add_loggers_model( + model: torch.nn.Module, + example_inputs: Any, + qconfig_mapping: QConfigMapping, + backend_config: BackendConfig, +) -> torch.nn.Module: + r""" + Note: this API is not recommended for wide usage, it is only + provided for customers who need to migrate from the `add_loggers` + API. + + This creates a model which provides logging for the following + problem: if we quantize `model` with `qconfig_mapping` and feed + the same input through both models, log the comparisons of + corresponding intermediate layers. + + The problem is solved with a single model. Specifically, we + partition `model` into N subgraphs, create a copy of each relevant + subgraph, wrap it in a module, apply the quantization API to that + module, and hook up loggers to measure the comparisons. + + Example starting graph: + + x0 -> op0 -> x1 -> op1 -> x2 + + Example config: quantize op0 to int8, do nothing to op1. + The following graph will be created: + + .. code:: + + x0_0 -> op0_0 -> x1_0 -> log -----> op1_0 -> x2_0 -> log + \ \ \ # noqa: W605 + ---> op0_1 -> x1_1 ----> clog -> op1_0 -> x2_1 ----> clog + + Where op0_0 is op0, op0_1 is op0 wrapped in a submodule and quantized + to int8, op1_0 is op1 (appearing in the graph twice), log is a logger, + and clog is a comparison logger. + """ + + tracer = quantize_fx.QuantizationTracer([], []) + mt = torch.fx.GraphModule(model, tracer.trace(model)) + # this is necessary to ensure logger FQNs get populated + mt._node_name_to_scope = tracer.node_name_to_scope + + # run example input propagation, we need this to call prepare_fx on + # individual subgraphs + output_prop = OutputProp(mt) + output_prop.propagate(*example_inputs) + + # Find the set of subgraphs in the original graph which we need to + # consider. + modules = dict(mt.named_modules(remove_duplicate=False)) + patterns = _get_pattern_to_quantize_handlers(backend_config) + root_node_getter_mapping = \ + get_fusion_pattern_to_root_node_getter(backend_config) + standalone_module_names: List[str] = [] + standalone_module_classes: List[Type] = [] + custom_module_classes: List[Type] = [] + matches = _find_matches( + mt.graph, modules, patterns, root_node_getter_mapping, + standalone_module_names, standalone_module_classes, custom_module_classes) + subgraphs_dedup: Dict[str, List[Node]] = \ + _get_dedup_subgraphs(matches) + + # generate node to qconfig for each subgraph + node_name_to_qconfig = _generate_node_name_to_qconfig( + mt, modules, mt.graph, qconfig_mapping, tracer.node_name_to_scope) + + # Now, mutate the graph to be the add_loggers graph with propagation + # error. + create_add_loggers_graph( + mt, subgraphs_dedup, qconfig_mapping, node_name_to_qconfig) + + return mt + +# TODO(future PR): we should rethink the names of all the PNP APIs +def _n_shadows_compare_weights( + model: torch.nn.Module, + example_inputs: Any, + qconfig_mapping: QConfigMapping, + backend_config: BackendConfig, +) -> NSResultsType: + """ + Note: this API is not recommended for wide usage, it is only + provided for customers who need to migrate from the `add_loggers` + API. + """ + qconfig_multi_mapping = \ + QConfigMultiMapping.from_list_qconfig_mapping([qconfig_mapping]) + mp = prepare_n_shadows_model( + model, example_inputs, qconfig_multi_mapping, backend_config) + # passing inputs through the model is necessary to populate + # observers which observe weights with real values + mp(*example_inputs) + mq = convert_n_shadows_model(mp) + weight_comparison = extract_weight_comparison(mq) + return weight_comparison + +# TODO(future PR): consider aligning API signature with other similar quantization +# functions (enable_fake_quant, etc) +def loggers_set_enabled(model: torch.nn.Module, enabled: bool) -> None: + """ + Sets the `enabled` setting on a `model`'s loggers + """ + for name, child in model.named_modules(): + if isinstance(child, OutputLogger): + child.enabled = enabled + +# TODO(future PR): consider aligning API signature with other similar quantization +# functions (enable_fake_quant, etc) +def loggers_set_save_activations( + model: torch.nn.Module, + save_activations: bool, +) -> None: + """ + Sets the `save_activations` setting on a `model`'s loggers + """ + for name, child in model.named_modules(): + if isinstance(child, OutputLogger): + child.save_activations = save_activations + +def convert_n_shadows_model( + model: GraphModule, + custom_convert_fn: Optional[Callable] = None, + custom_convert_kwargs: Optional[Dict[str, Any]] = None +) -> GraphModule: + """ + Given a model from `prepare_n_shadows_model`, runs `convert_fx` + on each shadow submodule. + """ + for node in model.graph.nodes: + # TODO(future PR): consider matching in a safer way than + # node name string match + if node.name.startswith(SHADOW_WRAPPER_NODE_NAME_PREFIX): + orig_mod = getattr(model, node.name) + if custom_convert_fn is None: + converted_mod = torch.ao.quantization.quantize_fx.convert_fx( + orig_mod) + else: + if custom_convert_kwargs is None: + custom_convert_kwargs = {} + converted_mod = custom_convert_fn(orig_mod, **custom_convert_kwargs) + setattr(model, node.name, converted_mod) + + return model + +def extract_results_n_shadows_model(model: torch.nn.Module) -> NSResultsType: + """ + Extracts logger results from `model`. + """ + results: NSResultsType = {} + _extract_logger_info_one_model(model, results, OutputLogger) + return results + +def print_comparisons_n_shadows_model(results: NSResultsType) -> None: + """ + Prints a summary of extracted `results`. + """ + results_grouped = group_results_by_subgraph(results) + results_comparison = create_results_comparison(results_grouped) + print_n_shadows_summary(results_comparison) diff --git a/shared/package-files/6b/6bc078c51adb0d959d34bec559a0ec957cf446b9a84084d6813dba859c380e18/nsterm-c-s b/shared/package-files/6b/6bc078c51adb0d959d34bec559a0ec957cf446b9a84084d6813dba859c380e18/nsterm-c-s new file mode 100644 index 0000000000000000000000000000000000000000..aa9938dde75b107817b077d1a1e8f99c2ff53695 Binary files /dev/null and b/shared/package-files/6b/6bc078c51adb0d959d34bec559a0ec957cf446b9a84084d6813dba859c380e18/nsterm-c-s differ diff --git a/shared/package-files/6b/6bc108faf7b8404c99bb0055e55a6487132b883b5b2e7db150e540dc7ab3e312/matmul_native.h b/shared/package-files/6b/6bc108faf7b8404c99bb0055e55a6487132b883b5b2e7db150e540dc7ab3e312/matmul_native.h new file mode 100644 index 0000000000000000000000000000000000000000..45ccb67a4c778f22dab6686a002e811dc86ef318 --- /dev/null +++ b/shared/package-files/6b/6bc108faf7b8404c99bb0055e55a6487132b883b5b2e7db150e540dc7ab3e312/matmul_native.h @@ -0,0 +1,24 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor matmul(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & matmul_out(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor matmul_nested(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & matmul_out_nested(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/6b/6bc1dfd90bce922eff72181770c005324fa98938e8764b5f9dcdc745b5152645/tedlium.py b/shared/package-files/6b/6bc1dfd90bce922eff72181770c005324fa98938e8764b5f9dcdc745b5152645/tedlium.py new file mode 100644 index 0000000000000000000000000000000000000000..7e7d22195a772d18770f6db3253d83672743c81c --- /dev/null +++ b/shared/package-files/6b/6bc1dfd90bce922eff72181770c005324fa98938e8764b5f9dcdc745b5152645/tedlium.py @@ -0,0 +1,218 @@ +import os +from pathlib import Path +from typing import Tuple, Union + +import torchaudio +from torch import Tensor +from torch.utils.data import Dataset +from torchaudio._internal import download_url_to_file +from torchaudio.datasets.utils import _extract_tar + + +_RELEASE_CONFIGS = { + "release1": { + "folder_in_archive": "TEDLIUM_release1", + "url": "http://www.openslr.org/resources/7/TEDLIUM_release1.tar.gz", + "checksum": "30301975fd8c5cac4040c261c0852f57cfa8adbbad2ce78e77e4986957445f27", + "data_path": "", + "subset": "train", + "supported_subsets": ["train", "test", "dev"], + "dict": "TEDLIUM.150K.dic", + }, + "release2": { + "folder_in_archive": "TEDLIUM_release2", + "url": "http://www.openslr.org/resources/19/TEDLIUM_release2.tar.gz", + "checksum": "93281b5fcaaae5c88671c9d000b443cb3c7ea3499ad12010b3934ca41a7b9c58", + "data_path": "", + "subset": "train", + "supported_subsets": ["train", "test", "dev"], + "dict": "TEDLIUM.152k.dic", + }, + "release3": { + "folder_in_archive": "TEDLIUM_release-3", + "url": "http://www.openslr.org/resources/51/TEDLIUM_release-3.tgz", + "checksum": "ad1e454d14d1ad550bc2564c462d87c7a7ec83d4dc2b9210f22ab4973b9eccdb", + "data_path": "data/", + "subset": "train", + "supported_subsets": ["train", "test", "dev"], + "dict": "TEDLIUM.152k.dic", + }, +} + + +class TEDLIUM(Dataset): + """*Tedlium* :cite:`rousseau2012tedlium` dataset (releases 1,2 and 3). + + Args: + root (str or Path): Path to the directory where the dataset is found or downloaded. + release (str, optional): Release version. + Allowed values are ``"release1"``, ``"release2"`` or ``"release3"``. + (default: ``"release1"``). + subset (str, optional): The subset of dataset to use. Valid options are ``"train"``, ``"dev"``, + and ``"test"``. Defaults to ``"train"``. + download (bool, optional): + Whether to download the dataset if it is not found at root path. (default: ``False``). + audio_ext (str, optional): extension for audio file (default: ``".sph"``) + """ + + def __init__( + self, + root: Union[str, Path], + release: str = "release1", + subset: str = "train", + download: bool = False, + audio_ext: str = ".sph", + ) -> None: + self._ext_audio = audio_ext + if release in _RELEASE_CONFIGS.keys(): + folder_in_archive = _RELEASE_CONFIGS[release]["folder_in_archive"] + url = _RELEASE_CONFIGS[release]["url"] + subset = subset if subset else _RELEASE_CONFIGS[release]["subset"] + else: + # Raise warning + raise RuntimeError( + "The release {} does not match any of the supported tedlium releases{} ".format( + release, + _RELEASE_CONFIGS.keys(), + ) + ) + if subset not in _RELEASE_CONFIGS[release]["supported_subsets"]: + # Raise warning + raise RuntimeError( + "The subset {} does not match any of the supported tedlium subsets{} ".format( + subset, + _RELEASE_CONFIGS[release]["supported_subsets"], + ) + ) + + # Get string representation of 'root' in case Path object is passed + root = os.fspath(root) + + basename = os.path.basename(url) + archive = os.path.join(root, basename) + + basename = basename.split(".")[0] + + if release == "release3": + if subset == "train": + self._path = os.path.join(root, folder_in_archive, _RELEASE_CONFIGS[release]["data_path"]) + else: + self._path = os.path.join(root, folder_in_archive, "legacy", subset) + else: + self._path = os.path.join(root, folder_in_archive, _RELEASE_CONFIGS[release]["data_path"], subset) + + if download: + if not os.path.isdir(self._path): + if not os.path.isfile(archive): + checksum = _RELEASE_CONFIGS[release]["checksum"] + download_url_to_file(url, archive, hash_prefix=checksum) + _extract_tar(archive) + else: + if not os.path.exists(self._path): + raise RuntimeError( + f"The path {self._path} doesn't exist. " + "Please check the ``root`` path or set `download=True` to download it" + ) + + # Create list for all samples + self._filelist = [] + stm_path = os.path.join(self._path, "stm") + for file in sorted(os.listdir(stm_path)): + if file.endswith(".stm"): + stm_path = os.path.join(self._path, "stm", file) + with open(stm_path) as f: + l = len(f.readlines()) + file = file.replace(".stm", "") + self._filelist.extend((file, line) for line in range(l)) + # Create dict path for later read + self._dict_path = os.path.join(root, folder_in_archive, _RELEASE_CONFIGS[release]["dict"]) + self._phoneme_dict = None + + def _load_tedlium_item(self, fileid: str, line: int, path: str) -> Tuple[Tensor, int, str, int, int, int]: + """Loads a TEDLIUM dataset sample given a file name and corresponding sentence name. + + Args: + fileid (str): File id to identify both text and audio files corresponding to the sample + line (int): Line identifier for the sample inside the text file + path (str): Dataset root path + + Returns: + (Tensor, int, str, int, int, int): + ``(waveform, sample_rate, transcript, talk_id, speaker_id, identifier)`` + """ + transcript_path = os.path.join(path, "stm", fileid) + with open(transcript_path + ".stm") as f: + transcript = f.readlines()[line] + talk_id, _, speaker_id, start_time, end_time, identifier, transcript = transcript.split(" ", 6) + + wave_path = os.path.join(path, "sph", fileid) + waveform, sample_rate = self._load_audio(wave_path + self._ext_audio, start_time=start_time, end_time=end_time) + + return (waveform, sample_rate, transcript, talk_id, speaker_id, identifier) + + def _load_audio(self, path: str, start_time: float, end_time: float, sample_rate: int = 16000) -> [Tensor, int]: + """Default load function used in TEDLIUM dataset, you can overwrite this function to customize functionality + and load individual sentences from a full ted audio talk file. + + Args: + path (str): Path to audio file + start_time (int): Time in seconds where the sample sentence stars + end_time (int): Time in seconds where the sample sentence finishes + sample_rate (float, optional): Sampling rate + + Returns: + [Tensor, int]: Audio tensor representation and sample rate + """ + start_time = int(float(start_time) * sample_rate) + end_time = int(float(end_time) * sample_rate) + + kwargs = {"frame_offset": start_time, "num_frames": end_time - start_time} + + return torchaudio.load(path, **kwargs) + + def __getitem__(self, n: int) -> Tuple[Tensor, int, str, int, int, int]: + """Load the n-th sample from the dataset. + + Args: + n (int): The index of the sample to be loaded + + Returns: + Tuple of the following items; + + Tensor: + Waveform + int: + Sample rate + str: + Transcript + int: + Talk ID + int: + Speaker ID + int: + Identifier + """ + fileid, line = self._filelist[n] + return self._load_tedlium_item(fileid, line, self._path) + + def __len__(self) -> int: + """TEDLIUM dataset custom function overwritting len default behaviour. + + Returns: + int: TEDLIUM dataset length + """ + return len(self._filelist) + + @property + def phoneme_dict(self): + """dict[str, tuple[str]]: Phonemes. Mapping from word to tuple of phonemes. + Note that some words have empty phonemes. + """ + # Read phoneme dictionary + if not self._phoneme_dict: + self._phoneme_dict = {} + with open(self._dict_path, "r", encoding="utf-8") as f: + for line in f.readlines(): + content = line.strip().split() + self._phoneme_dict[content[0]] = tuple(content[1:]) # content[1:] can be empty list + return self._phoneme_dict.copy() diff --git a/shared/package-files/6b/6bc38c98b112dc5977034f7b1a7f1580297aa91d1bd332fa3ce37beac8e78a4f/__main__.py b/shared/package-files/6b/6bc38c98b112dc5977034f7b1a7f1580297aa91d1bd332fa3ce37beac8e78a4f/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..dde91ff0efe062c13395035b31d275e499d967de --- /dev/null +++ b/shared/package-files/6b/6bc38c98b112dc5977034f7b1a7f1580297aa91d1bd332fa3ce37beac8e78a4f/__main__.py @@ -0,0 +1,3 @@ +from conda_package_handling import cli + +cli.main(args=None) diff --git a/shared/package-files/6b/6bc44012fe0f4a0b00ca6bc59395663539194b16706fa4b07474d13914463e97/conv_expanded_weights.py b/shared/package-files/6b/6bc44012fe0f4a0b00ca6bc59395663539194b16706fa4b07474d13914463e97/conv_expanded_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..c10ccb90ae92f1f57513de5c0ab7a56c26996298 --- /dev/null +++ b/shared/package-files/6b/6bc44012fe0f4a0b00ca6bc59395663539194b16706fa4b07474d13914463e97/conv_expanded_weights.py @@ -0,0 +1,52 @@ +import torch +import torch.nn.functional as F + +from .conv_utils import conv_backward, conv_args_and_kwargs, conv_picker, conv_input_for_string_padding +from .expanded_weights_impl import ExpandedWeight, implements_per_sample_grads +from .expanded_weights_utils import forward_helper + +@implements_per_sample_grads(F.conv1d) +@implements_per_sample_grads(F.conv2d) +@implements_per_sample_grads(F.conv3d) +class ConvPerSampleGrad(torch.autograd.Function): + @staticmethod + def forward(ctx, kwarg_names, conv_fn, *expanded_args_and_kwargs): + expanded_args, expanded_kwargs = conv_args_and_kwargs(kwarg_names, expanded_args_and_kwargs) + orig_input = expanded_args[0] + was_same_padding = expanded_kwargs['padding'] == "same" + + if isinstance(expanded_kwargs['padding'], str): + # if padding is a string, we'll do the necessary padding (slowly) using F.pad + kernel_size = expanded_args[1].shape[2:] + padding, dilation = expanded_kwargs['padding'], expanded_kwargs['dilation'] + input = conv_input_for_string_padding(conv_fn, padding, expanded_args[0], dilation, kernel_size) + expanded_args = (input, expanded_args[1]) + # since we've already done the padding, don't need any more + expanded_kwargs['padding'] = 0 + + output = forward_helper(conv_fn, expanded_args, expanded_kwargs) + input, weight = expanded_args + batched_dim_size = conv_picker(conv_fn, 3, 4, 5) + if input.dim() != batched_dim_size: + raise RuntimeError(f"Expanded Weights only support convolution with batched input, got {conv_fn} with an" + f"unbatched input of dim {input.dim()}, expected input of dim {batched_dim_size}") + + ctx.conv_fn = conv_fn + + ctx.batch_size = orig_input.shape[0] + ctx.input_required_grad = orig_input.requires_grad + ctx.orig_input_shape = orig_input.shape + ctx.was_same_padding = was_same_padding + ctx.stride, ctx.padding = expanded_kwargs['stride'], expanded_kwargs['padding'] + ctx.dilation, ctx.groups = expanded_kwargs['dilation'], expanded_kwargs['groups'] + + if isinstance(weight, ExpandedWeight): + ctx.input = input + ctx.weight = weight + ctx.bias = expanded_kwargs['bias'] + + return output + + @staticmethod + def backward(ctx, grad_output): + return conv_backward(ctx.conv_fn, ctx, grad_output) diff --git a/shared/package-files/6b/6bc57a8649caba782a271f728340b0b46236f92cb90f8837f7bf197974afb11b/_infra.py b/shared/package-files/6b/6bc57a8649caba782a271f728340b0b46236f92cb90f8837f7bf197974afb11b/_infra.py new file mode 100644 index 0000000000000000000000000000000000000000..325cdc44ac7257cb7915db084295ae645e6c1eec --- /dev/null +++ b/shared/package-files/6b/6bc57a8649caba782a271f728340b0b46236f92cb90f8837f7bf197974afb11b/_infra.py @@ -0,0 +1,284 @@ +"""This file defines an additional layer of abstraction on top of the SARIF OM.""" + +from __future__ import annotations + +import dataclasses +import enum +import logging +from typing import FrozenSet, List, Mapping, Optional, Sequence, Tuple + +from torch.onnx._internal.diagnostics.infra import formatter, sarif + + +class Level(enum.IntEnum): + """The level of a diagnostic. + + This class is used to represent the level of a diagnostic. The levels are defined + by the SARIF specification, and are not modifiable. For alternative categories, + please use infra.Tag instead. When selecting a level, please consider the following + guidelines: + + - NONE: Informational result that does not indicate the presence of a problem. + - NOTE: An opportunity for improvement was found. + - WARNING: A potential problem was found. + - ERROR: A serious problem was found. + + This level is a subclass of enum.IntEnum, and can be used as an integer. Its integer + value maps to the logging levels in Python's logging module. The mapping is as + follows: + + Level.NONE = logging.DEBUG = 10 + Level.NOTE = logging.INFO = 20 + Level.WARNING = logging.WARNING = 30 + Level.ERROR = logging.ERROR = 40 + """ + + NONE = 10 + NOTE = 20 + WARNING = 30 + ERROR = 40 + + +levels = Level + + +class Tag(enum.Enum): + """The tag of a diagnostic. This class can be inherited to define custom tags.""" + + +class PatchedPropertyBag(sarif.PropertyBag): + """Key/value pairs that provide additional information about the object. + + The definition of PropertyBag via SARIF spec is "A property bag is an object (§3.6) + containing an unordered set of properties with arbitrary names." However it is not + reflected in the json file, and therefore not captured by the python representation. + This patch adds additional **kwargs to the `__init__` method to allow recording + arbitrary key/value pairs. + """ + + def __init__(self, tags: Optional[List[str]] = None, **kwargs): + super().__init__(tags=tags) + self.__dict__.update(kwargs) + + +@dataclasses.dataclass(frozen=True) +class Rule: + id: str + name: str + message_default_template: str + short_description: Optional[str] = None + full_description: Optional[str] = None + full_description_markdown: Optional[str] = None + help_uri: Optional[str] = None + + @classmethod + def from_sarif(cls, **kwargs): + """Returns a rule from the SARIF reporting descriptor.""" + short_description = kwargs.get("short_description", {}).get("text") + full_description = kwargs.get("full_description", {}).get("text") + full_description_markdown = kwargs.get("full_description", {}).get("markdown") + help_uri = kwargs.get("help_uri") + + rule = cls( + id=kwargs["id"], + name=kwargs["name"], + message_default_template=kwargs["message_strings"]["default"]["text"], + short_description=short_description, + full_description=full_description, + full_description_markdown=full_description_markdown, + help_uri=help_uri, + ) + return rule + + def sarif(self) -> sarif.ReportingDescriptor: + """Returns a SARIF reporting descriptor of this Rule.""" + short_description = ( + sarif.MultiformatMessageString(text=self.short_description) + if self.short_description is not None + else None + ) + full_description = ( + sarif.MultiformatMessageString( + text=self.full_description, markdown=self.full_description_markdown + ) + if self.full_description is not None + else None + ) + return sarif.ReportingDescriptor( + id=self.id, + name=self.name, + short_description=short_description, + full_description=full_description, + help_uri=self.help_uri, + ) + + def format(self, level: Level, *args, **kwargs) -> Tuple[Rule, Level, str]: + """Returns a tuple of (rule, level, message) for a diagnostic. + + This method is used to format the message of a diagnostic. The message is + formatted using the default template of this rule, and the arguments passed in + as `*args` and `**kwargs`. The level is used to override the default level of + this rule. + """ + return (self, level, self.format_message(*args, **kwargs)) + + def format_message(self, *args, **kwargs) -> str: + """Returns the formatted default message of this Rule. + + This method should be overridden (with code generation) by subclasses to reflect + the exact arguments needed by the message template. This is a helper method to + create the default message for a diagnostic. + """ + return self.message_default_template.format(*args, **kwargs) + + +@dataclasses.dataclass +class Location: + uri: Optional[str] = None + line: Optional[int] = None + message: Optional[str] = None + start_column: Optional[int] = None + end_column: Optional[int] = None + snippet: Optional[str] = None + function: Optional[str] = None + + def sarif(self) -> sarif.Location: + """Returns the SARIF representation of this location.""" + return sarif.Location( + physical_location=sarif.PhysicalLocation( + artifact_location=sarif.ArtifactLocation(uri=self.uri), + region=sarif.Region( + start_line=self.line, + start_column=self.start_column, + end_column=self.end_column, + snippet=sarif.ArtifactContent(text=self.snippet), + ), + ), + message=sarif.Message(text=self.message) + if self.message is not None + else None, + ) + + +@dataclasses.dataclass +class StackFrame: + location: Location + + def sarif(self) -> sarif.StackFrame: + """Returns the SARIF representation of this stack frame.""" + return sarif.StackFrame(location=self.location.sarif()) + + +@dataclasses.dataclass +class Stack: + """Records a stack trace. The frames are in order from newest to oldest stack frame.""" + + frames: List[StackFrame] = dataclasses.field(default_factory=list) + message: Optional[str] = None + + def sarif(self) -> sarif.Stack: + """Returns the SARIF representation of this stack.""" + return sarif.Stack( + frames=[frame.sarif() for frame in self.frames], + message=sarif.Message(text=self.message) + if self.message is not None + else None, + ) + + +@dataclasses.dataclass +class ThreadFlowLocation: + """Records code location and the initial state.""" + + location: Location + state: Mapping[str, str] + index: int + stack: Optional[Stack] = None + + def sarif(self) -> sarif.ThreadFlowLocation: + """Returns the SARIF representation of this thread flow location.""" + return sarif.ThreadFlowLocation( + location=self.location.sarif(), + state=self.state, + stack=self.stack.sarif() if self.stack is not None else None, + ) + + +@dataclasses.dataclass +class Graph: + """A graph of diagnostics. + + This class stores the string representation of a model graph. + The `nodes` and `edges` fields are unused in the current implementation. + """ + + graph: str + name: str + description: Optional[str] = None + + def sarif(self) -> sarif.Graph: + """Returns the SARIF representation of this graph.""" + return sarif.Graph( + description=sarif.Message(text=self.graph), + properties=PatchedPropertyBag(name=self.name, description=self.description), + ) + + +@dataclasses.dataclass +class RuleCollection: + _rule_id_name_set: FrozenSet[Tuple[str, str]] = dataclasses.field(init=False) + + def __post_init__(self) -> None: + self._rule_id_name_set = frozenset( + { + (field.default.id, field.default.name) + for field in dataclasses.fields(self) + if isinstance(field.default, Rule) + } + ) + + def __contains__(self, rule: Rule) -> bool: + """Checks if the rule is in the collection.""" + return (rule.id, rule.name) in self._rule_id_name_set + + @classmethod + def custom_collection_from_list( + cls, new_collection_class_name: str, rules: Sequence[Rule] + ) -> RuleCollection: + """Creates a custom class inherited from RuleCollection with the list of rules.""" + return dataclasses.make_dataclass( + new_collection_class_name, + [ + ( + formatter.kebab_case_to_snake_case(rule.name), + type(rule), + dataclasses.field(default=rule), + ) + for rule in rules + ], + bases=(cls,), + )() + + +class Invocation: + # TODO: Implement this. + # Tracks top level call arguments and diagnostic options. + def __init__(self) -> None: + raise NotImplementedError() + + +@dataclasses.dataclass +class DiagnosticOptions: + """Options for diagnostic context. + + Attributes: + verbosity_level: Set the amount of information logged for each diagnostics, + equivalent to the 'level' in Python logging module. + warnings_as_errors: When True, warning diagnostics are treated as error diagnostics. + """ + + verbosity_level: int = dataclasses.field(default=logging.INFO) + """Set the amount of information logged for each diagnostics, equivalent to the 'level' in Python logging module.""" + + warnings_as_errors: bool = dataclasses.field(default=False) + """If True, warning diagnostics are treated as error diagnostics.""" diff --git a/shared/package-files/6b/6bc659102acf45f7ec6ecd14ca0791e3bfdf394959a699f1f903ecb2b217b41d/line_endings.py b/shared/package-files/6b/6bc659102acf45f7ec6ecd14ca0791e3bfdf394959a699f1f903ecb2b217b41d/line_endings.py new file mode 100644 index 0000000000000000000000000000000000000000..686e5ebd937fff16d5aa7f154d5c823ed17d9e0a --- /dev/null +++ b/shared/package-files/6b/6bc659102acf45f7ec6ecd14ca0791e3bfdf394959a699f1f903ecb2b217b41d/line_endings.py @@ -0,0 +1,77 @@ +""" Functions for converting from DOS to UNIX line endings + +""" +import os +import re +import sys + + +def dos2unix(file): + "Replace CRLF with LF in argument files. Print names of changed files." + if os.path.isdir(file): + print(file, "Directory!") + return + + with open(file, "rb") as fp: + data = fp.read() + if '\0' in data: + print(file, "Binary!") + return + + newdata = re.sub("\r\n", "\n", data) + if newdata != data: + print('dos2unix:', file) + with open(file, "wb") as f: + f.write(newdata) + return file + else: + print(file, 'ok') + +def dos2unix_one_dir(modified_files, dir_name, file_names): + for file in file_names: + full_path = os.path.join(dir_name, file) + file = dos2unix(full_path) + if file is not None: + modified_files.append(file) + +def dos2unix_dir(dir_name): + modified_files = [] + os.path.walk(dir_name, dos2unix_one_dir, modified_files) + return modified_files +#---------------------------------- + +def unix2dos(file): + "Replace LF with CRLF in argument files. Print names of changed files." + if os.path.isdir(file): + print(file, "Directory!") + return + + with open(file, "rb") as fp: + data = fp.read() + if '\0' in data: + print(file, "Binary!") + return + newdata = re.sub("\r\n", "\n", data) + newdata = re.sub("\n", "\r\n", newdata) + if newdata != data: + print('unix2dos:', file) + with open(file, "wb") as f: + f.write(newdata) + return file + else: + print(file, 'ok') + +def unix2dos_one_dir(modified_files, dir_name, file_names): + for file in file_names: + full_path = os.path.join(dir_name, file) + unix2dos(full_path) + if file is not None: + modified_files.append(file) + +def unix2dos_dir(dir_name): + modified_files = [] + os.path.walk(dir_name, unix2dos_one_dir, modified_files) + return modified_files + +if __name__ == "__main__": + dos2unix_dir(sys.argv[1]) diff --git a/shared/package-files/6b/6bc8f382eb11cd9a8d42658d1ec45c22fc93433374fb172c4dd5aa31a9ff1726/vec512_complex_float.h b/shared/package-files/6b/6bc8f382eb11cd9a8d42658d1ec45c22fc93433374fb172c4dd5aa31a9ff1726/vec512_complex_float.h new file mode 100644 index 0000000000000000000000000000000000000000..a5d790c98b2f26fbe5d6fbdab3c8486dc0709d47 --- /dev/null +++ b/shared/package-files/6b/6bc8f382eb11cd9a8d42658d1ec45c22fc93433374fb172c4dd5aa31a9ff1726/vec512_complex_float.h @@ -0,0 +1,1018 @@ +#pragma once + +// DO NOT DEFINE STATIC DATA IN THIS HEADER! +// See Note [Do not compile initializers with AVX] + +#include +#include +#include +#include +#if defined(CPU_CAPABILITY_AVX512) && !defined(_MSC_VER) +#include +#endif + +namespace at { +namespace vec { +// See Note [CPU_CAPABILITY namespace] +inline namespace CPU_CAPABILITY { + +#if defined(CPU_CAPABILITY_AVX512) && !defined(_MSC_VER) + +template <> class Vectorized> { +private: + __m512 values; + static constexpr __m512i zero_vector {0, 0, 0, 0, 0, 0, 0, 0}; +public: + using value_type = c10::complex; + using size_type = int; + static constexpr size_type size() { + return 8; + } + Vectorized() {} + Vectorized(__m512 v) : values(v) {} + Vectorized(c10::complex val) { + float real_value = val.real(); + float imag_value = val.imag(); + values = _mm512_setr_ps(real_value, imag_value, + real_value, imag_value, + real_value, imag_value, + real_value, imag_value, + real_value, imag_value, + real_value, imag_value, + real_value, imag_value, + real_value, imag_value); + } + Vectorized(c10::complex val1, c10::complex val2, + c10::complex val3, c10::complex val4, + c10::complex val5, c10::complex val6, + c10::complex val7, c10::complex val8) { + values = _mm512_setr_ps(val1.real(), val1.imag(), + val2.real(), val2.imag(), + val3.real(), val3.imag(), + val4.real(), val4.imag(), + val5.real(), val5.imag(), + val6.real(), val6.imag(), + val7.real(), val7.imag(), + val8.real(), val8.imag()); + } + operator __m512() const { + return values; + } + template + static Vectorized> blend(const Vectorized>& a, + const Vectorized>& b) { + // convert c10::complex index mask to V index mask: xy -> xxyy + static_assert(mask > -1 && mask < 256, "Unexpected mask value"); + // The compiler would hopefully convert this switch condition + // into a jump table + switch (mask) { + case 0: + return a; + case 1: + return _mm512_mask_blend_ps(0x03, a.values, b.values); + case 2: + return _mm512_mask_blend_ps(0x0C, a.values, b.values); + case 3: + return _mm512_mask_blend_ps(0x0F, a.values, b.values); + case 4: + return _mm512_mask_blend_ps(0x30, a.values, b.values); + case 5: + return _mm512_mask_blend_ps(0x33, a.values, b.values); + case 6: + return _mm512_mask_blend_ps(0x3C, a.values, b.values); + case 7: + return _mm512_mask_blend_ps(0x3F, a.values, b.values); + case 8: + return _mm512_mask_blend_ps(0xC0, a.values, b.values); + case 9: + return _mm512_mask_blend_ps(0xC3, a.values, b.values); + case 10: + return _mm512_mask_blend_ps(0xCC, a.values, b.values); + case 11: + return _mm512_mask_blend_ps(0xCF, a.values, b.values); + case 12: + return _mm512_mask_blend_ps(0xF0, a.values, b.values); + case 13: + return _mm512_mask_blend_ps(0xF3, a.values, b.values); + case 14: + return _mm512_mask_blend_ps(0xFC, a.values, b.values); + case 15: + return _mm512_mask_blend_ps(0xFF, a.values, b.values); + case 16: + return _mm512_mask_blend_ps(0x300, a.values, b.values); + case 17: + return _mm512_mask_blend_ps(0x303, a.values, b.values); + case 18: + return _mm512_mask_blend_ps(0x30C, a.values, b.values); + case 19: + return _mm512_mask_blend_ps(0x30F, a.values, b.values); + case 20: + return _mm512_mask_blend_ps(0x330, a.values, b.values); + case 21: + return _mm512_mask_blend_ps(0x333, a.values, b.values); + case 22: + return _mm512_mask_blend_ps(0x33C, a.values, b.values); + case 23: + return _mm512_mask_blend_ps(0x33F, a.values, b.values); + case 24: + return _mm512_mask_blend_ps(0x3C0, a.values, b.values); + case 25: + return _mm512_mask_blend_ps(0x3C3, a.values, b.values); + case 26: + return _mm512_mask_blend_ps(0x3CC, a.values, b.values); + case 27: + return _mm512_mask_blend_ps(0x3CF, a.values, b.values); + case 28: + return _mm512_mask_blend_ps(0x3F0, a.values, b.values); + case 29: + return _mm512_mask_blend_ps(0x3F3, a.values, b.values); + case 30: + return _mm512_mask_blend_ps(0x3FC, a.values, b.values); + case 31: + return _mm512_mask_blend_ps(0x3FF, a.values, b.values); + case 32: + return _mm512_mask_blend_ps(0xC00, a.values, b.values); + case 33: + return _mm512_mask_blend_ps(0xC03, a.values, b.values); + case 34: + return _mm512_mask_blend_ps(0xC0C, a.values, b.values); + case 35: + return _mm512_mask_blend_ps(0xC0F, a.values, b.values); + case 36: + return _mm512_mask_blend_ps(0xC30, a.values, b.values); + case 37: + return _mm512_mask_blend_ps(0xC33, a.values, b.values); + case 38: + return _mm512_mask_blend_ps(0xC3C, a.values, b.values); + case 39: + return _mm512_mask_blend_ps(0xC3F, a.values, b.values); + case 40: + return _mm512_mask_blend_ps(0xCC0, a.values, b.values); + case 41: + return _mm512_mask_blend_ps(0xCC3, a.values, b.values); + case 42: + return _mm512_mask_blend_ps(0xCCC, a.values, b.values); + case 43: + return _mm512_mask_blend_ps(0xCCF, a.values, b.values); + case 44: + return _mm512_mask_blend_ps(0xCF0, a.values, b.values); + case 45: + return _mm512_mask_blend_ps(0xCF3, a.values, b.values); + case 46: + return _mm512_mask_blend_ps(0xCFC, a.values, b.values); + case 47: + return _mm512_mask_blend_ps(0xCFF, a.values, b.values); + case 48: + return _mm512_mask_blend_ps(0xF00, a.values, b.values); + case 49: + return _mm512_mask_blend_ps(0xF03, a.values, b.values); + case 50: + return _mm512_mask_blend_ps(0xF0C, a.values, b.values); + case 51: + return _mm512_mask_blend_ps(0xF0F, a.values, b.values); + case 52: + return _mm512_mask_blend_ps(0xF30, a.values, b.values); + case 53: + return _mm512_mask_blend_ps(0xF33, a.values, b.values); + case 54: + return _mm512_mask_blend_ps(0xF3C, a.values, b.values); + case 55: + return _mm512_mask_blend_ps(0xF3F, a.values, b.values); + case 56: + return _mm512_mask_blend_ps(0xFC0, a.values, b.values); + case 57: + return _mm512_mask_blend_ps(0xFC3, a.values, b.values); + case 58: + return _mm512_mask_blend_ps(0xFCC, a.values, b.values); + case 59: + return _mm512_mask_blend_ps(0xFCF, a.values, b.values); + case 60: + return _mm512_mask_blend_ps(0xFF0, a.values, b.values); + case 61: + return _mm512_mask_blend_ps(0xFF3, a.values, b.values); + case 62: + return _mm512_mask_blend_ps(0xFFC, a.values, b.values); + case 63: + return _mm512_mask_blend_ps(0xFFF, a.values, b.values); + case 64: + return _mm512_mask_blend_ps(0x3000, a.values, b.values); + case 65: + return _mm512_mask_blend_ps(0x3003, a.values, b.values); + case 66: + return _mm512_mask_blend_ps(0x300C, a.values, b.values); + case 67: + return _mm512_mask_blend_ps(0x300F, a.values, b.values); + case 68: + return _mm512_mask_blend_ps(0x3030, a.values, b.values); + case 69: + return _mm512_mask_blend_ps(0x3033, a.values, b.values); + case 70: + return _mm512_mask_blend_ps(0x303C, a.values, b.values); + case 71: + return _mm512_mask_blend_ps(0x303F, a.values, b.values); + case 72: + return _mm512_mask_blend_ps(0x30C0, a.values, b.values); + case 73: + return _mm512_mask_blend_ps(0X30C3, a.values, b.values); + case 74: + return _mm512_mask_blend_ps(0x30CC, a.values, b.values); + case 75: + return _mm512_mask_blend_ps(0x30CF, a.values, b.values); + case 76: + return _mm512_mask_blend_ps(0x30F0, a.values, b.values); + case 77: + return _mm512_mask_blend_ps(0x30F3, a.values, b.values); + case 78: + return _mm512_mask_blend_ps(0x30FC, a.values, b.values); + case 79: + return _mm512_mask_blend_ps(0x30FF, a.values, b.values); + case 80: + return _mm512_mask_blend_ps(0x3300, a.values, b.values); + case 81: + return _mm512_mask_blend_ps(0X3303, a.values, b.values); + case 82: + return _mm512_mask_blend_ps(0x330C, a.values, b.values); + case 83: + return _mm512_mask_blend_ps(0x330F, a.values, b.values); + case 84: + return _mm512_mask_blend_ps(0x3330, a.values, b.values); + case 85: + return _mm512_mask_blend_ps(0x3333, a.values, b.values); + case 86: + return _mm512_mask_blend_ps(0x333C, a.values, b.values); + case 87: + return _mm512_mask_blend_ps(0X333F, a.values, b.values); + case 88: + return _mm512_mask_blend_ps(0x33C0, a.values, b.values); + case 89: + return _mm512_mask_blend_ps(0x33C3, a.values, b.values); + case 90: + return _mm512_mask_blend_ps(0x33CC, a.values, b.values); + case 91: + return _mm512_mask_blend_ps(0x33CF, a.values, b.values); + case 92: + return _mm512_mask_blend_ps(0x33F0, a.values, b.values); + case 93: + return _mm512_mask_blend_ps(0x33F3, a.values, b.values); + case 94: + return _mm512_mask_blend_ps(0x33FC, a.values, b.values); + case 95: + return _mm512_mask_blend_ps(0x33FF, a.values, b.values); + case 96: + return _mm512_mask_blend_ps(0X3C00, a.values, b.values); + case 97: + return _mm512_mask_blend_ps(0x3C03, a.values, b.values); + case 98: + return _mm512_mask_blend_ps(0x3C0C, a.values, b.values); + case 99: + return _mm512_mask_blend_ps(0x3C0F, a.values, b.values); + case 100: + return _mm512_mask_blend_ps(0x3C30, a.values, b.values); + case 101: + return _mm512_mask_blend_ps(0x3C33, a.values, b.values); + case 102: + return _mm512_mask_blend_ps(0x3C3C, a.values, b.values); + case 103: + return _mm512_mask_blend_ps(0x3C3F, a.values, b.values); + case 104: + return _mm512_mask_blend_ps(0x3CC0, a.values, b.values); + case 105: + return _mm512_mask_blend_ps(0x3CC3, a.values, b.values); + case 106: + return _mm512_mask_blend_ps(0x3CCC, a.values, b.values); + case 107: + return _mm512_mask_blend_ps(0x3CCF, a.values, b.values); + case 108: + return _mm512_mask_blend_ps(0x3CF0, a.values, b.values); + case 109: + return _mm512_mask_blend_ps(0x3CF3, a.values, b.values); + case 110: + return _mm512_mask_blend_ps(0x3CFC, a.values, b.values); + case 111: + return _mm512_mask_blend_ps(0x3CFF, a.values, b.values); + case 112: + return _mm512_mask_blend_ps(0x3F00, a.values, b.values); + case 113: + return _mm512_mask_blend_ps(0x3F03, a.values, b.values); + case 114: + return _mm512_mask_blend_ps(0x3F0C, a.values, b.values); + case 115: + return _mm512_mask_blend_ps(0x3F0F, a.values, b.values); + case 116: + return _mm512_mask_blend_ps(0x3F30, a.values, b.values); + case 117: + return _mm512_mask_blend_ps(0x3F33, a.values, b.values); + case 118: + return _mm512_mask_blend_ps(0x3F3C, a.values, b.values); + case 119: + return _mm512_mask_blend_ps(0x3F3F, a.values, b.values); + case 120: + return _mm512_mask_blend_ps(0x3FC0, a.values, b.values); + case 121: + return _mm512_mask_blend_ps(0x3FC3, a.values, b.values); + case 122: + return _mm512_mask_blend_ps(0x3FCC, a.values, b.values); + case 123: + return _mm512_mask_blend_ps(0x3FCF, a.values, b.values); + case 124: + return _mm512_mask_blend_ps(0x3FF0, a.values, b.values); + case 125: + return _mm512_mask_blend_ps(0x3FF3, a.values, b.values); + case 126: + return _mm512_mask_blend_ps(0x3FFC, a.values, b.values); + case 127: + return _mm512_mask_blend_ps(0x3FFF, a.values, b.values); + case 128: + return _mm512_mask_blend_ps(0xC000, a.values, b.values); + case 129: + return _mm512_mask_blend_ps(0xC003, a.values, b.values); + case 130: + return _mm512_mask_blend_ps(0xC00C, a.values, b.values); + case 131: + return _mm512_mask_blend_ps(0xC00F, a.values, b.values); + case 132: + return _mm512_mask_blend_ps(0xC030, a.values, b.values); + case 133: + return _mm512_mask_blend_ps(0xC033, a.values, b.values); + case 134: + return _mm512_mask_blend_ps(0xC03C, a.values, b.values); + case 135: + return _mm512_mask_blend_ps(0xC03F, a.values, b.values); + case 136: + return _mm512_mask_blend_ps(0xC0C0, a.values, b.values); + case 137: + return _mm512_mask_blend_ps(0xC0C3, a.values, b.values); + case 138: + return _mm512_mask_blend_ps(0xC0CC, a.values, b.values); + case 139: + return _mm512_mask_blend_ps(0xC0CF, a.values, b.values); + case 140: + return _mm512_mask_blend_ps(0xC0F0, a.values, b.values); + case 141: + return _mm512_mask_blend_ps(0xC0F3, a.values, b.values); + case 142: + return _mm512_mask_blend_ps(0xC0FC, a.values, b.values); + case 143: + return _mm512_mask_blend_ps(0xC0FF, a.values, b.values); + case 144: + return _mm512_mask_blend_ps(0xC300, a.values, b.values); + case 145: + return _mm512_mask_blend_ps(0xC303, a.values, b.values); + case 146: + return _mm512_mask_blend_ps(0xC30C, a.values, b.values); + case 147: + return _mm512_mask_blend_ps(0xC30F, a.values, b.values); + case 148: + return _mm512_mask_blend_ps(0xC330, a.values, b.values); + case 149: + return _mm512_mask_blend_ps(0xC333, a.values, b.values); + case 150: + return _mm512_mask_blend_ps(0xC33C, a.values, b.values); + case 151: + return _mm512_mask_blend_ps(0xC33F, a.values, b.values); + case 152: + return _mm512_mask_blend_ps(0xC3C0, a.values, b.values); + case 153: + return _mm512_mask_blend_ps(0xC3C3, a.values, b.values); + case 154: + return _mm512_mask_blend_ps(0xC3CC, a.values, b.values); + case 155: + return _mm512_mask_blend_ps(0xC3CF, a.values, b.values); + case 156: + return _mm512_mask_blend_ps(0xC3F0, a.values, b.values); + case 157: + return _mm512_mask_blend_ps(0xC3F3, a.values, b.values); + case 158: + return _mm512_mask_blend_ps(0xC3FC, a.values, b.values); + case 159: + return _mm512_mask_blend_ps(0xC3FF, a.values, b.values); + case 160: + return _mm512_mask_blend_ps(0xCC00, a.values, b.values); + case 161: + return _mm512_mask_blend_ps(0xCC03, a.values, b.values); + case 162: + return _mm512_mask_blend_ps(0xCC0C, a.values, b.values); + case 163: + return _mm512_mask_blend_ps(0xCC0F, a.values, b.values); + case 164: + return _mm512_mask_blend_ps(0xCC30, a.values, b.values); + case 165: + return _mm512_mask_blend_ps(0xCC33, a.values, b.values); + case 166: + return _mm512_mask_blend_ps(0xCC3C, a.values, b.values); + case 167: + return _mm512_mask_blend_ps(0xCC3F, a.values, b.values); + case 168: + return _mm512_mask_blend_ps(0xCCC0, a.values, b.values); + case 169: + return _mm512_mask_blend_ps(0xCCC3, a.values, b.values); + case 170: + return _mm512_mask_blend_ps(0xCCCC, a.values, b.values); + case 171: + return _mm512_mask_blend_ps(0xCCCF, a.values, b.values); + case 172: + return _mm512_mask_blend_ps(0xCCF0, a.values, b.values); + case 173: + return _mm512_mask_blend_ps(0xCCF3, a.values, b.values); + case 174: + return _mm512_mask_blend_ps(0xCCFC, a.values, b.values); + case 175: + return _mm512_mask_blend_ps(0xCCFF, a.values, b.values); + case 176: + return _mm512_mask_blend_ps(0xCF00, a.values, b.values); + case 177: + return _mm512_mask_blend_ps(0xCF03, a.values, b.values); + case 178: + return _mm512_mask_blend_ps(0xCF0C, a.values, b.values); + case 179: + return _mm512_mask_blend_ps(0xCF0F, a.values, b.values); + case 180: + return _mm512_mask_blend_ps(0xCF30, a.values, b.values); + case 181: + return _mm512_mask_blend_ps(0xCF33, a.values, b.values); + case 182: + return _mm512_mask_blend_ps(0xCF3C, a.values, b.values); + case 183: + return _mm512_mask_blend_ps(0xCF3F, a.values, b.values); + case 184: + return _mm512_mask_blend_ps(0xCFC0, a.values, b.values); + case 185: + return _mm512_mask_blend_ps(0xCFC3, a.values, b.values); + case 186: + return _mm512_mask_blend_ps(0xCFCC, a.values, b.values); + case 187: + return _mm512_mask_blend_ps(0xCFCF, a.values, b.values); + case 188: + return _mm512_mask_blend_ps(0xCFF0, a.values, b.values); + case 189: + return _mm512_mask_blend_ps(0xCFF3, a.values, b.values); + case 190: + return _mm512_mask_blend_ps(0xCFFC, a.values, b.values); + case 191: + return _mm512_mask_blend_ps(0xCFFF, a.values, b.values); + case 192: + return _mm512_mask_blend_ps(0xF000, a.values, b.values); + case 193: + return _mm512_mask_blend_ps(0xF003, a.values, b.values); + case 194: + return _mm512_mask_blend_ps(0xF00C, a.values, b.values); + case 195: + return _mm512_mask_blend_ps(0xF00F, a.values, b.values); + case 196: + return _mm512_mask_blend_ps(0xF030, a.values, b.values); + case 197: + return _mm512_mask_blend_ps(0xF033, a.values, b.values); + case 198: + return _mm512_mask_blend_ps(0xF03C, a.values, b.values); + case 199: + return _mm512_mask_blend_ps(0xF03F, a.values, b.values); + case 200: + return _mm512_mask_blend_ps(0XF0C0, a.values, b.values); + case 201: + return _mm512_mask_blend_ps(0xF0C3, a.values, b.values); + case 202: + return _mm512_mask_blend_ps(0xF0CC, a.values, b.values); + case 203: + return _mm512_mask_blend_ps(0xF0CF, a.values, b.values); + case 204: + return _mm512_mask_blend_ps(0xF0F0, a.values, b.values); + case 205: + return _mm512_mask_blend_ps(0xF0F3, a.values, b.values); + case 206: + return _mm512_mask_blend_ps(0xF0FC, a.values, b.values); + case 207: + return _mm512_mask_blend_ps(0xF0FF, a.values, b.values); + case 208: + return _mm512_mask_blend_ps(0XF300, a.values, b.values); + case 209: + return _mm512_mask_blend_ps(0xF303, a.values, b.values); + case 210: + return _mm512_mask_blend_ps(0xF30C, a.values, b.values); + case 211: + return _mm512_mask_blend_ps(0xF30F, a.values, b.values); + case 212: + return _mm512_mask_blend_ps(0xF330, a.values, b.values); + case 213: + return _mm512_mask_blend_ps(0xF333, a.values, b.values); + case 214: + return _mm512_mask_blend_ps(0XF33C, a.values, b.values); + case 215: + return _mm512_mask_blend_ps(0xF33F, a.values, b.values); + case 216: + return _mm512_mask_blend_ps(0xF3C0, a.values, b.values); + case 217: + return _mm512_mask_blend_ps(0xF3C3, a.values, b.values); + case 218: + return _mm512_mask_blend_ps(0xF3CC, a.values, b.values); + case 219: + return _mm512_mask_blend_ps(0xF3CF, a.values, b.values); + case 220: + return _mm512_mask_blend_ps(0xF3F0, a.values, b.values); + case 221: + return _mm512_mask_blend_ps(0xF3F3, a.values, b.values); + case 222: + return _mm512_mask_blend_ps(0xF3FC, a.values, b.values); + case 223: + return _mm512_mask_blend_ps(0XF3FF, a.values, b.values); + case 224: + return _mm512_mask_blend_ps(0xFC00, a.values, b.values); + case 225: + return _mm512_mask_blend_ps(0xFC03, a.values, b.values); + case 226: + return _mm512_mask_blend_ps(0xFC0C, a.values, b.values); + case 227: + return _mm512_mask_blend_ps(0xFC0F, a.values, b.values); + case 228: + return _mm512_mask_blend_ps(0xFC30, a.values, b.values); + case 229: + return _mm512_mask_blend_ps(0xFC33, a.values, b.values); + case 230: + return _mm512_mask_blend_ps(0xFC3C, a.values, b.values); + case 231: + return _mm512_mask_blend_ps(0xFC3F, a.values, b.values); + case 232: + return _mm512_mask_blend_ps(0xFCC0, a.values, b.values); + case 233: + return _mm512_mask_blend_ps(0xFCC3, a.values, b.values); + case 234: + return _mm512_mask_blend_ps(0xFCCC, a.values, b.values); + case 235: + return _mm512_mask_blend_ps(0xFCCF, a.values, b.values); + case 236: + return _mm512_mask_blend_ps(0xFCF0, a.values, b.values); + case 237: + return _mm512_mask_blend_ps(0xFCF3, a.values, b.values); + case 238: + return _mm512_mask_blend_ps(0xFCFC, a.values, b.values); + case 239: + return _mm512_mask_blend_ps(0xFCFF, a.values, b.values); + case 240: + return _mm512_mask_blend_ps(0xFF00, a.values, b.values); + case 241: + return _mm512_mask_blend_ps(0xFF03, a.values, b.values); + case 242: + return _mm512_mask_blend_ps(0xFF0C, a.values, b.values); + case 243: + return _mm512_mask_blend_ps(0xFF0F, a.values, b.values); + case 244: + return _mm512_mask_blend_ps(0xFF30, a.values, b.values); + case 245: + return _mm512_mask_blend_ps(0xFF33, a.values, b.values); + case 246: + return _mm512_mask_blend_ps(0xFF3C, a.values, b.values); + case 247: + return _mm512_mask_blend_ps(0xFF3F, a.values, b.values); + case 248: + return _mm512_mask_blend_ps(0xFFC0, a.values, b.values); + case 249: + return _mm512_mask_blend_ps(0xFFC3, a.values, b.values); + case 250: + return _mm512_mask_blend_ps(0xFFCC, a.values, b.values); + case 251: + return _mm512_mask_blend_ps(0xFFCF, a.values, b.values); + case 252: + return _mm512_mask_blend_ps(0xFFF0, a.values, b.values); + case 253: + return _mm512_mask_blend_ps(0xFFF3, a.values, b.values); + case 254: + return _mm512_mask_blend_ps(0xFFFC, a.values, b.values); + default: break; + } + return b; + } + static Vectorized> blendv(const Vectorized>& a, + const Vectorized>& b, + const Vectorized>& mask) { + // convert c10::complex index mask to V index mask: xy -> xxyy + auto mask_ = _mm512_unpacklo_ps(mask.values, mask.values); + auto all_ones = _mm512_set1_epi32(0xFFFFFFFF); + auto mmask = _mm512_cmp_epi32_mask(_mm512_castps_si512(mask_), all_ones, _MM_CMPINT_EQ); + return _mm512_mask_blend_ps(mmask, a.values, b.values); + } + template + static Vectorized> arange(c10::complex base = 0., + step_t step = static_cast(1)) { + return Vectorized>(base, + base + step, + base + c10::complex(2)*step, + base + c10::complex(3)*step, + base + c10::complex(4)*step, + base + c10::complex(5)*step, + base + c10::complex(6)*step, + base + c10::complex(7)*step); + } + static Vectorized> set(const Vectorized>& a, + const Vectorized>& b, + int64_t count = size()) { + switch (count) { + case 0: + return a; + case 1: + return blend<1>(a, b); + case 2: + return blend<3>(a, b); + case 3: + return blend<7>(a, b); + case 4: + return blend<15>(a, b); + case 5: + return blend<31>(a, b); + case 6: + return blend<63>(a, b); + case 7: + return blend<127>(a, b); + } + return b; + } + static Vectorized> loadu(const void* ptr, int64_t count = size()) { + if (count == size()) + return _mm512_loadu_ps(reinterpret_cast(ptr)); + + __at_align__ float tmp_values[2*size()]; + // Ensure uninitialized memory does not change the output value See https://github.com/pytorch/pytorch/issues/32502 + // for more details. We do not initialize arrays to zero using "={0}" because gcc would compile it to two + // instructions while a loop would be compiled to one instruction. + for (const auto i : c10::irange(2*size())) { + tmp_values[i] = 0.0; + } + std::memcpy( + tmp_values, + reinterpret_cast(ptr), + count * sizeof(c10::complex)); + return _mm512_load_ps(tmp_values); + } + void store(void* ptr, int count = size()) const { + if (count == size()) { + _mm512_storeu_ps(reinterpret_cast(ptr), values); + } else if (count > 0) { + float tmp_values[2*size()]; + _mm512_storeu_ps(reinterpret_cast(tmp_values), values); + std::memcpy(ptr, tmp_values, count * sizeof(c10::complex)); + } + } + // AVX512 doesn't have horizontal add & horizontal sub instructions. + // TODO: hadd_pd() & hsub_pd() may have scope for improvement. + static inline __m512 hadd_ps(__m512 a, __m512 b) { + __m512i idx1 = _mm512_set_epi32(30, 14, 28, 12, 26, 10, 24, 8, 22, 6, 20, 4, 18, 2, 16, 0); + __m512i idx2 = _mm512_set_epi32(31, 15, 29, 13, 27, 11, 25, 9, 23, 7, 21, 5, 19, 3, 17, 1); + return _mm512_add_ps(_mm512_mask_permutex2var_ps(a, 0xffff, idx1, b), + _mm512_mask_permutex2var_ps(a, 0xffff, idx2, b)); + } + static inline __m512 hsub_ps(__m512 a, __m512 b) { + __m512i idx1 = _mm512_set_epi32(30, 14, 28, 12, 26, 10, 24, 8, 22, 6, 20, 4, 18, 2, 16, 0); + __m512i idx2 = _mm512_set_epi32(31, 15, 29, 13, 27, 11, 25, 9, 23, 7, 21, 5, 19, 3, 17, 1); + return _mm512_sub_ps(_mm512_mask_permutex2var_ps(a, 0xffff, idx1, b), + _mm512_mask_permutex2var_ps(a, 0xffff, idx2, b)); + } + const c10::complex& operator[](int idx) const = delete; + c10::complex& operator[](int idx) = delete; + Vectorized> map(c10::complex (*const f)(const c10::complex &)) const { + __at_align__ c10::complex tmp[size()]; + store(tmp); + for (const auto i : c10::irange(size())) { + tmp[i] = f(tmp[i]); + } + return loadu(tmp); + } + __m512 abs_2_() const { + auto val_2 = _mm512_mul_ps(values, values); // a*a b*b + auto ret = hadd_ps(val_2, val_2); // a*a+b*b a*a+b*b + return ret; + } + __m512 abs_() const { + auto real = _mm512_moveldup_ps(values); // real real + auto imag = _mm512_movehdup_ps(values); // imag imag + return Sleef_hypotf16_u05(real, imag); // abs abs + } + Vectorized> abs() const { + const __m512 real_mask = _mm512_castsi512_ps(_mm512_setr_epi32(0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000000, + 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000000, + 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000000, + 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000000)); + return _mm512_and_ps(abs_(), real_mask); // abs 0 + } + __m512 angle_() const { + //angle = atan2(b/a) + auto b_a = _mm512_permute_ps(values, 0xB1); // b a + return Sleef_atan2f16_u10(values, b_a); // 90-angle angle + } + Vectorized> angle() const { + const __m512 real_mask = _mm512_castsi512_ps(_mm512_setr_epi32(0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000000, + 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000000, + 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000000, + 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000000)); + auto angle = _mm512_permute_ps(angle_(), 0xB1); // angle 90-angle + return _mm512_and_ps(angle, real_mask); // angle 0 + } + Vectorized> sgn() const { + auto abs = abs_(); + auto zero = _mm512_setzero_ps(); + auto mask = _mm512_cmp_ps_mask(abs, zero, _CMP_EQ_OQ); + auto div = values / abs; + return _mm512_mask_blend_ps(mask, div, zero); + } + __m512 real_() const { + const __m512 real_mask = _mm512_castsi512_ps(_mm512_setr_epi32(0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000000, + 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000000, + 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000000, + 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000000)); + return _mm512_and_ps(values, real_mask); + } + Vectorized> real() const { + return real_(); + } + __m512 imag_() const { + const __m512 imag_mask = _mm512_castsi512_ps(_mm512_setr_epi32(0x00000000, 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, + 0x00000000, 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, + 0x00000000, 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, + 0x00000000, 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF)); + return _mm512_and_ps(values, imag_mask); + } + Vectorized> imag() const { + return _mm512_permute_ps(imag_(), 0xB1); //b a + } + __m512 conj_() const { + const __m512 sign_mask = _mm512_setr_ps(0.0, -0.0, 0.0, -0.0, 0.0, -0.0, 0.0, -0.0, + 0.0, -0.0, 0.0, -0.0, 0.0, -0.0, 0.0, -0.0); + return _mm512_xor_ps(values, sign_mask); // a -b + } + Vectorized> conj() const { + return conj_(); + } + Vectorized> log() const { + // Most trigonomic ops use the log() op to improve complex number performance. + return map(std::log); + } + Vectorized> log2() const { + const __m512 log2_ = _mm512_set1_ps(std::log(2)); + return _mm512_div_ps(log(), log2_); + } + Vectorized> log10() const { + const __m512 log10_ = _mm512_set1_ps(std::log(10)); + return _mm512_div_ps(log(), log10_); + } + Vectorized> log1p() const { + return map(std::log1p); + } + Vectorized> asin() const { + // asin(x) + // = -i*ln(iz + sqrt(1 -z^2)) + // = -i*ln((ai - b) + sqrt(1 - (a + bi)*(a + bi))) + // = -i*ln((-b + ai) + sqrt(1 - (a**2 - b**2) - 2*abi)) + const __m512 one = _mm512_set1_ps(1); + + auto conj = conj_(); + auto b_a = _mm512_permute_ps(conj, 0xB1); //-b a + auto ab = _mm512_mul_ps(conj, b_a); //-ab -ab + auto im = _mm512_add_ps(ab, ab); //-2ab -2ab + + auto val_2 = _mm512_mul_ps(values, values); // a*a b*b + auto re = hsub_ps(val_2, _mm512_permute_ps(val_2, 0xB1)); // a*a-b*b b*b-a*a + re = _mm512_sub_ps(one, re); + + auto root = Vectorized(_mm512_mask_blend_ps(0xAAAA, re, im)).sqrt(); //sqrt(re + i*im) + auto ln = Vectorized(_mm512_add_ps(b_a, root)).log(); //ln(iz + sqrt()) + return Vectorized(_mm512_permute_ps(ln.values, 0xB1)).conj(); //-i*ln() + } + Vectorized> acos() const { + return map(std::acos); + } + Vectorized> atan() const; + Vectorized> atanh() const { + return map(std::atanh); + } + Vectorized> exp() const { + //exp(a + bi) + // = exp(a)*(cos(b) + sin(b)i) + auto exp = Sleef_expf16_u10(values); //exp(a) exp(b) + exp = _mm512_mask_blend_ps(0xAAAA, exp, _mm512_permute_ps(exp, 0xB1)); //exp(a) exp(a) + + auto sin_cos = Sleef_sincosf16_u10(values); //[sin(a), cos(a)] [sin(b), cos(b)] + auto cos_sin = _mm512_mask_blend_ps(0xAAAA, _mm512_permute_ps(sin_cos.y, 0xB1), + sin_cos.x); //cos(b) sin(b) + return _mm512_mul_ps(exp, cos_sin); + } + Vectorized> exp2() const { + // Use identity 2**x = exp(log(2) * x) + const __m512 ln_2 = _mm512_set1_ps(c10::ln_2); + Vectorized> scaled_values = _mm512_mul_ps(values, ln_2); + return scaled_values.exp(); + } + Vectorized> expm1() const { + return map(std::expm1); + } + Vectorized> sin() const { + return map(std::sin); + } + Vectorized> sinh() const { + return map(std::sinh); + } + Vectorized> cos() const { + return map(std::cos); + } + Vectorized> cosh() const { + return map(std::cosh); + } + Vectorized> ceil() const { + return _mm512_ceil_ps(values); + } + Vectorized> floor() const { + return _mm512_floor_ps(values); + } + Vectorized> neg() const { + auto zero = _mm512_setzero_ps(); + return _mm512_sub_ps(zero, values); + } + Vectorized> round() const { + return _mm512_roundscale_ps(values, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + } + Vectorized> tan() const { + return map(std::tan); + } + Vectorized> tanh() const { + return map(std::tanh); + } + Vectorized> trunc() const { + return _mm512_roundscale_ps(values, (_MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC)); + } + Vectorized> sqrt() const { + return map(std::sqrt); + } + Vectorized> reciprocal() const; + Vectorized> rsqrt() const { + return sqrt().reciprocal(); + } + Vectorized> pow(const Vectorized> &exp) const { + __at_align__ c10::complex x_tmp[size()]; + __at_align__ c10::complex y_tmp[size()]; + store(x_tmp); + exp.store(y_tmp); + for (const auto i : c10::irange(size())) { + x_tmp[i] = std::pow(x_tmp[i], y_tmp[i]); + } + return loadu(x_tmp); + } + // Comparison using the _CMP_**_OQ predicate. + // `O`: get false if an operand is NaN + // `Q`: do not raise if an operand is NaN + Vectorized> operator==(const Vectorized>& other) const { + auto mask = _mm512_cmp_ps_mask(values, other.values, _CMP_EQ_OQ); + return _mm512_castsi512_ps(_mm512_mask_set1_epi32(zero_vector, mask, 0xFFFFFFFF)); + } + Vectorized> operator!=(const Vectorized>& other) const { + auto mask = _mm512_cmp_ps_mask(values, other.values, _CMP_NEQ_UQ); + return _mm512_castsi512_ps(_mm512_mask_set1_epi32(zero_vector, mask, 0xFFFFFFFF)); + } + Vectorized> operator<(const Vectorized>& other) const { + TORCH_CHECK(false, "not supported for complex numbers"); + } + Vectorized> operator<=(const Vectorized>& other) const { + TORCH_CHECK(false, "not supported for complex numbers"); + } + Vectorized> operator>(const Vectorized>& other) const { + TORCH_CHECK(false, "not supported for complex numbers"); + } + Vectorized> operator>=(const Vectorized>& other) const { + TORCH_CHECK(false, "not supported for complex numbers"); + } + + Vectorized> eq(const Vectorized>& other) const; + Vectorized> ne(const Vectorized>& other) const; +}; + +template <> Vectorized> inline operator+(const Vectorized> &a, + const Vectorized> &b) { + return _mm512_add_ps(a, b); +} + +template <> Vectorized> inline operator-(const Vectorized> &a, + const Vectorized> &b) { + return _mm512_sub_ps(a, b); +} + +template <> Vectorized> inline operator*(const Vectorized> &a, + const Vectorized> &b) { + //(a + bi) * (c + di) = (ac - bd) + (ad + bc)i + const __m512 sign_mask = _mm512_setr_ps(0.0, -0.0, 0.0, -0.0, 0.0, -0.0, 0.0, -0.0, + 0.0, -0.0, 0.0, -0.0, 0.0, -0.0, 0.0, -0.0); + auto ac_bd = _mm512_mul_ps(a, b); //ac bd + + auto d_c = _mm512_permute_ps(b, 0xB1); //d c + d_c = _mm512_xor_ps(sign_mask, d_c); //d -c + auto ad_bc = _mm512_mul_ps(a, d_c); //ad -bc + + auto ret = Vectorized>::hsub_ps(ac_bd, ad_bc); //ac - bd ad + bc + return ret; +} + +template <> Vectorized> inline operator/(const Vectorized> &a, + const Vectorized> &b) { + //re + im*i = (a + bi) / (c + di) + auto mask = _mm512_set1_ps(-0.f); + auto fabs_cd = _mm512_andnot_ps(mask, b); // |c| |d| + auto fabs_dc = _mm512_permute_ps(fabs_cd, 0xB1); // |d| |c| + auto scale = _mm512_rcp14_ps(_mm512_max_ps(fabs_cd, fabs_dc)); // 1/sc 1/sc + auto a2 = _mm512_mul_ps(a, scale); // a/sc b/sc + auto b2 = _mm512_mul_ps(b, scale); // c/sc d/sc + auto acbd2 = _mm512_mul_ps(a2, b2); + + const __m512 sign_mask = _mm512_setr_ps(-0.0, 0.0, -0.0, 0.0, -0.0, 0.0, -0.0, 0.0, + -0.0, 0.0, -0.0, 0.0, -0.0, 0.0, -0.0, 0.0); + auto dc2 = _mm512_permute_ps(b2, 0xB1); // d/sc c/sc + dc2 = _mm512_xor_ps(sign_mask, dc2); // -d/|c,d| c/sc + auto adbc2 = _mm512_mul_ps(a2, dc2); //-ad/sc^2 bc/sc^2 + auto res2 = Vectorized>::hadd_ps(acbd2, adbc2); //(ac+bd)/sc^2 (bc-ad)/sc^2 + + // get the denominator + auto denom2 = Vectorized>(b2).abs_2_(); // (c^2+d^2)/sc^2 (c^2+d^2)/sc^2 + res2 = _mm512_div_ps(res2, denom2); + return res2; +} + +// reciprocal. Implement this here so we can use multiplication. +inline Vectorized> Vectorized>::reciprocal() const { + //re + im*i = (a + bi) / (c + di) + //re = (ac + bd)/abs_2() = c/abs_2() + //im = (bc - ad)/abs_2() = d/abs_2() + const __m512 sign_mask = _mm512_setr_ps(0.0, -0.0, 0.0, -0.0, 0.0, -0.0, 0.0, -0.0, + 0.0, -0.0, 0.0, -0.0, 0.0, -0.0, 0.0, -0.0); + auto c_d = _mm512_xor_ps(sign_mask, values); //c -d + return _mm512_div_ps(c_d, abs_2_()); +} + +inline Vectorized> Vectorized>::atan() const { + // atan(x) = i/2 * ln((i + z)/(i - z)) + const __m512 i = _mm512_setr_ps(0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, + 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0); + const Vectorized i_half = _mm512_setr_ps(0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, + 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5); + + auto sum = Vectorized(_mm512_add_ps(i, values)); // a 1+b + auto sub = Vectorized(_mm512_sub_ps(i, values)); // -a 1-b + auto ln = (sum/sub).log(); // ln((i + z)/(i - z)) + return i_half*ln; // i/2*ln() +} + +template <> +Vectorized> inline maximum(const Vectorized>& a, + const Vectorized>& b) { + auto zero_vector = _mm512_set1_epi32(0); + auto abs_a = a.abs_2_(); + auto abs_b = b.abs_2_(); + auto mask = _mm512_cmp_ps_mask(abs_a, abs_b, _CMP_LT_OQ); + auto max = _mm512_mask_blend_ps(mask, a, b); + // Exploit the fact that all-ones is a NaN. + auto isnan_mask = _mm512_cmp_ps_mask(abs_a, abs_b, _CMP_UNORD_Q); + auto isnan = _mm512_mask_set1_epi32(zero_vector, isnan_mask, 0xFFFFFFFF); + return _mm512_or_ps(max, _mm512_castsi512_ps(isnan)); +} + +template <> +Vectorized> inline minimum(const Vectorized>& a, + const Vectorized>& b) { + auto zero_vector = _mm512_set1_epi32(0); + auto abs_a = a.abs_2_(); + auto abs_b = b.abs_2_(); + auto mask = _mm512_cmp_ps_mask(abs_a, abs_b, _CMP_GT_OQ); + auto min = _mm512_mask_blend_ps(mask, a, b); + // Exploit the fact that all-ones is a NaN. + auto isnan_mask = _mm512_cmp_ps_mask(abs_a, abs_b, _CMP_UNORD_Q); + auto isnan = _mm512_mask_set1_epi32(zero_vector, isnan_mask, 0xFFFFFFFF); + return _mm512_or_ps(min, _mm512_castsi512_ps(isnan)); +} + +template <> +Vectorized> inline operator&(const Vectorized>& a, + const Vectorized>& b) { + return _mm512_and_ps(a, b); +} + +template <> +Vectorized> inline operator|(const Vectorized>& a, + const Vectorized>& b) { + return _mm512_or_ps(a, b); +} + +template <> +Vectorized> inline operator^(const Vectorized>& a, + const Vectorized>& b) { + return _mm512_xor_ps(a, b); +} + +inline Vectorized> Vectorized>::eq( + const Vectorized>& other) const { + auto eq = (*this == other); // compares real and imag individually + // If both real numbers and imag numbers are equal, then the complex numbers are equal + return (eq.real() & eq.imag()) & Vectorized>(_mm512_set1_ps(1.0f)); +} + +inline Vectorized> Vectorized>::ne( + const Vectorized>& other) const { + auto ne = (*this != other); // compares real and imag individually + // If either real numbers or imag numbers are not equal, then the complex numbers are not equal + return (ne.real() | ne.imag()) & Vectorized>(_mm512_set1_ps(1.0f)); +} + +#endif + +}}} diff --git a/shared/package-files/6b/6bce635f4b7acfae2d23a69f1f34aa8d6d2b074bb084005057d0d4d743b42c84/_nearest_centroid.py b/shared/package-files/6b/6bce635f4b7acfae2d23a69f1f34aa8d6d2b074bb084005057d0d4d743b42c84/_nearest_centroid.py new file mode 100644 index 0000000000000000000000000000000000000000..a780c27587792478fcef0965127310d35238040d --- /dev/null +++ b/shared/package-files/6b/6bce635f4b7acfae2d23a69f1f34aa8d6d2b074bb084005057d0d4d743b42c84/_nearest_centroid.py @@ -0,0 +1,359 @@ +""" +Nearest Centroid Classification +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Real + +import numpy as np +from scipy import sparse as sp + +from ..base import BaseEstimator, ClassifierMixin, _fit_context +from ..discriminant_analysis import DiscriminantAnalysisPredictionMixin +from ..metrics.pairwise import ( + pairwise_distances, + pairwise_distances_argmin, +) +from ..preprocessing import LabelEncoder +from ..utils import get_tags +from ..utils._available_if import available_if +from ..utils._param_validation import Interval, StrOptions +from ..utils.multiclass import check_classification_targets +from ..utils.sparsefuncs import csc_median_axis_0 +from ..utils.validation import check_is_fitted, validate_data + + +class NearestCentroid( + DiscriminantAnalysisPredictionMixin, ClassifierMixin, BaseEstimator +): + """Nearest centroid classifier. + + Each class is represented by its centroid, with test samples classified to + the class with the nearest centroid. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + metric : {"euclidean", "manhattan"}, default="euclidean" + Metric to use for distance computation. + + If `metric="euclidean"`, the centroid for the samples corresponding to each + class is the arithmetic mean, which minimizes the sum of squared L1 distances. + If `metric="manhattan"`, the centroid is the feature-wise median, which + minimizes the sum of L1 distances. + + .. versionchanged:: 1.5 + All metrics but `"euclidean"` and `"manhattan"` were deprecated and + now raise an error. + + .. versionchanged:: 0.19 + `metric='precomputed'` was deprecated and now raises an error + + shrink_threshold : float, default=None + Threshold for shrinking centroids to remove features. + + priors : {"uniform", "empirical"} or array-like of shape (n_classes,), \ + default="uniform" + The class prior probabilities. By default, the class proportions are + inferred from the training data. + + .. versionadded:: 1.6 + + Attributes + ---------- + centroids_ : array-like of shape (n_classes, n_features) + Centroid of each class. + + classes_ : array of shape (n_classes,) + The unique classes labels. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + deviations_ : ndarray of shape (n_classes, n_features) + Deviations (or shrinkages) of the centroids of each class from the + overall centroid. Equal to eq. (18.4) if `shrink_threshold=None`, + else (18.5) p. 653 of [2]. Can be used to identify features used + for classification. + + .. versionadded:: 1.6 + + within_class_std_dev_ : ndarray of shape (n_features,) + Pooled or within-class standard deviation of input data. + + .. versionadded:: 1.6 + + class_prior_ : ndarray of shape (n_classes,) + The class prior probabilities. + + .. versionadded:: 1.6 + + See Also + -------- + KNeighborsClassifier : Nearest neighbors classifier. + + Notes + ----- + When used for text classification with tf-idf vectors, this classifier is + also known as the Rocchio classifier. + + References + ---------- + [1] Tibshirani, R., Hastie, T., Narasimhan, B., & Chu, G. (2002). Diagnosis of + multiple cancer types by shrunken centroids of gene expression. Proceedings + of the National Academy of Sciences of the United States of America, + 99(10), 6567-6572. The National Academy of Sciences. + + [2] Hastie, T., Tibshirani, R., Friedman, J. (2009). The Elements of Statistical + Learning Data Mining, Inference, and Prediction. 2nd Edition. New York, Springer. + + Examples + -------- + >>> from sklearn.neighbors import NearestCentroid + >>> import numpy as np + >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) + >>> y = np.array([1, 1, 1, 2, 2, 2]) + >>> clf = NearestCentroid() + >>> clf.fit(X, y) + NearestCentroid() + >>> print(clf.predict([[-0.8, -1]])) + [1] + """ + + _parameter_constraints: dict = { + "metric": [StrOptions({"manhattan", "euclidean"})], + "shrink_threshold": [Interval(Real, 0, None, closed="neither"), None], + "priors": ["array-like", StrOptions({"empirical", "uniform"})], + } + + def __init__( + self, + metric="euclidean", + *, + shrink_threshold=None, + priors="uniform", + ): + self.metric = metric + self.shrink_threshold = shrink_threshold + self.priors = priors + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y): + """ + Fit the NearestCentroid model according to the given training data. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples and + `n_features` is the number of features. + Note that centroid shrinking cannot be used with sparse matrices. + y : array-like of shape (n_samples,) + Target values. + + Returns + ------- + self : object + Fitted estimator. + """ + # If X is sparse and the metric is "manhattan", store it in a csc + # format is easier to calculate the median. + if self.metric == "manhattan": + X, y = validate_data(self, X, y, accept_sparse=["csc"]) + else: + ensure_all_finite = ( + "allow-nan" if get_tags(self).input_tags.allow_nan else True + ) + X, y = validate_data( + self, + X, + y, + ensure_all_finite=ensure_all_finite, + accept_sparse=["csr", "csc"], + ) + is_X_sparse = sp.issparse(X) + check_classification_targets(y) + + n_samples, n_features = X.shape + le = LabelEncoder() + y_ind = le.fit_transform(y) + self.classes_ = classes = le.classes_ + n_classes = classes.size + if n_classes < 2: + raise ValueError( + "The number of classes has to be greater than one; got %d class" + % (n_classes) + ) + + if self.priors == "empirical": # estimate priors from sample + _, class_counts = np.unique(y, return_inverse=True) # non-negative ints + self.class_prior_ = np.bincount(class_counts) / float(len(y)) + elif self.priors == "uniform": + self.class_prior_ = np.asarray([1 / n_classes] * n_classes) + else: + self.class_prior_ = np.asarray(self.priors) + + if (self.class_prior_ < 0).any(): + raise ValueError("priors must be non-negative") + if not np.isclose(self.class_prior_.sum(), 1.0): + warnings.warn( + "The priors do not sum to 1. Normalizing such that it sums to one.", + UserWarning, + ) + self.class_prior_ = self.class_prior_ / self.class_prior_.sum() + + # Mask mapping each class to its members. + self.centroids_ = np.empty((n_classes, n_features), dtype=np.float64) + + # Number of clusters in each class. + nk = np.zeros(n_classes) + + for cur_class in range(n_classes): + center_mask = y_ind == cur_class + nk[cur_class] = np.sum(center_mask) + if is_X_sparse: + center_mask = np.where(center_mask)[0] + + if self.metric == "manhattan": + # NumPy does not calculate median of sparse matrices. + if not is_X_sparse: + self.centroids_[cur_class] = np.median(X[center_mask], axis=0) + else: + self.centroids_[cur_class] = csc_median_axis_0(X[center_mask]) + else: # metric == "euclidean" + self.centroids_[cur_class] = X[center_mask].mean(axis=0) + + # Compute within-class std_dev with unshrunked centroids + variance = np.array(X - self.centroids_[y_ind], copy=False) ** 2 + self.within_class_std_dev_ = np.array( + np.sqrt(variance.sum(axis=0) / (n_samples - n_classes)), copy=False + ) + if any(self.within_class_std_dev_ == 0): + warnings.warn( + "self.within_class_std_dev_ has at least 1 zero standard deviation." + "Inputs within the same classes for at least 1 feature are identical." + ) + + err_msg = "All features have zero variance. Division by zero." + if is_X_sparse and np.all((X.max(axis=0) - X.min(axis=0)).toarray() == 0): + raise ValueError(err_msg) + elif not is_X_sparse and np.all(np.ptp(X, axis=0) == 0): + raise ValueError(err_msg) + + dataset_centroid_ = X.mean(axis=0) + # m parameter for determining deviation + m = np.sqrt((1.0 / nk) - (1.0 / n_samples)) + # Calculate deviation using the standard deviation of centroids. + # To deter outliers from affecting the results. + s = self.within_class_std_dev_ + np.median(self.within_class_std_dev_) + mm = m.reshape(len(m), 1) # Reshape to allow broadcasting. + ms = mm * s + self.deviations_ = np.array( + (self.centroids_ - dataset_centroid_) / ms, copy=False + ) + # Soft thresholding: if the deviation crosses 0 during shrinking, + # it becomes zero. + if self.shrink_threshold: + signs = np.sign(self.deviations_) + self.deviations_ = np.abs(self.deviations_) - self.shrink_threshold + np.clip(self.deviations_, 0, None, out=self.deviations_) + self.deviations_ *= signs + # Now adjust the centroids using the deviation + msd = ms * self.deviations_ + self.centroids_ = np.array(dataset_centroid_ + msd, copy=False) + return self + + def predict(self, X): + """Perform classification on an array of test vectors `X`. + + The predicted class `C` for each sample in `X` is returned. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input data. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) + The predicted classes. + """ + check_is_fitted(self) + if np.isclose(self.class_prior_, 1 / len(self.classes_)).all(): + # `validate_data` is called here since we are not calling `super()` + ensure_all_finite = ( + "allow-nan" if get_tags(self).input_tags.allow_nan else True + ) + X = validate_data( + self, + X, + ensure_all_finite=ensure_all_finite, + accept_sparse="csr", + reset=False, + ) + return self.classes_[ + pairwise_distances_argmin(X, self.centroids_, metric=self.metric) + ] + else: + return super().predict(X) + + def _decision_function(self, X): + # return discriminant scores, see eq. (18.2) p. 652 of the ESL. + check_is_fitted(self, "centroids_") + + X_normalized = validate_data( + self, X, copy=True, reset=False, accept_sparse="csr", dtype=np.float64 + ) + + discriminant_score = np.empty( + (X_normalized.shape[0], self.classes_.size), dtype=np.float64 + ) + + mask = self.within_class_std_dev_ != 0 + X_normalized[:, mask] /= self.within_class_std_dev_[mask] + centroids_normalized = self.centroids_.copy() + centroids_normalized[:, mask] /= self.within_class_std_dev_[mask] + + for class_idx in range(self.classes_.size): + distances = pairwise_distances( + X_normalized, centroids_normalized[[class_idx]], metric=self.metric + ).ravel() + distances **= 2 + discriminant_score[:, class_idx] = np.squeeze( + -distances + 2.0 * np.log(self.class_prior_[class_idx]) + ) + + return discriminant_score + + def _check_euclidean_metric(self): + return self.metric == "euclidean" + + decision_function = available_if(_check_euclidean_metric)( + DiscriminantAnalysisPredictionMixin.decision_function + ) + + predict_proba = available_if(_check_euclidean_metric)( + DiscriminantAnalysisPredictionMixin.predict_proba + ) + + predict_log_proba = available_if(_check_euclidean_metric)( + DiscriminantAnalysisPredictionMixin.predict_log_proba + ) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.allow_nan = self.metric == "nan_euclidean" + tags.input_tags.sparse = True + return tags diff --git a/shared/package-files/6b/6bce9f4a0049ab544ded1796c729f30f31097917fefd2356da93f946e6af10be/database.pyi b/shared/package-files/6b/6bce9f4a0049ab544ded1796c729f30f31097917fefd2356da93f946e6af10be/database.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b4f6b05f7d782bdc8b543464bc7c12a97dbc4a69 --- /dev/null +++ b/shared/package-files/6b/6bce9f4a0049ab544ded1796c729f30f31097917fefd2356da93f946e6af10be/database.pyi @@ -0,0 +1,3 @@ +from typing import Any, List + +def check_database_backends(*args: Any, **kwargs: Any) -> List[Any]: ... diff --git a/shared/package-files/6b/6bced6a5a065bf123880053d3a940e90df155096e2ad55987fe55f14b4c8a12e/Gibraltar b/shared/package-files/6b/6bced6a5a065bf123880053d3a940e90df155096e2ad55987fe55f14b4c8a12e/Gibraltar new file mode 100644 index 0000000000000000000000000000000000000000..a38f11ffdf2a9e538695ea8cae20b1d2c04164af Binary files /dev/null and b/shared/package-files/6b/6bced6a5a065bf123880053d3a940e90df155096e2ad55987fe55f14b4c8a12e/Gibraltar differ diff --git a/shared/package-files/6b/6bd066279911b59fe607b2a36c3596f8f12946e3623bf48c3b1413cb2d1a6eab/libdeviceimpl.py b/shared/package-files/6b/6bd066279911b59fe607b2a36c3596f8f12946e3623bf48c3b1413cb2d1a6eab/libdeviceimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..4bb2e905e033d02cb74d1f83d9749387ce58954d --- /dev/null +++ b/shared/package-files/6b/6bd066279911b59fe607b2a36c3596f8f12946e3623bf48c3b1413cb2d1a6eab/libdeviceimpl.py @@ -0,0 +1,83 @@ +from llvmlite import ir +from numba.core import cgutils, types +from numba.core.imputils import Registry +from numba.cuda import libdevice, libdevicefuncs + +registry = Registry() +lower = registry.lower + + +def libdevice_implement(func, retty, nbargs): + def core(context, builder, sig, args): + lmod = builder.module + fretty = context.get_value_type(retty) + fargtys = [context.get_value_type(arg.ty) for arg in nbargs] + fnty = ir.FunctionType(fretty, fargtys) + fn = cgutils.get_or_insert_function(lmod, fnty, func) + return builder.call(fn, args) + + key = getattr(libdevice, func[5:]) + + argtys = [arg.ty for arg in args if not arg.is_ptr] + lower(key, *argtys)(core) + + +def libdevice_implement_multiple_returns(func, retty, prototype_args): + sig = libdevicefuncs.create_signature(retty, prototype_args) + nb_retty = sig.return_type + + def core(context, builder, sig, args): + lmod = builder.module + + fargtys = [] + for arg in prototype_args: + ty = context.get_value_type(arg.ty) + if arg.is_ptr: + ty = ty.as_pointer() + fargtys.append(ty) + + fretty = context.get_value_type(retty) + + fnty = ir.FunctionType(fretty, fargtys) + fn = cgutils.get_or_insert_function(lmod, fnty, func) + + # For returned values that are returned through a pointer, we need to + # allocate variables on the stack and pass a pointer to them. + actual_args = [] + virtual_args = [] + arg_idx = 0 + for arg in prototype_args: + if arg.is_ptr: + # Allocate space for return value and add to args + tmp_arg = cgutils.alloca_once(builder, + context.get_value_type(arg.ty)) + actual_args.append(tmp_arg) + virtual_args.append(tmp_arg) + else: + actual_args.append(args[arg_idx]) + arg_idx += 1 + + ret = builder.call(fn, actual_args) + + # Following the call, we need to assemble the returned values into a + # tuple for returning back to the caller. + tuple_args = [] + if retty != types.void: + tuple_args.append(ret) + for arg in virtual_args: + tuple_args.append(builder.load(arg)) + + if isinstance(nb_retty, types.UniTuple): + return cgutils.pack_array(builder, tuple_args) + else: + return cgutils.pack_struct(builder, tuple_args) + + key = getattr(libdevice, func[5:]) + lower(key, *sig.args)(core) + + +for func, (retty, args) in libdevicefuncs.functions.items(): + if any([arg.is_ptr for arg in args]): + libdevice_implement_multiple_returns(func, retty, args) + else: + libdevice_implement(func, retty, args) diff --git a/shared/package-files/6b/6bd590eeda89bf6c6f1910573d6307e8de4cd54f313ce242887d79adc0a0616d/typeid.h b/shared/package-files/6b/6bd590eeda89bf6c6f1910573d6307e8de4cd54f313ce242887d79adc0a0616d/typeid.h new file mode 100644 index 0000000000000000000000000000000000000000..2c6ac38882f50beb02e7b3caf8b529ca41b1d5d1 --- /dev/null +++ b/shared/package-files/6b/6bd590eeda89bf6c6f1910573d6307e8de4cd54f313ce242887d79adc0a0616d/typeid.h @@ -0,0 +1,714 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +/* + * TypeIdentifier is a small type containing an id. + * Types must be registered using CAFFE_DECLARE_KNOWN_TYPE() (in their header) + * and CAFFE_DEFINE_KNOWN_TYPE() (in their .cpp file) for them to have a type + * id. If a type is registered, you can also create an object containing meta + * data like constructor, destructor, stringified name, ... about the type by + * calling TypeMeta::Make. This returns a TypeMeta() object, which is + * basically just a pointer to the type information, so it's cheap to pass + * around. + */ + +// TODO: This file is still in the caffe2 namespace, despite living +// in the ATen directory. This is because the macro +// CAFFE_KNOWN_TYPE (and CAFFE_DECLARE_KNOWN_TYPE) defines a template +// specialization, which relies +// on the namespace of TypeMeta matching the namespace where the macro is +// called. This requires us to fix all of the call-sites, which I want to do +// later. So the namespace is not fixed at the moment. + +// Make at::Half a fundamental type. + +namespace c10::guts { +template <> +struct is_fundamental : std::true_type {}; +} // namespace c10::guts + +namespace caffe2 { + +/** + * A type id is a unique id for a given C++ type. + * You need to register your types using CAFFE_KNOWN_TYPE(MyType) to be able to + * use TypeIdentifier with custom types. This is for example used to store the + * dtype of tensors. + */ +class C10_API TypeIdentifier final + : public at::IdWrapper { + public: + friend std::ostream& operator<<(std::ostream& stream, TypeIdentifier typeId); + friend constexpr bool operator<(TypeIdentifier lhs, TypeIdentifier rhs); + + /** + * Returns the unique id for the given type T. The id is unique for the type T + * in the sense that for any two different types, their ids are different; for + * the same type T, the id remains the same over different calls of the + * function. However, this is not guaranteed over different runs, as the id + * is generated during run-time. Do NOT serialize the id for storage. + */ + template + static C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA TypeIdentifier Get() noexcept { + return TypeIdentifier(c10::util::get_type_index()); + } + + static constexpr TypeIdentifier uninitialized() { + return TypeIdentifier(c10::util::type_index{0}); + } + + private: + constexpr explicit TypeIdentifier(c10::util::type_index id) : IdWrapper(id) {} +}; + +// Allow usage in std::map / std::set +// TODO Disallow this and rather use std::unordered_map/set everywhere +inline constexpr bool operator<(TypeIdentifier lhs, TypeIdentifier rhs) { + return lhs.underlyingId() < rhs.underlyingId(); +} + +inline std::ostream& operator<<( + std::ostream& stream, + caffe2::TypeIdentifier typeId) { + return stream << typeId.underlyingId(); +} + +} // namespace caffe2 + +namespace at { +using DataType = caffe2::TypeIdentifier; +} + +C10_DEFINE_HASH_FOR_IDWRAPPER(caffe2::TypeIdentifier) + +namespace caffe2 { + +namespace detail { + +// This struct holds the actual type information. There will be +// one allocated per type. TypeMeta objects will then point to the struct +// instance for the type they're configured for. +struct TypeMetaData final { + using New = void*(); + using PlacementNew = void(void*, size_t); + using Copy = void(const void*, void*, size_t); + using PlacementDelete = void(void*, size_t); + using Delete = void(void*); + + constexpr TypeMetaData() noexcept + : itemsize_(0), + new_(nullptr), + placementNew_(nullptr), + copy_(nullptr), + placementDelete_(nullptr), + delete_(nullptr), + id_(TypeIdentifier::uninitialized()), + name_("nullptr (uninitialized)") {} + + constexpr TypeMetaData( + size_t itemsize, + New* newFn, + PlacementNew* placementNew, + Copy* copy, + PlacementDelete* placementDelete, + Delete* deleteFn, + TypeIdentifier id, + c10::string_view name) noexcept + : itemsize_(itemsize), + new_(newFn), + placementNew_(placementNew), + copy_(copy), + placementDelete_(placementDelete), + delete_(deleteFn), + id_(id), + name_(name) {} + + size_t itemsize_; + New* new_; + PlacementNew* placementNew_; + Copy* copy_; + PlacementDelete* placementDelete_; + Delete* delete_; + TypeIdentifier id_; + c10::string_view name_; +}; + +// Mechanism for throwing errors which can't be prevented at compile time +// due to type erasure. E.g. somebody calling TypeMeta::copy() for +// non-copyable type. Right now just throws exception but is implemented +// in .cpp to manage dependencies +[[noreturn]] C10_API void _ThrowRuntimeTypeLogicError(const std::string& msg); + +/** + * Placement new function for the type. + */ +template +inline void _PlacementNew(void* ptr, size_t n) { + T* typed_ptr = static_cast(ptr); + for (const auto i : c10::irange(n)) { + new (typed_ptr + i) T; + } +} + +template +inline void _PlacementNewNotDefault(void* /*ptr*/, size_t /*n*/) { + _ThrowRuntimeTypeLogicError( + "Type " + std::string(c10::util::get_fully_qualified_type_name()) + + " is not default-constructible."); +} + +template < + typename T, + std::enable_if_t>* = nullptr> +inline constexpr TypeMetaData::PlacementNew* _PickPlacementNew() { + return (c10::guts::is_fundamental::value || std::is_pointer_v) + ? nullptr + : &_PlacementNew; +} + +template < + typename T, + std::enable_if_t>* = nullptr> +inline constexpr TypeMetaData::PlacementNew* _PickPlacementNew() { + static_assert( + !c10::guts::is_fundamental::value && !std::is_pointer_v, + "this should have picked the other SFINAE case"); + return &_PlacementNewNotDefault; +} + +template +inline void* _New() { + return new T; +} + +template +inline void* _NewNotDefault() { + _ThrowRuntimeTypeLogicError( + "Type " + std::string(c10::util::get_fully_qualified_type_name()) + + " is not default-constructible."); +} + +template < + typename T, + std::enable_if_t>* = nullptr> +inline constexpr TypeMetaData::New* _PickNew() { + return &_New; +} + +template < + typename T, + std::enable_if_t>* = nullptr> +inline constexpr TypeMetaData::New* _PickNew() { + return &_NewNotDefault; +} + +/** + * Typed copy function for classes. + */ +template +inline void _Copy(const void* src, void* dst, size_t n) { + const T* typed_src = static_cast(src); + T* typed_dst = static_cast(dst); + for (const auto i : c10::irange(n)) { + typed_dst[i] = typed_src[i]; + } +} + +/** + * A placeholder function for types that do not allow assignment. + */ +template +inline void _CopyNotAllowed(const void* /*src*/, void* /*dst*/, size_t /*n*/) { + _ThrowRuntimeTypeLogicError( + "Type " + std::string(c10::util::get_fully_qualified_type_name()) + + " does not allow assignment."); +} + +template >* = nullptr> +inline constexpr TypeMetaData::Copy* _PickCopy() { + return (c10::guts::is_fundamental::value || std::is_pointer_v) + ? nullptr + : &_Copy; +} + +template < + typename T, + std::enable_if_t>* = nullptr> +inline constexpr TypeMetaData::Copy* _PickCopy() { + static_assert( + !c10::guts::is_fundamental::value && !std::is_pointer_v, + "this should have picked the other SFINAE case"); + return &_CopyNotAllowed; +} + +/** + * Destructor for non-fundamental types. + */ +template +inline void _PlacementDelete(void* ptr, size_t n) { + T* typed_ptr = static_cast(ptr); + for (const auto i : c10::irange(n)) { + typed_ptr[i].~T(); + } +} + +template +inline constexpr TypeMetaData::PlacementDelete* _PickPlacementDelete() { + return (c10::guts::is_fundamental::value || std::is_pointer_v) + ? nullptr + : &_PlacementDelete; +} + +template +inline void _Delete(void* ptr) { + T* typed_ptr = static_cast(ptr); + delete typed_ptr; +} + +template +inline constexpr TypeMetaData::Delete* _PickDelete() noexcept { + return &_Delete; +} + +class _Uninitialized final {}; + +} // namespace detail + +// +// note: this is outside TypeMeta bc gcc seems to have trouble +// with scalarTypeItemSizes as a constexpr static member used by +// a public inline instance method +// + +// item sizes for TypeMeta::itemsize() fast path +static constexpr std::array scalarTypeItemSizes = { +#define SCALAR_TYPE_SIZE(T, name) sizeof(T), + AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_AND_QINTS(SCALAR_TYPE_SIZE) +#undef SCALAR_TYPE_SIZE + 0, // Undefined +}; + +/** + * TypeMeta is a thin class that allows us to store the type of a container such + * as a blob, or the data type of a tensor, with a unique run-time id. It also + * stores some additional data such as the item size and the name of the type + * for run-time inspection. + */ +class C10_API TypeMeta final { + public: + using New = detail::TypeMetaData::New; + using PlacementNew = detail::TypeMetaData::PlacementNew; + using Copy = detail::TypeMetaData::Copy; + using PlacementDelete = detail::TypeMetaData::PlacementDelete; + using Delete = detail::TypeMetaData::Delete; + + /** Create a dummy TypeMeta object. To create a TypeMeta object for a specific + * type, use TypeMeta::Make(). + */ + TypeMeta() noexcept; + + /** + * Copy constructor. + */ + TypeMeta(const TypeMeta& src) noexcept = default; + + /** + * Assignment operators. + */ + TypeMeta& operator=(const TypeMeta& src) noexcept = default; + + TypeMeta(TypeMeta&& rhs) noexcept = default; + + inline TypeMeta& operator=(ScalarType scalar_type) noexcept { + index_ = static_cast(scalar_type); + return *this; + } + + private: + // TypeMeta can only be created by Make, making sure that we do not + // create incorrectly mixed up TypeMeta objects. + explicit TypeMeta(const uint16_t index) noexcept : index_(index) {} + + public: + /** + * Returns the type id. + */ + TypeIdentifier id() const noexcept { + return data().id_; + } + /** + * true if we represent some ScalarType type + */ + inline bool isScalarType() const noexcept { + return index_ < NumScalarTypes; + } + /** + * true if we represent ScalarType scalar_type + */ + inline bool isScalarType(ScalarType scalar_type) const noexcept { + return index_ == static_cast(scalar_type); + } + /** + * Returns the size of the item. + */ + inline size_t itemsize() const noexcept { + if (C10_LIKELY(isScalarType())) { + return scalarTypeItemSizes[index_]; + } + return data().itemsize_; + } + /** + * Returns the new function pointer for individual items. + */ + New* newFn() const noexcept { + return data().new_; + } + /** + * Returns the placement new function pointer for individual items. + */ + PlacementNew* placementNew() const noexcept { + return data().placementNew_; + } + /** + * Returns the typed copy function pointer for individual iterms. + */ + Copy* copy() const noexcept { + return data().copy_; + } + /** + * Returns the destructor function pointer for individual items. + */ + PlacementDelete* placementDelete() const noexcept { + return data().placementDelete_; + } + Delete* deleteFn() const noexcept { + return data().delete_; + } + /** + * Returns a printable name for the type. + */ + c10::string_view name() const noexcept { + return data().name_; + } + + friend bool operator==(const TypeMeta& lhs, const TypeMeta& rhs) noexcept; + + template + bool Match() const noexcept { + return (*this == Make()); + } + + // Below are static functions that can be called by passing a specific type. + + template + static C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA TypeIdentifier Id() noexcept { + return TypeIdentifier::Get(); + } + + template + static c10::string_view TypeName() noexcept { + return c10::util::get_fully_qualified_type_name(); + } + + template + static constexpr size_t ItemSize() noexcept { + return sizeof(T); + } + + /** + * Returns a TypeMeta object that corresponds to the typename T. + */ + template + static TypeMeta Make() { + // The instance pointed to is declared here, but defined in a .cpp file. + // We need to silence the compiler warning about using an undefined + // variable template. '-Wpragmas' and '-Wunknown-warning-option' has to be + // disabled for compilers that don't know '-Wundefined-var-template' and + // would error at our attempt to disable it. +#ifndef _MSC_VER +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpragmas" +#pragma GCC diagnostic ignored "-Wunknown-warning-option" +#pragma GCC diagnostic ignored "-Wundefined-var-template" +#endif + return TypeMeta(_typeMetaData()); +#ifndef _MSC_VER +#pragma GCC diagnostic pop +#endif + } + + /** + * convert ScalarType enum values to TypeMeta handles + */ + static inline caffe2::TypeMeta fromScalarType(ScalarType scalar_type) { + const auto index = static_cast(scalar_type); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY( + index < NumScalarTypes, + "Unrecognized Scalartype ", + scalar_type, + " (please report this error)"); + return TypeMeta(index); + } + + /** + * convert TypeMeta handles to ScalarType enum values + */ + inline ScalarType toScalarType() { + if (C10_LIKELY(isScalarType())) { + return static_cast(index_); + } + error_unsupported_typemeta(*this); + } + + private: + [[noreturn]] static void error_unsupported_typemeta(caffe2::TypeMeta dtype); + + // hard limit number of registered types + // note: constexpr provokes Windows compilation error "member may not be + // initialized" static constexpr size_t MaxTypeIndex = 32; + // +#if defined C10_MOBILE +// The reason for this not to be UINT8_MAX is that the array +// initialization takes space which is proportional to the size of the array. +// The compiler seems to add code (or data padding) to initialize the array with +// empty elements. Please see +// https://github.com/pytorch/pytorch/pull/51881 for details. +// +#define MaxTypeIndex \ + (NumScalarTypes + 15 /* number of CAFFE_DEFINE_KNOWN_TYPE in typeid.cpp */ + \ + 1 /* 1 more for caffe2 tensor */) +#else +#define MaxTypeIndex UINT8_MAX +#endif + + // Protects type metadata allocation. + // NOLINTNEXTLINE(facebook-hte-NonPodStaticDeclaration) + static std::mutex& getTypeMetaDatasLock(); + static uint16_t nextTypeIndex; + + static detail::TypeMetaData* typeMetaDatas(); + + static uint16_t existingMetaDataIndexForType(TypeIdentifier identifier); + + public: +#ifdef __CUDACC__ + // NOTE [ TypeIdentifier::Get nvcc/clang discrepancy] + // nvcc and clang do not produce identical results for + // TypeIdentifier::Get, because TypeIdentifier::Get relies on + // __PRETTY_FUNCTION__ and they don't agree on the canonical names + // of types (e.g., nvcc normalizes to `short unsigned int`, but clang + // calls it `unsigned short`). Hide the implementation of this function + // from nvcc so that we always use clang (or whatever host C++ compiler) + // for TypeIdentifier::Get. + template + C10_EXPORT static uint16_t addTypeMetaData(); +#else + template + C10_EXPORT static uint16_t addTypeMetaData() { + const auto identifier = TypeIdentifier::Get(); + // Need to hold this for the rest of the function, protecting: + // 1) existingMetaDataIndexForType() + // 2) nextTypeIndex++ + // 3) the write into typeMetaDatas() + std::lock_guard lock(getTypeMetaDatasLock()); + // It may exist already if added in a different dynamic shared library. + const uint16_t existing_index = existingMetaDataIndexForType(identifier); + if (existing_index != MaxTypeIndex) { + return existing_index; + } + const uint16_t index = nextTypeIndex++; + TORCH_CHECK( + index <= MaxTypeIndex, + "Maximum number of CAFFE_KNOWN_TYPE declarations has been exceeded. ", + "Please report this issue."); + typeMetaDatas()[index] = detail::TypeMetaData{ + sizeof(T), + detail::_PickNew(), + detail::_PickPlacementNew(), + detail::_PickCopy(), + detail::_PickPlacementDelete(), + detail::_PickDelete(), + identifier, + c10::util::get_fully_qualified_type_name()}; + return index; + } +#endif + + private: + // specializations return indexes into typeMetaDataInstances() + template + C10_API static uint16_t _typeMetaData() noexcept; + + // + // TypeMeta just wraps this index + // + + uint16_t index_; + + inline const detail::TypeMetaData& data() const { + return typeMetaDatas()[index_]; + } +}; + +// specializations of TypeMeta::_typeMetaData for ScalarType types + +#define DEFINE_SCALAR_METADATA_INSTANCE(T, name) \ + template <> \ + constexpr uint16_t TypeMeta::_typeMetaData() noexcept { \ + return static_cast(ScalarType::name); \ + } +AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_AND_QINTS(DEFINE_SCALAR_METADATA_INSTANCE) +#undef DEFINE_SCALAR_METADATA_INSTANCE + +template <> +C10_EXPORT constexpr uint16_t TypeMeta::_typeMetaData< + detail::_Uninitialized>() noexcept { + return static_cast(ScalarType::Undefined); +} + +inline TypeMeta::TypeMeta() noexcept + : index_(_typeMetaData()) {} + +inline bool operator==(const TypeMeta& lhs, const TypeMeta& rhs) noexcept { + return (lhs.index_ == rhs.index_); +} +inline bool operator!=(const TypeMeta& lhs, const TypeMeta& rhs) noexcept { + return !operator==(lhs, rhs); +} + +inline std::ostream& operator<<( + std::ostream& stream, + caffe2::TypeMeta typeMeta) { + return stream << typeMeta.name(); +} + +/** + * Register unique id for a type so it can be used in TypeMeta context, e.g. be + * used as a type for Blob or for Tensor elements. + * + * CAFFE_KNOWN_TYPE is deprecated; prefer CAFFE_DECLARE_KNOWN_TYPE and + * CAFFE_DEFINE_KNOWN_TYPE. + * + * CAFFE_KNOWN_TYPE does explicit instantiation of TypeIdentifier::Get + * template function and thus needs to be put in a single translation unit (.cpp + * file) for a given type T. Other translation units that use type T as a type + * of the caffe2::Blob or element type of caffe2::Tensor need to depend on the + * translation unit that contains CAFFE_KNOWN_TYPE declaration via regular + * linkage dependencies. + * + * NOTE: the macro needs to be invoked in ::caffe2 namespace + */ +// Implementation note: in MSVC, we will need to prepend the C10_API +// keyword in order to get things compiled properly. in Linux, gcc seems to +// create attribute ignored error for explicit template instantiations, see +// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0537r0.html +// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51930 +// and as a result, we define these two macros slightly differently. +#if defined(_MSC_VER) || defined(__clang__) +#define EXPORT_IF_NOT_GCC C10_EXPORT +#else +#define EXPORT_IF_NOT_GCC +#endif + +// CAFFE_KNOWN_TYPE is deprecated! Use CAFFE_DECLARE_KNOWN_TYPE and +// CAFFE_DEFINE_KNOWN_TYPE instead. +#define CAFFE_KNOWN_TYPE(T) \ + template uint16_t TypeMeta::addTypeMetaData(); \ + template <> \ + EXPORT_IF_NOT_GCC uint16_t TypeMeta::_typeMetaData() noexcept { \ + static const uint16_t index = addTypeMetaData(); \ + return index; \ + } + +#define CAFFE_DEFINE_KNOWN_TYPE(T, ident) \ + template uint16_t TypeMeta::addTypeMetaData(); \ + namespace detail { \ + EXPORT_IF_NOT_GCC const uint16_t ident##_metadata_index = \ + TypeMeta::addTypeMetaData(); \ + } // namespace detail + +// Unlike CAFFE_KNOWN_TYPE, CAFFE_DECLARE_KNOWN_TYPE avoids a function +// call to access _typeMetaData in the common case. +#define CAFFE_DECLARE_KNOWN_TYPE(T, ident) \ + extern template uint16_t TypeMeta::addTypeMetaData(); \ + namespace detail { \ + extern C10_API const uint16_t ident##_metadata_index; \ + } /* namespace detail */ \ + template <> \ + EXPORT_IF_NOT_GCC C10_ALWAYS_INLINE uint16_t \ + TypeMeta::_typeMetaData() noexcept { \ + return detail::ident##_metadata_index; \ + } + +#define CAFFE_KNOWN_TYPE_NOEXPORT(T) \ + template <> \ + uint16_t TypeMeta::_typeMetaData() noexcept { \ + static const uint16_t index = addTypeMetaData(); \ + return index; \ + } + +CAFFE_DECLARE_KNOWN_TYPE(std::string, std_string) +CAFFE_DECLARE_KNOWN_TYPE(char, char) +CAFFE_DECLARE_KNOWN_TYPE(std::unique_ptr, std_unique_ptr_std_mutex) +CAFFE_DECLARE_KNOWN_TYPE( + std::unique_ptr>, + std_unique_ptr_std_atomic_bool) +CAFFE_DECLARE_KNOWN_TYPE(std::vector, std_vector_int32_t) +CAFFE_DECLARE_KNOWN_TYPE(std::vector, std_vector_int64_t) +CAFFE_DECLARE_KNOWN_TYPE(std::vector, std_vector_unsigned_long) +CAFFE_DECLARE_KNOWN_TYPE(bool*, bool_ptr) +CAFFE_DECLARE_KNOWN_TYPE(char*, char_ptr) +CAFFE_DECLARE_KNOWN_TYPE(int*, int_ptr) + +// For some of the compilers, long is defined separately from int32_t and +// int64_t. As a result we will need to actually define them separately. +// It is recommended that one does NOT use long - use int32_t and int64_t +// explicitly. Explicit long type annotation may go away in the future. +// details: This hack works by defining a _guard_long_unique type, which is +// long iff the compiler has a separate long type and is a dummy type otherwise. +// we then allocate a type id to that _guard_long_unique. If the compiler has a +// separate long type, this allocates a type id for long. Otherwise, it +// allocates a type id for the dummy type, which doesn't matter. +namespace detail { +template +class _guard_long_unique_dummy final {}; +template +using _guard_long_unique = std::conditional_t< + std::is_same_v || std::is_same_v, + _guard_long_unique_dummy, + T>; +} // namespace detail + +CAFFE_DECLARE_KNOWN_TYPE( + detail::_guard_long_unique, + detail_guard_long_unique_long); +CAFFE_DECLARE_KNOWN_TYPE( + detail::_guard_long_unique>, + detail_guard_long_unique_std_vector_long) + +CAFFE_DECLARE_KNOWN_TYPE(float*, float_ptr) +CAFFE_DECLARE_KNOWN_TYPE(at::Half*, at_Half) + +} // namespace caffe2 diff --git a/shared/package-files/6b/6bdb26b03c1b8a64cacb462757cf0e91c6d8aa574c824c7e5a257c2c1e3e306b/stubs.py b/shared/package-files/6b/6bdb26b03c1b8a64cacb462757cf0e91c6d8aa574c824c7e5a257c2c1e3e306b/stubs.py new file mode 100644 index 0000000000000000000000000000000000000000..fb6979a448185945a8ce1e5dbad83f2f23cc36a3 --- /dev/null +++ b/shared/package-files/6b/6bdb26b03c1b8a64cacb462757cf0e91c6d8aa574c824c7e5a257c2c1e3e306b/stubs.py @@ -0,0 +1,902 @@ +""" +This scripts specifies all PTX special objects. +""" +import numpy as np +from collections import defaultdict +import functools +import itertools +from inspect import Signature, Parameter + + +class Stub(object): + ''' + A stub object to represent special objects that are meaningless + outside the context of a CUDA kernel + ''' + _description_ = '' + __slots__ = () # don't allocate __dict__ + + def __new__(cls): + raise NotImplementedError("%s is not instantiable" % cls) + + def __repr__(self): + return self._description_ + + +def stub_function(fn): + ''' + A stub function to represent special functions that are meaningless + outside the context of a CUDA kernel + ''' + @functools.wraps(fn) + def wrapped(*args, **kwargs): + raise NotImplementedError("%s cannot be called from host code" % fn) + return wrapped + + +#------------------------------------------------------------------------------- +# Thread and grid indices and dimensions + + +class Dim3(Stub): + '''A triple, (x, y, z)''' + _description_ = '' + + @property + def x(self): + pass + + @property + def y(self): + pass + + @property + def z(self): + pass + + +class threadIdx(Dim3): + ''' + The thread indices in the current thread block. Each index is an integer + spanning the range from 0 inclusive to the corresponding value of the + attribute in :attr:`numba.cuda.blockDim` exclusive. + ''' + _description_ = '' + + +class blockIdx(Dim3): + ''' + The block indices in the grid of thread blocks. Each index is an integer + spanning the range from 0 inclusive to the corresponding value of the + attribute in :attr:`numba.cuda.gridDim` exclusive. + ''' + _description_ = '' + + +class blockDim(Dim3): + ''' + The shape of a block of threads, as declared when instantiating the kernel. + This value is the same for all threads in a given kernel launch, even if + they belong to different blocks (i.e. each block is "full"). + ''' + _description_ = '' + + +class gridDim(Dim3): + ''' + The shape of the grid of blocks. This value is the same for all threads in + a given kernel launch. + ''' + _description_ = '' + + +class warpsize(Stub): + ''' + The size of a warp. All architectures implemented to date have a warp size + of 32. + ''' + _description_ = '' + + +class laneid(Stub): + ''' + This thread's lane within a warp. Ranges from 0 to + :attr:`numba.cuda.warpsize` - 1. + ''' + _description_ = '' + + +#------------------------------------------------------------------------------- +# Array creation + +class shared(Stub): + ''' + Shared memory namespace + ''' + _description_ = '' + + @stub_function + def array(shape, dtype): + ''' + Allocate a shared array of the given *shape* and *type*. *shape* is + either an integer or a tuple of integers representing the array's + dimensions. *type* is a :ref:`Numba type ` of the + elements needing to be stored in the array. + + The returned array-like object can be read and written to like any + normal device array (e.g. through indexing). + ''' + + +class local(Stub): + ''' + Local memory namespace + ''' + _description_ = '' + + @stub_function + def array(shape, dtype): + ''' + Allocate a local array of the given *shape* and *type*. The array is + private to the current thread, and resides in global memory. An + array-like object is returned which can be read and written to like any + standard array (e.g. through indexing). + ''' + + +class const(Stub): + ''' + Constant memory namespace + ''' + + @stub_function + def array_like(ndarray): + ''' + Create a const array from *ndarry*. The resulting const array will have + the same shape, type, and values as *ndarray*. + ''' + + +# ------------------------------------------------------------------------------- +# warp level operations + +class syncwarp(Stub): + ''' + syncwarp(mask=0xFFFFFFFF) + + Synchronizes a masked subset of threads in a warp. + ''' + _description_ = '' + + +class shfl_sync_intrinsic(Stub): + ''' + shfl_sync_intrinsic(mask, mode, value, mode_offset, clamp) + + Nvvm intrinsic for shuffling data across a warp + docs.nvidia.com/cuda/nvvm-ir-spec/index.html#nvvm-intrin-warp-level-datamove + ''' + _description_ = '' + + +class vote_sync_intrinsic(Stub): + ''' + vote_sync_intrinsic(mask, mode, predictate) + + Nvvm intrinsic for performing a reduce and broadcast across a warp + docs.nvidia.com/cuda/nvvm-ir-spec/index.html#nvvm-intrin-warp-level-vote + ''' + _description_ = '' + + +class match_any_sync(Stub): + ''' + match_any_sync(mask, value) + + Nvvm intrinsic for performing a compare and broadcast across a warp. + Returns a mask of threads that have same value as the given value from + within the masked warp. + ''' + _description_ = '' + + +class match_all_sync(Stub): + ''' + match_all_sync(mask, value) + + Nvvm intrinsic for performing a compare and broadcast across a warp. + Returns a tuple of (mask, pred), where mask is a mask of threads that have + same value as the given value from within the masked warp, if they + all have the same value, otherwise it is 0. Pred is a boolean of whether + or not all threads in the mask warp have the same warp. + ''' + _description_ = '' + + +class activemask(Stub): + ''' + activemask() + + Returns a 32-bit integer mask of all currently active threads in the + calling warp. The Nth bit is set if the Nth lane in the warp is active when + activemask() is called. Inactive threads are represented by 0 bits in the + returned mask. Threads which have exited the kernel are always marked as + inactive. + ''' + _description_ = '' + + +class lanemask_lt(Stub): + ''' + lanemask_lt() + + Returns a 32-bit integer mask of all lanes (including inactive ones) with + ID less than the current lane. + ''' + _description_ = '' + + +# ------------------------------------------------------------------------------- +# memory fences + +class threadfence_block(Stub): + ''' + A memory fence at thread block level + ''' + _description_ = '' + + +class threadfence_system(Stub): + ''' + A memory fence at system level: across devices + ''' + _description_ = '' + + +class threadfence(Stub): + ''' + A memory fence at device level + ''' + _description_ = '' + + +#------------------------------------------------------------------------------- +# bit manipulation + +class popc(Stub): + """ + popc(x) + + Returns the number of set bits in x. + """ + + +class brev(Stub): + """ + brev(x) + + Returns the reverse of the bit pattern of x. For example, 0b10110110 + becomes 0b01101101. + """ + + +class clz(Stub): + """ + clz(x) + + Returns the number of leading zeros in z. + """ + + +class ffs(Stub): + """ + ffs(x) + + Returns the position of the first (least significant) bit set to 1 in x, + where the least significant bit position is 1. ffs(0) returns 0. + """ + + +#------------------------------------------------------------------------------- +# comparison and selection instructions + +class selp(Stub): + """ + selp(a, b, c) + + Select between source operands, based on the value of the predicate source + operand. + """ + + +#------------------------------------------------------------------------------- +# single / double precision arithmetic + +class fma(Stub): + """ + fma(a, b, c) + + Perform the fused multiply-add operation. + """ + + +class cbrt(Stub): + """" + cbrt(a) + + Perform the cube root operation. + """ + + +#------------------------------------------------------------------------------- +# atomic + +class atomic(Stub): + """Namespace for atomic operations + """ + _description_ = '' + + class add(Stub): + """add(ary, idx, val) + + Perform atomic ``ary[idx] += val``. Supported on int32, float32, and + float64 operands only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class sub(Stub): + """sub(ary, idx, val) + + Perform atomic ``ary[idx] -= val``. Supported on int32, float32, and + float64 operands only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class and_(Stub): + """and_(ary, idx, val) + + Perform atomic ``ary[idx] &= val``. Supported on int32, int64, uint32 + and uint64 operands only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class or_(Stub): + """or_(ary, idx, val) + + Perform atomic ``ary[idx] |= val``. Supported on int32, int64, uint32 + and uint64 operands only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class xor(Stub): + """xor(ary, idx, val) + + Perform atomic ``ary[idx] ^= val``. Supported on int32, int64, uint32 + and uint64 operands only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class inc(Stub): + """inc(ary, idx, val) + + Perform atomic ``ary[idx] += 1`` up to val, then reset to 0. Supported + on uint32, and uint64 operands only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class dec(Stub): + """dec(ary, idx, val) + + Performs:: + + ary[idx] = (value if (array[idx] == 0) or + (array[idx] > value) else array[idx] - 1) + + Supported on uint32, and uint64 operands only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class exch(Stub): + """exch(ary, idx, val) + + Perform atomic ``ary[idx] = val``. Supported on int32, int64, uint32 and + uint64 operands only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class max(Stub): + """max(ary, idx, val) + + Perform atomic ``ary[idx] = max(ary[idx], val)``. + + Supported on int32, int64, uint32, uint64, float32, float64 operands + only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class min(Stub): + """min(ary, idx, val) + + Perform atomic ``ary[idx] = min(ary[idx], val)``. + + Supported on int32, int64, uint32, uint64, float32, float64 operands + only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class nanmax(Stub): + """nanmax(ary, idx, val) + + Perform atomic ``ary[idx] = max(ary[idx], val)``. + + NOTE: NaN is treated as a missing value such that: + nanmax(NaN, n) == n, nanmax(n, NaN) == n + + Supported on int32, int64, uint32, uint64, float32, float64 operands + only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class nanmin(Stub): + """nanmin(ary, idx, val) + + Perform atomic ``ary[idx] = min(ary[idx], val)``. + + NOTE: NaN is treated as a missing value, such that: + nanmin(NaN, n) == n, nanmin(n, NaN) == n + + Supported on int32, int64, uint32, uint64, float32, float64 operands + only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class compare_and_swap(Stub): + """compare_and_swap(ary, old, val) + + Conditionally assign ``val`` to the first element of an 1D array ``ary`` + if the current value matches ``old``. + + Supported on int32, int64, uint32, uint64 operands only. + + Returns the old value as if it is loaded atomically. + """ + + class cas(Stub): + """cas(ary, idx, old, val) + + Conditionally assign ``val`` to the element ``idx`` of an array + ``ary`` if the current value of ``ary[idx]`` matches ``old``. + + Supported on int32, int64, uint32, uint64 operands only. + + Returns the old value as if it is loaded atomically. + """ + + +#------------------------------------------------------------------------------- +# timers + +class nanosleep(Stub): + ''' + nanosleep(ns) + + Suspends the thread for a sleep duration approximately close to the delay + `ns`, specified in nanoseconds. + ''' + _description_ = '' + +#------------------------------------------------------------------------------- +# Floating point 16 + + +class fp16(Stub): + """Namespace for fp16 operations + """ + _description_ = '' + + class hadd(Stub): + """hadd(a, b) + + Perform fp16 addition, (a + b) in round to nearest mode. Supported + on fp16 operands only. + + Returns the fp16 result of the addition. + + """ + + class hsub(Stub): + """hsub(a, b) + + Perform fp16 subtraction, (a - b) in round to nearest mode. Supported + on fp16 operands only. + + Returns the fp16 result of the subtraction. + + """ + + class hmul(Stub): + """hmul(a, b) + + Perform fp16 multiplication, (a * b) in round to nearest mode. Supported + on fp16 operands only. + + Returns the fp16 result of the multiplication. + + """ + + class hdiv(Stub): + """hdiv(a, b) + + Perform fp16 division, (a / b) in round to nearest mode. Supported + on fp16 operands only. + + Returns the fp16 result of the division + + """ + + class hfma(Stub): + """hfma(a, b, c) + + Perform fp16 multiply and accumulate, (a * b) + c in round to nearest + mode. Supported on fp16 operands only. + + Returns the fp16 result of the multiplication. + + """ + + class hneg(Stub): + """hneg(a) + + Perform fp16 negation, -(a). Supported on fp16 operands only. + + Returns the fp16 result of the negation. + + """ + + class habs(Stub): + """habs(a) + + Perform fp16 absolute value, |a|. Supported on fp16 operands only. + + Returns the fp16 result of the absolute value. + + """ + + class hsin(Stub): + """hsin(a) + + Calculate sine in round to nearest even mode. Supported on fp16 + operands only. + + Returns the sine result. + + """ + + class hcos(Stub): + """hsin(a) + + Calculate cosine in round to nearest even mode. Supported on fp16 + operands only. + + Returns the cosine result. + + """ + + class hlog(Stub): + """hlog(a) + + Calculate natural logarithm in round to nearest even mode. Supported + on fp16 operands only. + + Returns the natural logarithm result. + + """ + + class hlog10(Stub): + """hlog10(a) + + Calculate logarithm base 10 in round to nearest even mode. Supported + on fp16 operands only. + + Returns the logarithm base 10 result. + + """ + + class hlog2(Stub): + """hlog2(a) + + Calculate logarithm base 2 in round to nearest even mode. Supported + on fp16 operands only. + + Returns the logarithm base 2 result. + + """ + + class hexp(Stub): + """hexp(a) + + Calculate natural exponential, exp(a), in round to nearest mode. + Supported on fp16 operands only. + + Returns the natural exponential result. + + """ + + class hexp10(Stub): + """hexp10(a) + + Calculate exponential base 10 (10 ** a) in round to nearest mode. + Supported on fp16 operands only. + + Returns the exponential base 10 result. + + """ + + class hexp2(Stub): + """hexp2(a) + + Calculate exponential base 2 (2 ** a) in round to nearest mode. + Supported on fp16 operands only. + + Returns the exponential base 2 result. + + """ + + class hfloor(Stub): + """hfloor(a) + + Calculate the floor, the largest integer less than or equal to 'a'. + Supported on fp16 operands only. + + Returns the floor result. + + """ + + class hceil(Stub): + """hceil(a) + + Calculate the ceil, the smallest integer greater than or equal to 'a'. + Supported on fp16 operands only. + + Returns the ceil result. + + """ + + class hsqrt(Stub): + """hsqrt(a) + + Calculate the square root of the input argument in round to nearest + mode. Supported on fp16 operands only. + + Returns the square root result. + + """ + + class hrsqrt(Stub): + """hrsqrt(a) + + Calculate the reciprocal square root of the input argument in round + to nearest even mode. Supported on fp16 operands only. + + Returns the reciprocal square root result. + + """ + + class hrcp(Stub): + """hrcp(a) + + Calculate the reciprocal of the input argument in round to nearest + even mode. Supported on fp16 operands only. + + Returns the reciprocal result. + + """ + + class hrint(Stub): + """hrint(a) + + Round the input argument to nearest integer value. Supported on fp16 + operands only. + + Returns the rounded result. + + """ + + class htrunc(Stub): + """htrunc(a) + + Truncate the input argument to its integer portion. Supported + on fp16 operands only. + + Returns the truncated result. + + """ + + class heq(Stub): + """heq(a, b) + + Perform fp16 comparison, (a == b). Supported + on fp16 operands only. + + Returns True if a and b are equal and False otherwise. + + """ + + class hne(Stub): + """hne(a, b) + + Perform fp16 comparison, (a != b). Supported + on fp16 operands only. + + Returns True if a and b are not equal and False otherwise. + + """ + + class hge(Stub): + """hge(a, b) + + Perform fp16 comparison, (a >= b). Supported + on fp16 operands only. + + Returns True if a is >= b and False otherwise. + + """ + + class hgt(Stub): + """hgt(a, b) + + Perform fp16 comparison, (a > b). Supported + on fp16 operands only. + + Returns True if a is > b and False otherwise. + + """ + + class hle(Stub): + """hle(a, b) + + Perform fp16 comparison, (a <= b). Supported + on fp16 operands only. + + Returns True if a is <= b and False otherwise. + + """ + + class hlt(Stub): + """hlt(a, b) + + Perform fp16 comparison, (a < b). Supported + on fp16 operands only. + + Returns True if a is < b and False otherwise. + + """ + + class hmax(Stub): + """hmax(a, b) + + Perform fp16 maximum operation, max(a,b) Supported + on fp16 operands only. + + Returns a if a is greater than b, returns b otherwise. + + """ + + class hmin(Stub): + """hmin(a, b) + + Perform fp16 minimum operation, min(a,b). Supported + on fp16 operands only. + + Returns a if a is less than b, returns b otherwise. + + """ + + +#------------------------------------------------------------------------------- +# vector types + +def make_vector_type_stubs(): + """Make user facing objects for vector types""" + vector_type_stubs = [] + vector_type_prefix = ( + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "float32", + "float64" + ) + vector_type_element_counts = (1, 2, 3, 4) + vector_type_attribute_names = ("x", "y", "z", "w") + + for prefix, nelem in itertools.product( + vector_type_prefix, vector_type_element_counts + ): + type_name = f"{prefix}x{nelem}" + attr_names = vector_type_attribute_names[:nelem] + + vector_type_stub = type( + type_name, (Stub,), + { + **{attr: lambda self: None for attr in attr_names}, + **{ + "_description_": f"<{type_name}>", + "__signature__": Signature(parameters=[ + Parameter( + name=attr_name, kind=Parameter.POSITIONAL_ONLY + ) for attr_name in attr_names[:nelem] + ]), + "__doc__": f"A stub for {type_name} to be used in " + "CUDA kernels." + }, + **{"aliases": []} + } + ) + vector_type_stubs.append(vector_type_stub) + return vector_type_stubs + + +def map_vector_type_stubs_to_alias(vector_type_stubs): + """For each of the stubs, create its aliases. + + For example: float64x3 -> double3 + """ + # C-compatible type mapping, see: + # https://numpy.org/devdocs/reference/arrays.scalars.html#integer-types + base_type_to_alias = { + "char": f"int{np.dtype(np.byte).itemsize * 8}", + "short": f"int{np.dtype(np.short).itemsize * 8}", + "int": f"int{np.dtype(np.intc).itemsize * 8}", + "long": f"int{np.dtype(np.int_).itemsize * 8}", + "longlong": f"int{np.dtype(np.longlong).itemsize * 8}", + "uchar": f"uint{np.dtype(np.ubyte).itemsize * 8}", + "ushort": f"uint{np.dtype(np.ushort).itemsize * 8}", + "uint": f"uint{np.dtype(np.uintc).itemsize * 8}", + "ulong": f"uint{np.dtype(np.uint).itemsize * 8}", + "ulonglong": f"uint{np.dtype(np.ulonglong).itemsize * 8}", + "float": f"float{np.dtype(np.single).itemsize * 8}", + "double": f"float{np.dtype(np.double).itemsize * 8}" + } + + base_type_to_vector_type = defaultdict(list) + for stub in vector_type_stubs: + base_type_to_vector_type[stub.__name__[:-2]].append(stub) + + for alias, base_type in base_type_to_alias.items(): + vector_type_stubs = base_type_to_vector_type[base_type] + for stub in vector_type_stubs: + nelem = stub.__name__[-1] + stub.aliases.append(f"{alias}{nelem}") + + +_vector_type_stubs = make_vector_type_stubs() +map_vector_type_stubs_to_alias(_vector_type_stubs) diff --git a/shared/package-files/6b/6bdc34adf61dc4c37f3873081ebfe72a20d84dbcf84c1a1070df69a6a75e6acd/_upsample_nearest_exact2d_backward_cpu_dispatch.h b/shared/package-files/6b/6bdc34adf61dc4c37f3873081ebfe72a20d84dbcf84c1a1070df69a6a75e6acd/_upsample_nearest_exact2d_backward_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9600e8330f3d3730bc119f2c5b1b7c8514ec2f0d --- /dev/null +++ b/shared/package-files/6b/6bdc34adf61dc4c37f3873081ebfe72a20d84dbcf84c1a1070df69a6a75e6acd/_upsample_nearest_exact2d_backward_cpu_dispatch.h @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor _upsample_nearest_exact2d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor _upsample_nearest_exact2d_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_nearest_exact2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_nearest_exact2d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input); +TORCH_API at::Tensor & _upsample_nearest_exact2d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_nearest_exact2d_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/6b/6bde54d0458d20ed9e7d7e80c6e9c7322c0a4dae921e6812dfcb8cd29c06f65f/_neg_view_copy_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/6b/6bde54d0458d20ed9e7d7e80c6e9c7322c0a4dae921e6812dfcb8cd29c06f65f/_neg_view_copy_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..db89ea972bfe108fd755ccdc2a3ca44f4a1788fb --- /dev/null +++ b/shared/package-files/6b/6bde54d0458d20ed9e7d7e80c6e9c7322c0a4dae921e6812dfcb8cd29c06f65f/_neg_view_copy_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor _neg_view_copy(const at::Tensor & self); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/6b/6be1fa19912276c88fff8fa2370ee7483f7d00cc8de83347b12974214646200b/error_prop.py b/shared/package-files/6b/6be1fa19912276c88fff8fa2370ee7483f7d00cc8de83347b12974214646200b/error_prop.py new file mode 100644 index 0000000000000000000000000000000000000000..e6cacb894307fe60cbf096c7760e6ed57f385a91 --- /dev/null +++ b/shared/package-files/6b/6be1fa19912276c88fff8fa2370ee7483f7d00cc8de83347b12974214646200b/error_prop.py @@ -0,0 +1,100 @@ +"""Tools for arithmetic error propagation.""" + +from itertools import repeat, combinations + +from sympy.core.add import Add +from sympy.core.mul import Mul +from sympy.core.power import Pow +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.functions.elementary.exponential import exp +from sympy.simplify.simplify import simplify +from sympy.stats.symbolic_probability import RandomSymbol, Variance, Covariance +from sympy.stats.rv import is_random + +_arg0_or_var = lambda var: var.args[0] if len(var.args) > 0 else var + + +def variance_prop(expr, consts=(), include_covar=False): + r"""Symbolically propagates variance (`\sigma^2`) for expressions. + This is computed as as seen in [1]_. + + Parameters + ========== + + expr : Expr + A SymPy expression to compute the variance for. + consts : sequence of Symbols, optional + Represents symbols that are known constants in the expr, + and thus have zero variance. All symbols not in consts are + assumed to be variant. + include_covar : bool, optional + Flag for whether or not to include covariances, default=False. + + Returns + ======= + + var_expr : Expr + An expression for the total variance of the expr. + The variance for the original symbols (e.g. x) are represented + via instance of the Variance symbol (e.g. Variance(x)). + + Examples + ======== + + >>> from sympy import symbols, exp + >>> from sympy.stats.error_prop import variance_prop + >>> x, y = symbols('x y') + + >>> variance_prop(x + y) + Variance(x) + Variance(y) + + >>> variance_prop(x * y) + x**2*Variance(y) + y**2*Variance(x) + + >>> variance_prop(exp(2*x)) + 4*exp(4*x)*Variance(x) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Propagation_of_uncertainty + + """ + args = expr.args + if len(args) == 0: + if expr in consts: + return S.Zero + elif is_random(expr): + return Variance(expr).doit() + elif isinstance(expr, Symbol): + return Variance(RandomSymbol(expr)).doit() + else: + return S.Zero + nargs = len(args) + var_args = list(map(variance_prop, args, repeat(consts, nargs), + repeat(include_covar, nargs))) + if isinstance(expr, Add): + var_expr = Add(*var_args) + if include_covar: + terms = [2 * Covariance(_arg0_or_var(x), _arg0_or_var(y)).expand() \ + for x, y in combinations(var_args, 2)] + var_expr += Add(*terms) + elif isinstance(expr, Mul): + terms = [v/a**2 for a, v in zip(args, var_args)] + var_expr = simplify(expr**2 * Add(*terms)) + if include_covar: + terms = [2*Covariance(_arg0_or_var(x), _arg0_or_var(y)).expand()/(a*b) \ + for (a, b), (x, y) in zip(combinations(args, 2), + combinations(var_args, 2))] + var_expr += Add(*terms) + elif isinstance(expr, Pow): + b = args[1] + v = var_args[0] * (expr * b / args[0])**2 + var_expr = simplify(v) + elif isinstance(expr, exp): + var_expr = simplify(var_args[0] * expr**2) + else: + # unknown how to proceed, return variance of whole expr. + var_expr = Variance(expr) + return var_expr diff --git a/shared/package-files/6b/6be34990e986b66d0ff18f3c7bd7eba714706a9fa019996e1b4ee80d179ec938/ddm.py b/shared/package-files/6b/6be34990e986b66d0ff18f3c7bd7eba714706a9fa019996e1b4ee80d179ec938/ddm.py new file mode 100644 index 0000000000000000000000000000000000000000..d9e2ca778b8452e66e640bbe4b38add6747a4cfe --- /dev/null +++ b/shared/package-files/6b/6be34990e986b66d0ff18f3c7bd7eba714706a9fa019996e1b4ee80d179ec938/ddm.py @@ -0,0 +1,496 @@ +""" + +Module for the DDM class. + +The DDM class is an internal representation used by DomainMatrix. The letters +DDM stand for Dense Domain Matrix. A DDM instance represents a matrix using +elements from a polynomial Domain (e.g. ZZ, QQ, ...) in a dense-matrix +representation. + +Basic usage: + + >>> from sympy import ZZ, QQ + >>> from sympy.polys.matrices.ddm import DDM + >>> A = DDM([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ) + >>> A.shape + (2, 2) + >>> A + [[0, 1], [-1, 0]] + >>> type(A) + + >>> A @ A + [[-1, 0], [0, -1]] + +The ddm_* functions are designed to operate on DDM as well as on an ordinary +list of lists: + + >>> from sympy.polys.matrices.dense import ddm_idet + >>> ddm_idet(A, QQ) + 1 + >>> ddm_idet([[0, 1], [-1, 0]], QQ) + 1 + >>> A + [[-1, 0], [0, -1]] + +Note that ddm_idet modifies the input matrix in-place. It is recommended to +use the DDM.det method as a friendlier interface to this instead which takes +care of copying the matrix: + + >>> B = DDM([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ) + >>> B.det() + 1 + +Normally DDM would not be used directly and is just part of the internal +representation of DomainMatrix which adds further functionality including e.g. +unifying domains. + +The dense format used by DDM is a list of lists of elements e.g. the 2x2 +identity matrix is like [[1, 0], [0, 1]]. The DDM class itself is a subclass +of list and its list items are plain lists. Elements are accessed as e.g. +ddm[i][j] where ddm[i] gives the ith row and ddm[i][j] gets the element in the +jth column of that row. Subclassing list makes e.g. iteration and indexing +very efficient. We do not override __getitem__ because it would lose that +benefit. + +The core routines are implemented by the ddm_* functions defined in dense.py. +Those functions are intended to be able to operate on a raw list-of-lists +representation of matrices with most functions operating in-place. The DDM +class takes care of copying etc and also stores a Domain object associated +with its elements. This makes it possible to implement things like A + B with +domain checking and also shape checking so that the list of lists +representation is friendlier. + +""" +from itertools import chain + +from .exceptions import DMBadInputError, DMShapeError, DMDomainError + +from .dense import ( + ddm_transpose, + ddm_iadd, + ddm_isub, + ddm_ineg, + ddm_imul, + ddm_irmul, + ddm_imatmul, + ddm_irref, + ddm_idet, + ddm_iinv, + ddm_ilu_split, + ddm_ilu_solve, + ddm_berk, + ) + +from sympy.polys.domains import QQ +from .lll import ddm_lll, ddm_lll_transform + + +class DDM(list): + """Dense matrix based on polys domain elements + + This is a list subclass and is a wrapper for a list of lists that supports + basic matrix arithmetic +, -, *, **. + """ + + fmt = 'dense' + + def __init__(self, rowslist, shape, domain): + super().__init__(rowslist) + self.shape = self.rows, self.cols = m, n = shape + self.domain = domain + + if not (len(self) == m and all(len(row) == n for row in self)): + raise DMBadInputError("Inconsistent row-list/shape") + + def getitem(self, i, j): + return self[i][j] + + def setitem(self, i, j, value): + self[i][j] = value + + def extract_slice(self, slice1, slice2): + ddm = [row[slice2] for row in self[slice1]] + rows = len(ddm) + cols = len(ddm[0]) if ddm else len(range(self.shape[1])[slice2]) + return DDM(ddm, (rows, cols), self.domain) + + def extract(self, rows, cols): + ddm = [] + for i in rows: + rowi = self[i] + ddm.append([rowi[j] for j in cols]) + return DDM(ddm, (len(rows), len(cols)), self.domain) + + def to_list(self): + return list(self) + + def to_list_flat(self): + flat = [] + for row in self: + flat.extend(row) + return flat + + def flatiter(self): + return chain.from_iterable(self) + + def flat(self): + items = [] + for row in self: + items.extend(row) + return items + + def to_dok(self): + return {(i, j): e for i, row in enumerate(self) for j, e in enumerate(row)} + + def to_ddm(self): + return self + + def to_sdm(self): + return SDM.from_list(self, self.shape, self.domain) + + def convert_to(self, K): + Kold = self.domain + if K == Kold: + return self.copy() + rows = ([K.convert_from(e, Kold) for e in row] for row in self) + return DDM(rows, self.shape, K) + + def __str__(self): + rowsstr = ['[%s]' % ', '.join(map(str, row)) for row in self] + return '[%s]' % ', '.join(rowsstr) + + def __repr__(self): + cls = type(self).__name__ + rows = list.__repr__(self) + return '%s(%s, %s, %s)' % (cls, rows, self.shape, self.domain) + + def __eq__(self, other): + if not isinstance(other, DDM): + return False + return (super().__eq__(other) and self.domain == other.domain) + + def __ne__(self, other): + return not self.__eq__(other) + + @classmethod + def zeros(cls, shape, domain): + z = domain.zero + m, n = shape + rowslist = ([z] * n for _ in range(m)) + return DDM(rowslist, shape, domain) + + @classmethod + def ones(cls, shape, domain): + one = domain.one + m, n = shape + rowlist = ([one] * n for _ in range(m)) + return DDM(rowlist, shape, domain) + + @classmethod + def eye(cls, size, domain): + one = domain.one + ddm = cls.zeros((size, size), domain) + for i in range(size): + ddm[i][i] = one + return ddm + + def copy(self): + copyrows = (row[:] for row in self) + return DDM(copyrows, self.shape, self.domain) + + def transpose(self): + rows, cols = self.shape + if rows: + ddmT = ddm_transpose(self) + else: + ddmT = [[]] * cols + return DDM(ddmT, (cols, rows), self.domain) + + def __add__(a, b): + if not isinstance(b, DDM): + return NotImplemented + return a.add(b) + + def __sub__(a, b): + if not isinstance(b, DDM): + return NotImplemented + return a.sub(b) + + def __neg__(a): + return a.neg() + + def __mul__(a, b): + if b in a.domain: + return a.mul(b) + else: + return NotImplemented + + def __rmul__(a, b): + if b in a.domain: + return a.mul(b) + else: + return NotImplemented + + def __matmul__(a, b): + if isinstance(b, DDM): + return a.matmul(b) + else: + return NotImplemented + + @classmethod + def _check(cls, a, op, b, ashape, bshape): + if a.domain != b.domain: + msg = "Domain mismatch: %s %s %s" % (a.domain, op, b.domain) + raise DMDomainError(msg) + if ashape != bshape: + msg = "Shape mismatch: %s %s %s" % (a.shape, op, b.shape) + raise DMShapeError(msg) + + def add(a, b): + """a + b""" + a._check(a, '+', b, a.shape, b.shape) + c = a.copy() + ddm_iadd(c, b) + return c + + def sub(a, b): + """a - b""" + a._check(a, '-', b, a.shape, b.shape) + c = a.copy() + ddm_isub(c, b) + return c + + def neg(a): + """-a""" + b = a.copy() + ddm_ineg(b) + return b + + def mul(a, b): + c = a.copy() + ddm_imul(c, b) + return c + + def rmul(a, b): + c = a.copy() + ddm_irmul(c, b) + return c + + def matmul(a, b): + """a @ b (matrix product)""" + m, o = a.shape + o2, n = b.shape + a._check(a, '*', b, o, o2) + c = a.zeros((m, n), a.domain) + ddm_imatmul(c, a, b) + return c + + def mul_elementwise(a, b): + assert a.shape == b.shape + assert a.domain == b.domain + c = [[aij * bij for aij, bij in zip(ai, bi)] for ai, bi in zip(a, b)] + return DDM(c, a.shape, a.domain) + + def hstack(A, *B): + """Horizontally stacks :py:class:`~.DDM` matrices. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.sdm import DDM + + >>> A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> B = DDM([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ) + >>> A.hstack(B) + [[1, 2, 5, 6], [3, 4, 7, 8]] + + >>> C = DDM([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ) + >>> A.hstack(B, C) + [[1, 2, 5, 6, 9, 10], [3, 4, 7, 8, 11, 12]] + """ + Anew = list(A.copy()) + rows, cols = A.shape + domain = A.domain + + for Bk in B: + Bkrows, Bkcols = Bk.shape + assert Bkrows == rows + assert Bk.domain == domain + + cols += Bkcols + + for i, Bki in enumerate(Bk): + Anew[i].extend(Bki) + + return DDM(Anew, (rows, cols), A.domain) + + def vstack(A, *B): + """Vertically stacks :py:class:`~.DDM` matrices. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.sdm import DDM + + >>> A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> B = DDM([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ) + >>> A.vstack(B) + [[1, 2], [3, 4], [5, 6], [7, 8]] + + >>> C = DDM([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ) + >>> A.vstack(B, C) + [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]] + """ + Anew = list(A.copy()) + rows, cols = A.shape + domain = A.domain + + for Bk in B: + Bkrows, Bkcols = Bk.shape + assert Bkcols == cols + assert Bk.domain == domain + + rows += Bkrows + + Anew.extend(Bk.copy()) + + return DDM(Anew, (rows, cols), A.domain) + + def applyfunc(self, func, domain): + elements = (list(map(func, row)) for row in self) + return DDM(elements, self.shape, domain) + + def scc(a): + """Strongly connected components of a square matrix *a*. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.sdm import DDM + >>> A = DDM([[ZZ(1), ZZ(0)], [ZZ(0), ZZ(1)]], (2, 2), ZZ) + >>> A.scc() + [[0], [1]] + + See also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.scc + + """ + return a.to_sdm().scc() + + def rref(a): + """Reduced-row echelon form of a and list of pivots""" + b = a.copy() + K = a.domain + partial_pivot = K.is_RealField or K.is_ComplexField + pivots = ddm_irref(b, _partial_pivot=partial_pivot) + return b, pivots + + def nullspace(a): + rref, pivots = a.rref() + rows, cols = a.shape + domain = a.domain + + basis = [] + nonpivots = [] + for i in range(cols): + if i in pivots: + continue + nonpivots.append(i) + vec = [domain.one if i == j else domain.zero for j in range(cols)] + for ii, jj in enumerate(pivots): + vec[jj] -= rref[ii][i] + basis.append(vec) + + return DDM(basis, (len(basis), cols), domain), nonpivots + + def particular(a): + return a.to_sdm().particular().to_ddm() + + def det(a): + """Determinant of a""" + m, n = a.shape + if m != n: + raise DMShapeError("Determinant of non-square matrix") + b = a.copy() + K = b.domain + deta = ddm_idet(b, K) + return deta + + def inv(a): + """Inverse of a""" + m, n = a.shape + if m != n: + raise DMShapeError("Determinant of non-square matrix") + ainv = a.copy() + K = a.domain + ddm_iinv(ainv, a, K) + return ainv + + def lu(a): + """L, U decomposition of a""" + m, n = a.shape + K = a.domain + + U = a.copy() + L = a.eye(m, K) + swaps = ddm_ilu_split(L, U, K) + + return L, U, swaps + + def lu_solve(a, b): + """x where a*x = b""" + m, n = a.shape + m2, o = b.shape + a._check(a, 'lu_solve', b, m, m2) + + L, U, swaps = a.lu() + x = a.zeros((n, o), a.domain) + ddm_ilu_solve(x, L, U, swaps, b) + return x + + def charpoly(a): + """Coefficients of characteristic polynomial of a""" + K = a.domain + m, n = a.shape + if m != n: + raise DMShapeError("Charpoly of non-square matrix") + vec = ddm_berk(a, K) + coeffs = [vec[i][0] for i in range(n+1)] + return coeffs + + def is_zero_matrix(self): + """ + Says whether this matrix has all zero entries. + """ + zero = self.domain.zero + return all(Mij == zero for Mij in self.flatiter()) + + def is_upper(self): + """ + Says whether this matrix is upper-triangular. True can be returned + even if the matrix is not square. + """ + zero = self.domain.zero + return all(Mij == zero for i, Mi in enumerate(self) for Mij in Mi[:i]) + + def is_lower(self): + """ + Says whether this matrix is lower-triangular. True can be returned + even if the matrix is not square. + """ + zero = self.domain.zero + return all(Mij == zero for i, Mi in enumerate(self) for Mij in Mi[i+1:]) + + def lll(A, delta=QQ(3, 4)): + return ddm_lll(A, delta=delta) + + def lll_transform(A, delta=QQ(3, 4)): + return ddm_lll_transform(A, delta=delta) + + +from .sdm import SDM diff --git a/shared/package-files/6b/6be4c3c3b5d246c3dd0447dfc4ea280d5e160c57ee5e73b9f0fef975c003f3b2/usertools.py b/shared/package-files/6b/6be4c3c3b5d246c3dd0447dfc4ea280d5e160c57ee5e73b9f0fef975c003f3b2/usertools.py new file mode 100644 index 0000000000000000000000000000000000000000..8028a4c46f1c635a6857f1f2de48ac6675d3c6d3 --- /dev/null +++ b/shared/package-files/6b/6be4c3c3b5d246c3dd0447dfc4ea280d5e160c57ee5e73b9f0fef975c003f3b2/usertools.py @@ -0,0 +1,93 @@ + +def monitor(f, input='print', output='print'): + """ + Returns a wrapped copy of *f* that monitors evaluation by calling + *input* with every input (*args*, *kwargs*) passed to *f* and + *output* with every value returned from *f*. The default action + (specify using the special string value ``'print'``) is to print + inputs and outputs to stdout, along with the total evaluation + count:: + + >>> from mpmath import * + >>> mp.dps = 5; mp.pretty = False + >>> diff(monitor(exp), 1) # diff will eval f(x-h) and f(x+h) + in 0 (mpf('0.99999999906867742538452148'),) {} + out 0 mpf('2.7182818259274480055282064') + in 1 (mpf('1.0000000009313225746154785'),) {} + out 1 mpf('2.7182818309906424675501024') + mpf('2.7182808') + + To disable either the input or the output handler, you may + pass *None* as argument. + + Custom input and output handlers may be used e.g. to store + results for later analysis:: + + >>> mp.dps = 15 + >>> input = [] + >>> output = [] + >>> findroot(monitor(sin, input.append, output.append), 3.0) + mpf('3.1415926535897932') + >>> len(input) # Count number of evaluations + 9 + >>> print(input[3]); print(output[3]) + ((mpf('3.1415076583334066'),), {}) + 8.49952562843408e-5 + >>> print(input[4]); print(output[4]) + ((mpf('3.1415928201669122'),), {}) + -1.66577118985331e-7 + + """ + if not input: + input = lambda v: None + elif input == 'print': + incount = [0] + def input(value): + args, kwargs = value + print("in %s %r %r" % (incount[0], args, kwargs)) + incount[0] += 1 + if not output: + output = lambda v: None + elif output == 'print': + outcount = [0] + def output(value): + print("out %s %r" % (outcount[0], value)) + outcount[0] += 1 + def f_monitored(*args, **kwargs): + input((args, kwargs)) + v = f(*args, **kwargs) + output(v) + return v + return f_monitored + +def timing(f, *args, **kwargs): + """ + Returns time elapsed for evaluating ``f()``. Optionally arguments + may be passed to time the execution of ``f(*args, **kwargs)``. + + If the first call is very quick, ``f`` is called + repeatedly and the best time is returned. + """ + once = kwargs.get('once') + if 'once' in kwargs: + del kwargs['once'] + if args or kwargs: + if len(args) == 1 and not kwargs: + arg = args[0] + g = lambda: f(arg) + else: + g = lambda: f(*args, **kwargs) + else: + g = f + from timeit import default_timer as clock + t1=clock(); v=g(); t2=clock(); t=t2-t1 + if t > 0.05 or once: + return t + for i in range(3): + t1=clock(); + # Evaluate multiple times because the timer function + # has a significant overhead + g();g();g();g();g();g();g();g();g();g() + t2=clock() + t=min(t,(t2-t1)/10) + return t diff --git a/shared/package-files/6b/6be5005d38144eb24d14589059385b815bceb2a0895d78854f18ce1b84206e21/http_client.pyi b/shared/package-files/6b/6be5005d38144eb24d14589059385b815bceb2a0895d78854f18ce1b84206e21/http_client.pyi new file mode 100644 index 0000000000000000000000000000000000000000..36d29b9551bc7014616d3355f86bd7cc614b68d1 --- /dev/null +++ b/shared/package-files/6b/6be5005d38144eb24d14589059385b815bceb2a0895d78854f18ce1b84206e21/http_client.pyi @@ -0,0 +1 @@ +from http.client import * diff --git a/shared/package-files/6b/6be63a36ec9138f1c318fd842ec399352570054a06b40bf5c5065f8ac97d9521/test_usetex.py b/shared/package-files/6b/6be63a36ec9138f1c318fd842ec399352570054a06b40bf5c5065f8ac97d9521/test_usetex.py new file mode 100644 index 0000000000000000000000000000000000000000..342face4504fbc444c530fa08335cf19b3c98e6f --- /dev/null +++ b/shared/package-files/6b/6be63a36ec9138f1c318fd842ec399352570054a06b40bf5c5065f8ac97d9521/test_usetex.py @@ -0,0 +1,187 @@ +from tempfile import TemporaryFile + +import numpy as np +from packaging.version import parse as parse_version +import pytest + +import matplotlib as mpl +from matplotlib import dviread +from matplotlib.testing import _has_tex_package +from matplotlib.testing.decorators import check_figures_equal, image_comparison +from matplotlib.testing._markers import needs_usetex +import matplotlib.pyplot as plt + + +pytestmark = needs_usetex + + +@image_comparison( + baseline_images=['test_usetex'], + extensions=['pdf', 'png'], + style="mpl20") +def test_usetex(): + mpl.rcParams['text.usetex'] = True + fig, ax = plt.subplots() + kwargs = {"verticalalignment": "baseline", "size": 24, + "bbox": dict(pad=0, edgecolor="k", facecolor="none")} + ax.text(0.2, 0.7, + # the \LaTeX macro exercises character sizing and placement, + # \left[ ... \right\} draw some variable-height characters, + # \sqrt and \frac draw horizontal rules, \mathrm changes the font + r'\LaTeX\ $\left[\int\limits_e^{2e}' + r'\sqrt\frac{\log^3 x}{x}\,\mathrm{d}x \right\}$', + **kwargs) + ax.text(0.2, 0.3, "lg", **kwargs) + ax.text(0.4, 0.3, r"$\frac{1}{2}\pi$", **kwargs) + ax.text(0.6, 0.3, "$p^{3^A}$", **kwargs) + ax.text(0.8, 0.3, "$p_{3_2}$", **kwargs) + for x in {t.get_position()[0] for t in ax.texts}: + ax.axvline(x) + for y in {t.get_position()[1] for t in ax.texts}: + ax.axhline(y) + ax.set_axis_off() + + +@check_figures_equal() +def test_empty(fig_test, fig_ref): + mpl.rcParams['text.usetex'] = True + fig_test.text(.5, .5, "% a comment") + + +@check_figures_equal() +def test_unicode_minus(fig_test, fig_ref): + mpl.rcParams['text.usetex'] = True + fig_test.text(.5, .5, "$-$") + fig_ref.text(.5, .5, "\N{MINUS SIGN}") + + +def test_mathdefault(): + plt.rcParams["axes.formatter.use_mathtext"] = True + fig = plt.figure() + fig.add_subplot().set_xlim(-1, 1) + # Check that \mathdefault commands generated by tickers don't cause + # problems when later switching usetex on. + mpl.rcParams['text.usetex'] = True + fig.canvas.draw() + + +@image_comparison(['eqnarray.png']) +def test_multiline_eqnarray(): + text = ( + r'\begin{eqnarray*}' + r'foo\\' + r'bar\\' + r'baz\\' + r'\end{eqnarray*}' + ) + + fig = plt.figure(figsize=(1, 1)) + fig.text(0.5, 0.5, text, usetex=True, + horizontalalignment='center', verticalalignment='center') + + +@pytest.mark.parametrize("fontsize", [8, 10, 12]) +def test_minus_no_descent(fontsize): + # Test special-casing of minus descent in DviFont._height_depth_of, by + # checking that overdrawing a 1 and a -1 results in an overall height + # equivalent to drawing either of them separately. + mpl.style.use("mpl20") + mpl.rcParams['font.size'] = fontsize + heights = {} + fig = plt.figure() + for vals in [(1,), (-1,), (-1, 1)]: + fig.clear() + for x in vals: + fig.text(.5, .5, f"${x}$", usetex=True) + fig.canvas.draw() + # The following counts the number of non-fully-blank pixel rows. + heights[vals] = ((np.array(fig.canvas.buffer_rgba())[..., 0] != 255) + .any(axis=1).sum()) + assert len({*heights.values()}) == 1 + + +@pytest.mark.parametrize('pkg', ['xcolor', 'chemformula']) +def test_usetex_packages(pkg): + if not _has_tex_package(pkg): + pytest.skip(f'{pkg} is not available') + mpl.rcParams['text.usetex'] = True + + fig = plt.figure() + text = fig.text(0.5, 0.5, "Some text 0123456789") + fig.canvas.draw() + + mpl.rcParams['text.latex.preamble'] = ( + r'\PassOptionsToPackage{dvipsnames}{xcolor}\usepackage{%s}' % pkg) + fig = plt.figure() + text2 = fig.text(0.5, 0.5, "Some text 0123456789") + fig.canvas.draw() + np.testing.assert_array_equal(text2.get_window_extent(), + text.get_window_extent()) + + +@pytest.mark.parametrize( + "preamble", + [r"\usepackage[full]{textcomp}", r"\usepackage{underscore}"], +) +def test_latex_pkg_already_loaded(preamble): + plt.rcParams["text.latex.preamble"] = preamble + fig = plt.figure() + fig.text(.5, .5, "hello, world", usetex=True) + fig.canvas.draw() + + +def test_usetex_with_underscore(): + plt.rcParams["text.usetex"] = True + df = {"a_b": range(5)[::-1], "c": range(5)} + fig, ax = plt.subplots() + ax.plot("c", "a_b", data=df) + ax.legend() + ax.text(0, 0, "foo_bar", usetex=True) + plt.draw() + + +@pytest.mark.flaky(reruns=3) # Tends to hit a TeX cache lock on AppVeyor. +@pytest.mark.parametrize("fmt", ["pdf", "svg"]) +def test_missing_psfont(fmt, monkeypatch): + """An error is raised if a TeX font lacks a Type-1 equivalent""" + monkeypatch.setattr( + dviread.PsfontsMap, '__getitem__', + lambda self, k: dviread.PsFont( + texname=b'texfont', psname=b'Some Font', + effects=None, encoding=None, filename=None)) + mpl.rcParams['text.usetex'] = True + fig, ax = plt.subplots() + ax.text(0.5, 0.5, 'hello') + with TemporaryFile() as tmpfile, pytest.raises(ValueError): + fig.savefig(tmpfile, format=fmt) + + +try: + _old_gs_version = mpl._get_executable_info('gs').version < parse_version('9.55') +except mpl.ExecutableNotFoundError: + _old_gs_version = True + + +@image_comparison(baseline_images=['rotation'], extensions=['eps', 'pdf', 'png', 'svg'], + style='mpl20', tol=3.91 if _old_gs_version else 0) +def test_rotation(): + mpl.rcParams['text.usetex'] = True + + fig = plt.figure() + ax = fig.add_axes([0, 0, 1, 1]) + ax.set(xlim=[-0.5, 5], xticks=[], ylim=[-0.5, 3], yticks=[], frame_on=False) + + text = {val: val[0] for val in ['top', 'center', 'bottom', 'left', 'right']} + text['baseline'] = 'B' + text['center_baseline'] = 'C' + + for i, va in enumerate(['top', 'center', 'bottom', 'baseline', 'center_baseline']): + for j, ha in enumerate(['left', 'center', 'right']): + for k, angle in enumerate([0, 90, 180, 270]): + k //= 2 + x = i + k / 2 + y = j + k / 2 + ax.plot(x, y, '+', c=f'C{k}', markersize=20, markeredgewidth=0.5) + # 'My' checks full height letters plus descenders. + ax.text(x, y, f"$\\mathrm{{My {text[ha]}{text[va]} {angle}}}$", + rotation=angle, horizontalalignment=ha, verticalalignment=va) diff --git a/shared/package-files/6b/6be736f823317d714f82cd8239280d3be62d568e31e5592bc21e573b36de33ec/sidebar.py b/shared/package-files/6b/6be736f823317d714f82cd8239280d3be62d568e31e5592bc21e573b36de33ec/sidebar.py new file mode 100644 index 0000000000000000000000000000000000000000..fb1084dbf3f18b6a9720e13afcd7f414fa414947 --- /dev/null +++ b/shared/package-files/6b/6be736f823317d714f82cd8239280d3be62d568e31e5592bc21e573b36de33ec/sidebar.py @@ -0,0 +1,544 @@ +"""Line numbering implementation for IDLE as an extension. +Includes BaseSideBar which can be extended for other sidebar based extensions +""" +import contextlib +import functools +import itertools + +import tkinter as tk +from tkinter.font import Font +from idlelib.config import idleConf +from idlelib.delegator import Delegator +from idlelib import macosx + + +def get_lineno(text, index): + """Return the line number of an index in a Tk text widget.""" + text_index = text.index(index) + return int(float(text_index)) if text_index else None + + +def get_end_linenumber(text): + """Return the number of the last line in a Tk text widget.""" + return get_lineno(text, 'end-1c') + + +def get_displaylines(text, index): + """Display height, in lines, of a logical line in a Tk text widget.""" + res = text.count(f"{index} linestart", + f"{index} lineend", + "displaylines") + return res[0] if res else 0 + +def get_widget_padding(widget): + """Get the total padding of a Tk widget, including its border.""" + # TODO: use also in codecontext.py + manager = widget.winfo_manager() + if manager == 'pack': + info = widget.pack_info() + elif manager == 'grid': + info = widget.grid_info() + else: + raise ValueError(f"Unsupported geometry manager: {manager}") + + # All values are passed through getint(), since some + # values may be pixel objects, which can't simply be added to ints. + padx = sum(map(widget.tk.getint, [ + info['padx'], + widget.cget('padx'), + widget.cget('border'), + ])) + pady = sum(map(widget.tk.getint, [ + info['pady'], + widget.cget('pady'), + widget.cget('border'), + ])) + return padx, pady + + +@contextlib.contextmanager +def temp_enable_text_widget(text): + text.configure(state=tk.NORMAL) + try: + yield + finally: + text.configure(state=tk.DISABLED) + + +class BaseSideBar: + """A base class for sidebars using Text.""" + def __init__(self, editwin): + self.editwin = editwin + self.parent = editwin.text_frame + self.text = editwin.text + + self.is_shown = False + + self.main_widget = self.init_widgets() + + self.bind_events() + + self.update_font() + self.update_colors() + + def init_widgets(self): + """Initialize the sidebar's widgets, returning the main widget.""" + raise NotImplementedError + + def update_font(self): + """Update the sidebar text font, usually after config changes.""" + raise NotImplementedError + + def update_colors(self): + """Update the sidebar text colors, usually after config changes.""" + raise NotImplementedError + + def grid(self): + """Layout the widget, always using grid layout.""" + raise NotImplementedError + + def show_sidebar(self): + if not self.is_shown: + self.grid() + self.is_shown = True + + def hide_sidebar(self): + if self.is_shown: + self.main_widget.grid_forget() + self.is_shown = False + + def yscroll_event(self, *args, **kwargs): + """Hook for vertical scrolling for sub-classes to override.""" + raise NotImplementedError + + def redirect_yscroll_event(self, *args, **kwargs): + """Redirect vertical scrolling to the main editor text widget. + + The scroll bar is also updated. + """ + self.editwin.vbar.set(*args) + return self.yscroll_event(*args, **kwargs) + + def redirect_focusin_event(self, event): + """Redirect focus-in events to the main editor text widget.""" + self.text.focus_set() + return 'break' + + def redirect_mousebutton_event(self, event, event_name): + """Redirect mouse button events to the main editor text widget.""" + self.text.focus_set() + self.text.event_generate(event_name, x=0, y=event.y) + return 'break' + + def redirect_mousewheel_event(self, event): + """Redirect mouse wheel events to the editwin text widget.""" + self.text.event_generate('', + x=0, y=event.y, delta=event.delta) + return 'break' + + def bind_events(self): + self.text['yscrollcommand'] = self.redirect_yscroll_event + + # Ensure focus is always redirected to the main editor text widget. + self.main_widget.bind('', self.redirect_focusin_event) + + # Redirect mouse scrolling to the main editor text widget. + # + # Note that without this, scrolling with the mouse only scrolls + # the line numbers. + self.main_widget.bind('', self.redirect_mousewheel_event) + + # Redirect mouse button events to the main editor text widget, + # except for the left mouse button (1). + # + # Note: X-11 sends Button-4 and Button-5 events for the scroll wheel. + def bind_mouse_event(event_name, target_event_name): + handler = functools.partial(self.redirect_mousebutton_event, + event_name=target_event_name) + self.main_widget.bind(event_name, handler) + + for button in [2, 3, 4, 5]: + for event_name in (f'', + f'', + f'', + ): + bind_mouse_event(event_name, target_event_name=event_name) + + # Convert double- and triple-click events to normal click events, + # since event_generate() doesn't allow generating such events. + for event_name in (f'', + f'', + ): + bind_mouse_event(event_name, + target_event_name=f'') + + # start_line is set upon to allow selecting a range of rows + # by dragging. It is cleared upon . + start_line = None + + # last_y is initially set upon and is continuously updated + # upon , until or the mouse button is released. + # It is used in text_auto_scroll(), which is called repeatedly and + # does have a mouse event available. + last_y = None + + # auto_scrolling_after_id is set whenever text_auto_scroll is + # scheduled via .after(). It is used to stop the auto-scrolling + # upon , as well as to avoid scheduling the function several + # times in parallel. + auto_scrolling_after_id = None + + def drag_update_selection_and_insert_mark(y_coord): + """Helper function for drag and selection event handlers.""" + lineno = get_lineno(self.text, f"@0,{y_coord}") + a, b = sorted([start_line, lineno]) + self.text.tag_remove("sel", "1.0", "end") + self.text.tag_add("sel", f"{a}.0", f"{b+1}.0") + self.text.mark_set("insert", + f"{lineno if lineno == a else lineno + 1}.0") + + def b1_mousedown_handler(event): + nonlocal start_line + nonlocal last_y + start_line = int(float(self.text.index(f"@0,{event.y}"))) + last_y = event.y + + drag_update_selection_and_insert_mark(event.y) + self.main_widget.bind('', b1_mousedown_handler) + + def b1_mouseup_handler(event): + # On mouse up, we're no longer dragging. Set the shared persistent + # variables to None to represent this. + nonlocal start_line + nonlocal last_y + start_line = None + last_y = None + self.text.event_generate('', x=0, y=event.y) + self.main_widget.bind('', b1_mouseup_handler) + + def b1_drag_handler(event): + nonlocal last_y + if last_y is None: # i.e. if not currently dragging + return + last_y = event.y + drag_update_selection_and_insert_mark(event.y) + self.main_widget.bind('', b1_drag_handler) + + def text_auto_scroll(): + """Mimic Text auto-scrolling when dragging outside of it.""" + # See: https://github.com/tcltk/tk/blob/064ff9941b4b80b85916a8afe86a6c21fd388b54/library/text.tcl#L670 + nonlocal auto_scrolling_after_id + y = last_y + if y is None: + self.main_widget.after_cancel(auto_scrolling_after_id) + auto_scrolling_after_id = None + return + elif y < 0: + self.text.yview_scroll(-1 + y, 'pixels') + drag_update_selection_and_insert_mark(y) + elif y > self.main_widget.winfo_height(): + self.text.yview_scroll(1 + y - self.main_widget.winfo_height(), + 'pixels') + drag_update_selection_and_insert_mark(y) + auto_scrolling_after_id = \ + self.main_widget.after(50, text_auto_scroll) + + def b1_leave_handler(event): + # Schedule the initial call to text_auto_scroll(), if not already + # scheduled. + nonlocal auto_scrolling_after_id + if auto_scrolling_after_id is None: + nonlocal last_y + last_y = event.y + auto_scrolling_after_id = \ + self.main_widget.after(0, text_auto_scroll) + self.main_widget.bind('', b1_leave_handler) + + def b1_enter_handler(event): + # Cancel the scheduling of text_auto_scroll(), if it exists. + nonlocal auto_scrolling_after_id + if auto_scrolling_after_id is not None: + self.main_widget.after_cancel(auto_scrolling_after_id) + auto_scrolling_after_id = None + self.main_widget.bind('', b1_enter_handler) + + +class EndLineDelegator(Delegator): + """Generate callbacks with the current end line number. + + The provided callback is called after every insert and delete. + """ + def __init__(self, changed_callback): + Delegator.__init__(self) + self.changed_callback = changed_callback + + def insert(self, index, chars, tags=None): + self.delegate.insert(index, chars, tags) + self.changed_callback(get_end_linenumber(self.delegate)) + + def delete(self, index1, index2=None): + self.delegate.delete(index1, index2) + self.changed_callback(get_end_linenumber(self.delegate)) + + +class LineNumbers(BaseSideBar): + """Line numbers support for editor windows.""" + def __init__(self, editwin): + super().__init__(editwin) + + end_line_delegator = EndLineDelegator(self.update_sidebar_text) + # Insert the delegator after the undo delegator, so that line numbers + # are properly updated after undo and redo actions. + self.editwin.per.insertfilterafter(end_line_delegator, + after=self.editwin.undo) + + def init_widgets(self): + _padx, pady = get_widget_padding(self.text) + self.sidebar_text = tk.Text(self.parent, width=1, wrap=tk.NONE, + padx=2, pady=pady, + borderwidth=0, highlightthickness=0) + self.sidebar_text.config(state=tk.DISABLED) + + self.prev_end = 1 + self._sidebar_width_type = type(self.sidebar_text['width']) + with temp_enable_text_widget(self.sidebar_text): + self.sidebar_text.insert('insert', '1', 'linenumber') + self.sidebar_text.config(takefocus=False, exportselection=False) + self.sidebar_text.tag_config('linenumber', justify=tk.RIGHT) + + end = get_end_linenumber(self.text) + self.update_sidebar_text(end) + + return self.sidebar_text + + def grid(self): + self.sidebar_text.grid(row=1, column=0, sticky=tk.NSEW) + + def update_font(self): + font = idleConf.GetFont(self.text, 'main', 'EditorWindow') + self.sidebar_text['font'] = font + + def update_colors(self): + """Update the sidebar text colors, usually after config changes.""" + colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'linenumber') + foreground = colors['foreground'] + background = colors['background'] + self.sidebar_text.config( + fg=foreground, bg=background, + selectforeground=foreground, selectbackground=background, + inactiveselectbackground=background, + ) + + def update_sidebar_text(self, end): + """ + Perform the following action: + Each line sidebar_text contains the linenumber for that line + Synchronize with editwin.text so that both sidebar_text and + editwin.text contain the same number of lines""" + if end == self.prev_end: + return + + width_difference = len(str(end)) - len(str(self.prev_end)) + if width_difference: + cur_width = int(float(self.sidebar_text['width'])) + new_width = cur_width + width_difference + self.sidebar_text['width'] = self._sidebar_width_type(new_width) + + with temp_enable_text_widget(self.sidebar_text): + if end > self.prev_end: + new_text = '\n'.join(itertools.chain( + [''], + map(str, range(self.prev_end + 1, end + 1)), + )) + self.sidebar_text.insert(f'end -1c', new_text, 'linenumber') + else: + self.sidebar_text.delete(f'{end+1}.0 -1c', 'end -1c') + + self.prev_end = end + + def yscroll_event(self, *args, **kwargs): + self.sidebar_text.yview_moveto(args[0]) + return 'break' + + +class WrappedLineHeightChangeDelegator(Delegator): + def __init__(self, callback): + """ + callback - Callable, will be called when an insert, delete or replace + action on the text widget may require updating the shell + sidebar. + """ + Delegator.__init__(self) + self.callback = callback + + def insert(self, index, chars, tags=None): + is_single_line = '\n' not in chars + if is_single_line: + before_displaylines = get_displaylines(self, index) + + self.delegate.insert(index, chars, tags) + + if is_single_line: + after_displaylines = get_displaylines(self, index) + if after_displaylines == before_displaylines: + return # no need to update the sidebar + + self.callback() + + def delete(self, index1, index2=None): + if index2 is None: + index2 = index1 + "+1c" + is_single_line = get_lineno(self, index1) == get_lineno(self, index2) + if is_single_line: + before_displaylines = get_displaylines(self, index1) + + self.delegate.delete(index1, index2) + + if is_single_line: + after_displaylines = get_displaylines(self, index1) + if after_displaylines == before_displaylines: + return # no need to update the sidebar + + self.callback() + + +class ShellSidebar(BaseSideBar): + """Sidebar for the PyShell window, for prompts etc.""" + def __init__(self, editwin): + self.canvas = None + self.line_prompts = {} + + super().__init__(editwin) + + change_delegator = \ + WrappedLineHeightChangeDelegator(self.change_callback) + # Insert the TextChangeDelegator after the last delegator, so that + # the sidebar reflects final changes to the text widget contents. + d = self.editwin.per.top + if d.delegate is not self.text: + while d.delegate is not self.editwin.per.bottom: + d = d.delegate + self.editwin.per.insertfilterafter(change_delegator, after=d) + + self.is_shown = True + + def init_widgets(self): + self.canvas = tk.Canvas(self.parent, width=30, + borderwidth=0, highlightthickness=0, + takefocus=False) + self.update_sidebar() + self.grid() + return self.canvas + + def bind_events(self): + super().bind_events() + + self.main_widget.bind( + # AquaTk defines <2> as the right button, not <3>. + "" if macosx.isAquaTk() else "", + self.context_menu_event, + ) + + def context_menu_event(self, event): + rmenu = tk.Menu(self.main_widget, tearoff=0) + has_selection = bool(self.text.tag_nextrange('sel', '1.0')) + def mkcmd(eventname): + return lambda: self.text.event_generate(eventname) + rmenu.add_command(label='Copy', + command=mkcmd('<>'), + state='normal' if has_selection else 'disabled') + rmenu.add_command(label='Copy with prompts', + command=mkcmd('<>'), + state='normal' if has_selection else 'disabled') + rmenu.tk_popup(event.x_root, event.y_root) + return "break" + + def grid(self): + self.canvas.grid(row=1, column=0, sticky=tk.NSEW, padx=2, pady=0) + + def change_callback(self): + if self.is_shown: + self.update_sidebar() + + def update_sidebar(self): + text = self.text + text_tagnames = text.tag_names + canvas = self.canvas + line_prompts = self.line_prompts = {} + + canvas.delete(tk.ALL) + + index = text.index("@0,0") + if index.split('.', 1)[1] != '0': + index = text.index(f'{index}+1line linestart') + while (lineinfo := text.dlineinfo(index)) is not None: + y = lineinfo[1] + prev_newline_tagnames = text_tagnames(f"{index} linestart -1c") + prompt = ( + '>>>' if "console" in prev_newline_tagnames else + '...' if "stdin" in prev_newline_tagnames else + None + ) + if prompt: + canvas.create_text(2, y, anchor=tk.NW, text=prompt, + font=self.font, fill=self.colors[0]) + lineno = get_lineno(text, index) + line_prompts[lineno] = prompt + index = text.index(f'{index}+1line') + + def yscroll_event(self, *args, **kwargs): + """Redirect vertical scrolling to the main editor text widget. + + The scroll bar is also updated. + """ + self.change_callback() + return 'break' + + def update_font(self): + """Update the sidebar text font, usually after config changes.""" + font = idleConf.GetFont(self.text, 'main', 'EditorWindow') + tk_font = Font(self.text, font=font) + char_width = max(tk_font.measure(char) for char in ['>', '.']) + self.canvas.configure(width=char_width * 3 + 4) + self.font = font + self.change_callback() + + def update_colors(self): + """Update the sidebar text colors, usually after config changes.""" + linenumbers_colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'linenumber') + prompt_colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'console') + foreground = prompt_colors['foreground'] + background = linenumbers_colors['background'] + self.colors = (foreground, background) + self.canvas.configure(background=background) + self.change_callback() + + +def _linenumbers_drag_scrolling(parent): # htest # + from idlelib.idle_test.test_sidebar import Dummy_editwin + + toplevel = tk.Toplevel(parent) + text_frame = tk.Frame(toplevel) + text_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) + text_frame.rowconfigure(1, weight=1) + text_frame.columnconfigure(1, weight=1) + + font = idleConf.GetFont(toplevel, 'main', 'EditorWindow') + text = tk.Text(text_frame, width=80, height=24, wrap=tk.NONE, font=font) + text.grid(row=1, column=1, sticky=tk.NSEW) + + editwin = Dummy_editwin(text) + editwin.vbar = tk.Scrollbar(text_frame) + + linenumbers = LineNumbers(editwin) + linenumbers.show_sidebar() + + text.insert('1.0', '\n'.join('a'*i for i in range(1, 101))) + + +if __name__ == '__main__': + from unittest import main + main('idlelib.idle_test.test_sidebar', verbosity=2, exit=False) + + from idlelib.idle_test.htest import run + run(_linenumbers_drag_scrolling) diff --git a/shared/package-files/6b/6be97732f03f7ccc2aad60d0a070d0e8fd19bf14f8df9ec91f6322a000cb98a5/fbgemm_linear_int8_weight_fp32_activation_ops.h b/shared/package-files/6b/6be97732f03f7ccc2aad60d0a070d0e8fd19bf14f8df9ec91f6322a000cb98a5/fbgemm_linear_int8_weight_fp32_activation_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..ce42287295874dc61f70c1466b7e8f06edaacef8 --- /dev/null +++ b/shared/package-files/6b/6be97732f03f7ccc2aad60d0a070d0e8fd19bf14f8df9ec91f6322a000cb98a5/fbgemm_linear_int8_weight_fp32_activation_ops.h @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API fbgemm_linear_int8_weight_fp32_activation { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::fbgemm_linear_int8_weight_fp32_activation") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fbgemm_linear_int8_weight_fp32_activation(Tensor input, Tensor weight, Tensor packed, Tensor col_offsets, Scalar weight_scale, Scalar weight_zero_point, Tensor bias) -> Tensor") + static at::Tensor call(const at::Tensor & input, const at::Tensor & weight, const at::Tensor & packed, const at::Tensor & col_offsets, const at::Scalar & weight_scale, const at::Scalar & weight_zero_point, const at::Tensor & bias); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & weight, const at::Tensor & packed, const at::Tensor & col_offsets, const at::Scalar & weight_scale, const at::Scalar & weight_zero_point, const at::Tensor & bias); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/6b/6bebdccd287b92780502b2e116c27609735d931e56425ce29711cb773183905c/defaults.py b/shared/package-files/6b/6bebdccd287b92780502b2e116c27609735d931e56425ce29711cb773183905c/defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..483eeb2092e48119776b341da92d66e2f549abbf --- /dev/null +++ b/shared/package-files/6b/6bebdccd287b92780502b2e116c27609735d931e56425ce29711cb773183905c/defaults.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +import io +import sys +from typing import ContextManager, TextIO + +from .base import DummyInput, Input, PipeInput + +__all__ = [ + "create_input", + "create_pipe_input", +] + + +def create_input(stdin: TextIO | None = None, always_prefer_tty: bool = False) -> Input: + """ + Create the appropriate `Input` object for the current os/environment. + + :param always_prefer_tty: When set, if `sys.stdin` is connected to a Unix + `pipe`, check whether `sys.stdout` or `sys.stderr` are connected to a + pseudo terminal. If so, open the tty for reading instead of reading for + `sys.stdin`. (We can open `stdout` or `stderr` for reading, this is how + a `$PAGER` works.) + """ + if sys.platform == "win32": + from .win32 import Win32Input + + # If `stdin` was assigned `None` (which happens with pythonw.exe), use + # a `DummyInput`. This triggers `EOFError` in the application code. + if stdin is None and sys.stdin is None: + return DummyInput() + + return Win32Input(stdin or sys.stdin) + else: + from .vt100 import Vt100Input + + # If no input TextIO is given, use stdin/stdout. + if stdin is None: + stdin = sys.stdin + + if always_prefer_tty: + for obj in [sys.stdin, sys.stdout, sys.stderr]: + if obj.isatty(): + stdin = obj + break + + # If we can't access the file descriptor for the selected stdin, return + # a `DummyInput` instead. This can happen for instance in unit tests, + # when `sys.stdin` is patched by something that's not an actual file. + # (Instantiating `Vt100Input` would fail in this case.) + try: + stdin.fileno() + except io.UnsupportedOperation: + return DummyInput() + + return Vt100Input(stdin) + + +def create_pipe_input() -> ContextManager[PipeInput]: + """ + Create an input pipe. + This is mostly useful for unit testing. + + Usage:: + + with create_pipe_input() as input: + input.send_text('inputdata') + + Breaking change: In prompt_toolkit 3.0.28 and earlier, this was returning + the `PipeInput` directly, rather than through a context manager. + """ + if sys.platform == "win32": + from .win32_pipe import Win32PipeInput + + return Win32PipeInput.create() + else: + from .posix_pipe import PosixPipeInput + + return PosixPipeInput.create() diff --git a/shared/package-files/6b/6bef878d7cd8ead75ecbd450e9642bc85456d8022d64aad79c453f792c2c9625/METADATA b/shared/package-files/6b/6bef878d7cd8ead75ecbd450e9642bc85456d8022d64aad79c453f792c2c9625/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..84a33d4dbafe5cec7ea8e983c27416b84b8e70b5 --- /dev/null +++ b/shared/package-files/6b/6bef878d7cd8ead75ecbd450e9642bc85456d8022d64aad79c453f792c2c9625/METADATA @@ -0,0 +1,42 @@ +Metadata-Version: 2.1 +Name: conda-package-handling +Version: 2.2.0 +Summary: Create and extract conda packages of various formats. +Home-page: https://github.com/conda/conda-package-handling +Author: Anaconda, Inc. +Author-email: conda@anaconda.com +Keywords: conda-package-handling +Classifier: Programming Language :: Python :: 3 +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +License-File: LICENSE +License-File: AUTHORS.md +Requires-Dist: conda-package-streaming (>=0.9.0) +Provides-Extra: docs +Requires-Dist: furo ; extra == 'docs' +Requires-Dist: sphinx ; extra == 'docs' +Requires-Dist: sphinx-argparse ; extra == 'docs' +Requires-Dist: myst-parser ; extra == 'docs' +Requires-Dist: mdit-py-plugins (>=0.3.0) ; extra == 'docs' +Provides-Extra: test +Requires-Dist: mock ; extra == 'test' +Requires-Dist: pytest ; extra == 'test' +Requires-Dist: pytest-cov ; extra == 'test' +Requires-Dist: pytest-mock ; extra == 'test' + +# conda-package-handling + +[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/conda/conda-package-handling/main.svg)](https://results.pre-commit.ci/latest/github/conda/conda-package-handling/main) + +Create and extract conda packages of various formats. + +`conda` and `conda-build` use `conda_package_handling.api` to create and extract +conda packages. This package also provides the `cph` command line tool to +extract, create, and convert between formats. + +See also +[conda-package-streaming](https://conda.github.io/conda-package-streaming), an +efficient library to read from new and old format .conda and .tar.bz2 conda +packages. + +Full documentation at [https://conda.github.io/conda-package-handling/](https://conda.github.io/conda-package-handling/) diff --git a/shared/package-files/6b/6befcd2f7a570c1804de3d5984345cfafcc3a4006b51e692c48761700062d2f4/SymFloat.h b/shared/package-files/6b/6befcd2f7a570c1804de3d5984345cfafcc3a4006b51e692c48761700062d2f4/SymFloat.h new file mode 100644 index 0000000000000000000000000000000000000000..6b0c7a2688c9cc616434038e5742351b9884b4cf --- /dev/null +++ b/shared/package-files/6b/6befcd2f7a570c1804de3d5984345cfafcc3a4006b51e692c48761700062d2f4/SymFloat.h @@ -0,0 +1,113 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace c10 { + +// NB: this is actually double precision; we're using the Python naming here +class C10_API SymFloat { + public: + /*implicit*/ SymFloat(double d) : data_(d){}; + SymFloat(SymNode ptr) + : data_(std::numeric_limits::quiet_NaN()), ptr_(std::move(ptr)) { + TORCH_CHECK(ptr_->is_float()); + }; + SymFloat() : data_(0.0) {} + + SymNodeImpl* toSymNodeImplUnowned() const { + return ptr_.get(); + } + + SymNodeImpl* release() && { + return std::move(ptr_).release(); + } + + // Only valid if is_symbolic() + SymNode toSymNodeImpl() const; + + // Guaranteed to return a SymNode, wrapping using base if necessary + SymNode wrap_node(const SymNode& base) const; + + double expect_float() const { + TORCH_CHECK(!is_symbolic()); + return data_; + } + + SymFloat operator+(const SymFloat&) const; + SymFloat operator-(const SymFloat&) const; + SymFloat operator*(const SymFloat&) const; + SymFloat operator/(const SymFloat&) const; + + SymBool sym_eq(const SymFloat&) const; + SymBool sym_ne(const SymFloat&) const; + SymBool sym_lt(const SymFloat&) const; + SymBool sym_le(const SymFloat&) const; + SymBool sym_gt(const SymFloat&) const; + SymBool sym_ge(const SymFloat&) const; + + bool operator==(const SymFloat& o) const { + return sym_eq(o).guard_bool(__FILE__, __LINE__); + } + bool operator!=(const SymFloat& o) const { + return sym_ne(o).guard_bool(__FILE__, __LINE__); + } + bool operator<(const SymFloat& o) const { + return sym_lt(o).guard_bool(__FILE__, __LINE__); + } + bool operator<=(const SymFloat& o) const { + return sym_le(o).guard_bool(__FILE__, __LINE__); + } + bool operator>(const SymFloat& o) const { + return sym_gt(o).guard_bool(__FILE__, __LINE__); + } + bool operator>=(const SymFloat& o) const { + return sym_ge(o).guard_bool(__FILE__, __LINE__); + } + + SymFloat min(const SymFloat& sci) const; + SymFloat max(const SymFloat& sci) const; + + // Need guidance on where to put this code + SymFloat sqrt() const; + + // Insert a guard for the float to be its concrete value, and then return + // that value. This operation always works, even if the float is symbolic, + // so long as we know what the underlying value is. Don't blindly put this + // everywhere; you can cause overspecialization of PyTorch programs with + // this method. + // + // It should be called as guard_float(__FILE__, __LINE__). The file and line + // number can be used to diagnose overspecialization. + double guard_float(const char* file, int64_t line) const; + + bool has_hint() const; + + // N.B. It's important to keep this definition in the header + // as we expect if checks to be folded for mobile builds + // where `is_symbolic` is always false + C10_ALWAYS_INLINE bool is_symbolic() const { + return ptr_; + } + + double as_float_unchecked() const { + return data_; + } + + private: + // TODO: optimize to union + double data_; + SymNode ptr_; +}; + +C10_API std::ostream& operator<<(std::ostream& os, const SymFloat& s); +} // namespace c10 diff --git a/shared/package-files/6b/6bf18a7f716978d37ccdf31cf95f00692ad0b44235a222df24e728d952a248a2/test_abstract_nodes.py b/shared/package-files/6b/6bf18a7f716978d37ccdf31cf95f00692ad0b44235a222df24e728d952a248a2/test_abstract_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..89e1f73ff8cb24a4a865aa51304ec66e9901e3cb --- /dev/null +++ b/shared/package-files/6b/6bf18a7f716978d37ccdf31cf95f00692ad0b44235a222df24e728d952a248a2/test_abstract_nodes.py @@ -0,0 +1,14 @@ +from sympy.core.symbol import symbols +from sympy.codegen.abstract_nodes import List + + +def test_List(): + l = List(2, 3, 4) + assert l == List(2, 3, 4) + assert str(l) == "[2, 3, 4]" + x, y, z = symbols('x y z') + l = List(x**2,y**3,z**4) + # contrary to python's built-in list, we can call e.g. "replace" on List. + m = l.replace(lambda arg: arg.is_Pow and arg.exp>2, lambda p: p.base-p.exp) + assert m == [x**2, y-3, z-4] + hash(m) diff --git a/shared/package-files/6b/6bf2328356233c1461e81f8dfe7fc11885631637b82be10f89b295f9b3db17b1/array_float32_pointer_3d.sav b/shared/package-files/6b/6bf2328356233c1461e81f8dfe7fc11885631637b82be10f89b295f9b3db17b1/array_float32_pointer_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..285da7f78ffbbf2155fd2e4e648f19a1d3a42ac3 Binary files /dev/null and b/shared/package-files/6b/6bf2328356233c1461e81f8dfe7fc11885631637b82be10f89b295f9b3db17b1/array_float32_pointer_3d.sav differ diff --git a/shared/package-files/6b/6bf472da7297e566e149ed419369345baf9558ea554e0d059c0f6ef2b352215e/test_accumulationbounds.py b/shared/package-files/6b/6bf472da7297e566e149ed419369345baf9558ea554e0d059c0f6ef2b352215e/test_accumulationbounds.py new file mode 100644 index 0000000000000000000000000000000000000000..bcc47c66327fe21ddca3a6b73ca5914e0441b38e --- /dev/null +++ b/shared/package-files/6b/6bf472da7297e566e149ed419369345baf9558ea554e0d059c0f6ef2b352215e/test_accumulationbounds.py @@ -0,0 +1,336 @@ +from sympy.core.numbers import (E, Rational, oo, pi, zoo) +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt) +from sympy.functions.elementary.trigonometric import (cos, sin, tan) +from sympy.calculus.accumulationbounds import AccumBounds +from sympy.core import Add, Mul, Pow +from sympy.core.expr import unchanged +from sympy.testing.pytest import raises, XFAIL +from sympy.abc import x + +a = Symbol('a', real=True) +B = AccumBounds + + +def test_AccumBounds(): + assert B(1, 2).args == (1, 2) + assert B(1, 2).delta is S.One + assert B(1, 2).mid == Rational(3, 2) + assert B(1, 3).is_real == True + + assert B(1, 1) is S.One + + assert B(1, 2) + 1 == B(2, 3) + assert 1 + B(1, 2) == B(2, 3) + assert B(1, 2) + B(2, 3) == B(3, 5) + + assert -B(1, 2) == B(-2, -1) + + assert B(1, 2) - 1 == B(0, 1) + assert 1 - B(1, 2) == B(-1, 0) + assert B(2, 3) - B(1, 2) == B(0, 2) + + assert x + B(1, 2) == Add(B(1, 2), x) + assert a + B(1, 2) == B(1 + a, 2 + a) + assert B(1, 2) - x == Add(B(1, 2), -x) + + assert B(-oo, 1) + oo == B(-oo, oo) + assert B(1, oo) + oo is oo + assert B(1, oo) - oo == B(-oo, oo) + assert (-oo - B(-1, oo)) is -oo + assert B(-oo, 1) - oo is -oo + + assert B(1, oo) - oo == B(-oo, oo) + assert B(-oo, 1) - (-oo) == B(-oo, oo) + assert (oo - B(1, oo)) == B(-oo, oo) + assert (-oo - B(1, oo)) is -oo + + assert B(1, 2)/2 == B(S.Half, 1) + assert 2/B(2, 3) == B(Rational(2, 3), 1) + assert 1/B(-1, 1) == B(-oo, oo) + + assert abs(B(1, 2)) == B(1, 2) + assert abs(B(-2, -1)) == B(1, 2) + assert abs(B(-2, 1)) == B(0, 2) + assert abs(B(-1, 2)) == B(0, 2) + c = Symbol('c') + raises(ValueError, lambda: B(0, c)) + raises(ValueError, lambda: B(1, -1)) + r = Symbol('r', real=True) + raises(ValueError, lambda: B(r, r - 1)) + + +def test_AccumBounds_mul(): + assert B(1, 2)*2 == B(2, 4) + assert 2*B(1, 2) == B(2, 4) + assert B(1, 2)*B(2, 3) == B(2, 6) + assert B(0, 2)*B(2, oo) == B(0, oo) + l, r = B(-oo, oo), B(-a, a) + assert l*r == B(-oo, oo) + assert r*l == B(-oo, oo) + l, r = B(1, oo), B(-3, -2) + assert l*r == B(-oo, -2) + assert r*l == B(-oo, -2) + assert B(1, 2)*0 == 0 + assert B(1, oo)*0 == B(0, oo) + assert B(-oo, 1)*0 == B(-oo, 0) + assert B(-oo, oo)*0 == B(-oo, oo) + + assert B(1, 2)*x == Mul(B(1, 2), x, evaluate=False) + + assert B(0, 2)*oo == B(0, oo) + assert B(-2, 0)*oo == B(-oo, 0) + assert B(0, 2)*(-oo) == B(-oo, 0) + assert B(-2, 0)*(-oo) == B(0, oo) + assert B(-1, 1)*oo == B(-oo, oo) + assert B(-1, 1)*(-oo) == B(-oo, oo) + assert B(-oo, oo)*oo == B(-oo, oo) + + +def test_AccumBounds_div(): + assert B(-1, 3)/B(3, 4) == B(Rational(-1, 3), 1) + assert B(-2, 4)/B(-3, 4) == B(-oo, oo) + assert B(-3, -2)/B(-4, 0) == B(S.Half, oo) + + # these two tests can have a better answer + # after Union of B is improved + assert B(-3, -2)/B(-2, 1) == B(-oo, oo) + assert B(2, 3)/B(-2, 2) == B(-oo, oo) + + assert B(-3, -2)/B(0, 4) == B(-oo, Rational(-1, 2)) + assert B(2, 4)/B(-3, 0) == B(-oo, Rational(-2, 3)) + assert B(2, 4)/B(0, 3) == B(Rational(2, 3), oo) + + assert B(0, 1)/B(0, 1) == B(0, oo) + assert B(-1, 0)/B(0, 1) == B(-oo, 0) + assert B(-1, 2)/B(-2, 2) == B(-oo, oo) + + assert 1/B(-1, 2) == B(-oo, oo) + assert 1/B(0, 2) == B(S.Half, oo) + assert (-1)/B(0, 2) == B(-oo, Rational(-1, 2)) + assert 1/B(-oo, 0) == B(-oo, 0) + assert 1/B(-1, 0) == B(-oo, -1) + assert (-2)/B(-oo, 0) == B(0, oo) + assert 1/B(-oo, -1) == B(-1, 0) + + assert B(1, 2)/a == Mul(B(1, 2), 1/a, evaluate=False) + + assert B(1, 2)/0 == B(1, 2)*zoo + assert B(1, oo)/oo == B(0, oo) + assert B(1, oo)/(-oo) == B(-oo, 0) + assert B(-oo, -1)/oo == B(-oo, 0) + assert B(-oo, -1)/(-oo) == B(0, oo) + assert B(-oo, oo)/oo == B(-oo, oo) + assert B(-oo, oo)/(-oo) == B(-oo, oo) + assert B(-1, oo)/oo == B(0, oo) + assert B(-1, oo)/(-oo) == B(-oo, 0) + assert B(-oo, 1)/oo == B(-oo, 0) + assert B(-oo, 1)/(-oo) == B(0, oo) + + +def test_issue_18795(): + r = Symbol('r', real=True) + a = B(-1,1) + c = B(7, oo) + b = B(-oo, oo) + assert c - tan(r) == B(7-tan(r), oo) + assert b + tan(r) == B(-oo, oo) + assert (a + r)/a == B(-oo, oo)*B(r - 1, r + 1) + assert (b + a)/a == B(-oo, oo) + + +def test_AccumBounds_func(): + assert (x**2 + 2*x + 1).subs(x, B(-1, 1)) == B(-1, 4) + assert exp(B(0, 1)) == B(1, E) + assert exp(B(-oo, oo)) == B(0, oo) + assert log(B(3, 6)) == B(log(3), log(6)) + + +@XFAIL +def test_AccumBounds_powf(): + nn = Symbol('nn', nonnegative=True) + assert B(1 + nn, 2 + nn)**B(1, 2) == B(1 + nn, (2 + nn)**2) + i = Symbol('i', integer=True, negative=True) + assert B(1, 2)**i == B(2**i, 1) + + +def test_AccumBounds_pow(): + assert B(0, 2)**2 == B(0, 4) + assert B(-1, 1)**2 == B(0, 1) + assert B(1, 2)**2 == B(1, 4) + assert B(-1, 2)**3 == B(-1, 8) + assert B(-1, 1)**0 == 1 + + assert B(1, 2)**Rational(5, 2) == B(1, 4*sqrt(2)) + assert B(0, 2)**S.Half == B(0, sqrt(2)) + + neg = Symbol('neg', negative=True) + assert unchanged(Pow, B(neg, 1), S.Half) + nn = Symbol('nn', nonnegative=True) + assert B(nn, nn + 1)**S.Half == B(sqrt(nn), sqrt(nn + 1)) + assert B(nn, nn + 1)**nn == B(nn**nn, (nn + 1)**nn) + assert unchanged(Pow, B(nn, nn + 1), x) + i = Symbol('i', integer=True) + assert B(1, 2)**i == B(Min(1, 2**i), Max(1, 2**i)) + i = Symbol('i', integer=True, nonnegative=True) + assert B(1, 2)**i == B(1, 2**i) + assert B(0, 1)**i == B(0**i, 1) + + assert B(1, 5)**(-2) == B(Rational(1, 25), 1) + assert B(-1, 3)**(-2) == B(0, oo) + assert B(0, 2)**(-3) == B(Rational(1, 8), oo) + assert B(-2, 0)**(-3) == B(-oo, -Rational(1, 8)) + assert B(0, 2)**(-2) == B(Rational(1, 4), oo) + assert B(-1, 2)**(-3) == B(-oo, oo) + assert B(-3, -2)**(-3) == B(Rational(-1, 8), Rational(-1, 27)) + assert B(-3, -2)**(-2) == B(Rational(1, 9), Rational(1, 4)) + assert B(0, oo)**S.Half == B(0, oo) + assert B(-oo, 0)**(-2) == B(0, oo) + assert B(-2, 0)**(-2) == B(Rational(1, 4), oo) + + assert B(Rational(1, 3), S.Half)**oo is S.Zero + assert B(0, S.Half)**oo is S.Zero + assert B(S.Half, 1)**oo == B(0, oo) + assert B(0, 1)**oo == B(0, oo) + assert B(2, 3)**oo is oo + assert B(1, 2)**oo == B(0, oo) + assert B(S.Half, 3)**oo == B(0, oo) + assert B(Rational(-1, 3), Rational(-1, 4))**oo is S.Zero + assert B(-1, Rational(-1, 2))**oo is S.NaN + assert B(-3, -2)**oo is zoo + assert B(-2, -1)**oo is S.NaN + assert B(-2, Rational(-1, 2))**oo is S.NaN + assert B(Rational(-1, 2), S.Half)**oo is S.Zero + assert B(Rational(-1, 2), 1)**oo == B(0, oo) + assert B(Rational(-2, 3), 2)**oo == B(0, oo) + assert B(-1, 1)**oo == B(-oo, oo) + assert B(-1, S.Half)**oo == B(-oo, oo) + assert B(-1, 2)**oo == B(-oo, oo) + assert B(-2, S.Half)**oo == B(-oo, oo) + + assert B(1, 2)**x == Pow(B(1, 2), x, evaluate=False) + + assert B(2, 3)**(-oo) is S.Zero + assert B(0, 2)**(-oo) == B(0, oo) + assert B(-1, 2)**(-oo) == B(-oo, oo) + + assert (tan(x)**sin(2*x)).subs(x, B(0, pi/2)) == \ + Pow(B(-oo, oo), B(0, 1)) + + +def test_AccumBounds_exponent(): + # base is 0 + z = 0**B(a, a + S.Half) + assert z.subs(a, 0) == B(0, 1) + assert z.subs(a, 1) == 0 + p = z.subs(a, -1) + assert p.is_Pow and p.args == (0, B(-1, -S.Half)) + # base > 0 + # when base is 1 the type of bounds does not matter + assert 1**B(a, a + 1) == 1 + # otherwise we need to know if 0 is in the bounds + assert S.Half**B(-2, 2) == B(S(1)/4, 4) + assert 2**B(-2, 2) == B(S(1)/4, 4) + + # +eps may introduce +oo + # if there is a negative integer exponent + assert B(0, 1)**B(S(1)/2, 1) == B(0, 1) + assert B(0, 1)**B(0, 1) == B(0, 1) + + # positive bases have positive bounds + assert B(2, 3)**B(-3, -2) == B(S(1)/27, S(1)/4) + assert B(2, 3)**B(-3, 2) == B(S(1)/27, 9) + + # bounds generating imaginary parts unevaluated + assert unchanged(Pow, B(-1, 1), B(1, 2)) + assert B(0, S(1)/2)**B(1, oo) == B(0, S(1)/2) + assert B(0, 1)**B(1, oo) == B(0, oo) + assert B(0, 2)**B(1, oo) == B(0, oo) + assert B(0, oo)**B(1, oo) == B(0, oo) + assert B(S(1)/2, 1)**B(1, oo) == B(0, oo) + assert B(S(1)/2, 1)**B(-oo, -1) == B(0, oo) + assert B(S(1)/2, 1)**B(-oo, oo) == B(0, oo) + assert B(S(1)/2, 2)**B(1, oo) == B(0, oo) + assert B(S(1)/2, 2)**B(-oo, -1) == B(0, oo) + assert B(S(1)/2, 2)**B(-oo, oo) == B(0, oo) + assert B(S(1)/2, oo)**B(1, oo) == B(0, oo) + assert B(S(1)/2, oo)**B(-oo, -1) == B(0, oo) + assert B(S(1)/2, oo)**B(-oo, oo) == B(0, oo) + assert B(1, 2)**B(1, oo) == B(0, oo) + assert B(1, 2)**B(-oo, -1) == B(0, oo) + assert B(1, 2)**B(-oo, oo) == B(0, oo) + assert B(1, oo)**B(1, oo) == B(0, oo) + assert B(1, oo)**B(-oo, -1) == B(0, oo) + assert B(1, oo)**B(-oo, oo) == B(0, oo) + assert B(2, oo)**B(1, oo) == B(2, oo) + assert B(2, oo)**B(-oo, -1) == B(0, S(1)/2) + assert B(2, oo)**B(-oo, oo) == B(0, oo) + + +def test_comparison_AccumBounds(): + assert (B(1, 3) < 4) == S.true + assert (B(1, 3) < -1) == S.false + assert (B(1, 3) < 2).rel_op == '<' + assert (B(1, 3) <= 2).rel_op == '<=' + + assert (B(1, 3) > 4) == S.false + assert (B(1, 3) > -1) == S.true + assert (B(1, 3) > 2).rel_op == '>' + assert (B(1, 3) >= 2).rel_op == '>=' + + assert (B(1, 3) < B(4, 6)) == S.true + assert (B(1, 3) < B(2, 4)).rel_op == '<' + assert (B(1, 3) < B(-2, 0)) == S.false + + assert (B(1, 3) <= B(4, 6)) == S.true + assert (B(1, 3) <= B(-2, 0)) == S.false + + assert (B(1, 3) > B(4, 6)) == S.false + assert (B(1, 3) > B(-2, 0)) == S.true + + assert (B(1, 3) >= B(4, 6)) == S.false + assert (B(1, 3) >= B(-2, 0)) == S.true + + # issue 13499 + assert (cos(x) > 0).subs(x, oo) == (B(-1, 1) > 0) + + c = Symbol('c') + raises(TypeError, lambda: (B(0, 1) < c)) + raises(TypeError, lambda: (B(0, 1) <= c)) + raises(TypeError, lambda: (B(0, 1) > c)) + raises(TypeError, lambda: (B(0, 1) >= c)) + + +def test_contains_AccumBounds(): + assert (1 in B(1, 2)) == S.true + raises(TypeError, lambda: a in B(1, 2)) + assert 0 in B(-1, 0) + raises(TypeError, lambda: + (cos(1)**2 + sin(1)**2 - 1) in B(-1, 0)) + assert (-oo in B(1, oo)) == S.true + assert (oo in B(-oo, 0)) == S.true + + # issue 13159 + assert Mul(0, B(-1, 1)) == Mul(B(-1, 1), 0) == 0 + import itertools + for perm in itertools.permutations([0, B(-1, 1), x]): + assert Mul(*perm) == 0 + + +def test_intersection_AccumBounds(): + assert B(0, 3).intersection(B(1, 2)) == B(1, 2) + assert B(0, 3).intersection(B(1, 4)) == B(1, 3) + assert B(0, 3).intersection(B(-1, 2)) == B(0, 2) + assert B(0, 3).intersection(B(-1, 4)) == B(0, 3) + assert B(0, 1).intersection(B(2, 3)) == S.EmptySet + raises(TypeError, lambda: B(0, 3).intersection(1)) + + +def test_union_AccumBounds(): + assert B(0, 3).union(B(1, 2)) == B(0, 3) + assert B(0, 3).union(B(1, 4)) == B(0, 4) + assert B(0, 3).union(B(-1, 2)) == B(-1, 3) + assert B(0, 3).union(B(-1, 4)) == B(-1, 4) + raises(TypeError, lambda: B(0, 3).union(1)) diff --git a/shared/package-files/6b/6bf642f871445f15d33e9f8fb485e187c39e6f44b1b30eb7dcfae599cf48768e/arctan_compositeimplicitautograd_dispatch.h b/shared/package-files/6b/6bf642f871445f15d33e9f8fb485e187c39e6f44b1b30eb7dcfae599cf48768e/arctan_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..58d9b00c34891c0eb226df3135e66e0379a06361 --- /dev/null +++ b/shared/package-files/6b/6bf642f871445f15d33e9f8fb485e187c39e6f44b1b30eb7dcfae599cf48768e/arctan_compositeimplicitautograd_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor arctan(const at::Tensor & self); +TORCH_API at::Tensor & arctan_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & arctan_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & arctan_(at::Tensor & self); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/6b/6bf89520280dd74e8888f1f65abd5fdb63563f4612c732f0081251eba80d9838/upsample_nearest1d_compositeimplicitautograd_dispatch.h b/shared/package-files/6b/6bf89520280dd74e8888f1f65abd5fdb63563f4612c732f0081251eba80d9838/upsample_nearest1d_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b1daec7c2f09bc13ab6f3c9013e41a4459345f71 --- /dev/null +++ b/shared/package-files/6b/6bf89520280dd74e8888f1f65abd5fdb63563f4612c732f0081251eba80d9838/upsample_nearest1d_compositeimplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor upsample_nearest1d(const at::Tensor & input, at::OptionalIntArrayRef output_size, c10::optional> scale_factors); +TORCH_API at::Tensor upsample_nearest1d_symint(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, c10::optional> scale_factors); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/6b/6bf950330899f0b81208710b0dd0ab992f0bc4a7e7cf1188096d34f76d8f853b/api.py b/shared/package-files/6b/6bf950330899f0b81208710b0dd0ab992f0bc4a7e7cf1188096d34f76d8f853b/api.py new file mode 100644 index 0000000000000000000000000000000000000000..ef3d49e48af53a8d2a0a8daa6700c4949a71d3ca --- /dev/null +++ b/shared/package-files/6b/6bf950330899f0b81208710b0dd0ab992f0bc4a7e7cf1188096d34f76d8f853b/api.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 + +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import json +from dataclasses import asdict, dataclass, field +from enum import Enum +from typing import Dict, Optional, Union + + +EventMetadataValue = Union[str, int, float, bool, None] + + +class EventSource(str, Enum): + """ + Known identifiers of the event producers. + """ + + AGENT = "AGENT" + WORKER = "WORKER" + + +@dataclass +class Event: + """ + The class represents the generic event that occurs during the torchelastic + job execution. The event can be any kind of meaningful action. + + Args: + name: event name. + source: the event producer, e.g. agent or worker + timestamp: timestamp in milliseconds when event occured. + metadata: additional data that is associated with the event. + """ + + name: str + source: EventSource + timestamp: int = 0 + metadata: Dict[str, EventMetadataValue] = field(default_factory=dict) + + def __str__(self): + return self.serialize() + + @staticmethod + def deserialize(data: Union[str, "Event"]) -> "Event": + if isinstance(data, Event): + return data + if isinstance(data, str): + data_dict = json.loads(data) + data_dict["source"] = EventSource[data_dict["source"]] + return Event(**data_dict) + + def serialize(self) -> str: + return json.dumps(asdict(self)) + + +@dataclass +class TsmEvent: + """ + The class represents the event produced by tsm api calls. + + Arguments: + session: Session id that was used to execute request. + scheduler: Scheduler that is used to execute request + api: Api name + unix_user: Unix user that executes request + source_hostname: Hostname of server that executes request + app_id: Unique id that is set by the underlying scheduler + runcfg: Run config that was used to schedule app. + """ + + session: str + scheduler: str + api: str + unix_user: str + source_hostname: str + app_id: Optional[str] = None + runcfg: Optional[str] = None + raw_exception: Optional[str] = None + + def __str__(self): + return self.serialize() + + @staticmethod + def deserialize(data: Union[str, "TsmEvent"]) -> "TsmEvent": + if isinstance(data, TsmEvent): + return data + if isinstance(data, str): + data_dict = json.loads(data) + + return TsmEvent(**data_dict) + + def serialize(self) -> str: + return json.dumps(asdict(self)) diff --git a/shared/package-files/6b/6bfe238c93ef44a7bc5b9f1f7c517a5fd8dc738233960dd18980eceb0f4a7ff1/xlogy_cpu_dispatch.h b/shared/package-files/6b/6bfe238c93ef44a7bc5b9f1f7c517a5fd8dc738233960dd18980eceb0f4a7ff1/xlogy_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9010f9c905d49bf2d3438b5968b1a0db8b7db231 --- /dev/null +++ b/shared/package-files/6b/6bfe238c93ef44a7bc5b9f1f7c517a5fd8dc738233960dd18980eceb0f4a7ff1/xlogy_cpu_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor xlogy(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & xlogy_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & xlogy_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor & xlogy_(at::Tensor & self, const at::Tensor & other); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/71/71014242986b9b59e54ea270600ae20089af55bf164840cc94d0bdfd9ef6c665/hp+printer b/shared/package-files/71/71014242986b9b59e54ea270600ae20089af55bf164840cc94d0bdfd9ef6c665/hp+printer new file mode 100644 index 0000000000000000000000000000000000000000..29ef6e6fe27662ad38269003f59d11700d41de28 Binary files /dev/null and b/shared/package-files/71/71014242986b9b59e54ea270600ae20089af55bf164840cc94d0bdfd9ef6c665/hp+printer differ diff --git a/shared/package-files/71/710391b80f29474bf0dd9c187de1a459a4f5b4f53aea7310db144a4f54f561be/Danmarkshavn b/shared/package-files/71/710391b80f29474bf0dd9c187de1a459a4f5b4f53aea7310db144a4f54f561be/Danmarkshavn new file mode 100644 index 0000000000000000000000000000000000000000..8718efcce25cd28ff9fa0f48bba0a2a7e6be4ed0 Binary files /dev/null and b/shared/package-files/71/710391b80f29474bf0dd9c187de1a459a4f5b4f53aea7310db144a4f54f561be/Danmarkshavn differ diff --git a/shared/package-files/71/7104e6af62c53f029013fb0641a81e31c98589c8f27b5ea6289b25b092c74321/Times-Bold.afm b/shared/package-files/71/7104e6af62c53f029013fb0641a81e31c98589c8f27b5ea6289b25b092c74321/Times-Bold.afm new file mode 100644 index 0000000000000000000000000000000000000000..559ebaeb6f099c547502c0e5186df745e36774a7 --- /dev/null +++ b/shared/package-files/71/7104e6af62c53f029013fb0641a81e31c98589c8f27b5ea6289b25b092c74321/Times-Bold.afm @@ -0,0 +1,2588 @@ +StartFontMetrics 4.1 +Comment Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. +Comment Creation Date: Thu May 1 12:52:56 1997 +Comment UniqueID 43065 +Comment VMusage 41636 52661 +FontName Times-Bold +FullName Times Bold +FamilyName Times +Weight Bold +ItalicAngle 0 +IsFixedPitch false +CharacterSet ExtendedRoman +FontBBox -168 -218 1000 935 +UnderlinePosition -100 +UnderlineThickness 50 +Version 002.000 +Notice Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries. +EncodingScheme AdobeStandardEncoding +CapHeight 676 +XHeight 461 +Ascender 683 +Descender -217 +StdHW 44 +StdVW 139 +StartCharMetrics 315 +C 32 ; WX 250 ; N space ; B 0 0 0 0 ; +C 33 ; WX 333 ; N exclam ; B 81 -13 251 691 ; +C 34 ; WX 555 ; N quotedbl ; B 83 404 472 691 ; +C 35 ; WX 500 ; N numbersign ; B 4 0 496 700 ; +C 36 ; WX 500 ; N dollar ; B 29 -99 472 750 ; +C 37 ; WX 1000 ; N percent ; B 124 -14 877 692 ; +C 38 ; WX 833 ; N ampersand ; B 62 -16 787 691 ; +C 39 ; WX 333 ; N quoteright ; B 79 356 263 691 ; +C 40 ; WX 333 ; N parenleft ; B 46 -168 306 694 ; +C 41 ; WX 333 ; N parenright ; B 27 -168 287 694 ; +C 42 ; WX 500 ; N asterisk ; B 56 255 447 691 ; +C 43 ; WX 570 ; N plus ; B 33 0 537 506 ; +C 44 ; WX 250 ; N comma ; B 39 -180 223 155 ; +C 45 ; WX 333 ; N hyphen ; B 44 171 287 287 ; +C 46 ; WX 250 ; N period ; B 41 -13 210 156 ; +C 47 ; WX 278 ; N slash ; B -24 -19 302 691 ; +C 48 ; WX 500 ; N zero ; B 24 -13 476 688 ; +C 49 ; WX 500 ; N one ; B 65 0 442 688 ; +C 50 ; WX 500 ; N two ; B 17 0 478 688 ; +C 51 ; WX 500 ; N three ; B 16 -14 468 688 ; +C 52 ; WX 500 ; N four ; B 19 0 475 688 ; +C 53 ; WX 500 ; N five ; B 22 -8 470 676 ; +C 54 ; WX 500 ; N six ; B 28 -13 475 688 ; +C 55 ; WX 500 ; N seven ; B 17 0 477 676 ; +C 56 ; WX 500 ; N eight ; B 28 -13 472 688 ; +C 57 ; WX 500 ; N nine ; B 26 -13 473 688 ; +C 58 ; WX 333 ; N colon ; B 82 -13 251 472 ; +C 59 ; WX 333 ; N semicolon ; B 82 -180 266 472 ; +C 60 ; WX 570 ; N less ; B 31 -8 539 514 ; +C 61 ; WX 570 ; N equal ; B 33 107 537 399 ; +C 62 ; WX 570 ; N greater ; B 31 -8 539 514 ; +C 63 ; WX 500 ; N question ; B 57 -13 445 689 ; +C 64 ; WX 930 ; N at ; B 108 -19 822 691 ; +C 65 ; WX 722 ; N A ; B 9 0 689 690 ; +C 66 ; WX 667 ; N B ; B 16 0 619 676 ; +C 67 ; WX 722 ; N C ; B 49 -19 687 691 ; +C 68 ; WX 722 ; N D ; B 14 0 690 676 ; +C 69 ; WX 667 ; N E ; B 16 0 641 676 ; +C 70 ; WX 611 ; N F ; B 16 0 583 676 ; +C 71 ; WX 778 ; N G ; B 37 -19 755 691 ; +C 72 ; WX 778 ; N H ; B 21 0 759 676 ; +C 73 ; WX 389 ; N I ; B 20 0 370 676 ; +C 74 ; WX 500 ; N J ; B 3 -96 479 676 ; +C 75 ; WX 778 ; N K ; B 30 0 769 676 ; +C 76 ; WX 667 ; N L ; B 19 0 638 676 ; +C 77 ; WX 944 ; N M ; B 14 0 921 676 ; +C 78 ; WX 722 ; N N ; B 16 -18 701 676 ; +C 79 ; WX 778 ; N O ; B 35 -19 743 691 ; +C 80 ; WX 611 ; N P ; B 16 0 600 676 ; +C 81 ; WX 778 ; N Q ; B 35 -176 743 691 ; +C 82 ; WX 722 ; N R ; B 26 0 715 676 ; +C 83 ; WX 556 ; N S ; B 35 -19 513 692 ; +C 84 ; WX 667 ; N T ; B 31 0 636 676 ; +C 85 ; WX 722 ; N U ; B 16 -19 701 676 ; +C 86 ; WX 722 ; N V ; B 16 -18 701 676 ; +C 87 ; WX 1000 ; N W ; B 19 -15 981 676 ; +C 88 ; WX 722 ; N X ; B 16 0 699 676 ; +C 89 ; WX 722 ; N Y ; B 15 0 699 676 ; +C 90 ; WX 667 ; N Z ; B 28 0 634 676 ; +C 91 ; WX 333 ; N bracketleft ; B 67 -149 301 678 ; +C 92 ; WX 278 ; N backslash ; B -25 -19 303 691 ; +C 93 ; WX 333 ; N bracketright ; B 32 -149 266 678 ; +C 94 ; WX 581 ; N asciicircum ; B 73 311 509 676 ; +C 95 ; WX 500 ; N underscore ; B 0 -125 500 -75 ; +C 96 ; WX 333 ; N quoteleft ; B 70 356 254 691 ; +C 97 ; WX 500 ; N a ; B 25 -14 488 473 ; +C 98 ; WX 556 ; N b ; B 17 -14 521 676 ; +C 99 ; WX 444 ; N c ; B 25 -14 430 473 ; +C 100 ; WX 556 ; N d ; B 25 -14 534 676 ; +C 101 ; WX 444 ; N e ; B 25 -14 426 473 ; +C 102 ; WX 333 ; N f ; B 14 0 389 691 ; L i fi ; L l fl ; +C 103 ; WX 500 ; N g ; B 28 -206 483 473 ; +C 104 ; WX 556 ; N h ; B 16 0 534 676 ; +C 105 ; WX 278 ; N i ; B 16 0 255 691 ; +C 106 ; WX 333 ; N j ; B -57 -203 263 691 ; +C 107 ; WX 556 ; N k ; B 22 0 543 676 ; +C 108 ; WX 278 ; N l ; B 16 0 255 676 ; +C 109 ; WX 833 ; N m ; B 16 0 814 473 ; +C 110 ; WX 556 ; N n ; B 21 0 539 473 ; +C 111 ; WX 500 ; N o ; B 25 -14 476 473 ; +C 112 ; WX 556 ; N p ; B 19 -205 524 473 ; +C 113 ; WX 556 ; N q ; B 34 -205 536 473 ; +C 114 ; WX 444 ; N r ; B 29 0 434 473 ; +C 115 ; WX 389 ; N s ; B 25 -14 361 473 ; +C 116 ; WX 333 ; N t ; B 20 -12 332 630 ; +C 117 ; WX 556 ; N u ; B 16 -14 537 461 ; +C 118 ; WX 500 ; N v ; B 21 -14 485 461 ; +C 119 ; WX 722 ; N w ; B 23 -14 707 461 ; +C 120 ; WX 500 ; N x ; B 12 0 484 461 ; +C 121 ; WX 500 ; N y ; B 16 -205 480 461 ; +C 122 ; WX 444 ; N z ; B 21 0 420 461 ; +C 123 ; WX 394 ; N braceleft ; B 22 -175 340 698 ; +C 124 ; WX 220 ; N bar ; B 66 -218 154 782 ; +C 125 ; WX 394 ; N braceright ; B 54 -175 372 698 ; +C 126 ; WX 520 ; N asciitilde ; B 29 173 491 333 ; +C 161 ; WX 333 ; N exclamdown ; B 82 -203 252 501 ; +C 162 ; WX 500 ; N cent ; B 53 -140 458 588 ; +C 163 ; WX 500 ; N sterling ; B 21 -14 477 684 ; +C 164 ; WX 167 ; N fraction ; B -168 -12 329 688 ; +C 165 ; WX 500 ; N yen ; B -64 0 547 676 ; +C 166 ; WX 500 ; N florin ; B 0 -155 498 706 ; +C 167 ; WX 500 ; N section ; B 57 -132 443 691 ; +C 168 ; WX 500 ; N currency ; B -26 61 526 613 ; +C 169 ; WX 278 ; N quotesingle ; B 75 404 204 691 ; +C 170 ; WX 500 ; N quotedblleft ; B 32 356 486 691 ; +C 171 ; WX 500 ; N guillemotleft ; B 23 36 473 415 ; +C 172 ; WX 333 ; N guilsinglleft ; B 51 36 305 415 ; +C 173 ; WX 333 ; N guilsinglright ; B 28 36 282 415 ; +C 174 ; WX 556 ; N fi ; B 14 0 536 691 ; +C 175 ; WX 556 ; N fl ; B 14 0 536 691 ; +C 177 ; WX 500 ; N endash ; B 0 181 500 271 ; +C 178 ; WX 500 ; N dagger ; B 47 -134 453 691 ; +C 179 ; WX 500 ; N daggerdbl ; B 45 -132 456 691 ; +C 180 ; WX 250 ; N periodcentered ; B 41 248 210 417 ; +C 182 ; WX 540 ; N paragraph ; B 0 -186 519 676 ; +C 183 ; WX 350 ; N bullet ; B 35 198 315 478 ; +C 184 ; WX 333 ; N quotesinglbase ; B 79 -180 263 155 ; +C 185 ; WX 500 ; N quotedblbase ; B 14 -180 468 155 ; +C 186 ; WX 500 ; N quotedblright ; B 14 356 468 691 ; +C 187 ; WX 500 ; N guillemotright ; B 27 36 477 415 ; +C 188 ; WX 1000 ; N ellipsis ; B 82 -13 917 156 ; +C 189 ; WX 1000 ; N perthousand ; B 7 -29 995 706 ; +C 191 ; WX 500 ; N questiondown ; B 55 -201 443 501 ; +C 193 ; WX 333 ; N grave ; B 8 528 246 713 ; +C 194 ; WX 333 ; N acute ; B 86 528 324 713 ; +C 195 ; WX 333 ; N circumflex ; B -2 528 335 704 ; +C 196 ; WX 333 ; N tilde ; B -16 547 349 674 ; +C 197 ; WX 333 ; N macron ; B 1 565 331 637 ; +C 198 ; WX 333 ; N breve ; B 15 528 318 691 ; +C 199 ; WX 333 ; N dotaccent ; B 103 536 258 691 ; +C 200 ; WX 333 ; N dieresis ; B -2 537 335 667 ; +C 202 ; WX 333 ; N ring ; B 60 527 273 740 ; +C 203 ; WX 333 ; N cedilla ; B 68 -218 294 0 ; +C 205 ; WX 333 ; N hungarumlaut ; B -13 528 425 713 ; +C 206 ; WX 333 ; N ogonek ; B 90 -193 319 24 ; +C 207 ; WX 333 ; N caron ; B -2 528 335 704 ; +C 208 ; WX 1000 ; N emdash ; B 0 181 1000 271 ; +C 225 ; WX 1000 ; N AE ; B 4 0 951 676 ; +C 227 ; WX 300 ; N ordfeminine ; B -1 397 301 688 ; +C 232 ; WX 667 ; N Lslash ; B 19 0 638 676 ; +C 233 ; WX 778 ; N Oslash ; B 35 -74 743 737 ; +C 234 ; WX 1000 ; N OE ; B 22 -5 981 684 ; +C 235 ; WX 330 ; N ordmasculine ; B 18 397 312 688 ; +C 241 ; WX 722 ; N ae ; B 33 -14 693 473 ; +C 245 ; WX 278 ; N dotlessi ; B 16 0 255 461 ; +C 248 ; WX 278 ; N lslash ; B -22 0 303 676 ; +C 249 ; WX 500 ; N oslash ; B 25 -92 476 549 ; +C 250 ; WX 722 ; N oe ; B 22 -14 696 473 ; +C 251 ; WX 556 ; N germandbls ; B 19 -12 517 691 ; +C -1 ; WX 389 ; N Idieresis ; B 20 0 370 877 ; +C -1 ; WX 444 ; N eacute ; B 25 -14 426 713 ; +C -1 ; WX 500 ; N abreve ; B 25 -14 488 691 ; +C -1 ; WX 556 ; N uhungarumlaut ; B 16 -14 557 713 ; +C -1 ; WX 444 ; N ecaron ; B 25 -14 426 704 ; +C -1 ; WX 722 ; N Ydieresis ; B 15 0 699 877 ; +C -1 ; WX 570 ; N divide ; B 33 -31 537 537 ; +C -1 ; WX 722 ; N Yacute ; B 15 0 699 923 ; +C -1 ; WX 722 ; N Acircumflex ; B 9 0 689 914 ; +C -1 ; WX 500 ; N aacute ; B 25 -14 488 713 ; +C -1 ; WX 722 ; N Ucircumflex ; B 16 -19 701 914 ; +C -1 ; WX 500 ; N yacute ; B 16 -205 480 713 ; +C -1 ; WX 389 ; N scommaaccent ; B 25 -218 361 473 ; +C -1 ; WX 444 ; N ecircumflex ; B 25 -14 426 704 ; +C -1 ; WX 722 ; N Uring ; B 16 -19 701 935 ; +C -1 ; WX 722 ; N Udieresis ; B 16 -19 701 877 ; +C -1 ; WX 500 ; N aogonek ; B 25 -193 504 473 ; +C -1 ; WX 722 ; N Uacute ; B 16 -19 701 923 ; +C -1 ; WX 556 ; N uogonek ; B 16 -193 539 461 ; +C -1 ; WX 667 ; N Edieresis ; B 16 0 641 877 ; +C -1 ; WX 722 ; N Dcroat ; B 6 0 690 676 ; +C -1 ; WX 250 ; N commaaccent ; B 47 -218 203 -50 ; +C -1 ; WX 747 ; N copyright ; B 26 -19 721 691 ; +C -1 ; WX 667 ; N Emacron ; B 16 0 641 847 ; +C -1 ; WX 444 ; N ccaron ; B 25 -14 430 704 ; +C -1 ; WX 500 ; N aring ; B 25 -14 488 740 ; +C -1 ; WX 722 ; N Ncommaaccent ; B 16 -188 701 676 ; +C -1 ; WX 278 ; N lacute ; B 16 0 297 923 ; +C -1 ; WX 500 ; N agrave ; B 25 -14 488 713 ; +C -1 ; WX 667 ; N Tcommaaccent ; B 31 -218 636 676 ; +C -1 ; WX 722 ; N Cacute ; B 49 -19 687 923 ; +C -1 ; WX 500 ; N atilde ; B 25 -14 488 674 ; +C -1 ; WX 667 ; N Edotaccent ; B 16 0 641 901 ; +C -1 ; WX 389 ; N scaron ; B 25 -14 363 704 ; +C -1 ; WX 389 ; N scedilla ; B 25 -218 361 473 ; +C -1 ; WX 278 ; N iacute ; B 16 0 289 713 ; +C -1 ; WX 494 ; N lozenge ; B 10 0 484 745 ; +C -1 ; WX 722 ; N Rcaron ; B 26 0 715 914 ; +C -1 ; WX 778 ; N Gcommaaccent ; B 37 -218 755 691 ; +C -1 ; WX 556 ; N ucircumflex ; B 16 -14 537 704 ; +C -1 ; WX 500 ; N acircumflex ; B 25 -14 488 704 ; +C -1 ; WX 722 ; N Amacron ; B 9 0 689 847 ; +C -1 ; WX 444 ; N rcaron ; B 29 0 434 704 ; +C -1 ; WX 444 ; N ccedilla ; B 25 -218 430 473 ; +C -1 ; WX 667 ; N Zdotaccent ; B 28 0 634 901 ; +C -1 ; WX 611 ; N Thorn ; B 16 0 600 676 ; +C -1 ; WX 778 ; N Omacron ; B 35 -19 743 847 ; +C -1 ; WX 722 ; N Racute ; B 26 0 715 923 ; +C -1 ; WX 556 ; N Sacute ; B 35 -19 513 923 ; +C -1 ; WX 672 ; N dcaron ; B 25 -14 681 682 ; +C -1 ; WX 722 ; N Umacron ; B 16 -19 701 847 ; +C -1 ; WX 556 ; N uring ; B 16 -14 537 740 ; +C -1 ; WX 300 ; N threesuperior ; B 3 268 297 688 ; +C -1 ; WX 778 ; N Ograve ; B 35 -19 743 923 ; +C -1 ; WX 722 ; N Agrave ; B 9 0 689 923 ; +C -1 ; WX 722 ; N Abreve ; B 9 0 689 901 ; +C -1 ; WX 570 ; N multiply ; B 48 16 522 490 ; +C -1 ; WX 556 ; N uacute ; B 16 -14 537 713 ; +C -1 ; WX 667 ; N Tcaron ; B 31 0 636 914 ; +C -1 ; WX 494 ; N partialdiff ; B 11 -21 494 750 ; +C -1 ; WX 500 ; N ydieresis ; B 16 -205 480 667 ; +C -1 ; WX 722 ; N Nacute ; B 16 -18 701 923 ; +C -1 ; WX 278 ; N icircumflex ; B -37 0 300 704 ; +C -1 ; WX 667 ; N Ecircumflex ; B 16 0 641 914 ; +C -1 ; WX 500 ; N adieresis ; B 25 -14 488 667 ; +C -1 ; WX 444 ; N edieresis ; B 25 -14 426 667 ; +C -1 ; WX 444 ; N cacute ; B 25 -14 430 713 ; +C -1 ; WX 556 ; N nacute ; B 21 0 539 713 ; +C -1 ; WX 556 ; N umacron ; B 16 -14 537 637 ; +C -1 ; WX 722 ; N Ncaron ; B 16 -18 701 914 ; +C -1 ; WX 389 ; N Iacute ; B 20 0 370 923 ; +C -1 ; WX 570 ; N plusminus ; B 33 0 537 506 ; +C -1 ; WX 220 ; N brokenbar ; B 66 -143 154 707 ; +C -1 ; WX 747 ; N registered ; B 26 -19 721 691 ; +C -1 ; WX 778 ; N Gbreve ; B 37 -19 755 901 ; +C -1 ; WX 389 ; N Idotaccent ; B 20 0 370 901 ; +C -1 ; WX 600 ; N summation ; B 14 -10 585 706 ; +C -1 ; WX 667 ; N Egrave ; B 16 0 641 923 ; +C -1 ; WX 444 ; N racute ; B 29 0 434 713 ; +C -1 ; WX 500 ; N omacron ; B 25 -14 476 637 ; +C -1 ; WX 667 ; N Zacute ; B 28 0 634 923 ; +C -1 ; WX 667 ; N Zcaron ; B 28 0 634 914 ; +C -1 ; WX 549 ; N greaterequal ; B 26 0 523 704 ; +C -1 ; WX 722 ; N Eth ; B 6 0 690 676 ; +C -1 ; WX 722 ; N Ccedilla ; B 49 -218 687 691 ; +C -1 ; WX 278 ; N lcommaaccent ; B 16 -218 255 676 ; +C -1 ; WX 416 ; N tcaron ; B 20 -12 425 815 ; +C -1 ; WX 444 ; N eogonek ; B 25 -193 426 473 ; +C -1 ; WX 722 ; N Uogonek ; B 16 -193 701 676 ; +C -1 ; WX 722 ; N Aacute ; B 9 0 689 923 ; +C -1 ; WX 722 ; N Adieresis ; B 9 0 689 877 ; +C -1 ; WX 444 ; N egrave ; B 25 -14 426 713 ; +C -1 ; WX 444 ; N zacute ; B 21 0 420 713 ; +C -1 ; WX 278 ; N iogonek ; B 16 -193 274 691 ; +C -1 ; WX 778 ; N Oacute ; B 35 -19 743 923 ; +C -1 ; WX 500 ; N oacute ; B 25 -14 476 713 ; +C -1 ; WX 500 ; N amacron ; B 25 -14 488 637 ; +C -1 ; WX 389 ; N sacute ; B 25 -14 361 713 ; +C -1 ; WX 278 ; N idieresis ; B -37 0 300 667 ; +C -1 ; WX 778 ; N Ocircumflex ; B 35 -19 743 914 ; +C -1 ; WX 722 ; N Ugrave ; B 16 -19 701 923 ; +C -1 ; WX 612 ; N Delta ; B 6 0 608 688 ; +C -1 ; WX 556 ; N thorn ; B 19 -205 524 676 ; +C -1 ; WX 300 ; N twosuperior ; B 0 275 300 688 ; +C -1 ; WX 778 ; N Odieresis ; B 35 -19 743 877 ; +C -1 ; WX 556 ; N mu ; B 33 -206 536 461 ; +C -1 ; WX 278 ; N igrave ; B -27 0 255 713 ; +C -1 ; WX 500 ; N ohungarumlaut ; B 25 -14 529 713 ; +C -1 ; WX 667 ; N Eogonek ; B 16 -193 644 676 ; +C -1 ; WX 556 ; N dcroat ; B 25 -14 534 676 ; +C -1 ; WX 750 ; N threequarters ; B 23 -12 733 688 ; +C -1 ; WX 556 ; N Scedilla ; B 35 -218 513 692 ; +C -1 ; WX 394 ; N lcaron ; B 16 0 412 682 ; +C -1 ; WX 778 ; N Kcommaaccent ; B 30 -218 769 676 ; +C -1 ; WX 667 ; N Lacute ; B 19 0 638 923 ; +C -1 ; WX 1000 ; N trademark ; B 24 271 977 676 ; +C -1 ; WX 444 ; N edotaccent ; B 25 -14 426 691 ; +C -1 ; WX 389 ; N Igrave ; B 20 0 370 923 ; +C -1 ; WX 389 ; N Imacron ; B 20 0 370 847 ; +C -1 ; WX 667 ; N Lcaron ; B 19 0 652 682 ; +C -1 ; WX 750 ; N onehalf ; B -7 -12 775 688 ; +C -1 ; WX 549 ; N lessequal ; B 29 0 526 704 ; +C -1 ; WX 500 ; N ocircumflex ; B 25 -14 476 704 ; +C -1 ; WX 556 ; N ntilde ; B 21 0 539 674 ; +C -1 ; WX 722 ; N Uhungarumlaut ; B 16 -19 701 923 ; +C -1 ; WX 667 ; N Eacute ; B 16 0 641 923 ; +C -1 ; WX 444 ; N emacron ; B 25 -14 426 637 ; +C -1 ; WX 500 ; N gbreve ; B 28 -206 483 691 ; +C -1 ; WX 750 ; N onequarter ; B 28 -12 743 688 ; +C -1 ; WX 556 ; N Scaron ; B 35 -19 513 914 ; +C -1 ; WX 556 ; N Scommaaccent ; B 35 -218 513 692 ; +C -1 ; WX 778 ; N Ohungarumlaut ; B 35 -19 743 923 ; +C -1 ; WX 400 ; N degree ; B 57 402 343 688 ; +C -1 ; WX 500 ; N ograve ; B 25 -14 476 713 ; +C -1 ; WX 722 ; N Ccaron ; B 49 -19 687 914 ; +C -1 ; WX 556 ; N ugrave ; B 16 -14 537 713 ; +C -1 ; WX 549 ; N radical ; B 10 -46 512 850 ; +C -1 ; WX 722 ; N Dcaron ; B 14 0 690 914 ; +C -1 ; WX 444 ; N rcommaaccent ; B 29 -218 434 473 ; +C -1 ; WX 722 ; N Ntilde ; B 16 -18 701 884 ; +C -1 ; WX 500 ; N otilde ; B 25 -14 476 674 ; +C -1 ; WX 722 ; N Rcommaaccent ; B 26 -218 715 676 ; +C -1 ; WX 667 ; N Lcommaaccent ; B 19 -218 638 676 ; +C -1 ; WX 722 ; N Atilde ; B 9 0 689 884 ; +C -1 ; WX 722 ; N Aogonek ; B 9 -193 699 690 ; +C -1 ; WX 722 ; N Aring ; B 9 0 689 935 ; +C -1 ; WX 778 ; N Otilde ; B 35 -19 743 884 ; +C -1 ; WX 444 ; N zdotaccent ; B 21 0 420 691 ; +C -1 ; WX 667 ; N Ecaron ; B 16 0 641 914 ; +C -1 ; WX 389 ; N Iogonek ; B 20 -193 370 676 ; +C -1 ; WX 556 ; N kcommaaccent ; B 22 -218 543 676 ; +C -1 ; WX 570 ; N minus ; B 33 209 537 297 ; +C -1 ; WX 389 ; N Icircumflex ; B 20 0 370 914 ; +C -1 ; WX 556 ; N ncaron ; B 21 0 539 704 ; +C -1 ; WX 333 ; N tcommaaccent ; B 20 -218 332 630 ; +C -1 ; WX 570 ; N logicalnot ; B 33 108 537 399 ; +C -1 ; WX 500 ; N odieresis ; B 25 -14 476 667 ; +C -1 ; WX 556 ; N udieresis ; B 16 -14 537 667 ; +C -1 ; WX 549 ; N notequal ; B 15 -49 540 570 ; +C -1 ; WX 500 ; N gcommaaccent ; B 28 -206 483 829 ; +C -1 ; WX 500 ; N eth ; B 25 -14 476 691 ; +C -1 ; WX 444 ; N zcaron ; B 21 0 420 704 ; +C -1 ; WX 556 ; N ncommaaccent ; B 21 -218 539 473 ; +C -1 ; WX 300 ; N onesuperior ; B 28 275 273 688 ; +C -1 ; WX 278 ; N imacron ; B -8 0 272 637 ; +C -1 ; WX 500 ; N Euro ; B 0 0 0 0 ; +EndCharMetrics +StartKernData +StartKernPairs 2242 +KPX A C -55 +KPX A Cacute -55 +KPX A Ccaron -55 +KPX A Ccedilla -55 +KPX A G -55 +KPX A Gbreve -55 +KPX A Gcommaaccent -55 +KPX A O -45 +KPX A Oacute -45 +KPX A Ocircumflex -45 +KPX A Odieresis -45 +KPX A Ograve -45 +KPX A Ohungarumlaut -45 +KPX A Omacron -45 +KPX A Oslash -45 +KPX A Otilde -45 +KPX A Q -45 +KPX A T -95 +KPX A Tcaron -95 +KPX A Tcommaaccent -95 +KPX A U -50 +KPX A Uacute -50 +KPX A Ucircumflex -50 +KPX A Udieresis -50 +KPX A Ugrave -50 +KPX A Uhungarumlaut -50 +KPX A Umacron -50 +KPX A Uogonek -50 +KPX A Uring -50 +KPX A V -145 +KPX A W -130 +KPX A Y -100 +KPX A Yacute -100 +KPX A Ydieresis -100 +KPX A p -25 +KPX A quoteright -74 +KPX A u -50 +KPX A uacute -50 +KPX A ucircumflex -50 +KPX A udieresis -50 +KPX A ugrave -50 +KPX A uhungarumlaut -50 +KPX A umacron -50 +KPX A uogonek -50 +KPX A uring -50 +KPX A v -100 +KPX A w -90 +KPX A y -74 +KPX A yacute -74 +KPX A ydieresis -74 +KPX Aacute C -55 +KPX Aacute Cacute -55 +KPX Aacute Ccaron -55 +KPX Aacute Ccedilla -55 +KPX Aacute G -55 +KPX Aacute Gbreve -55 +KPX Aacute Gcommaaccent -55 +KPX Aacute O -45 +KPX Aacute Oacute -45 +KPX Aacute Ocircumflex -45 +KPX Aacute Odieresis -45 +KPX Aacute Ograve -45 +KPX Aacute Ohungarumlaut -45 +KPX Aacute Omacron -45 +KPX Aacute Oslash -45 +KPX Aacute Otilde -45 +KPX Aacute Q -45 +KPX Aacute T -95 +KPX Aacute Tcaron -95 +KPX Aacute Tcommaaccent -95 +KPX Aacute U -50 +KPX Aacute Uacute -50 +KPX Aacute Ucircumflex -50 +KPX Aacute Udieresis -50 +KPX Aacute Ugrave -50 +KPX Aacute Uhungarumlaut -50 +KPX Aacute Umacron -50 +KPX Aacute Uogonek -50 +KPX Aacute Uring -50 +KPX Aacute V -145 +KPX Aacute W -130 +KPX Aacute Y -100 +KPX Aacute Yacute -100 +KPX Aacute Ydieresis -100 +KPX Aacute p -25 +KPX Aacute quoteright -74 +KPX Aacute u -50 +KPX Aacute uacute -50 +KPX Aacute ucircumflex -50 +KPX Aacute udieresis -50 +KPX Aacute ugrave -50 +KPX Aacute uhungarumlaut -50 +KPX Aacute umacron -50 +KPX Aacute uogonek -50 +KPX Aacute uring -50 +KPX Aacute v -100 +KPX Aacute w -90 +KPX Aacute y -74 +KPX Aacute yacute -74 +KPX Aacute ydieresis -74 +KPX Abreve C -55 +KPX Abreve Cacute -55 +KPX Abreve Ccaron -55 +KPX Abreve Ccedilla -55 +KPX Abreve G -55 +KPX Abreve Gbreve -55 +KPX Abreve Gcommaaccent -55 +KPX Abreve O -45 +KPX Abreve Oacute -45 +KPX Abreve Ocircumflex -45 +KPX Abreve Odieresis -45 +KPX Abreve Ograve -45 +KPX Abreve Ohungarumlaut -45 +KPX Abreve Omacron -45 +KPX Abreve Oslash -45 +KPX Abreve Otilde -45 +KPX Abreve Q -45 +KPX Abreve T -95 +KPX Abreve Tcaron -95 +KPX Abreve Tcommaaccent -95 +KPX Abreve U -50 +KPX Abreve Uacute -50 +KPX Abreve Ucircumflex -50 +KPX Abreve Udieresis -50 +KPX Abreve Ugrave -50 +KPX Abreve Uhungarumlaut -50 +KPX Abreve Umacron -50 +KPX Abreve Uogonek -50 +KPX Abreve Uring -50 +KPX Abreve V -145 +KPX Abreve W -130 +KPX Abreve Y -100 +KPX Abreve Yacute -100 +KPX Abreve Ydieresis -100 +KPX Abreve p -25 +KPX Abreve quoteright -74 +KPX Abreve u -50 +KPX Abreve uacute -50 +KPX Abreve ucircumflex -50 +KPX Abreve udieresis -50 +KPX Abreve ugrave -50 +KPX Abreve uhungarumlaut -50 +KPX Abreve umacron -50 +KPX Abreve uogonek -50 +KPX Abreve uring -50 +KPX Abreve v -100 +KPX Abreve w -90 +KPX Abreve y -74 +KPX Abreve yacute -74 +KPX Abreve ydieresis -74 +KPX Acircumflex C -55 +KPX Acircumflex Cacute -55 +KPX Acircumflex Ccaron -55 +KPX Acircumflex Ccedilla -55 +KPX Acircumflex G -55 +KPX Acircumflex Gbreve -55 +KPX Acircumflex Gcommaaccent -55 +KPX Acircumflex O -45 +KPX Acircumflex Oacute -45 +KPX Acircumflex Ocircumflex -45 +KPX Acircumflex Odieresis -45 +KPX Acircumflex Ograve -45 +KPX Acircumflex Ohungarumlaut -45 +KPX Acircumflex Omacron -45 +KPX Acircumflex Oslash -45 +KPX Acircumflex Otilde -45 +KPX Acircumflex Q -45 +KPX Acircumflex T -95 +KPX Acircumflex Tcaron -95 +KPX Acircumflex Tcommaaccent -95 +KPX Acircumflex U -50 +KPX Acircumflex Uacute -50 +KPX Acircumflex Ucircumflex -50 +KPX Acircumflex Udieresis -50 +KPX Acircumflex Ugrave -50 +KPX Acircumflex Uhungarumlaut -50 +KPX Acircumflex Umacron -50 +KPX Acircumflex Uogonek -50 +KPX Acircumflex Uring -50 +KPX Acircumflex V -145 +KPX Acircumflex W -130 +KPX Acircumflex Y -100 +KPX Acircumflex Yacute -100 +KPX Acircumflex Ydieresis -100 +KPX Acircumflex p -25 +KPX Acircumflex quoteright -74 +KPX Acircumflex u -50 +KPX Acircumflex uacute -50 +KPX Acircumflex ucircumflex -50 +KPX Acircumflex udieresis -50 +KPX Acircumflex ugrave -50 +KPX Acircumflex uhungarumlaut -50 +KPX Acircumflex umacron -50 +KPX Acircumflex uogonek -50 +KPX Acircumflex uring -50 +KPX Acircumflex v -100 +KPX Acircumflex w -90 +KPX Acircumflex y -74 +KPX Acircumflex yacute -74 +KPX Acircumflex ydieresis -74 +KPX Adieresis C -55 +KPX Adieresis Cacute -55 +KPX Adieresis Ccaron -55 +KPX Adieresis Ccedilla -55 +KPX Adieresis G -55 +KPX Adieresis Gbreve -55 +KPX Adieresis Gcommaaccent -55 +KPX Adieresis O -45 +KPX Adieresis Oacute -45 +KPX Adieresis Ocircumflex -45 +KPX Adieresis Odieresis -45 +KPX Adieresis Ograve -45 +KPX Adieresis Ohungarumlaut -45 +KPX Adieresis Omacron -45 +KPX Adieresis Oslash -45 +KPX Adieresis Otilde -45 +KPX Adieresis Q -45 +KPX Adieresis T -95 +KPX Adieresis Tcaron -95 +KPX Adieresis Tcommaaccent -95 +KPX Adieresis U -50 +KPX Adieresis Uacute -50 +KPX Adieresis Ucircumflex -50 +KPX Adieresis Udieresis -50 +KPX Adieresis Ugrave -50 +KPX Adieresis Uhungarumlaut -50 +KPX Adieresis Umacron -50 +KPX Adieresis Uogonek -50 +KPX Adieresis Uring -50 +KPX Adieresis V -145 +KPX Adieresis W -130 +KPX Adieresis Y -100 +KPX Adieresis Yacute -100 +KPX Adieresis Ydieresis -100 +KPX Adieresis p -25 +KPX Adieresis quoteright -74 +KPX Adieresis u -50 +KPX Adieresis uacute -50 +KPX Adieresis ucircumflex -50 +KPX Adieresis udieresis -50 +KPX Adieresis ugrave -50 +KPX Adieresis uhungarumlaut -50 +KPX Adieresis umacron -50 +KPX Adieresis uogonek -50 +KPX Adieresis uring -50 +KPX Adieresis v -100 +KPX Adieresis w -90 +KPX Adieresis y -74 +KPX Adieresis yacute -74 +KPX Adieresis ydieresis -74 +KPX Agrave C -55 +KPX Agrave Cacute -55 +KPX Agrave Ccaron -55 +KPX Agrave Ccedilla -55 +KPX Agrave G -55 +KPX Agrave Gbreve -55 +KPX Agrave Gcommaaccent -55 +KPX Agrave O -45 +KPX Agrave Oacute -45 +KPX Agrave Ocircumflex -45 +KPX Agrave Odieresis -45 +KPX Agrave Ograve -45 +KPX Agrave Ohungarumlaut -45 +KPX Agrave Omacron -45 +KPX Agrave Oslash -45 +KPX Agrave Otilde -45 +KPX Agrave Q -45 +KPX Agrave T -95 +KPX Agrave Tcaron -95 +KPX Agrave Tcommaaccent -95 +KPX Agrave U -50 +KPX Agrave Uacute -50 +KPX Agrave Ucircumflex -50 +KPX Agrave Udieresis -50 +KPX Agrave Ugrave -50 +KPX Agrave Uhungarumlaut -50 +KPX Agrave Umacron -50 +KPX Agrave Uogonek -50 +KPX Agrave Uring -50 +KPX Agrave V -145 +KPX Agrave W -130 +KPX Agrave Y -100 +KPX Agrave Yacute -100 +KPX Agrave Ydieresis -100 +KPX Agrave p -25 +KPX Agrave quoteright -74 +KPX Agrave u -50 +KPX Agrave uacute -50 +KPX Agrave ucircumflex -50 +KPX Agrave udieresis -50 +KPX Agrave ugrave -50 +KPX Agrave uhungarumlaut -50 +KPX Agrave umacron -50 +KPX Agrave uogonek -50 +KPX Agrave uring -50 +KPX Agrave v -100 +KPX Agrave w -90 +KPX Agrave y -74 +KPX Agrave yacute -74 +KPX Agrave ydieresis -74 +KPX Amacron C -55 +KPX Amacron Cacute -55 +KPX Amacron Ccaron -55 +KPX Amacron Ccedilla -55 +KPX Amacron G -55 +KPX Amacron Gbreve -55 +KPX Amacron Gcommaaccent -55 +KPX Amacron O -45 +KPX Amacron Oacute -45 +KPX Amacron Ocircumflex -45 +KPX Amacron Odieresis -45 +KPX Amacron Ograve -45 +KPX Amacron Ohungarumlaut -45 +KPX Amacron Omacron -45 +KPX Amacron Oslash -45 +KPX Amacron Otilde -45 +KPX Amacron Q -45 +KPX Amacron T -95 +KPX Amacron Tcaron -95 +KPX Amacron Tcommaaccent -95 +KPX Amacron U -50 +KPX Amacron Uacute -50 +KPX Amacron Ucircumflex -50 +KPX Amacron Udieresis -50 +KPX Amacron Ugrave -50 +KPX Amacron Uhungarumlaut -50 +KPX Amacron Umacron -50 +KPX Amacron Uogonek -50 +KPX Amacron Uring -50 +KPX Amacron V -145 +KPX Amacron W -130 +KPX Amacron Y -100 +KPX Amacron Yacute -100 +KPX Amacron Ydieresis -100 +KPX Amacron p -25 +KPX Amacron quoteright -74 +KPX Amacron u -50 +KPX Amacron uacute -50 +KPX Amacron ucircumflex -50 +KPX Amacron udieresis -50 +KPX Amacron ugrave -50 +KPX Amacron uhungarumlaut -50 +KPX Amacron umacron -50 +KPX Amacron uogonek -50 +KPX Amacron uring -50 +KPX Amacron v -100 +KPX Amacron w -90 +KPX Amacron y -74 +KPX Amacron yacute -74 +KPX Amacron ydieresis -74 +KPX Aogonek C -55 +KPX Aogonek Cacute -55 +KPX Aogonek Ccaron -55 +KPX Aogonek Ccedilla -55 +KPX Aogonek G -55 +KPX Aogonek Gbreve -55 +KPX Aogonek Gcommaaccent -55 +KPX Aogonek O -45 +KPX Aogonek Oacute -45 +KPX Aogonek Ocircumflex -45 +KPX Aogonek Odieresis -45 +KPX Aogonek Ograve -45 +KPX Aogonek Ohungarumlaut -45 +KPX Aogonek Omacron -45 +KPX Aogonek Oslash -45 +KPX Aogonek Otilde -45 +KPX Aogonek Q -45 +KPX Aogonek T -95 +KPX Aogonek Tcaron -95 +KPX Aogonek Tcommaaccent -95 +KPX Aogonek U -50 +KPX Aogonek Uacute -50 +KPX Aogonek Ucircumflex -50 +KPX Aogonek Udieresis -50 +KPX Aogonek Ugrave -50 +KPX Aogonek Uhungarumlaut -50 +KPX Aogonek Umacron -50 +KPX Aogonek Uogonek -50 +KPX Aogonek Uring -50 +KPX Aogonek V -145 +KPX Aogonek W -130 +KPX Aogonek Y -100 +KPX Aogonek Yacute -100 +KPX Aogonek Ydieresis -100 +KPX Aogonek p -25 +KPX Aogonek quoteright -74 +KPX Aogonek u -50 +KPX Aogonek uacute -50 +KPX Aogonek ucircumflex -50 +KPX Aogonek udieresis -50 +KPX Aogonek ugrave -50 +KPX Aogonek uhungarumlaut -50 +KPX Aogonek umacron -50 +KPX Aogonek uogonek -50 +KPX Aogonek uring -50 +KPX Aogonek v -100 +KPX Aogonek w -90 +KPX Aogonek y -34 +KPX Aogonek yacute -34 +KPX Aogonek ydieresis -34 +KPX Aring C -55 +KPX Aring Cacute -55 +KPX Aring Ccaron -55 +KPX Aring Ccedilla -55 +KPX Aring G -55 +KPX Aring Gbreve -55 +KPX Aring Gcommaaccent -55 +KPX Aring O -45 +KPX Aring Oacute -45 +KPX Aring Ocircumflex -45 +KPX Aring Odieresis -45 +KPX Aring Ograve -45 +KPX Aring Ohungarumlaut -45 +KPX Aring Omacron -45 +KPX Aring Oslash -45 +KPX Aring Otilde -45 +KPX Aring Q -45 +KPX Aring T -95 +KPX Aring Tcaron -95 +KPX Aring Tcommaaccent -95 +KPX Aring U -50 +KPX Aring Uacute -50 +KPX Aring Ucircumflex -50 +KPX Aring Udieresis -50 +KPX Aring Ugrave -50 +KPX Aring Uhungarumlaut -50 +KPX Aring Umacron -50 +KPX Aring Uogonek -50 +KPX Aring Uring -50 +KPX Aring V -145 +KPX Aring W -130 +KPX Aring Y -100 +KPX Aring Yacute -100 +KPX Aring Ydieresis -100 +KPX Aring p -25 +KPX Aring quoteright -74 +KPX Aring u -50 +KPX Aring uacute -50 +KPX Aring ucircumflex -50 +KPX Aring udieresis -50 +KPX Aring ugrave -50 +KPX Aring uhungarumlaut -50 +KPX Aring umacron -50 +KPX Aring uogonek -50 +KPX Aring uring -50 +KPX Aring v -100 +KPX Aring w -90 +KPX Aring y -74 +KPX Aring yacute -74 +KPX Aring ydieresis -74 +KPX Atilde C -55 +KPX Atilde Cacute -55 +KPX Atilde Ccaron -55 +KPX Atilde Ccedilla -55 +KPX Atilde G -55 +KPX Atilde Gbreve -55 +KPX Atilde Gcommaaccent -55 +KPX Atilde O -45 +KPX Atilde Oacute -45 +KPX Atilde Ocircumflex -45 +KPX Atilde Odieresis -45 +KPX Atilde Ograve -45 +KPX Atilde Ohungarumlaut -45 +KPX Atilde Omacron -45 +KPX Atilde Oslash -45 +KPX Atilde Otilde -45 +KPX Atilde Q -45 +KPX Atilde T -95 +KPX Atilde Tcaron -95 +KPX Atilde Tcommaaccent -95 +KPX Atilde U -50 +KPX Atilde Uacute -50 +KPX Atilde Ucircumflex -50 +KPX Atilde Udieresis -50 +KPX Atilde Ugrave -50 +KPX Atilde Uhungarumlaut -50 +KPX Atilde Umacron -50 +KPX Atilde Uogonek -50 +KPX Atilde Uring -50 +KPX Atilde V -145 +KPX Atilde W -130 +KPX Atilde Y -100 +KPX Atilde Yacute -100 +KPX Atilde Ydieresis -100 +KPX Atilde p -25 +KPX Atilde quoteright -74 +KPX Atilde u -50 +KPX Atilde uacute -50 +KPX Atilde ucircumflex -50 +KPX Atilde udieresis -50 +KPX Atilde ugrave -50 +KPX Atilde uhungarumlaut -50 +KPX Atilde umacron -50 +KPX Atilde uogonek -50 +KPX Atilde uring -50 +KPX Atilde v -100 +KPX Atilde w -90 +KPX Atilde y -74 +KPX Atilde yacute -74 +KPX Atilde ydieresis -74 +KPX B A -30 +KPX B Aacute -30 +KPX B Abreve -30 +KPX B Acircumflex -30 +KPX B Adieresis -30 +KPX B Agrave -30 +KPX B Amacron -30 +KPX B Aogonek -30 +KPX B Aring -30 +KPX B Atilde -30 +KPX B U -10 +KPX B Uacute -10 +KPX B Ucircumflex -10 +KPX B Udieresis -10 +KPX B Ugrave -10 +KPX B Uhungarumlaut -10 +KPX B Umacron -10 +KPX B Uogonek -10 +KPX B Uring -10 +KPX D A -35 +KPX D Aacute -35 +KPX D Abreve -35 +KPX D Acircumflex -35 +KPX D Adieresis -35 +KPX D Agrave -35 +KPX D Amacron -35 +KPX D Aogonek -35 +KPX D Aring -35 +KPX D Atilde -35 +KPX D V -40 +KPX D W -40 +KPX D Y -40 +KPX D Yacute -40 +KPX D Ydieresis -40 +KPX D period -20 +KPX Dcaron A -35 +KPX Dcaron Aacute -35 +KPX Dcaron Abreve -35 +KPX Dcaron Acircumflex -35 +KPX Dcaron Adieresis -35 +KPX Dcaron Agrave -35 +KPX Dcaron Amacron -35 +KPX Dcaron Aogonek -35 +KPX Dcaron Aring -35 +KPX Dcaron Atilde -35 +KPX Dcaron V -40 +KPX Dcaron W -40 +KPX Dcaron Y -40 +KPX Dcaron Yacute -40 +KPX Dcaron Ydieresis -40 +KPX Dcaron period -20 +KPX Dcroat A -35 +KPX Dcroat Aacute -35 +KPX Dcroat Abreve -35 +KPX Dcroat Acircumflex -35 +KPX Dcroat Adieresis -35 +KPX Dcroat Agrave -35 +KPX Dcroat Amacron -35 +KPX Dcroat Aogonek -35 +KPX Dcroat Aring -35 +KPX Dcroat Atilde -35 +KPX Dcroat V -40 +KPX Dcroat W -40 +KPX Dcroat Y -40 +KPX Dcroat Yacute -40 +KPX Dcroat Ydieresis -40 +KPX Dcroat period -20 +KPX F A -90 +KPX F Aacute -90 +KPX F Abreve -90 +KPX F Acircumflex -90 +KPX F Adieresis -90 +KPX F Agrave -90 +KPX F Amacron -90 +KPX F Aogonek -90 +KPX F Aring -90 +KPX F Atilde -90 +KPX F a -25 +KPX F aacute -25 +KPX F abreve -25 +KPX F acircumflex -25 +KPX F adieresis -25 +KPX F agrave -25 +KPX F amacron -25 +KPX F aogonek -25 +KPX F aring -25 +KPX F atilde -25 +KPX F comma -92 +KPX F e -25 +KPX F eacute -25 +KPX F ecaron -25 +KPX F ecircumflex -25 +KPX F edieresis -25 +KPX F edotaccent -25 +KPX F egrave -25 +KPX F emacron -25 +KPX F eogonek -25 +KPX F o -25 +KPX F oacute -25 +KPX F ocircumflex -25 +KPX F odieresis -25 +KPX F ograve -25 +KPX F ohungarumlaut -25 +KPX F omacron -25 +KPX F oslash -25 +KPX F otilde -25 +KPX F period -110 +KPX J A -30 +KPX J Aacute -30 +KPX J Abreve -30 +KPX J Acircumflex -30 +KPX J Adieresis -30 +KPX J Agrave -30 +KPX J Amacron -30 +KPX J Aogonek -30 +KPX J Aring -30 +KPX J Atilde -30 +KPX J a -15 +KPX J aacute -15 +KPX J abreve -15 +KPX J acircumflex -15 +KPX J adieresis -15 +KPX J agrave -15 +KPX J amacron -15 +KPX J aogonek -15 +KPX J aring -15 +KPX J atilde -15 +KPX J e -15 +KPX J eacute -15 +KPX J ecaron -15 +KPX J ecircumflex -15 +KPX J edieresis -15 +KPX J edotaccent -15 +KPX J egrave -15 +KPX J emacron -15 +KPX J eogonek -15 +KPX J o -15 +KPX J oacute -15 +KPX J ocircumflex -15 +KPX J odieresis -15 +KPX J ograve -15 +KPX J ohungarumlaut -15 +KPX J omacron -15 +KPX J oslash -15 +KPX J otilde -15 +KPX J period -20 +KPX J u -15 +KPX J uacute -15 +KPX J ucircumflex -15 +KPX J udieresis -15 +KPX J ugrave -15 +KPX J uhungarumlaut -15 +KPX J umacron -15 +KPX J uogonek -15 +KPX J uring -15 +KPX K O -30 +KPX K Oacute -30 +KPX K Ocircumflex -30 +KPX K Odieresis -30 +KPX K Ograve -30 +KPX K Ohungarumlaut -30 +KPX K Omacron -30 +KPX K Oslash -30 +KPX K Otilde -30 +KPX K e -25 +KPX K eacute -25 +KPX K ecaron -25 +KPX K ecircumflex -25 +KPX K edieresis -25 +KPX K edotaccent -25 +KPX K egrave -25 +KPX K emacron -25 +KPX K eogonek -25 +KPX K o -25 +KPX K oacute -25 +KPX K ocircumflex -25 +KPX K odieresis -25 +KPX K ograve -25 +KPX K ohungarumlaut -25 +KPX K omacron -25 +KPX K oslash -25 +KPX K otilde -25 +KPX K u -15 +KPX K uacute -15 +KPX K ucircumflex -15 +KPX K udieresis -15 +KPX K ugrave -15 +KPX K uhungarumlaut -15 +KPX K umacron -15 +KPX K uogonek -15 +KPX K uring -15 +KPX K y -45 +KPX K yacute -45 +KPX K ydieresis -45 +KPX Kcommaaccent O -30 +KPX Kcommaaccent Oacute -30 +KPX Kcommaaccent Ocircumflex -30 +KPX Kcommaaccent Odieresis -30 +KPX Kcommaaccent Ograve -30 +KPX Kcommaaccent Ohungarumlaut -30 +KPX Kcommaaccent Omacron -30 +KPX Kcommaaccent Oslash -30 +KPX Kcommaaccent Otilde -30 +KPX Kcommaaccent e -25 +KPX Kcommaaccent eacute -25 +KPX Kcommaaccent ecaron -25 +KPX Kcommaaccent ecircumflex -25 +KPX Kcommaaccent edieresis -25 +KPX Kcommaaccent edotaccent -25 +KPX Kcommaaccent egrave -25 +KPX Kcommaaccent emacron -25 +KPX Kcommaaccent eogonek -25 +KPX Kcommaaccent o -25 +KPX Kcommaaccent oacute -25 +KPX Kcommaaccent ocircumflex -25 +KPX Kcommaaccent odieresis -25 +KPX Kcommaaccent ograve -25 +KPX Kcommaaccent ohungarumlaut -25 +KPX Kcommaaccent omacron -25 +KPX Kcommaaccent oslash -25 +KPX Kcommaaccent otilde -25 +KPX Kcommaaccent u -15 +KPX Kcommaaccent uacute -15 +KPX Kcommaaccent ucircumflex -15 +KPX Kcommaaccent udieresis -15 +KPX Kcommaaccent ugrave -15 +KPX Kcommaaccent uhungarumlaut -15 +KPX Kcommaaccent umacron -15 +KPX Kcommaaccent uogonek -15 +KPX Kcommaaccent uring -15 +KPX Kcommaaccent y -45 +KPX Kcommaaccent yacute -45 +KPX Kcommaaccent ydieresis -45 +KPX L T -92 +KPX L Tcaron -92 +KPX L Tcommaaccent -92 +KPX L V -92 +KPX L W -92 +KPX L Y -92 +KPX L Yacute -92 +KPX L Ydieresis -92 +KPX L quotedblright -20 +KPX L quoteright -110 +KPX L y -55 +KPX L yacute -55 +KPX L ydieresis -55 +KPX Lacute T -92 +KPX Lacute Tcaron -92 +KPX Lacute Tcommaaccent -92 +KPX Lacute V -92 +KPX Lacute W -92 +KPX Lacute Y -92 +KPX Lacute Yacute -92 +KPX Lacute Ydieresis -92 +KPX Lacute quotedblright -20 +KPX Lacute quoteright -110 +KPX Lacute y -55 +KPX Lacute yacute -55 +KPX Lacute ydieresis -55 +KPX Lcommaaccent T -92 +KPX Lcommaaccent Tcaron -92 +KPX Lcommaaccent Tcommaaccent -92 +KPX Lcommaaccent V -92 +KPX Lcommaaccent W -92 +KPX Lcommaaccent Y -92 +KPX Lcommaaccent Yacute -92 +KPX Lcommaaccent Ydieresis -92 +KPX Lcommaaccent quotedblright -20 +KPX Lcommaaccent quoteright -110 +KPX Lcommaaccent y -55 +KPX Lcommaaccent yacute -55 +KPX Lcommaaccent ydieresis -55 +KPX Lslash T -92 +KPX Lslash Tcaron -92 +KPX Lslash Tcommaaccent -92 +KPX Lslash V -92 +KPX Lslash W -92 +KPX Lslash Y -92 +KPX Lslash Yacute -92 +KPX Lslash Ydieresis -92 +KPX Lslash quotedblright -20 +KPX Lslash quoteright -110 +KPX Lslash y -55 +KPX Lslash yacute -55 +KPX Lslash ydieresis -55 +KPX N A -20 +KPX N Aacute -20 +KPX N Abreve -20 +KPX N Acircumflex -20 +KPX N Adieresis -20 +KPX N Agrave -20 +KPX N Amacron -20 +KPX N Aogonek -20 +KPX N Aring -20 +KPX N Atilde -20 +KPX Nacute A -20 +KPX Nacute Aacute -20 +KPX Nacute Abreve -20 +KPX Nacute Acircumflex -20 +KPX Nacute Adieresis -20 +KPX Nacute Agrave -20 +KPX Nacute Amacron -20 +KPX Nacute Aogonek -20 +KPX Nacute Aring -20 +KPX Nacute Atilde -20 +KPX Ncaron A -20 +KPX Ncaron Aacute -20 +KPX Ncaron Abreve -20 +KPX Ncaron Acircumflex -20 +KPX Ncaron Adieresis -20 +KPX Ncaron Agrave -20 +KPX Ncaron Amacron -20 +KPX Ncaron Aogonek -20 +KPX Ncaron Aring -20 +KPX Ncaron Atilde -20 +KPX Ncommaaccent A -20 +KPX Ncommaaccent Aacute -20 +KPX Ncommaaccent Abreve -20 +KPX Ncommaaccent Acircumflex -20 +KPX Ncommaaccent Adieresis -20 +KPX Ncommaaccent Agrave -20 +KPX Ncommaaccent Amacron -20 +KPX Ncommaaccent Aogonek -20 +KPX Ncommaaccent Aring -20 +KPX Ncommaaccent Atilde -20 +KPX Ntilde A -20 +KPX Ntilde Aacute -20 +KPX Ntilde Abreve -20 +KPX Ntilde Acircumflex -20 +KPX Ntilde Adieresis -20 +KPX Ntilde Agrave -20 +KPX Ntilde Amacron -20 +KPX Ntilde Aogonek -20 +KPX Ntilde Aring -20 +KPX Ntilde Atilde -20 +KPX O A -40 +KPX O Aacute -40 +KPX O Abreve -40 +KPX O Acircumflex -40 +KPX O Adieresis -40 +KPX O Agrave -40 +KPX O Amacron -40 +KPX O Aogonek -40 +KPX O Aring -40 +KPX O Atilde -40 +KPX O T -40 +KPX O Tcaron -40 +KPX O Tcommaaccent -40 +KPX O V -50 +KPX O W -50 +KPX O X -40 +KPX O Y -50 +KPX O Yacute -50 +KPX O Ydieresis -50 +KPX Oacute A -40 +KPX Oacute Aacute -40 +KPX Oacute Abreve -40 +KPX Oacute Acircumflex -40 +KPX Oacute Adieresis -40 +KPX Oacute Agrave -40 +KPX Oacute Amacron -40 +KPX Oacute Aogonek -40 +KPX Oacute Aring -40 +KPX Oacute Atilde -40 +KPX Oacute T -40 +KPX Oacute Tcaron -40 +KPX Oacute Tcommaaccent -40 +KPX Oacute V -50 +KPX Oacute W -50 +KPX Oacute X -40 +KPX Oacute Y -50 +KPX Oacute Yacute -50 +KPX Oacute Ydieresis -50 +KPX Ocircumflex A -40 +KPX Ocircumflex Aacute -40 +KPX Ocircumflex Abreve -40 +KPX Ocircumflex Acircumflex -40 +KPX Ocircumflex Adieresis -40 +KPX Ocircumflex Agrave -40 +KPX Ocircumflex Amacron -40 +KPX Ocircumflex Aogonek -40 +KPX Ocircumflex Aring -40 +KPX Ocircumflex Atilde -40 +KPX Ocircumflex T -40 +KPX Ocircumflex Tcaron -40 +KPX Ocircumflex Tcommaaccent -40 +KPX Ocircumflex V -50 +KPX Ocircumflex W -50 +KPX Ocircumflex X -40 +KPX Ocircumflex Y -50 +KPX Ocircumflex Yacute -50 +KPX Ocircumflex Ydieresis -50 +KPX Odieresis A -40 +KPX Odieresis Aacute -40 +KPX Odieresis Abreve -40 +KPX Odieresis Acircumflex -40 +KPX Odieresis Adieresis -40 +KPX Odieresis Agrave -40 +KPX Odieresis Amacron -40 +KPX Odieresis Aogonek -40 +KPX Odieresis Aring -40 +KPX Odieresis Atilde -40 +KPX Odieresis T -40 +KPX Odieresis Tcaron -40 +KPX Odieresis Tcommaaccent -40 +KPX Odieresis V -50 +KPX Odieresis W -50 +KPX Odieresis X -40 +KPX Odieresis Y -50 +KPX Odieresis Yacute -50 +KPX Odieresis Ydieresis -50 +KPX Ograve A -40 +KPX Ograve Aacute -40 +KPX Ograve Abreve -40 +KPX Ograve Acircumflex -40 +KPX Ograve Adieresis -40 +KPX Ograve Agrave -40 +KPX Ograve Amacron -40 +KPX Ograve Aogonek -40 +KPX Ograve Aring -40 +KPX Ograve Atilde -40 +KPX Ograve T -40 +KPX Ograve Tcaron -40 +KPX Ograve Tcommaaccent -40 +KPX Ograve V -50 +KPX Ograve W -50 +KPX Ograve X -40 +KPX Ograve Y -50 +KPX Ograve Yacute -50 +KPX Ograve Ydieresis -50 +KPX Ohungarumlaut A -40 +KPX Ohungarumlaut Aacute -40 +KPX Ohungarumlaut Abreve -40 +KPX Ohungarumlaut Acircumflex -40 +KPX Ohungarumlaut Adieresis -40 +KPX Ohungarumlaut Agrave -40 +KPX Ohungarumlaut Amacron -40 +KPX Ohungarumlaut Aogonek -40 +KPX Ohungarumlaut Aring -40 +KPX Ohungarumlaut Atilde -40 +KPX Ohungarumlaut T -40 +KPX Ohungarumlaut Tcaron -40 +KPX Ohungarumlaut Tcommaaccent -40 +KPX Ohungarumlaut V -50 +KPX Ohungarumlaut W -50 +KPX Ohungarumlaut X -40 +KPX Ohungarumlaut Y -50 +KPX Ohungarumlaut Yacute -50 +KPX Ohungarumlaut Ydieresis -50 +KPX Omacron A -40 +KPX Omacron Aacute -40 +KPX Omacron Abreve -40 +KPX Omacron Acircumflex -40 +KPX Omacron Adieresis -40 +KPX Omacron Agrave -40 +KPX Omacron Amacron -40 +KPX Omacron Aogonek -40 +KPX Omacron Aring -40 +KPX Omacron Atilde -40 +KPX Omacron T -40 +KPX Omacron Tcaron -40 +KPX Omacron Tcommaaccent -40 +KPX Omacron V -50 +KPX Omacron W -50 +KPX Omacron X -40 +KPX Omacron Y -50 +KPX Omacron Yacute -50 +KPX Omacron Ydieresis -50 +KPX Oslash A -40 +KPX Oslash Aacute -40 +KPX Oslash Abreve -40 +KPX Oslash Acircumflex -40 +KPX Oslash Adieresis -40 +KPX Oslash Agrave -40 +KPX Oslash Amacron -40 +KPX Oslash Aogonek -40 +KPX Oslash Aring -40 +KPX Oslash Atilde -40 +KPX Oslash T -40 +KPX Oslash Tcaron -40 +KPX Oslash Tcommaaccent -40 +KPX Oslash V -50 +KPX Oslash W -50 +KPX Oslash X -40 +KPX Oslash Y -50 +KPX Oslash Yacute -50 +KPX Oslash Ydieresis -50 +KPX Otilde A -40 +KPX Otilde Aacute -40 +KPX Otilde Abreve -40 +KPX Otilde Acircumflex -40 +KPX Otilde Adieresis -40 +KPX Otilde Agrave -40 +KPX Otilde Amacron -40 +KPX Otilde Aogonek -40 +KPX Otilde Aring -40 +KPX Otilde Atilde -40 +KPX Otilde T -40 +KPX Otilde Tcaron -40 +KPX Otilde Tcommaaccent -40 +KPX Otilde V -50 +KPX Otilde W -50 +KPX Otilde X -40 +KPX Otilde Y -50 +KPX Otilde Yacute -50 +KPX Otilde Ydieresis -50 +KPX P A -74 +KPX P Aacute -74 +KPX P Abreve -74 +KPX P Acircumflex -74 +KPX P Adieresis -74 +KPX P Agrave -74 +KPX P Amacron -74 +KPX P Aogonek -74 +KPX P Aring -74 +KPX P Atilde -74 +KPX P a -10 +KPX P aacute -10 +KPX P abreve -10 +KPX P acircumflex -10 +KPX P adieresis -10 +KPX P agrave -10 +KPX P amacron -10 +KPX P aogonek -10 +KPX P aring -10 +KPX P atilde -10 +KPX P comma -92 +KPX P e -20 +KPX P eacute -20 +KPX P ecaron -20 +KPX P ecircumflex -20 +KPX P edieresis -20 +KPX P edotaccent -20 +KPX P egrave -20 +KPX P emacron -20 +KPX P eogonek -20 +KPX P o -20 +KPX P oacute -20 +KPX P ocircumflex -20 +KPX P odieresis -20 +KPX P ograve -20 +KPX P ohungarumlaut -20 +KPX P omacron -20 +KPX P oslash -20 +KPX P otilde -20 +KPX P period -110 +KPX Q U -10 +KPX Q Uacute -10 +KPX Q Ucircumflex -10 +KPX Q Udieresis -10 +KPX Q Ugrave -10 +KPX Q Uhungarumlaut -10 +KPX Q Umacron -10 +KPX Q Uogonek -10 +KPX Q Uring -10 +KPX Q period -20 +KPX R O -30 +KPX R Oacute -30 +KPX R Ocircumflex -30 +KPX R Odieresis -30 +KPX R Ograve -30 +KPX R Ohungarumlaut -30 +KPX R Omacron -30 +KPX R Oslash -30 +KPX R Otilde -30 +KPX R T -40 +KPX R Tcaron -40 +KPX R Tcommaaccent -40 +KPX R U -30 +KPX R Uacute -30 +KPX R Ucircumflex -30 +KPX R Udieresis -30 +KPX R Ugrave -30 +KPX R Uhungarumlaut -30 +KPX R Umacron -30 +KPX R Uogonek -30 +KPX R Uring -30 +KPX R V -55 +KPX R W -35 +KPX R Y -35 +KPX R Yacute -35 +KPX R Ydieresis -35 +KPX Racute O -30 +KPX Racute Oacute -30 +KPX Racute Ocircumflex -30 +KPX Racute Odieresis -30 +KPX Racute Ograve -30 +KPX Racute Ohungarumlaut -30 +KPX Racute Omacron -30 +KPX Racute Oslash -30 +KPX Racute Otilde -30 +KPX Racute T -40 +KPX Racute Tcaron -40 +KPX Racute Tcommaaccent -40 +KPX Racute U -30 +KPX Racute Uacute -30 +KPX Racute Ucircumflex -30 +KPX Racute Udieresis -30 +KPX Racute Ugrave -30 +KPX Racute Uhungarumlaut -30 +KPX Racute Umacron -30 +KPX Racute Uogonek -30 +KPX Racute Uring -30 +KPX Racute V -55 +KPX Racute W -35 +KPX Racute Y -35 +KPX Racute Yacute -35 +KPX Racute Ydieresis -35 +KPX Rcaron O -30 +KPX Rcaron Oacute -30 +KPX Rcaron Ocircumflex -30 +KPX Rcaron Odieresis -30 +KPX Rcaron Ograve -30 +KPX Rcaron Ohungarumlaut -30 +KPX Rcaron Omacron -30 +KPX Rcaron Oslash -30 +KPX Rcaron Otilde -30 +KPX Rcaron T -40 +KPX Rcaron Tcaron -40 +KPX Rcaron Tcommaaccent -40 +KPX Rcaron U -30 +KPX Rcaron Uacute -30 +KPX Rcaron Ucircumflex -30 +KPX Rcaron Udieresis -30 +KPX Rcaron Ugrave -30 +KPX Rcaron Uhungarumlaut -30 +KPX Rcaron Umacron -30 +KPX Rcaron Uogonek -30 +KPX Rcaron Uring -30 +KPX Rcaron V -55 +KPX Rcaron W -35 +KPX Rcaron Y -35 +KPX Rcaron Yacute -35 +KPX Rcaron Ydieresis -35 +KPX Rcommaaccent O -30 +KPX Rcommaaccent Oacute -30 +KPX Rcommaaccent Ocircumflex -30 +KPX Rcommaaccent Odieresis -30 +KPX Rcommaaccent Ograve -30 +KPX Rcommaaccent Ohungarumlaut -30 +KPX Rcommaaccent Omacron -30 +KPX Rcommaaccent Oslash -30 +KPX Rcommaaccent Otilde -30 +KPX Rcommaaccent T -40 +KPX Rcommaaccent Tcaron -40 +KPX Rcommaaccent Tcommaaccent -40 +KPX Rcommaaccent U -30 +KPX Rcommaaccent Uacute -30 +KPX Rcommaaccent Ucircumflex -30 +KPX Rcommaaccent Udieresis -30 +KPX Rcommaaccent Ugrave -30 +KPX Rcommaaccent Uhungarumlaut -30 +KPX Rcommaaccent Umacron -30 +KPX Rcommaaccent Uogonek -30 +KPX Rcommaaccent Uring -30 +KPX Rcommaaccent V -55 +KPX Rcommaaccent W -35 +KPX Rcommaaccent Y -35 +KPX Rcommaaccent Yacute -35 +KPX Rcommaaccent Ydieresis -35 +KPX T A -90 +KPX T Aacute -90 +KPX T Abreve -90 +KPX T Acircumflex -90 +KPX T Adieresis -90 +KPX T Agrave -90 +KPX T Amacron -90 +KPX T Aogonek -90 +KPX T Aring -90 +KPX T Atilde -90 +KPX T O -18 +KPX T Oacute -18 +KPX T Ocircumflex -18 +KPX T Odieresis -18 +KPX T Ograve -18 +KPX T Ohungarumlaut -18 +KPX T Omacron -18 +KPX T Oslash -18 +KPX T Otilde -18 +KPX T a -92 +KPX T aacute -92 +KPX T abreve -52 +KPX T acircumflex -52 +KPX T adieresis -52 +KPX T agrave -52 +KPX T amacron -52 +KPX T aogonek -92 +KPX T aring -92 +KPX T atilde -52 +KPX T colon -74 +KPX T comma -74 +KPX T e -92 +KPX T eacute -92 +KPX T ecaron -92 +KPX T ecircumflex -92 +KPX T edieresis -52 +KPX T edotaccent -92 +KPX T egrave -52 +KPX T emacron -52 +KPX T eogonek -92 +KPX T hyphen -92 +KPX T i -18 +KPX T iacute -18 +KPX T iogonek -18 +KPX T o -92 +KPX T oacute -92 +KPX T ocircumflex -92 +KPX T odieresis -92 +KPX T ograve -92 +KPX T ohungarumlaut -92 +KPX T omacron -92 +KPX T oslash -92 +KPX T otilde -92 +KPX T period -90 +KPX T r -74 +KPX T racute -74 +KPX T rcaron -74 +KPX T rcommaaccent -74 +KPX T semicolon -74 +KPX T u -92 +KPX T uacute -92 +KPX T ucircumflex -92 +KPX T udieresis -92 +KPX T ugrave -92 +KPX T uhungarumlaut -92 +KPX T umacron -92 +KPX T uogonek -92 +KPX T uring -92 +KPX T w -74 +KPX T y -34 +KPX T yacute -34 +KPX T ydieresis -34 +KPX Tcaron A -90 +KPX Tcaron Aacute -90 +KPX Tcaron Abreve -90 +KPX Tcaron Acircumflex -90 +KPX Tcaron Adieresis -90 +KPX Tcaron Agrave -90 +KPX Tcaron Amacron -90 +KPX Tcaron Aogonek -90 +KPX Tcaron Aring -90 +KPX Tcaron Atilde -90 +KPX Tcaron O -18 +KPX Tcaron Oacute -18 +KPX Tcaron Ocircumflex -18 +KPX Tcaron Odieresis -18 +KPX Tcaron Ograve -18 +KPX Tcaron Ohungarumlaut -18 +KPX Tcaron Omacron -18 +KPX Tcaron Oslash -18 +KPX Tcaron Otilde -18 +KPX Tcaron a -92 +KPX Tcaron aacute -92 +KPX Tcaron abreve -52 +KPX Tcaron acircumflex -52 +KPX Tcaron adieresis -52 +KPX Tcaron agrave -52 +KPX Tcaron amacron -52 +KPX Tcaron aogonek -92 +KPX Tcaron aring -92 +KPX Tcaron atilde -52 +KPX Tcaron colon -74 +KPX Tcaron comma -74 +KPX Tcaron e -92 +KPX Tcaron eacute -92 +KPX Tcaron ecaron -92 +KPX Tcaron ecircumflex -92 +KPX Tcaron edieresis -52 +KPX Tcaron edotaccent -92 +KPX Tcaron egrave -52 +KPX Tcaron emacron -52 +KPX Tcaron eogonek -92 +KPX Tcaron hyphen -92 +KPX Tcaron i -18 +KPX Tcaron iacute -18 +KPX Tcaron iogonek -18 +KPX Tcaron o -92 +KPX Tcaron oacute -92 +KPX Tcaron ocircumflex -92 +KPX Tcaron odieresis -92 +KPX Tcaron ograve -92 +KPX Tcaron ohungarumlaut -92 +KPX Tcaron omacron -92 +KPX Tcaron oslash -92 +KPX Tcaron otilde -92 +KPX Tcaron period -90 +KPX Tcaron r -74 +KPX Tcaron racute -74 +KPX Tcaron rcaron -74 +KPX Tcaron rcommaaccent -74 +KPX Tcaron semicolon -74 +KPX Tcaron u -92 +KPX Tcaron uacute -92 +KPX Tcaron ucircumflex -92 +KPX Tcaron udieresis -92 +KPX Tcaron ugrave -92 +KPX Tcaron uhungarumlaut -92 +KPX Tcaron umacron -92 +KPX Tcaron uogonek -92 +KPX Tcaron uring -92 +KPX Tcaron w -74 +KPX Tcaron y -34 +KPX Tcaron yacute -34 +KPX Tcaron ydieresis -34 +KPX Tcommaaccent A -90 +KPX Tcommaaccent Aacute -90 +KPX Tcommaaccent Abreve -90 +KPX Tcommaaccent Acircumflex -90 +KPX Tcommaaccent Adieresis -90 +KPX Tcommaaccent Agrave -90 +KPX Tcommaaccent Amacron -90 +KPX Tcommaaccent Aogonek -90 +KPX Tcommaaccent Aring -90 +KPX Tcommaaccent Atilde -90 +KPX Tcommaaccent O -18 +KPX Tcommaaccent Oacute -18 +KPX Tcommaaccent Ocircumflex -18 +KPX Tcommaaccent Odieresis -18 +KPX Tcommaaccent Ograve -18 +KPX Tcommaaccent Ohungarumlaut -18 +KPX Tcommaaccent Omacron -18 +KPX Tcommaaccent Oslash -18 +KPX Tcommaaccent Otilde -18 +KPX Tcommaaccent a -92 +KPX Tcommaaccent aacute -92 +KPX Tcommaaccent abreve -52 +KPX Tcommaaccent acircumflex -52 +KPX Tcommaaccent adieresis -52 +KPX Tcommaaccent agrave -52 +KPX Tcommaaccent amacron -52 +KPX Tcommaaccent aogonek -92 +KPX Tcommaaccent aring -92 +KPX Tcommaaccent atilde -52 +KPX Tcommaaccent colon -74 +KPX Tcommaaccent comma -74 +KPX Tcommaaccent e -92 +KPX Tcommaaccent eacute -92 +KPX Tcommaaccent ecaron -92 +KPX Tcommaaccent ecircumflex -92 +KPX Tcommaaccent edieresis -52 +KPX Tcommaaccent edotaccent -92 +KPX Tcommaaccent egrave -52 +KPX Tcommaaccent emacron -52 +KPX Tcommaaccent eogonek -92 +KPX Tcommaaccent hyphen -92 +KPX Tcommaaccent i -18 +KPX Tcommaaccent iacute -18 +KPX Tcommaaccent iogonek -18 +KPX Tcommaaccent o -92 +KPX Tcommaaccent oacute -92 +KPX Tcommaaccent ocircumflex -92 +KPX Tcommaaccent odieresis -92 +KPX Tcommaaccent ograve -92 +KPX Tcommaaccent ohungarumlaut -92 +KPX Tcommaaccent omacron -92 +KPX Tcommaaccent oslash -92 +KPX Tcommaaccent otilde -92 +KPX Tcommaaccent period -90 +KPX Tcommaaccent r -74 +KPX Tcommaaccent racute -74 +KPX Tcommaaccent rcaron -74 +KPX Tcommaaccent rcommaaccent -74 +KPX Tcommaaccent semicolon -74 +KPX Tcommaaccent u -92 +KPX Tcommaaccent uacute -92 +KPX Tcommaaccent ucircumflex -92 +KPX Tcommaaccent udieresis -92 +KPX Tcommaaccent ugrave -92 +KPX Tcommaaccent uhungarumlaut -92 +KPX Tcommaaccent umacron -92 +KPX Tcommaaccent uogonek -92 +KPX Tcommaaccent uring -92 +KPX Tcommaaccent w -74 +KPX Tcommaaccent y -34 +KPX Tcommaaccent yacute -34 +KPX Tcommaaccent ydieresis -34 +KPX U A -60 +KPX U Aacute -60 +KPX U Abreve -60 +KPX U Acircumflex -60 +KPX U Adieresis -60 +KPX U Agrave -60 +KPX U Amacron -60 +KPX U Aogonek -60 +KPX U Aring -60 +KPX U Atilde -60 +KPX U comma -50 +KPX U period -50 +KPX Uacute A -60 +KPX Uacute Aacute -60 +KPX Uacute Abreve -60 +KPX Uacute Acircumflex -60 +KPX Uacute Adieresis -60 +KPX Uacute Agrave -60 +KPX Uacute Amacron -60 +KPX Uacute Aogonek -60 +KPX Uacute Aring -60 +KPX Uacute Atilde -60 +KPX Uacute comma -50 +KPX Uacute period -50 +KPX Ucircumflex A -60 +KPX Ucircumflex Aacute -60 +KPX Ucircumflex Abreve -60 +KPX Ucircumflex Acircumflex -60 +KPX Ucircumflex Adieresis -60 +KPX Ucircumflex Agrave -60 +KPX Ucircumflex Amacron -60 +KPX Ucircumflex Aogonek -60 +KPX Ucircumflex Aring -60 +KPX Ucircumflex Atilde -60 +KPX Ucircumflex comma -50 +KPX Ucircumflex period -50 +KPX Udieresis A -60 +KPX Udieresis Aacute -60 +KPX Udieresis Abreve -60 +KPX Udieresis Acircumflex -60 +KPX Udieresis Adieresis -60 +KPX Udieresis Agrave -60 +KPX Udieresis Amacron -60 +KPX Udieresis Aogonek -60 +KPX Udieresis Aring -60 +KPX Udieresis Atilde -60 +KPX Udieresis comma -50 +KPX Udieresis period -50 +KPX Ugrave A -60 +KPX Ugrave Aacute -60 +KPX Ugrave Abreve -60 +KPX Ugrave Acircumflex -60 +KPX Ugrave Adieresis -60 +KPX Ugrave Agrave -60 +KPX Ugrave Amacron -60 +KPX Ugrave Aogonek -60 +KPX Ugrave Aring -60 +KPX Ugrave Atilde -60 +KPX Ugrave comma -50 +KPX Ugrave period -50 +KPX Uhungarumlaut A -60 +KPX Uhungarumlaut Aacute -60 +KPX Uhungarumlaut Abreve -60 +KPX Uhungarumlaut Acircumflex -60 +KPX Uhungarumlaut Adieresis -60 +KPX Uhungarumlaut Agrave -60 +KPX Uhungarumlaut Amacron -60 +KPX Uhungarumlaut Aogonek -60 +KPX Uhungarumlaut Aring -60 +KPX Uhungarumlaut Atilde -60 +KPX Uhungarumlaut comma -50 +KPX Uhungarumlaut period -50 +KPX Umacron A -60 +KPX Umacron Aacute -60 +KPX Umacron Abreve -60 +KPX Umacron Acircumflex -60 +KPX Umacron Adieresis -60 +KPX Umacron Agrave -60 +KPX Umacron Amacron -60 +KPX Umacron Aogonek -60 +KPX Umacron Aring -60 +KPX Umacron Atilde -60 +KPX Umacron comma -50 +KPX Umacron period -50 +KPX Uogonek A -60 +KPX Uogonek Aacute -60 +KPX Uogonek Abreve -60 +KPX Uogonek Acircumflex -60 +KPX Uogonek Adieresis -60 +KPX Uogonek Agrave -60 +KPX Uogonek Amacron -60 +KPX Uogonek Aogonek -60 +KPX Uogonek Aring -60 +KPX Uogonek Atilde -60 +KPX Uogonek comma -50 +KPX Uogonek period -50 +KPX Uring A -60 +KPX Uring Aacute -60 +KPX Uring Abreve -60 +KPX Uring Acircumflex -60 +KPX Uring Adieresis -60 +KPX Uring Agrave -60 +KPX Uring Amacron -60 +KPX Uring Aogonek -60 +KPX Uring Aring -60 +KPX Uring Atilde -60 +KPX Uring comma -50 +KPX Uring period -50 +KPX V A -135 +KPX V Aacute -135 +KPX V Abreve -135 +KPX V Acircumflex -135 +KPX V Adieresis -135 +KPX V Agrave -135 +KPX V Amacron -135 +KPX V Aogonek -135 +KPX V Aring -135 +KPX V Atilde -135 +KPX V G -30 +KPX V Gbreve -30 +KPX V Gcommaaccent -30 +KPX V O -45 +KPX V Oacute -45 +KPX V Ocircumflex -45 +KPX V Odieresis -45 +KPX V Ograve -45 +KPX V Ohungarumlaut -45 +KPX V Omacron -45 +KPX V Oslash -45 +KPX V Otilde -45 +KPX V a -92 +KPX V aacute -92 +KPX V abreve -92 +KPX V acircumflex -92 +KPX V adieresis -92 +KPX V agrave -92 +KPX V amacron -92 +KPX V aogonek -92 +KPX V aring -92 +KPX V atilde -92 +KPX V colon -92 +KPX V comma -129 +KPX V e -100 +KPX V eacute -100 +KPX V ecaron -100 +KPX V ecircumflex -100 +KPX V edieresis -100 +KPX V edotaccent -100 +KPX V egrave -100 +KPX V emacron -100 +KPX V eogonek -100 +KPX V hyphen -74 +KPX V i -37 +KPX V iacute -37 +KPX V icircumflex -37 +KPX V idieresis -37 +KPX V igrave -37 +KPX V imacron -37 +KPX V iogonek -37 +KPX V o -100 +KPX V oacute -100 +KPX V ocircumflex -100 +KPX V odieresis -100 +KPX V ograve -100 +KPX V ohungarumlaut -100 +KPX V omacron -100 +KPX V oslash -100 +KPX V otilde -100 +KPX V period -145 +KPX V semicolon -92 +KPX V u -92 +KPX V uacute -92 +KPX V ucircumflex -92 +KPX V udieresis -92 +KPX V ugrave -92 +KPX V uhungarumlaut -92 +KPX V umacron -92 +KPX V uogonek -92 +KPX V uring -92 +KPX W A -120 +KPX W Aacute -120 +KPX W Abreve -120 +KPX W Acircumflex -120 +KPX W Adieresis -120 +KPX W Agrave -120 +KPX W Amacron -120 +KPX W Aogonek -120 +KPX W Aring -120 +KPX W Atilde -120 +KPX W O -10 +KPX W Oacute -10 +KPX W Ocircumflex -10 +KPX W Odieresis -10 +KPX W Ograve -10 +KPX W Ohungarumlaut -10 +KPX W Omacron -10 +KPX W Oslash -10 +KPX W Otilde -10 +KPX W a -65 +KPX W aacute -65 +KPX W abreve -65 +KPX W acircumflex -65 +KPX W adieresis -65 +KPX W agrave -65 +KPX W amacron -65 +KPX W aogonek -65 +KPX W aring -65 +KPX W atilde -65 +KPX W colon -55 +KPX W comma -92 +KPX W e -65 +KPX W eacute -65 +KPX W ecaron -65 +KPX W ecircumflex -65 +KPX W edieresis -65 +KPX W edotaccent -65 +KPX W egrave -65 +KPX W emacron -65 +KPX W eogonek -65 +KPX W hyphen -37 +KPX W i -18 +KPX W iacute -18 +KPX W iogonek -18 +KPX W o -75 +KPX W oacute -75 +KPX W ocircumflex -75 +KPX W odieresis -75 +KPX W ograve -75 +KPX W ohungarumlaut -75 +KPX W omacron -75 +KPX W oslash -75 +KPX W otilde -75 +KPX W period -92 +KPX W semicolon -55 +KPX W u -50 +KPX W uacute -50 +KPX W ucircumflex -50 +KPX W udieresis -50 +KPX W ugrave -50 +KPX W uhungarumlaut -50 +KPX W umacron -50 +KPX W uogonek -50 +KPX W uring -50 +KPX W y -60 +KPX W yacute -60 +KPX W ydieresis -60 +KPX Y A -110 +KPX Y Aacute -110 +KPX Y Abreve -110 +KPX Y Acircumflex -110 +KPX Y Adieresis -110 +KPX Y Agrave -110 +KPX Y Amacron -110 +KPX Y Aogonek -110 +KPX Y Aring -110 +KPX Y Atilde -110 +KPX Y O -35 +KPX Y Oacute -35 +KPX Y Ocircumflex -35 +KPX Y Odieresis -35 +KPX Y Ograve -35 +KPX Y Ohungarumlaut -35 +KPX Y Omacron -35 +KPX Y Oslash -35 +KPX Y Otilde -35 +KPX Y a -85 +KPX Y aacute -85 +KPX Y abreve -85 +KPX Y acircumflex -85 +KPX Y adieresis -85 +KPX Y agrave -85 +KPX Y amacron -85 +KPX Y aogonek -85 +KPX Y aring -85 +KPX Y atilde -85 +KPX Y colon -92 +KPX Y comma -92 +KPX Y e -111 +KPX Y eacute -111 +KPX Y ecaron -111 +KPX Y ecircumflex -111 +KPX Y edieresis -71 +KPX Y edotaccent -111 +KPX Y egrave -71 +KPX Y emacron -71 +KPX Y eogonek -111 +KPX Y hyphen -92 +KPX Y i -37 +KPX Y iacute -37 +KPX Y iogonek -37 +KPX Y o -111 +KPX Y oacute -111 +KPX Y ocircumflex -111 +KPX Y odieresis -111 +KPX Y ograve -111 +KPX Y ohungarumlaut -111 +KPX Y omacron -111 +KPX Y oslash -111 +KPX Y otilde -111 +KPX Y period -92 +KPX Y semicolon -92 +KPX Y u -92 +KPX Y uacute -92 +KPX Y ucircumflex -92 +KPX Y udieresis -92 +KPX Y ugrave -92 +KPX Y uhungarumlaut -92 +KPX Y umacron -92 +KPX Y uogonek -92 +KPX Y uring -92 +KPX Yacute A -110 +KPX Yacute Aacute -110 +KPX Yacute Abreve -110 +KPX Yacute Acircumflex -110 +KPX Yacute Adieresis -110 +KPX Yacute Agrave -110 +KPX Yacute Amacron -110 +KPX Yacute Aogonek -110 +KPX Yacute Aring -110 +KPX Yacute Atilde -110 +KPX Yacute O -35 +KPX Yacute Oacute -35 +KPX Yacute Ocircumflex -35 +KPX Yacute Odieresis -35 +KPX Yacute Ograve -35 +KPX Yacute Ohungarumlaut -35 +KPX Yacute Omacron -35 +KPX Yacute Oslash -35 +KPX Yacute Otilde -35 +KPX Yacute a -85 +KPX Yacute aacute -85 +KPX Yacute abreve -85 +KPX Yacute acircumflex -85 +KPX Yacute adieresis -85 +KPX Yacute agrave -85 +KPX Yacute amacron -85 +KPX Yacute aogonek -85 +KPX Yacute aring -85 +KPX Yacute atilde -85 +KPX Yacute colon -92 +KPX Yacute comma -92 +KPX Yacute e -111 +KPX Yacute eacute -111 +KPX Yacute ecaron -111 +KPX Yacute ecircumflex -111 +KPX Yacute edieresis -71 +KPX Yacute edotaccent -111 +KPX Yacute egrave -71 +KPX Yacute emacron -71 +KPX Yacute eogonek -111 +KPX Yacute hyphen -92 +KPX Yacute i -37 +KPX Yacute iacute -37 +KPX Yacute iogonek -37 +KPX Yacute o -111 +KPX Yacute oacute -111 +KPX Yacute ocircumflex -111 +KPX Yacute odieresis -111 +KPX Yacute ograve -111 +KPX Yacute ohungarumlaut -111 +KPX Yacute omacron -111 +KPX Yacute oslash -111 +KPX Yacute otilde -111 +KPX Yacute period -92 +KPX Yacute semicolon -92 +KPX Yacute u -92 +KPX Yacute uacute -92 +KPX Yacute ucircumflex -92 +KPX Yacute udieresis -92 +KPX Yacute ugrave -92 +KPX Yacute uhungarumlaut -92 +KPX Yacute umacron -92 +KPX Yacute uogonek -92 +KPX Yacute uring -92 +KPX Ydieresis A -110 +KPX Ydieresis Aacute -110 +KPX Ydieresis Abreve -110 +KPX Ydieresis Acircumflex -110 +KPX Ydieresis Adieresis -110 +KPX Ydieresis Agrave -110 +KPX Ydieresis Amacron -110 +KPX Ydieresis Aogonek -110 +KPX Ydieresis Aring -110 +KPX Ydieresis Atilde -110 +KPX Ydieresis O -35 +KPX Ydieresis Oacute -35 +KPX Ydieresis Ocircumflex -35 +KPX Ydieresis Odieresis -35 +KPX Ydieresis Ograve -35 +KPX Ydieresis Ohungarumlaut -35 +KPX Ydieresis Omacron -35 +KPX Ydieresis Oslash -35 +KPX Ydieresis Otilde -35 +KPX Ydieresis a -85 +KPX Ydieresis aacute -85 +KPX Ydieresis abreve -85 +KPX Ydieresis acircumflex -85 +KPX Ydieresis adieresis -85 +KPX Ydieresis agrave -85 +KPX Ydieresis amacron -85 +KPX Ydieresis aogonek -85 +KPX Ydieresis aring -85 +KPX Ydieresis atilde -85 +KPX Ydieresis colon -92 +KPX Ydieresis comma -92 +KPX Ydieresis e -111 +KPX Ydieresis eacute -111 +KPX Ydieresis ecaron -111 +KPX Ydieresis ecircumflex -111 +KPX Ydieresis edieresis -71 +KPX Ydieresis edotaccent -111 +KPX Ydieresis egrave -71 +KPX Ydieresis emacron -71 +KPX Ydieresis eogonek -111 +KPX Ydieresis hyphen -92 +KPX Ydieresis i -37 +KPX Ydieresis iacute -37 +KPX Ydieresis iogonek -37 +KPX Ydieresis o -111 +KPX Ydieresis oacute -111 +KPX Ydieresis ocircumflex -111 +KPX Ydieresis odieresis -111 +KPX Ydieresis ograve -111 +KPX Ydieresis ohungarumlaut -111 +KPX Ydieresis omacron -111 +KPX Ydieresis oslash -111 +KPX Ydieresis otilde -111 +KPX Ydieresis period -92 +KPX Ydieresis semicolon -92 +KPX Ydieresis u -92 +KPX Ydieresis uacute -92 +KPX Ydieresis ucircumflex -92 +KPX Ydieresis udieresis -92 +KPX Ydieresis ugrave -92 +KPX Ydieresis uhungarumlaut -92 +KPX Ydieresis umacron -92 +KPX Ydieresis uogonek -92 +KPX Ydieresis uring -92 +KPX a v -25 +KPX aacute v -25 +KPX abreve v -25 +KPX acircumflex v -25 +KPX adieresis v -25 +KPX agrave v -25 +KPX amacron v -25 +KPX aogonek v -25 +KPX aring v -25 +KPX atilde v -25 +KPX b b -10 +KPX b period -40 +KPX b u -20 +KPX b uacute -20 +KPX b ucircumflex -20 +KPX b udieresis -20 +KPX b ugrave -20 +KPX b uhungarumlaut -20 +KPX b umacron -20 +KPX b uogonek -20 +KPX b uring -20 +KPX b v -15 +KPX comma quotedblright -45 +KPX comma quoteright -55 +KPX d w -15 +KPX dcroat w -15 +KPX e v -15 +KPX eacute v -15 +KPX ecaron v -15 +KPX ecircumflex v -15 +KPX edieresis v -15 +KPX edotaccent v -15 +KPX egrave v -15 +KPX emacron v -15 +KPX eogonek v -15 +KPX f comma -15 +KPX f dotlessi -35 +KPX f i -25 +KPX f o -25 +KPX f oacute -25 +KPX f ocircumflex -25 +KPX f odieresis -25 +KPX f ograve -25 +KPX f ohungarumlaut -25 +KPX f omacron -25 +KPX f oslash -25 +KPX f otilde -25 +KPX f period -15 +KPX f quotedblright 50 +KPX f quoteright 55 +KPX g period -15 +KPX gbreve period -15 +KPX gcommaaccent period -15 +KPX h y -15 +KPX h yacute -15 +KPX h ydieresis -15 +KPX i v -10 +KPX iacute v -10 +KPX icircumflex v -10 +KPX idieresis v -10 +KPX igrave v -10 +KPX imacron v -10 +KPX iogonek v -10 +KPX k e -10 +KPX k eacute -10 +KPX k ecaron -10 +KPX k ecircumflex -10 +KPX k edieresis -10 +KPX k edotaccent -10 +KPX k egrave -10 +KPX k emacron -10 +KPX k eogonek -10 +KPX k o -15 +KPX k oacute -15 +KPX k ocircumflex -15 +KPX k odieresis -15 +KPX k ograve -15 +KPX k ohungarumlaut -15 +KPX k omacron -15 +KPX k oslash -15 +KPX k otilde -15 +KPX k y -15 +KPX k yacute -15 +KPX k ydieresis -15 +KPX kcommaaccent e -10 +KPX kcommaaccent eacute -10 +KPX kcommaaccent ecaron -10 +KPX kcommaaccent ecircumflex -10 +KPX kcommaaccent edieresis -10 +KPX kcommaaccent edotaccent -10 +KPX kcommaaccent egrave -10 +KPX kcommaaccent emacron -10 +KPX kcommaaccent eogonek -10 +KPX kcommaaccent o -15 +KPX kcommaaccent oacute -15 +KPX kcommaaccent ocircumflex -15 +KPX kcommaaccent odieresis -15 +KPX kcommaaccent ograve -15 +KPX kcommaaccent ohungarumlaut -15 +KPX kcommaaccent omacron -15 +KPX kcommaaccent oslash -15 +KPX kcommaaccent otilde -15 +KPX kcommaaccent y -15 +KPX kcommaaccent yacute -15 +KPX kcommaaccent ydieresis -15 +KPX n v -40 +KPX nacute v -40 +KPX ncaron v -40 +KPX ncommaaccent v -40 +KPX ntilde v -40 +KPX o v -10 +KPX o w -10 +KPX oacute v -10 +KPX oacute w -10 +KPX ocircumflex v -10 +KPX ocircumflex w -10 +KPX odieresis v -10 +KPX odieresis w -10 +KPX ograve v -10 +KPX ograve w -10 +KPX ohungarumlaut v -10 +KPX ohungarumlaut w -10 +KPX omacron v -10 +KPX omacron w -10 +KPX oslash v -10 +KPX oslash w -10 +KPX otilde v -10 +KPX otilde w -10 +KPX period quotedblright -55 +KPX period quoteright -55 +KPX quotedblleft A -10 +KPX quotedblleft Aacute -10 +KPX quotedblleft Abreve -10 +KPX quotedblleft Acircumflex -10 +KPX quotedblleft Adieresis -10 +KPX quotedblleft Agrave -10 +KPX quotedblleft Amacron -10 +KPX quotedblleft Aogonek -10 +KPX quotedblleft Aring -10 +KPX quotedblleft Atilde -10 +KPX quoteleft A -10 +KPX quoteleft Aacute -10 +KPX quoteleft Abreve -10 +KPX quoteleft Acircumflex -10 +KPX quoteleft Adieresis -10 +KPX quoteleft Agrave -10 +KPX quoteleft Amacron -10 +KPX quoteleft Aogonek -10 +KPX quoteleft Aring -10 +KPX quoteleft Atilde -10 +KPX quoteleft quoteleft -63 +KPX quoteright d -20 +KPX quoteright dcroat -20 +KPX quoteright quoteright -63 +KPX quoteright r -20 +KPX quoteright racute -20 +KPX quoteright rcaron -20 +KPX quoteright rcommaaccent -20 +KPX quoteright s -37 +KPX quoteright sacute -37 +KPX quoteright scaron -37 +KPX quoteright scedilla -37 +KPX quoteright scommaaccent -37 +KPX quoteright space -74 +KPX quoteright v -20 +KPX r c -18 +KPX r cacute -18 +KPX r ccaron -18 +KPX r ccedilla -18 +KPX r comma -92 +KPX r e -18 +KPX r eacute -18 +KPX r ecaron -18 +KPX r ecircumflex -18 +KPX r edieresis -18 +KPX r edotaccent -18 +KPX r egrave -18 +KPX r emacron -18 +KPX r eogonek -18 +KPX r g -10 +KPX r gbreve -10 +KPX r gcommaaccent -10 +KPX r hyphen -37 +KPX r n -15 +KPX r nacute -15 +KPX r ncaron -15 +KPX r ncommaaccent -15 +KPX r ntilde -15 +KPX r o -18 +KPX r oacute -18 +KPX r ocircumflex -18 +KPX r odieresis -18 +KPX r ograve -18 +KPX r ohungarumlaut -18 +KPX r omacron -18 +KPX r oslash -18 +KPX r otilde -18 +KPX r p -10 +KPX r period -100 +KPX r q -18 +KPX r v -10 +KPX racute c -18 +KPX racute cacute -18 +KPX racute ccaron -18 +KPX racute ccedilla -18 +KPX racute comma -92 +KPX racute e -18 +KPX racute eacute -18 +KPX racute ecaron -18 +KPX racute ecircumflex -18 +KPX racute edieresis -18 +KPX racute edotaccent -18 +KPX racute egrave -18 +KPX racute emacron -18 +KPX racute eogonek -18 +KPX racute g -10 +KPX racute gbreve -10 +KPX racute gcommaaccent -10 +KPX racute hyphen -37 +KPX racute n -15 +KPX racute nacute -15 +KPX racute ncaron -15 +KPX racute ncommaaccent -15 +KPX racute ntilde -15 +KPX racute o -18 +KPX racute oacute -18 +KPX racute ocircumflex -18 +KPX racute odieresis -18 +KPX racute ograve -18 +KPX racute ohungarumlaut -18 +KPX racute omacron -18 +KPX racute oslash -18 +KPX racute otilde -18 +KPX racute p -10 +KPX racute period -100 +KPX racute q -18 +KPX racute v -10 +KPX rcaron c -18 +KPX rcaron cacute -18 +KPX rcaron ccaron -18 +KPX rcaron ccedilla -18 +KPX rcaron comma -92 +KPX rcaron e -18 +KPX rcaron eacute -18 +KPX rcaron ecaron -18 +KPX rcaron ecircumflex -18 +KPX rcaron edieresis -18 +KPX rcaron edotaccent -18 +KPX rcaron egrave -18 +KPX rcaron emacron -18 +KPX rcaron eogonek -18 +KPX rcaron g -10 +KPX rcaron gbreve -10 +KPX rcaron gcommaaccent -10 +KPX rcaron hyphen -37 +KPX rcaron n -15 +KPX rcaron nacute -15 +KPX rcaron ncaron -15 +KPX rcaron ncommaaccent -15 +KPX rcaron ntilde -15 +KPX rcaron o -18 +KPX rcaron oacute -18 +KPX rcaron ocircumflex -18 +KPX rcaron odieresis -18 +KPX rcaron ograve -18 +KPX rcaron ohungarumlaut -18 +KPX rcaron omacron -18 +KPX rcaron oslash -18 +KPX rcaron otilde -18 +KPX rcaron p -10 +KPX rcaron period -100 +KPX rcaron q -18 +KPX rcaron v -10 +KPX rcommaaccent c -18 +KPX rcommaaccent cacute -18 +KPX rcommaaccent ccaron -18 +KPX rcommaaccent ccedilla -18 +KPX rcommaaccent comma -92 +KPX rcommaaccent e -18 +KPX rcommaaccent eacute -18 +KPX rcommaaccent ecaron -18 +KPX rcommaaccent ecircumflex -18 +KPX rcommaaccent edieresis -18 +KPX rcommaaccent edotaccent -18 +KPX rcommaaccent egrave -18 +KPX rcommaaccent emacron -18 +KPX rcommaaccent eogonek -18 +KPX rcommaaccent g -10 +KPX rcommaaccent gbreve -10 +KPX rcommaaccent gcommaaccent -10 +KPX rcommaaccent hyphen -37 +KPX rcommaaccent n -15 +KPX rcommaaccent nacute -15 +KPX rcommaaccent ncaron -15 +KPX rcommaaccent ncommaaccent -15 +KPX rcommaaccent ntilde -15 +KPX rcommaaccent o -18 +KPX rcommaaccent oacute -18 +KPX rcommaaccent ocircumflex -18 +KPX rcommaaccent odieresis -18 +KPX rcommaaccent ograve -18 +KPX rcommaaccent ohungarumlaut -18 +KPX rcommaaccent omacron -18 +KPX rcommaaccent oslash -18 +KPX rcommaaccent otilde -18 +KPX rcommaaccent p -10 +KPX rcommaaccent period -100 +KPX rcommaaccent q -18 +KPX rcommaaccent v -10 +KPX space A -55 +KPX space Aacute -55 +KPX space Abreve -55 +KPX space Acircumflex -55 +KPX space Adieresis -55 +KPX space Agrave -55 +KPX space Amacron -55 +KPX space Aogonek -55 +KPX space Aring -55 +KPX space Atilde -55 +KPX space T -30 +KPX space Tcaron -30 +KPX space Tcommaaccent -30 +KPX space V -45 +KPX space W -30 +KPX space Y -55 +KPX space Yacute -55 +KPX space Ydieresis -55 +KPX v a -10 +KPX v aacute -10 +KPX v abreve -10 +KPX v acircumflex -10 +KPX v adieresis -10 +KPX v agrave -10 +KPX v amacron -10 +KPX v aogonek -10 +KPX v aring -10 +KPX v atilde -10 +KPX v comma -55 +KPX v e -10 +KPX v eacute -10 +KPX v ecaron -10 +KPX v ecircumflex -10 +KPX v edieresis -10 +KPX v edotaccent -10 +KPX v egrave -10 +KPX v emacron -10 +KPX v eogonek -10 +KPX v o -10 +KPX v oacute -10 +KPX v ocircumflex -10 +KPX v odieresis -10 +KPX v ograve -10 +KPX v ohungarumlaut -10 +KPX v omacron -10 +KPX v oslash -10 +KPX v otilde -10 +KPX v period -70 +KPX w comma -55 +KPX w o -10 +KPX w oacute -10 +KPX w ocircumflex -10 +KPX w odieresis -10 +KPX w ograve -10 +KPX w ohungarumlaut -10 +KPX w omacron -10 +KPX w oslash -10 +KPX w otilde -10 +KPX w period -70 +KPX y comma -55 +KPX y e -10 +KPX y eacute -10 +KPX y ecaron -10 +KPX y ecircumflex -10 +KPX y edieresis -10 +KPX y edotaccent -10 +KPX y egrave -10 +KPX y emacron -10 +KPX y eogonek -10 +KPX y o -25 +KPX y oacute -25 +KPX y ocircumflex -25 +KPX y odieresis -25 +KPX y ograve -25 +KPX y ohungarumlaut -25 +KPX y omacron -25 +KPX y oslash -25 +KPX y otilde -25 +KPX y period -70 +KPX yacute comma -55 +KPX yacute e -10 +KPX yacute eacute -10 +KPX yacute ecaron -10 +KPX yacute ecircumflex -10 +KPX yacute edieresis -10 +KPX yacute edotaccent -10 +KPX yacute egrave -10 +KPX yacute emacron -10 +KPX yacute eogonek -10 +KPX yacute o -25 +KPX yacute oacute -25 +KPX yacute ocircumflex -25 +KPX yacute odieresis -25 +KPX yacute ograve -25 +KPX yacute ohungarumlaut -25 +KPX yacute omacron -25 +KPX yacute oslash -25 +KPX yacute otilde -25 +KPX yacute period -70 +KPX ydieresis comma -55 +KPX ydieresis e -10 +KPX ydieresis eacute -10 +KPX ydieresis ecaron -10 +KPX ydieresis ecircumflex -10 +KPX ydieresis edieresis -10 +KPX ydieresis edotaccent -10 +KPX ydieresis egrave -10 +KPX ydieresis emacron -10 +KPX ydieresis eogonek -10 +KPX ydieresis o -25 +KPX ydieresis oacute -25 +KPX ydieresis ocircumflex -25 +KPX ydieresis odieresis -25 +KPX ydieresis ograve -25 +KPX ydieresis ohungarumlaut -25 +KPX ydieresis omacron -25 +KPX ydieresis oslash -25 +KPX ydieresis otilde -25 +KPX ydieresis period -70 +EndKernPairs +EndKernData +EndFontMetrics diff --git a/shared/package-files/71/71062534abc8d949316a81df395ad027f260b16c54d0f609e44d7d5e59d0f89e/_types.py b/shared/package-files/71/71062534abc8d949316a81df395ad027f260b16c54d0f609e44d7d5e59d0f89e/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..dae83d00fcb2ee7534e08e5a3882a57977a34806 --- /dev/null +++ b/shared/package-files/71/71062534abc8d949316a81df395ad027f260b16c54d0f609e44d7d5e59d0f89e/_types.py @@ -0,0 +1,195 @@ +from __future__ import annotations + +from typing import Any, Callable, Mapping +import numbers + +from attrs import evolve, field, frozen +from rpds import HashTrieMap + +from jsonschema.exceptions import UndefinedTypeCheck + + +# unfortunately, the type of HashTrieMap is generic, and if used as an attrs +# converter, the generic type is presented to mypy, which then fails to match +# the concrete type of a type checker mapping +# this "do nothing" wrapper presents the correct information to mypy +def _typed_map_converter( + init_val: Mapping[str, Callable[[TypeChecker, Any], bool]], +) -> HashTrieMap[str, Callable[[TypeChecker, Any], bool]]: + return HashTrieMap.convert(init_val) + + +def is_array(checker, instance): + return isinstance(instance, list) + + +def is_bool(checker, instance): + return isinstance(instance, bool) + + +def is_integer(checker, instance): + # bool inherits from int, so ensure bools aren't reported as ints + if isinstance(instance, bool): + return False + return isinstance(instance, int) + + +def is_null(checker, instance): + return instance is None + + +def is_number(checker, instance): + # bool inherits from int, so ensure bools aren't reported as ints + if isinstance(instance, bool): + return False + return isinstance(instance, numbers.Number) + + +def is_object(checker, instance): + return isinstance(instance, dict) + + +def is_string(checker, instance): + return isinstance(instance, str) + + +def is_any(checker, instance): + return True + + +@frozen(repr=False) +class TypeChecker: + """ + A :kw:`type` property checker. + + A `TypeChecker` performs type checking for a `Validator`, converting + between the defined JSON Schema types and some associated Python types or + objects. + + Modifying the behavior just mentioned by redefining which Python objects + are considered to be of which JSON Schema types can be done using + `TypeChecker.redefine` or `TypeChecker.redefine_many`, and types can be + removed via `TypeChecker.remove`. Each of these return a new `TypeChecker`. + + Arguments: + + type_checkers: + + The initial mapping of types to their checking functions. + """ + + _type_checkers: HashTrieMap[ + str, Callable[[TypeChecker, Any], bool], + ] = field(default=HashTrieMap(), converter=_typed_map_converter) + + def __repr__(self): + types = ", ".join(repr(k) for k in sorted(self._type_checkers)) + return f"<{self.__class__.__name__} types={{{types}}}>" + + def is_type(self, instance, type: str) -> bool: + """ + Check if the instance is of the appropriate type. + + Arguments: + + instance: + + The instance to check + + type: + + The name of the type that is expected. + + Raises: + + `jsonschema.exceptions.UndefinedTypeCheck`: + + if ``type`` is unknown to this object. + """ + try: + fn = self._type_checkers[type] + except KeyError: + raise UndefinedTypeCheck(type) from None + + return fn(self, instance) + + def redefine(self, type: str, fn) -> TypeChecker: + """ + Produce a new checker with the given type redefined. + + Arguments: + + type: + + The name of the type to check. + + fn (collections.abc.Callable): + + A callable taking exactly two parameters - the type + checker calling the function and the instance to check. + The function should return true if instance is of this + type and false otherwise. + """ + return self.redefine_many({type: fn}) + + def redefine_many(self, definitions=()) -> TypeChecker: + """ + Produce a new checker with the given types redefined. + + Arguments: + + definitions (dict): + + A dictionary mapping types to their checking functions. + """ + type_checkers = self._type_checkers.update(definitions) + return evolve(self, type_checkers=type_checkers) + + def remove(self, *types) -> TypeChecker: + """ + Produce a new checker with the given types forgotten. + + Arguments: + + types: + + the names of the types to remove. + + Raises: + + `jsonschema.exceptions.UndefinedTypeCheck`: + + if any given type is unknown to this object + """ + type_checkers = self._type_checkers + for each in types: + try: + type_checkers = type_checkers.remove(each) + except KeyError: + raise UndefinedTypeCheck(each) + return evolve(self, type_checkers=type_checkers) + + +draft3_type_checker = TypeChecker( + { + "any": is_any, + "array": is_array, + "boolean": is_bool, + "integer": is_integer, + "object": is_object, + "null": is_null, + "number": is_number, + "string": is_string, + }, +) +draft4_type_checker = draft3_type_checker.remove("any") +draft6_type_checker = draft4_type_checker.redefine( + "integer", + lambda checker, instance: ( + is_integer(checker, instance) + or isinstance(instance, float) and instance.is_integer() + ), +) +draft7_type_checker = draft6_type_checker +draft201909_type_checker = draft7_type_checker +draft202012_type_checker = draft201909_type_checker diff --git a/shared/package-files/71/71063cd9641cd7d3ecaacb11b03f978db1c3fb9a201b4d0376b0568e07db0fe3/__init__.py b/shared/package-files/71/71063cd9641cd7d3ecaacb11b03f978db1c3fb9a201b4d0376b0568e07db0fe3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..59bfbd5dcab3169e3f8f7b78bd02c5033dbd0719 --- /dev/null +++ b/shared/package-files/71/71063cd9641cd7d3ecaacb11b03f978db1c3fb9a201b4d0376b0568e07db0fe3/__init__.py @@ -0,0 +1,101 @@ +# DON'T EDIT! This file is generated by MetaTools/buildTableList.py. +def _moduleFinderHint(): + """Dummy function to let modulefinder know what tables may be + dynamically imported. Generated by MetaTools/buildTableList.py. + + >>> _moduleFinderHint() + """ + from . import B_A_S_E_ + from . import C_B_D_T_ + from . import C_B_L_C_ + from . import C_F_F_ + from . import C_F_F__2 + from . import C_O_L_R_ + from . import C_P_A_L_ + from . import D_S_I_G_ + from . import D__e_b_g + from . import E_B_D_T_ + from . import E_B_L_C_ + from . import E_B_S_C_ + from . import F_F_T_M_ + from . import F__e_a_t + from . import G_D_E_F_ + from . import G_P_O_S_ + from . import G_S_U_B_ + from . import G_V_A_R_ + from . import G__l_a_t + from . import G__l_o_c + from . import H_V_A_R_ + from . import I_F_T_ + from . import I_F_T_X_ + from . import J_S_T_F_ + from . import L_T_S_H_ + from . import M_A_T_H_ + from . import M_V_A_R_ + from . import O_S_2f_2 + from . import S_T_A_T_ + from . import S_V_G_ + from . import S__i_l_f + from . import S__i_l_l + from . import T_S_I_B_ + from . import T_S_I_C_ + from . import T_S_I_D_ + from . import T_S_I_J_ + from . import T_S_I_P_ + from . import T_S_I_S_ + from . import T_S_I_V_ + from . import T_S_I__0 + from . import T_S_I__1 + from . import T_S_I__2 + from . import T_S_I__3 + from . import T_S_I__5 + from . import T_T_F_A_ + from . import V_A_R_C_ + from . import V_D_M_X_ + from . import V_O_R_G_ + from . import V_V_A_R_ + from . import _a_n_k_r + from . import _a_v_a_r + from . import _b_d_a_t + from . import _b_g_c_l + from . import _b_h_e_d + from . import _b_l_o_c + from . import _b_s_l_n + from . import _c_i_d_g + from . import _c_m_a_p + from . import _c_v_a_r + from . import _c_v_t + from . import _f_e_a_t + from . import _f_p_g_m + from . import _f_v_a_r + from . import _g_a_s_p + from . import _g_c_i_d + from . import _g_l_y_f + from . import _g_v_a_r + from . import _h_d_m_x + from . import _h_e_a_d + from . import _h_h_e_a + from . import _h_m_t_x + from . import _k_e_r_n + from . import _l_c_a_r + from . import _l_o_c_a + from . import _l_t_a_g + from . import _m_a_x_p + from . import _m_e_t_a + from . import _m_o_r_t + from . import _m_o_r_x + from . import _n_a_m_e + from . import _o_p_b_d + from . import _p_o_s_t + from . import _p_r_e_p + from . import _p_r_o_p + from . import _s_b_i_x + from . import _t_r_a_k + from . import _v_h_e_a + from . import _v_m_t_x + + +if __name__ == "__main__": + import doctest, sys + + sys.exit(doctest.testmod().failed) diff --git a/shared/package-files/71/7106923be8e26aa50664dd4166821235202f2ccf66f58f16dbe0c9e508bdcad0/attr_list.pyi b/shared/package-files/71/7106923be8e26aa50664dd4166821235202f2ccf66f58f16dbe0c9e508bdcad0/attr_list.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d073b486ada1d69f7880e44315d96fd6c24cf15a --- /dev/null +++ b/shared/package-files/71/7106923be8e26aa50664dd4166821235202f2ccf66f58f16dbe0c9e508bdcad0/attr_list.pyi @@ -0,0 +1,20 @@ +from typing import Any, Pattern + +from markdown.extensions import Extension +from markdown.treeprocessors import Treeprocessor + +def get_attrs(str): ... +def isheader(elem): ... + +class AttrListTreeprocessor(Treeprocessor): + BASE_RE: str = ... + HEADER_RE: Pattern + BLOCK_RE: Pattern + INLINE_RE: Pattern + NAME_RE: Pattern + def assign_attrs(self, elem, attrs) -> None: ... + def sanitize_name(self, name): ... + +class AttrListExtension(Extension): ... + +def makeExtension(**kwargs): ... diff --git a/shared/package-files/71/710accaf531842fe4b652e44df836e99daaa78af21bdc37a76e2d14da799e86a/test_iat.py b/shared/package-files/71/710accaf531842fe4b652e44df836e99daaa78af21bdc37a76e2d14da799e86a/test_iat.py new file mode 100644 index 0000000000000000000000000000000000000000..5b8c4f2d4b9b97228eb768797b224cedffb239a8 --- /dev/null +++ b/shared/package-files/71/710accaf531842fe4b652e44df836e99daaa78af21bdc37a76e2d14da799e86a/test_iat.py @@ -0,0 +1,53 @@ +import numpy as np + +from pandas import ( + DataFrame, + Series, + period_range, +) +import pandas._testing as tm + + +def test_iat(float_frame): + for i, row in enumerate(float_frame.index): + for j, col in enumerate(float_frame.columns): + result = float_frame.iat[i, j] + expected = float_frame.at[row, col] + assert result == expected + + +def test_iat_duplicate_columns(): + # https://github.com/pandas-dev/pandas/issues/11754 + df = DataFrame([[1, 2]], columns=["x", "x"]) + assert df.iat[0, 0] == 1 + + +def test_iat_getitem_series_with_period_index(): + # GH#4390, iat incorrectly indexing + index = period_range("1/1/2001", periods=10) + ser = Series(np.random.default_rng(2).standard_normal(10), index=index) + expected = ser[index[0]] + result = ser.iat[0] + assert expected == result + + +def test_iat_setitem_item_cache_cleared( + indexer_ial, using_copy_on_write, warn_copy_on_write +): + # GH#45684 + data = {"x": np.arange(8, dtype=np.int64), "y": np.int64(0)} + df = DataFrame(data).copy() + ser = df["y"] + + # previously this iat setting would split the block and fail to clear + # the item_cache. + with tm.assert_cow_warning(warn_copy_on_write): + indexer_ial(df)[7, 0] = 9999 + + with tm.assert_cow_warning(warn_copy_on_write): + indexer_ial(df)[7, 1] = 1234 + + assert df.iat[7, 1] == 1234 + if not using_copy_on_write: + assert ser.iloc[-1] == 1234 + assert df.iloc[-1, -1] == 1234 diff --git a/shared/package-files/71/710de44c5caf70a8961c0c48e40c1c84dab154eaec22b809e9bae0ac7e365aaf/flags.py b/shared/package-files/71/710de44c5caf70a8961c0c48e40c1c84dab154eaec22b809e9bae0ac7e365aaf/flags.py new file mode 100644 index 0000000000000000000000000000000000000000..4c60be1330b789a9a727fd943a59b44c9b8b8107 --- /dev/null +++ b/shared/package-files/71/710de44c5caf70a8961c0c48e40c1c84dab154eaec22b809e9bae0ac7e365aaf/flags.py @@ -0,0 +1,123 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2001-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS Message Flags.""" + +import enum +from typing import Any + +# Standard DNS flags + + +class Flag(enum.IntFlag): + #: Query Response + QR = 0x8000 + #: Authoritative Answer + AA = 0x0400 + #: Truncated Response + TC = 0x0200 + #: Recursion Desired + RD = 0x0100 + #: Recursion Available + RA = 0x0080 + #: Authentic Data + AD = 0x0020 + #: Checking Disabled + CD = 0x0010 + + +# EDNS flags + + +class EDNSFlag(enum.IntFlag): + #: DNSSEC answer OK + DO = 0x8000 + + +def _from_text(text: str, enum_class: Any) -> int: + flags = 0 + tokens = text.split() + for t in tokens: + flags |= enum_class[t.upper()] + return flags + + +def _to_text(flags: int, enum_class: Any) -> str: + text_flags = [] + for k, v in enum_class.__members__.items(): + if flags & v != 0: + text_flags.append(k) + return " ".join(text_flags) + + +def from_text(text: str) -> int: + """Convert a space-separated list of flag text values into a flags + value. + + Returns an ``int`` + """ + + return _from_text(text, Flag) + + +def to_text(flags: int) -> str: + """Convert a flags value into a space-separated list of flag text + values. + + Returns a ``str``. + """ + + return _to_text(flags, Flag) + + +def edns_from_text(text: str) -> int: + """Convert a space-separated list of EDNS flag text values into a EDNS + flags value. + + Returns an ``int`` + """ + + return _from_text(text, EDNSFlag) + + +def edns_to_text(flags: int) -> str: + """Convert an EDNS flags value into a space-separated list of EDNS flag + text values. + + Returns a ``str``. + """ + + return _to_text(flags, EDNSFlag) + + +### BEGIN generated Flag constants + +QR = Flag.QR +AA = Flag.AA +TC = Flag.TC +RD = Flag.RD +RA = Flag.RA +AD = Flag.AD +CD = Flag.CD + +### END generated Flag constants + +### BEGIN generated EDNSFlag constants + +DO = EDNSFlag.DO + +### END generated EDNSFlag constants diff --git a/shared/package-files/71/710ee47ea556fb6ca76799cc73349d8425857e9e6593c0799e44e3a6f25b9611/_sparse_sum_backward_native.h b/shared/package-files/71/710ee47ea556fb6ca76799cc73349d8425857e9e6593c0799e44e3a6f25b9611/_sparse_sum_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..70bf2d16432e36ffee4ec288f10648b7eb2c918d --- /dev/null +++ b/shared/package-files/71/710ee47ea556fb6ca76799cc73349d8425857e9e6593c0799e44e3a6f25b9611/_sparse_sum_backward_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & _sparse_sum_backward_out(const at::Tensor & grad, const at::Tensor & self, at::IntArrayRef dim, at::Tensor & out); +TORCH_API at::Tensor _sparse_sum_backward_cpu(const at::Tensor & grad, const at::Tensor & self, at::IntArrayRef dim); +TORCH_API at::Tensor _sparse_sum_backward_cuda(const at::Tensor & grad, const at::Tensor & self, at::IntArrayRef dim); +} // namespace native +} // namespace at diff --git a/shared/package-files/71/710f4dacbfc04f5b5eee62f9cff2d6ae89d6ed1a9836fc4dace881f0c59a57a6/isreal_native.h b/shared/package-files/71/710f4dacbfc04f5b5eee62f9cff2d6ae89d6ed1a9836fc4dace881f0c59a57a6/isreal_native.h new file mode 100644 index 0000000000000000000000000000000000000000..c0ad0e51976ae300fd778f6a3504dcf7ebde5442 --- /dev/null +++ b/shared/package-files/71/710f4dacbfc04f5b5eee62f9cff2d6ae89d6ed1a9836fc4dace881f0c59a57a6/isreal_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor isreal(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/71/710fa81f3359cae5f0407fedb46c4bd67eaf30084d6c6491341ba9e7d139982a/_cufft_get_plan_cache_max_size.h b/shared/package-files/71/710fa81f3359cae5f0407fedb46c4bd67eaf30084d6c6491341ba9e7d139982a/_cufft_get_plan_cache_max_size.h new file mode 100644 index 0000000000000000000000000000000000000000..b006fbc6445fae58ff324afc6ca8e84de182987c --- /dev/null +++ b/shared/package-files/71/710fa81f3359cae5f0407fedb46c4bd67eaf30084d6c6491341ba9e7d139982a/_cufft_get_plan_cache_max_size.h @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_cufft_get_plan_cache_max_size(DeviceIndex device_index) -> int +inline int64_t _cufft_get_plan_cache_max_size(at::DeviceIndex device_index) { + return at::_ops::_cufft_get_plan_cache_max_size::call(device_index); +} + +} diff --git a/shared/package-files/71/71124b39f6be2cf232837dddd7d99f177a3d375b243329bd4ede936506a7b6d3/test_aggregate.py b/shared/package-files/71/71124b39f6be2cf232837dddd7d99f177a3d375b243329bd4ede936506a7b6d3/test_aggregate.py new file mode 100644 index 0000000000000000000000000000000000000000..f02a828fe8d1735f7014dc3437a492bb1f682506 --- /dev/null +++ b/shared/package-files/71/71124b39f6be2cf232837dddd7d99f177a3d375b243329bd4ede936506a7b6d3/test_aggregate.py @@ -0,0 +1,1672 @@ +""" +test .agg behavior / note that .apply is tested generally in test_groupby.py +""" +import datetime +import functools +from functools import partial +import re + +import numpy as np +import pytest + +from pandas.errors import SpecificationError + +from pandas.core.dtypes.common import is_integer_dtype + +import pandas as pd +from pandas import ( + DataFrame, + Index, + MultiIndex, + Series, + concat, + to_datetime, +) +import pandas._testing as tm +from pandas.core.groupby.grouper import Grouping + + +def test_groupby_agg_no_extra_calls(): + # GH#31760 + df = DataFrame({"key": ["a", "b", "c", "c"], "value": [1, 2, 3, 4]}) + gb = df.groupby("key")["value"] + + def dummy_func(x): + assert len(x) != 0 + return x.sum() + + gb.agg(dummy_func) + + +def test_agg_regression1(tsframe): + grouped = tsframe.groupby([lambda x: x.year, lambda x: x.month]) + result = grouped.agg("mean") + expected = grouped.mean() + tm.assert_frame_equal(result, expected) + + +def test_agg_must_agg(df): + grouped = df.groupby("A")["C"] + + msg = "Must produce aggregated value" + with pytest.raises(Exception, match=msg): + grouped.agg(lambda x: x.describe()) + with pytest.raises(Exception, match=msg): + grouped.agg(lambda x: x.index[:2]) + + +def test_agg_ser_multi_key(df): + f = lambda x: x.sum() + results = df.C.groupby([df.A, df.B]).aggregate(f) + expected = df.groupby(["A", "B"]).sum()["C"] + tm.assert_series_equal(results, expected) + + +def test_groupby_aggregation_mixed_dtype(): + # GH 6212 + expected = DataFrame( + { + "v1": [5, 5, 7, np.nan, 3, 3, 4, 1], + "v2": [55, 55, 77, np.nan, 33, 33, 44, 11], + }, + index=MultiIndex.from_tuples( + [ + (1, 95), + (1, 99), + (2, 95), + (2, 99), + ("big", "damp"), + ("blue", "dry"), + ("red", "red"), + ("red", "wet"), + ], + names=["by1", "by2"], + ), + ) + + df = DataFrame( + { + "v1": [1, 3, 5, 7, 8, 3, 5, np.nan, 4, 5, 7, 9], + "v2": [11, 33, 55, 77, 88, 33, 55, np.nan, 44, 55, 77, 99], + "by1": ["red", "blue", 1, 2, np.nan, "big", 1, 2, "red", 1, np.nan, 12], + "by2": [ + "wet", + "dry", + 99, + 95, + np.nan, + "damp", + 95, + 99, + "red", + 99, + np.nan, + np.nan, + ], + } + ) + + g = df.groupby(["by1", "by2"]) + result = g[["v1", "v2"]].mean() + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregation_multi_level_column(): + # GH 29772 + lst = [ + [True, True, True, False], + [True, False, np.nan, False], + [True, True, np.nan, False], + [True, True, np.nan, False], + ] + df = DataFrame( + data=lst, + columns=MultiIndex.from_tuples([("A", 0), ("A", 1), ("B", 0), ("B", 1)]), + ) + + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(level=1, axis=1) + result = gb.sum(numeric_only=False) + expected = DataFrame({0: [2.0, True, True, True], 1: [1, 0, 1, 1]}) + + tm.assert_frame_equal(result, expected) + + +def test_agg_apply_corner(ts, tsframe): + # nothing to group, all NA + grouped = ts.groupby(ts * np.nan, group_keys=False) + assert ts.dtype == np.float64 + + # groupby float64 values results in a float64 Index + exp = Series([], dtype=np.float64, index=Index([], dtype=np.float64)) + tm.assert_series_equal(grouped.sum(), exp) + tm.assert_series_equal(grouped.agg("sum"), exp) + tm.assert_series_equal(grouped.apply("sum"), exp, check_index_type=False) + + # DataFrame + grouped = tsframe.groupby(tsframe["A"] * np.nan, group_keys=False) + exp_df = DataFrame( + columns=tsframe.columns, + dtype=float, + index=Index([], name="A", dtype=np.float64), + ) + tm.assert_frame_equal(grouped.sum(), exp_df) + tm.assert_frame_equal(grouped.agg("sum"), exp_df) + + msg = "The behavior of DataFrame.sum with axis=None is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False): + res = grouped.apply(np.sum) + tm.assert_frame_equal(res, exp_df) + + +def test_agg_grouping_is_list_tuple(ts): + df = DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=30, freq="B"), + ) + + grouped = df.groupby(lambda x: x.year) + grouper = grouped._grouper.groupings[0].grouping_vector + grouped._grouper.groupings[0] = Grouping(ts.index, list(grouper)) + + result = grouped.agg("mean") + expected = grouped.mean() + tm.assert_frame_equal(result, expected) + + grouped._grouper.groupings[0] = Grouping(ts.index, tuple(grouper)) + + result = grouped.agg("mean") + expected = grouped.mean() + tm.assert_frame_equal(result, expected) + + +def test_agg_python_multiindex(multiindex_dataframe_random_data): + grouped = multiindex_dataframe_random_data.groupby(["A", "B"]) + + result = grouped.agg("mean") + expected = grouped.mean() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "groupbyfunc", [lambda x: x.weekday(), [lambda x: x.month, lambda x: x.weekday()]] +) +def test_aggregate_str_func(tsframe, groupbyfunc): + grouped = tsframe.groupby(groupbyfunc) + + # single series + result = grouped["A"].agg("std") + expected = grouped["A"].std() + tm.assert_series_equal(result, expected) + + # group frame by function name + result = grouped.aggregate("var") + expected = grouped.var() + tm.assert_frame_equal(result, expected) + + # group frame by function dict + result = grouped.agg({"A": "var", "B": "std", "C": "mean", "D": "sem"}) + expected = DataFrame( + { + "A": grouped["A"].var(), + "B": grouped["B"].std(), + "C": grouped["C"].mean(), + "D": grouped["D"].sem(), + } + ) + tm.assert_frame_equal(result, expected) + + +def test_std_masked_dtype(any_numeric_ea_dtype): + # GH#35516 + df = DataFrame( + { + "a": [2, 1, 1, 1, 2, 2, 1], + "b": Series([pd.NA, 1, 2, 1, 1, 1, 2], dtype="Float64"), + } + ) + result = df.groupby("a").std() + expected = DataFrame( + {"b": [0.57735, 0]}, index=Index([1, 2], name="a"), dtype="Float64" + ) + tm.assert_frame_equal(result, expected) + + +def test_agg_str_with_kwarg_axis_1_raises(df, reduction_func): + gb = df.groupby(level=0) + warn_msg = f"DataFrameGroupBy.{reduction_func} with axis=1 is deprecated" + if reduction_func in ("idxmax", "idxmin"): + error = TypeError + msg = "'[<>]' not supported between instances of 'float' and 'str'" + warn = FutureWarning + else: + error = ValueError + msg = f"Operation {reduction_func} does not support axis=1" + warn = None + with pytest.raises(error, match=msg): + with tm.assert_produces_warning(warn, match=warn_msg): + gb.agg(reduction_func, axis=1) + + +@pytest.mark.parametrize( + "func, expected, dtype, result_dtype_dict", + [ + ("sum", [5, 7, 9], "int64", {}), + ("std", [4.5**0.5] * 3, int, {"i": float, "j": float, "k": float}), + ("var", [4.5] * 3, int, {"i": float, "j": float, "k": float}), + ("sum", [5, 7, 9], "Int64", {"j": "int64"}), + ("std", [4.5**0.5] * 3, "Int64", {"i": float, "j": float, "k": float}), + ("var", [4.5] * 3, "Int64", {"i": "float64", "j": "float64", "k": "float64"}), + ], +) +def test_multiindex_groupby_mixed_cols_axis1(func, expected, dtype, result_dtype_dict): + # GH#43209 + df = DataFrame( + [[1, 2, 3, 4, 5, 6]] * 3, + columns=MultiIndex.from_product([["a", "b"], ["i", "j", "k"]]), + ).astype({("a", "j"): dtype, ("b", "j"): dtype}) + + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(level=1, axis=1) + result = gb.agg(func) + expected = DataFrame([expected] * 3, columns=["i", "j", "k"]).astype( + result_dtype_dict + ) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "func, expected_data, result_dtype_dict", + [ + ("sum", [[2, 4], [10, 12], [18, 20]], {10: "int64", 20: "int64"}), + # std should ideally return Int64 / Float64 #43330 + ("std", [[2**0.5] * 2] * 3, "float64"), + ("var", [[2] * 2] * 3, {10: "float64", 20: "float64"}), + ], +) +def test_groupby_mixed_cols_axis1(func, expected_data, result_dtype_dict): + # GH#43209 + df = DataFrame( + np.arange(12).reshape(3, 4), + index=Index([0, 1, 0], name="y"), + columns=Index([10, 20, 10, 20], name="x"), + dtype="int64", + ).astype({10: "Int64"}) + + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby("x", axis=1) + result = gb.agg(func) + expected = DataFrame( + data=expected_data, + index=Index([0, 1, 0], name="y"), + columns=Index([10, 20], name="x"), + ).astype(result_dtype_dict) + tm.assert_frame_equal(result, expected) + + +def test_aggregate_item_by_item(df): + grouped = df.groupby("A") + + aggfun_0 = lambda ser: ser.size + result = grouped.agg(aggfun_0) + foosum = (df.A == "foo").sum() + barsum = (df.A == "bar").sum() + K = len(result.columns) + + # GH5782 + exp = Series(np.array([foosum] * K), index=list("BCD"), name="foo") + tm.assert_series_equal(result.xs("foo"), exp) + + exp = Series(np.array([barsum] * K), index=list("BCD"), name="bar") + tm.assert_almost_equal(result.xs("bar"), exp) + + def aggfun_1(ser): + return ser.size + + result = DataFrame().groupby(df.A).agg(aggfun_1) + assert isinstance(result, DataFrame) + assert len(result) == 0 + + +def test_wrap_agg_out(three_group): + grouped = three_group.groupby(["A", "B"]) + + def func(ser): + if ser.dtype in (object, "string"): + raise TypeError("Test error message") + return ser.sum() + + with pytest.raises(TypeError, match="Test error message"): + grouped.aggregate(func) + result = grouped[["D", "E", "F"]].aggregate(func) + exp_grouped = three_group.loc[:, ["A", "B", "D", "E", "F"]] + expected = exp_grouped.groupby(["A", "B"]).aggregate(func) + tm.assert_frame_equal(result, expected) + + +def test_agg_multiple_functions_maintain_order(df): + # GH #610 + funcs = [("mean", np.mean), ("max", np.max), ("min", np.min)] + msg = "is currently using SeriesGroupBy.mean" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A")["C"].agg(funcs) + exp_cols = Index(["mean", "max", "min"]) + + tm.assert_index_equal(result.columns, exp_cols) + + +def test_series_index_name(df): + grouped = df.loc[:, ["C"]].groupby(df["A"]) + result = grouped.agg(lambda x: x.mean()) + assert result.index.name == "A" + + +def test_agg_multiple_functions_same_name(): + # GH 30880 + df = DataFrame( + np.random.default_rng(2).standard_normal((1000, 3)), + index=pd.date_range("1/1/2012", freq="s", periods=1000), + columns=["A", "B", "C"], + ) + result = df.resample("3min").agg( + {"A": [partial(np.quantile, q=0.9999), partial(np.quantile, q=0.1111)]} + ) + expected_index = pd.date_range("1/1/2012", freq="3min", periods=6) + expected_columns = MultiIndex.from_tuples([("A", "quantile"), ("A", "quantile")]) + expected_values = np.array( + [df.resample("3min").A.quantile(q=q).values for q in [0.9999, 0.1111]] + ).T + expected = DataFrame( + expected_values, columns=expected_columns, index=expected_index + ) + tm.assert_frame_equal(result, expected) + + +def test_agg_multiple_functions_same_name_with_ohlc_present(): + # GH 30880 + # ohlc expands dimensions, so different test to the above is required. + df = DataFrame( + np.random.default_rng(2).standard_normal((1000, 3)), + index=pd.date_range("1/1/2012", freq="s", periods=1000, name="dti"), + columns=Index(["A", "B", "C"], name="alpha"), + ) + result = df.resample("3min").agg( + {"A": ["ohlc", partial(np.quantile, q=0.9999), partial(np.quantile, q=0.1111)]} + ) + expected_index = pd.date_range("1/1/2012", freq="3min", periods=6, name="dti") + expected_columns = MultiIndex.from_tuples( + [ + ("A", "ohlc", "open"), + ("A", "ohlc", "high"), + ("A", "ohlc", "low"), + ("A", "ohlc", "close"), + ("A", "quantile", "A"), + ("A", "quantile", "A"), + ], + names=["alpha", None, None], + ) + non_ohlc_expected_values = np.array( + [df.resample("3min").A.quantile(q=q).values for q in [0.9999, 0.1111]] + ).T + expected_values = np.hstack( + [df.resample("3min").A.ohlc(), non_ohlc_expected_values] + ) + expected = DataFrame( + expected_values, columns=expected_columns, index=expected_index + ) + tm.assert_frame_equal(result, expected) + + +def test_multiple_functions_tuples_and_non_tuples(df): + # #1359 + # Columns B and C would cause partial failure + df = df.drop(columns=["B", "C"]) + + funcs = [("foo", "mean"), "std"] + ex_funcs = [("foo", "mean"), ("std", "std")] + + result = df.groupby("A")["D"].agg(funcs) + expected = df.groupby("A")["D"].agg(ex_funcs) + tm.assert_frame_equal(result, expected) + + result = df.groupby("A").agg(funcs) + expected = df.groupby("A").agg(ex_funcs) + tm.assert_frame_equal(result, expected) + + +def test_more_flexible_frame_multi_function(df): + grouped = df.groupby("A") + + exmean = grouped.agg({"C": "mean", "D": "mean"}) + exstd = grouped.agg({"C": "std", "D": "std"}) + + expected = concat([exmean, exstd], keys=["mean", "std"], axis=1) + expected = expected.swaplevel(0, 1, axis=1).sort_index(level=0, axis=1) + + d = {"C": ["mean", "std"], "D": ["mean", "std"]} + result = grouped.aggregate(d) + + tm.assert_frame_equal(result, expected) + + # be careful + result = grouped.aggregate({"C": "mean", "D": ["mean", "std"]}) + expected = grouped.aggregate({"C": "mean", "D": ["mean", "std"]}) + tm.assert_frame_equal(result, expected) + + def numpymean(x): + return np.mean(x) + + def numpystd(x): + return np.std(x, ddof=1) + + # this uses column selection & renaming + msg = r"nested renamer is not supported" + with pytest.raises(SpecificationError, match=msg): + d = {"C": "mean", "D": {"foo": "mean", "bar": "std"}} + grouped.aggregate(d) + + # But without renaming, these functions are OK + d = {"C": ["mean"], "D": [numpymean, numpystd]} + grouped.aggregate(d) + + +def test_multi_function_flexible_mix(df): + # GH #1268 + grouped = df.groupby("A") + + # Expected + d = {"C": {"foo": "mean", "bar": "std"}, "D": {"sum": "sum"}} + # this uses column selection & renaming + msg = r"nested renamer is not supported" + with pytest.raises(SpecificationError, match=msg): + grouped.aggregate(d) + + # Test 1 + d = {"C": {"foo": "mean", "bar": "std"}, "D": "sum"} + # this uses column selection & renaming + with pytest.raises(SpecificationError, match=msg): + grouped.aggregate(d) + + # Test 2 + d = {"C": {"foo": "mean", "bar": "std"}, "D": "sum"} + # this uses column selection & renaming + with pytest.raises(SpecificationError, match=msg): + grouped.aggregate(d) + + +def test_groupby_agg_coercing_bools(): + # issue 14873 + dat = DataFrame({"a": [1, 1, 2, 2], "b": [0, 1, 2, 3], "c": [None, None, 1, 1]}) + gp = dat.groupby("a") + + index = Index([1, 2], name="a") + + result = gp["b"].aggregate(lambda x: (x != 0).all()) + expected = Series([False, True], index=index, name="b") + tm.assert_series_equal(result, expected) + + result = gp["c"].aggregate(lambda x: x.isnull().all()) + expected = Series([True, False], index=index, name="c") + tm.assert_series_equal(result, expected) + + +def test_groupby_agg_dict_with_getitem(): + # issue 25471 + dat = DataFrame({"A": ["A", "A", "B", "B", "B"], "B": [1, 2, 1, 1, 2]}) + result = dat.groupby("A")[["B"]].agg({"B": "sum"}) + + expected = DataFrame({"B": [3, 4]}, index=["A", "B"]).rename_axis("A", axis=0) + + tm.assert_frame_equal(result, expected) + + +def test_groupby_agg_dict_dup_columns(): + # GH#55006 + df = DataFrame( + [[1, 2, 3, 4], [1, 3, 4, 5], [2, 4, 5, 6]], + columns=["a", "b", "c", "c"], + ) + gb = df.groupby("a") + result = gb.agg({"b": "sum"}) + expected = DataFrame({"b": [5, 4]}, index=Index([1, 2], name="a")) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "op", + [ + lambda x: x.sum(), + lambda x: x.cumsum(), + lambda x: x.transform("sum"), + lambda x: x.transform("cumsum"), + lambda x: x.agg("sum"), + lambda x: x.agg("cumsum"), + ], +) +def test_bool_agg_dtype(op): + # GH 7001 + # Bool sum aggregations result in int + df = DataFrame({"a": [1, 1], "b": [False, True]}) + s = df.set_index("a")["b"] + + result = op(df.groupby("a"))["b"].dtype + assert is_integer_dtype(result) + + result = op(s.groupby("a")).dtype + assert is_integer_dtype(result) + + +@pytest.mark.parametrize( + "keys, agg_index", + [ + (["a"], Index([1], name="a")), + (["a", "b"], MultiIndex([[1], [2]], [[0], [0]], names=["a", "b"])), + ], +) +@pytest.mark.parametrize( + "input_dtype", ["bool", "int32", "int64", "float32", "float64"] +) +@pytest.mark.parametrize( + "result_dtype", ["bool", "int32", "int64", "float32", "float64"] +) +@pytest.mark.parametrize("method", ["apply", "aggregate", "transform"]) +def test_callable_result_dtype_frame( + keys, agg_index, input_dtype, result_dtype, method +): + # GH 21240 + df = DataFrame({"a": [1], "b": [2], "c": [True]}) + df["c"] = df["c"].astype(input_dtype) + op = getattr(df.groupby(keys)[["c"]], method) + result = op(lambda x: x.astype(result_dtype).iloc[0]) + expected_index = pd.RangeIndex(0, 1) if method == "transform" else agg_index + expected = DataFrame({"c": [df["c"].iloc[0]]}, index=expected_index).astype( + result_dtype + ) + if method == "apply": + expected.columns.names = [0] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "keys, agg_index", + [ + (["a"], Index([1], name="a")), + (["a", "b"], MultiIndex([[1], [2]], [[0], [0]], names=["a", "b"])), + ], +) +@pytest.mark.parametrize("input", [True, 1, 1.0]) +@pytest.mark.parametrize("dtype", [bool, int, float]) +@pytest.mark.parametrize("method", ["apply", "aggregate", "transform"]) +def test_callable_result_dtype_series(keys, agg_index, input, dtype, method): + # GH 21240 + df = DataFrame({"a": [1], "b": [2], "c": [input]}) + op = getattr(df.groupby(keys)["c"], method) + result = op(lambda x: x.astype(dtype).iloc[0]) + expected_index = pd.RangeIndex(0, 1) if method == "transform" else agg_index + expected = Series([df["c"].iloc[0]], index=expected_index, name="c").astype(dtype) + tm.assert_series_equal(result, expected) + + +def test_order_aggregate_multiple_funcs(): + # GH 25692 + df = DataFrame({"A": [1, 1, 2, 2], "B": [1, 2, 3, 4]}) + + res = df.groupby("A").agg(["sum", "max", "mean", "ohlc", "min"]) + result = res.columns.levels[1] + + expected = Index(["sum", "max", "mean", "ohlc", "min"]) + + tm.assert_index_equal(result, expected) + + +def test_ohlc_ea_dtypes(any_numeric_ea_dtype): + # GH#37493 + df = DataFrame( + {"a": [1, 1, 2, 3, 4, 4], "b": [22, 11, pd.NA, 10, 20, pd.NA]}, + dtype=any_numeric_ea_dtype, + ) + gb = df.groupby("a") + result = gb.ohlc() + expected = DataFrame( + [[22, 22, 11, 11], [pd.NA] * 4, [10] * 4, [20] * 4], + columns=MultiIndex.from_product([["b"], ["open", "high", "low", "close"]]), + index=Index([1, 2, 3, 4], dtype=any_numeric_ea_dtype, name="a"), + dtype=any_numeric_ea_dtype, + ) + tm.assert_frame_equal(result, expected) + + gb2 = df.groupby("a", as_index=False) + result2 = gb2.ohlc() + expected2 = expected.reset_index() + tm.assert_frame_equal(result2, expected2) + + +@pytest.mark.parametrize("dtype", [np.int64, np.uint64]) +@pytest.mark.parametrize("how", ["first", "last", "min", "max", "mean", "median"]) +def test_uint64_type_handling(dtype, how): + # GH 26310 + df = DataFrame({"x": 6903052872240755750, "y": [1, 2]}) + expected = df.groupby("y").agg({"x": how}) + df.x = df.x.astype(dtype) + result = df.groupby("y").agg({"x": how}) + if how not in ("mean", "median"): + # mean and median always result in floats + result.x = result.x.astype(np.int64) + tm.assert_frame_equal(result, expected, check_exact=True) + + +def test_func_duplicates_raises(): + # GH28426 + msg = "Function names" + df = DataFrame({"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]}) + with pytest.raises(SpecificationError, match=msg): + df.groupby("A").agg(["min", "min"]) + + +@pytest.mark.parametrize( + "index", + [ + pd.CategoricalIndex(list("abc")), + pd.interval_range(0, 3), + pd.period_range("2020", periods=3, freq="D"), + MultiIndex.from_tuples([("a", 0), ("a", 1), ("b", 0)]), + ], +) +def test_agg_index_has_complex_internals(index): + # GH 31223 + df = DataFrame({"group": [1, 1, 2], "value": [0, 1, 0]}, index=index) + result = df.groupby("group").agg({"value": Series.nunique}) + expected = DataFrame({"group": [1, 2], "value": [2, 1]}).set_index("group") + tm.assert_frame_equal(result, expected) + + +def test_agg_split_block(): + # https://github.com/pandas-dev/pandas/issues/31522 + df = DataFrame( + { + "key1": ["a", "a", "b", "b", "a"], + "key2": ["one", "two", "one", "two", "one"], + "key3": ["three", "three", "three", "six", "six"], + } + ) + result = df.groupby("key1").min() + expected = DataFrame( + {"key2": ["one", "one"], "key3": ["six", "six"]}, + index=Index(["a", "b"], name="key1"), + ) + tm.assert_frame_equal(result, expected) + + +def test_agg_split_object_part_datetime(): + # https://github.com/pandas-dev/pandas/pull/31616 + df = DataFrame( + { + "A": pd.date_range("2000", periods=4), + "B": ["a", "b", "c", "d"], + "C": [1, 2, 3, 4], + "D": ["b", "c", "d", "e"], + "E": pd.date_range("2000", periods=4), + "F": [1, 2, 3, 4], + } + ).astype(object) + result = df.groupby([0, 0, 0, 0]).min() + expected = DataFrame( + { + "A": [pd.Timestamp("2000")], + "B": ["a"], + "C": [1], + "D": ["b"], + "E": [pd.Timestamp("2000")], + "F": [1], + }, + index=np.array([0]), + dtype=object, + ) + tm.assert_frame_equal(result, expected) + + +class TestNamedAggregationSeries: + def test_series_named_agg(self): + df = Series([1, 2, 3, 4]) + gr = df.groupby([0, 0, 1, 1]) + result = gr.agg(a="sum", b="min") + expected = DataFrame( + {"a": [3, 7], "b": [1, 3]}, columns=["a", "b"], index=np.array([0, 1]) + ) + tm.assert_frame_equal(result, expected) + + result = gr.agg(b="min", a="sum") + expected = expected[["b", "a"]] + tm.assert_frame_equal(result, expected) + + def test_no_args_raises(self): + gr = Series([1, 2]).groupby([0, 1]) + with pytest.raises(TypeError, match="Must provide"): + gr.agg() + + # but we do allow this + result = gr.agg([]) + expected = DataFrame(columns=[]) + tm.assert_frame_equal(result, expected) + + def test_series_named_agg_duplicates_no_raises(self): + # GH28426 + gr = Series([1, 2, 3]).groupby([0, 0, 1]) + grouped = gr.agg(a="sum", b="sum") + expected = DataFrame({"a": [3, 3], "b": [3, 3]}, index=np.array([0, 1])) + tm.assert_frame_equal(expected, grouped) + + def test_mangled(self): + gr = Series([1, 2, 3]).groupby([0, 0, 1]) + result = gr.agg(a=lambda x: 0, b=lambda x: 1) + expected = DataFrame({"a": [0, 0], "b": [1, 1]}, index=np.array([0, 1])) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "inp", + [ + pd.NamedAgg(column="anything", aggfunc="min"), + ("anything", "min"), + ["anything", "min"], + ], + ) + def test_named_agg_nametuple(self, inp): + # GH34422 + s = Series([1, 1, 2, 2, 3, 3, 4, 5]) + msg = f"func is expected but received {type(inp).__name__}" + with pytest.raises(TypeError, match=msg): + s.groupby(s.values).agg(a=inp) + + +class TestNamedAggregationDataFrame: + def test_agg_relabel(self): + df = DataFrame( + {"group": ["a", "a", "b", "b"], "A": [0, 1, 2, 3], "B": [5, 6, 7, 8]} + ) + result = df.groupby("group").agg(a_max=("A", "max"), b_max=("B", "max")) + expected = DataFrame( + {"a_max": [1, 3], "b_max": [6, 8]}, + index=Index(["a", "b"], name="group"), + columns=["a_max", "b_max"], + ) + tm.assert_frame_equal(result, expected) + + # order invariance + p98 = functools.partial(np.percentile, q=98) + result = df.groupby("group").agg( + b_min=("B", "min"), + a_min=("A", "min"), + a_mean=("A", "mean"), + a_max=("A", "max"), + b_max=("B", "max"), + a_98=("A", p98), + ) + expected = DataFrame( + { + "b_min": [5, 7], + "a_min": [0, 2], + "a_mean": [0.5, 2.5], + "a_max": [1, 3], + "b_max": [6, 8], + "a_98": [0.98, 2.98], + }, + index=Index(["a", "b"], name="group"), + columns=["b_min", "a_min", "a_mean", "a_max", "b_max", "a_98"], + ) + tm.assert_frame_equal(result, expected) + + def test_agg_relabel_non_identifier(self): + df = DataFrame( + {"group": ["a", "a", "b", "b"], "A": [0, 1, 2, 3], "B": [5, 6, 7, 8]} + ) + + result = df.groupby("group").agg(**{"my col": ("A", "max")}) + expected = DataFrame({"my col": [1, 3]}, index=Index(["a", "b"], name="group")) + tm.assert_frame_equal(result, expected) + + def test_duplicate_no_raises(self): + # GH 28426, if use same input function on same column, + # no error should raise + df = DataFrame({"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]}) + + grouped = df.groupby("A").agg(a=("B", "min"), b=("B", "min")) + expected = DataFrame({"a": [1, 3], "b": [1, 3]}, index=Index([0, 1], name="A")) + tm.assert_frame_equal(grouped, expected) + + quant50 = functools.partial(np.percentile, q=50) + quant70 = functools.partial(np.percentile, q=70) + quant50.__name__ = "quant50" + quant70.__name__ = "quant70" + + test = DataFrame({"col1": ["a", "a", "b", "b", "b"], "col2": [1, 2, 3, 4, 5]}) + + grouped = test.groupby("col1").agg( + quantile_50=("col2", quant50), quantile_70=("col2", quant70) + ) + expected = DataFrame( + {"quantile_50": [1.5, 4.0], "quantile_70": [1.7, 4.4]}, + index=Index(["a", "b"], name="col1"), + ) + tm.assert_frame_equal(grouped, expected) + + def test_agg_relabel_with_level(self): + df = DataFrame( + {"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]}, + index=MultiIndex.from_product([["A", "B"], ["a", "b"]]), + ) + result = df.groupby(level=0).agg( + aa=("A", "max"), bb=("A", "min"), cc=("B", "mean") + ) + expected = DataFrame( + {"aa": [0, 1], "bb": [0, 1], "cc": [1.5, 3.5]}, index=["A", "B"] + ) + tm.assert_frame_equal(result, expected) + + def test_agg_relabel_other_raises(self): + df = DataFrame({"A": [0, 0, 1], "B": [1, 2, 3]}) + grouped = df.groupby("A") + match = "Must provide" + with pytest.raises(TypeError, match=match): + grouped.agg(foo=1) + + with pytest.raises(TypeError, match=match): + grouped.agg() + + with pytest.raises(TypeError, match=match): + grouped.agg(a=("B", "max"), b=(1, 2, 3)) + + def test_missing_raises(self): + df = DataFrame({"A": [0, 1], "B": [1, 2]}) + match = re.escape("Column(s) ['C'] do not exist") + with pytest.raises(KeyError, match=match): + df.groupby("A").agg(c=("C", "sum")) + + def test_agg_namedtuple(self): + df = DataFrame({"A": [0, 1], "B": [1, 2]}) + result = df.groupby("A").agg( + b=pd.NamedAgg("B", "sum"), c=pd.NamedAgg(column="B", aggfunc="count") + ) + expected = df.groupby("A").agg(b=("B", "sum"), c=("B", "count")) + tm.assert_frame_equal(result, expected) + + def test_mangled(self): + df = DataFrame({"A": [0, 1], "B": [1, 2], "C": [3, 4]}) + result = df.groupby("A").agg(b=("B", lambda x: 0), c=("C", lambda x: 1)) + expected = DataFrame({"b": [0, 0], "c": [1, 1]}, index=Index([0, 1], name="A")) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "agg_col1, agg_col2, agg_col3, agg_result1, agg_result2, agg_result3", + [ + ( + (("y", "A"), "max"), + (("y", "A"), np.mean), + (("y", "B"), "mean"), + [1, 3], + [0.5, 2.5], + [5.5, 7.5], + ), + ( + (("y", "A"), lambda x: max(x)), + (("y", "A"), lambda x: 1), + (("y", "B"), np.mean), + [1, 3], + [1, 1], + [5.5, 7.5], + ), + ( + pd.NamedAgg(("y", "A"), "max"), + pd.NamedAgg(("y", "B"), np.mean), + pd.NamedAgg(("y", "A"), lambda x: 1), + [1, 3], + [5.5, 7.5], + [1, 1], + ), + ], +) +def test_agg_relabel_multiindex_column( + agg_col1, agg_col2, agg_col3, agg_result1, agg_result2, agg_result3 +): + # GH 29422, add tests for multiindex column cases + df = DataFrame( + {"group": ["a", "a", "b", "b"], "A": [0, 1, 2, 3], "B": [5, 6, 7, 8]} + ) + df.columns = MultiIndex.from_tuples([("x", "group"), ("y", "A"), ("y", "B")]) + idx = Index(["a", "b"], name=("x", "group")) + + result = df.groupby(("x", "group")).agg(a_max=(("y", "A"), "max")) + expected = DataFrame({"a_max": [1, 3]}, index=idx) + tm.assert_frame_equal(result, expected) + + msg = "is currently using SeriesGroupBy.mean" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby(("x", "group")).agg( + col_1=agg_col1, col_2=agg_col2, col_3=agg_col3 + ) + expected = DataFrame( + {"col_1": agg_result1, "col_2": agg_result2, "col_3": agg_result3}, index=idx + ) + tm.assert_frame_equal(result, expected) + + +def test_agg_relabel_multiindex_raises_not_exist(): + # GH 29422, add test for raises scenario when aggregate column does not exist + df = DataFrame( + {"group": ["a", "a", "b", "b"], "A": [0, 1, 2, 3], "B": [5, 6, 7, 8]} + ) + df.columns = MultiIndex.from_tuples([("x", "group"), ("y", "A"), ("y", "B")]) + + with pytest.raises(KeyError, match="do not exist"): + df.groupby(("x", "group")).agg(a=(("Y", "a"), "max")) + + +def test_agg_relabel_multiindex_duplicates(): + # GH29422, add test for raises scenario when getting duplicates + # GH28426, after this change, duplicates should also work if the relabelling is + # different + df = DataFrame( + {"group": ["a", "a", "b", "b"], "A": [0, 1, 2, 3], "B": [5, 6, 7, 8]} + ) + df.columns = MultiIndex.from_tuples([("x", "group"), ("y", "A"), ("y", "B")]) + + result = df.groupby(("x", "group")).agg( + a=(("y", "A"), "min"), b=(("y", "A"), "min") + ) + idx = Index(["a", "b"], name=("x", "group")) + expected = DataFrame({"a": [0, 2], "b": [0, 2]}, index=idx) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("kwargs", [{"c": ["min"]}, {"b": [], "c": ["min"]}]) +def test_groupby_aggregate_empty_key(kwargs): + # GH: 32580 + df = DataFrame({"a": [1, 1, 2], "b": [1, 2, 3], "c": [1, 2, 4]}) + result = df.groupby("a").agg(kwargs) + expected = DataFrame( + [1, 4], + index=Index([1, 2], dtype="int64", name="a"), + columns=MultiIndex.from_tuples([["c", "min"]]), + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregate_empty_key_empty_return(): + # GH: 32580 Check if everything works, when return is empty + df = DataFrame({"a": [1, 1, 2], "b": [1, 2, 3], "c": [1, 2, 4]}) + result = df.groupby("a").agg({"b": []}) + expected = DataFrame(columns=MultiIndex(levels=[["b"], []], codes=[[], []])) + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregate_empty_with_multiindex_frame(): + # GH 39178 + df = DataFrame(columns=["a", "b", "c"]) + result = df.groupby(["a", "b"], group_keys=False).agg(d=("c", list)) + expected = DataFrame( + columns=["d"], index=MultiIndex([[], []], [[], []], names=["a", "b"]) + ) + tm.assert_frame_equal(result, expected) + + +def test_grouby_agg_loses_results_with_as_index_false_relabel(): + # GH 32240: When the aggregate function relabels column names and + # as_index=False is specified, the results are dropped. + + df = DataFrame( + {"key": ["x", "y", "z", "x", "y", "z"], "val": [1.0, 0.8, 2.0, 3.0, 3.6, 0.75]} + ) + + grouped = df.groupby("key", as_index=False) + result = grouped.agg(min_val=pd.NamedAgg(column="val", aggfunc="min")) + expected = DataFrame({"key": ["x", "y", "z"], "min_val": [1.0, 0.8, 0.75]}) + tm.assert_frame_equal(result, expected) + + +def test_grouby_agg_loses_results_with_as_index_false_relabel_multiindex(): + # GH 32240: When the aggregate function relabels column names and + # as_index=False is specified, the results are dropped. Check if + # multiindex is returned in the right order + + df = DataFrame( + { + "key": ["x", "y", "x", "y", "x", "x"], + "key1": ["a", "b", "c", "b", "a", "c"], + "val": [1.0, 0.8, 2.0, 3.0, 3.6, 0.75], + } + ) + + grouped = df.groupby(["key", "key1"], as_index=False) + result = grouped.agg(min_val=pd.NamedAgg(column="val", aggfunc="min")) + expected = DataFrame( + {"key": ["x", "x", "y"], "key1": ["a", "c", "b"], "min_val": [1.0, 0.75, 0.8]} + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "func", [lambda s: s.mean(), lambda s: np.mean(s), lambda s: np.nanmean(s)] +) +def test_multiindex_custom_func(func): + # GH 31777 + data = [[1, 4, 2], [5, 7, 1]] + df = DataFrame( + data, + columns=MultiIndex.from_arrays( + [[1, 1, 2], [3, 4, 3]], names=["Sisko", "Janeway"] + ), + ) + result = df.groupby(np.array([0, 1])).agg(func) + expected_dict = { + (1, 3): {0: 1.0, 1: 5.0}, + (1, 4): {0: 4.0, 1: 7.0}, + (2, 3): {0: 2.0, 1: 1.0}, + } + expected = DataFrame(expected_dict, index=np.array([0, 1]), columns=df.columns) + tm.assert_frame_equal(result, expected) + + +def myfunc(s): + return np.percentile(s, q=0.90) + + +@pytest.mark.parametrize("func", [lambda s: np.percentile(s, q=0.90), myfunc]) +def test_lambda_named_agg(func): + # see gh-28467 + animals = DataFrame( + { + "kind": ["cat", "dog", "cat", "dog"], + "height": [9.1, 6.0, 9.5, 34.0], + "weight": [7.9, 7.5, 9.9, 198.0], + } + ) + + result = animals.groupby("kind").agg( + mean_height=("height", "mean"), perc90=("height", func) + ) + expected = DataFrame( + [[9.3, 9.1036], [20.0, 6.252]], + columns=["mean_height", "perc90"], + index=Index(["cat", "dog"], name="kind"), + ) + + tm.assert_frame_equal(result, expected) + + +def test_aggregate_mixed_types(): + # GH 16916 + df = DataFrame( + data=np.array([0] * 9).reshape(3, 3), columns=list("XYZ"), index=list("abc") + ) + df["grouping"] = ["group 1", "group 1", 2] + result = df.groupby("grouping").aggregate(lambda x: x.tolist()) + expected_data = [[[0], [0], [0]], [[0, 0], [0, 0], [0, 0]]] + expected = DataFrame( + expected_data, + index=Index([2, "group 1"], dtype="object", name="grouping"), + columns=Index(["X", "Y", "Z"]), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.xfail(reason="Not implemented;see GH 31256") +def test_aggregate_udf_na_extension_type(): + # https://github.com/pandas-dev/pandas/pull/31359 + # This is currently failing to cast back to Int64Dtype. + # The presence of the NA causes two problems + # 1. NA is not an instance of Int64Dtype.type (numpy.int64) + # 2. The presence of an NA forces object type, so the non-NA values is + # a Python int rather than a NumPy int64. Python ints aren't + # instances of numpy.int64. + def aggfunc(x): + if all(x > 2): + return 1 + else: + return pd.NA + + df = DataFrame({"A": pd.array([1, 2, 3])}) + result = df.groupby([1, 1, 2]).agg(aggfunc) + expected = DataFrame({"A": pd.array([1, pd.NA], dtype="Int64")}, index=[1, 2]) + tm.assert_frame_equal(result, expected) + + +class TestLambdaMangling: + def test_basic(self): + df = DataFrame({"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]}) + result = df.groupby("A").agg({"B": [lambda x: 0, lambda x: 1]}) + + expected = DataFrame( + {("B", ""): [0, 0], ("B", ""): [1, 1]}, + index=Index([0, 1], name="A"), + ) + tm.assert_frame_equal(result, expected) + + def test_mangle_series_groupby(self): + gr = Series([1, 2, 3, 4]).groupby([0, 0, 1, 1]) + result = gr.agg([lambda x: 0, lambda x: 1]) + exp_data = {"": [0, 0], "": [1, 1]} + expected = DataFrame(exp_data, index=np.array([0, 1])) + tm.assert_frame_equal(result, expected) + + @pytest.mark.xfail(reason="GH-26611. kwargs for multi-agg.") + def test_with_kwargs(self): + f1 = lambda x, y, b=1: x.sum() + y + b + f2 = lambda x, y, b=2: x.sum() + y * b + result = Series([1, 2]).groupby([0, 0]).agg([f1, f2], 0) + expected = DataFrame({"": [4], "": [6]}) + tm.assert_frame_equal(result, expected) + + result = Series([1, 2]).groupby([0, 0]).agg([f1, f2], 0, b=10) + expected = DataFrame({"": [13], "": [30]}) + tm.assert_frame_equal(result, expected) + + def test_agg_with_one_lambda(self): + # GH 25719, write tests for DataFrameGroupby.agg with only one lambda + df = DataFrame( + { + "kind": ["cat", "dog", "cat", "dog"], + "height": [9.1, 6.0, 9.5, 34.0], + "weight": [7.9, 7.5, 9.9, 198.0], + } + ) + + columns = ["height_sqr_min", "height_max", "weight_max"] + expected = DataFrame( + { + "height_sqr_min": [82.81, 36.00], + "height_max": [9.5, 34.0], + "weight_max": [9.9, 198.0], + }, + index=Index(["cat", "dog"], name="kind"), + columns=columns, + ) + + # check pd.NameAgg case + result1 = df.groupby(by="kind").agg( + height_sqr_min=pd.NamedAgg( + column="height", aggfunc=lambda x: np.min(x**2) + ), + height_max=pd.NamedAgg(column="height", aggfunc="max"), + weight_max=pd.NamedAgg(column="weight", aggfunc="max"), + ) + tm.assert_frame_equal(result1, expected) + + # check agg(key=(col, aggfunc)) case + result2 = df.groupby(by="kind").agg( + height_sqr_min=("height", lambda x: np.min(x**2)), + height_max=("height", "max"), + weight_max=("weight", "max"), + ) + tm.assert_frame_equal(result2, expected) + + def test_agg_multiple_lambda(self): + # GH25719, test for DataFrameGroupby.agg with multiple lambdas + # with mixed aggfunc + df = DataFrame( + { + "kind": ["cat", "dog", "cat", "dog"], + "height": [9.1, 6.0, 9.5, 34.0], + "weight": [7.9, 7.5, 9.9, 198.0], + } + ) + columns = [ + "height_sqr_min", + "height_max", + "weight_max", + "height_max_2", + "weight_min", + ] + expected = DataFrame( + { + "height_sqr_min": [82.81, 36.00], + "height_max": [9.5, 34.0], + "weight_max": [9.9, 198.0], + "height_max_2": [9.5, 34.0], + "weight_min": [7.9, 7.5], + }, + index=Index(["cat", "dog"], name="kind"), + columns=columns, + ) + + # check agg(key=(col, aggfunc)) case + result1 = df.groupby(by="kind").agg( + height_sqr_min=("height", lambda x: np.min(x**2)), + height_max=("height", "max"), + weight_max=("weight", "max"), + height_max_2=("height", lambda x: np.max(x)), + weight_min=("weight", lambda x: np.min(x)), + ) + tm.assert_frame_equal(result1, expected) + + # check pd.NamedAgg case + result2 = df.groupby(by="kind").agg( + height_sqr_min=pd.NamedAgg( + column="height", aggfunc=lambda x: np.min(x**2) + ), + height_max=pd.NamedAgg(column="height", aggfunc="max"), + weight_max=pd.NamedAgg(column="weight", aggfunc="max"), + height_max_2=pd.NamedAgg(column="height", aggfunc=lambda x: np.max(x)), + weight_min=pd.NamedAgg(column="weight", aggfunc=lambda x: np.min(x)), + ) + tm.assert_frame_equal(result2, expected) + + +def test_groupby_get_by_index(): + # GH 33439 + df = DataFrame({"A": ["S", "W", "W"], "B": [1.0, 1.0, 2.0]}) + res = df.groupby("A").agg({"B": lambda x: x.get(x.index[-1])}) + expected = DataFrame({"A": ["S", "W"], "B": [1.0, 2.0]}).set_index("A") + tm.assert_frame_equal(res, expected) + + +@pytest.mark.parametrize( + "grp_col_dict, exp_data", + [ + ({"nr": "min", "cat_ord": "min"}, {"nr": [1, 5], "cat_ord": ["a", "c"]}), + ({"cat_ord": "min"}, {"cat_ord": ["a", "c"]}), + ({"nr": "min"}, {"nr": [1, 5]}), + ], +) +def test_groupby_single_agg_cat_cols(grp_col_dict, exp_data): + # test single aggregations on ordered categorical cols GHGH27800 + + # create the result dataframe + input_df = DataFrame( + { + "nr": [1, 2, 3, 4, 5, 6, 7, 8], + "cat_ord": list("aabbccdd"), + "cat": list("aaaabbbb"), + } + ) + + input_df = input_df.astype({"cat": "category", "cat_ord": "category"}) + input_df["cat_ord"] = input_df["cat_ord"].cat.as_ordered() + result_df = input_df.groupby("cat", observed=False).agg(grp_col_dict) + + # create expected dataframe + cat_index = pd.CategoricalIndex( + ["a", "b"], categories=["a", "b"], ordered=False, name="cat", dtype="category" + ) + + expected_df = DataFrame(data=exp_data, index=cat_index) + + if "cat_ord" in expected_df: + # ordered categorical columns should be preserved + dtype = input_df["cat_ord"].dtype + expected_df["cat_ord"] = expected_df["cat_ord"].astype(dtype) + + tm.assert_frame_equal(result_df, expected_df) + + +@pytest.mark.parametrize( + "grp_col_dict, exp_data", + [ + ({"nr": ["min", "max"], "cat_ord": "min"}, [(1, 4, "a"), (5, 8, "c")]), + ({"nr": "min", "cat_ord": ["min", "max"]}, [(1, "a", "b"), (5, "c", "d")]), + ({"cat_ord": ["min", "max"]}, [("a", "b"), ("c", "d")]), + ], +) +def test_groupby_combined_aggs_cat_cols(grp_col_dict, exp_data): + # test combined aggregations on ordered categorical cols GH27800 + + # create the result dataframe + input_df = DataFrame( + { + "nr": [1, 2, 3, 4, 5, 6, 7, 8], + "cat_ord": list("aabbccdd"), + "cat": list("aaaabbbb"), + } + ) + + input_df = input_df.astype({"cat": "category", "cat_ord": "category"}) + input_df["cat_ord"] = input_df["cat_ord"].cat.as_ordered() + result_df = input_df.groupby("cat", observed=False).agg(grp_col_dict) + + # create expected dataframe + cat_index = pd.CategoricalIndex( + ["a", "b"], categories=["a", "b"], ordered=False, name="cat", dtype="category" + ) + + # unpack the grp_col_dict to create the multi-index tuple + # this tuple will be used to create the expected dataframe index + multi_index_list = [] + for k, v in grp_col_dict.items(): + if isinstance(v, list): + multi_index_list.extend([k, value] for value in v) + else: + multi_index_list.append([k, v]) + multi_index = MultiIndex.from_tuples(tuple(multi_index_list)) + + expected_df = DataFrame(data=exp_data, columns=multi_index, index=cat_index) + for col in expected_df.columns: + if isinstance(col, tuple) and "cat_ord" in col: + # ordered categorical should be preserved + expected_df[col] = expected_df[col].astype(input_df["cat_ord"].dtype) + + tm.assert_frame_equal(result_df, expected_df) + + +def test_nonagg_agg(): + # GH 35490 - Single/Multiple agg of non-agg function give same results + # TODO: agg should raise for functions that don't aggregate + df = DataFrame({"a": [1, 1, 2, 2], "b": [1, 2, 2, 1]}) + g = df.groupby("a") + + result = g.agg(["cumsum"]) + result.columns = result.columns.droplevel(-1) + expected = g.agg("cumsum") + + tm.assert_frame_equal(result, expected) + + +def test_aggregate_datetime_objects(): + # https://github.com/pandas-dev/pandas/issues/36003 + # ensure we don't raise an error but keep object dtype for out-of-bounds + # datetimes + df = DataFrame( + { + "A": ["X", "Y"], + "B": [ + datetime.datetime(2005, 1, 1, 10, 30, 23, 540000), + datetime.datetime(3005, 1, 1, 10, 30, 23, 540000), + ], + } + ) + result = df.groupby("A").B.max() + expected = df.set_index("A")["B"] + tm.assert_series_equal(result, expected) + + +def test_groupby_index_object_dtype(): + # GH 40014 + df = DataFrame({"c0": ["x", "x", "x"], "c1": ["x", "x", "y"], "p": [0, 1, 2]}) + df.index = df.index.astype("O") + grouped = df.groupby(["c0", "c1"]) + res = grouped.p.agg(lambda x: all(x > 0)) + # Check that providing a user-defined function in agg() + # produces the correct index shape when using an object-typed index. + expected_index = MultiIndex.from_tuples( + [("x", "x"), ("x", "y")], names=("c0", "c1") + ) + expected = Series([False, True], index=expected_index, name="p") + tm.assert_series_equal(res, expected) + + +def test_timeseries_groupby_agg(): + # GH#43290 + + def func(ser): + if ser.isna().all(): + return None + return np.sum(ser) + + df = DataFrame([1.0], index=[pd.Timestamp("2018-01-16 00:00:00+00:00")]) + res = df.groupby(lambda x: 1).agg(func) + + expected = DataFrame([[1.0]], index=[1]) + tm.assert_frame_equal(res, expected) + + +def test_groupby_agg_precision(any_real_numeric_dtype): + if any_real_numeric_dtype in tm.ALL_INT_NUMPY_DTYPES: + max_value = np.iinfo(any_real_numeric_dtype).max + if any_real_numeric_dtype in tm.FLOAT_NUMPY_DTYPES: + max_value = np.finfo(any_real_numeric_dtype).max + if any_real_numeric_dtype in tm.FLOAT_EA_DTYPES: + max_value = np.finfo(any_real_numeric_dtype.lower()).max + if any_real_numeric_dtype in tm.ALL_INT_EA_DTYPES: + max_value = np.iinfo(any_real_numeric_dtype.lower()).max + + df = DataFrame( + { + "key1": ["a"], + "key2": ["b"], + "key3": pd.array([max_value], dtype=any_real_numeric_dtype), + } + ) + arrays = [["a"], ["b"]] + index = MultiIndex.from_arrays(arrays, names=("key1", "key2")) + + expected = DataFrame( + {"key3": pd.array([max_value], dtype=any_real_numeric_dtype)}, index=index + ) + result = df.groupby(["key1", "key2"]).agg(lambda x: x) + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregate_directory(reduction_func): + # GH#32793 + if reduction_func in ["corrwith", "nth"]: + return None + + obj = DataFrame([[0, 1], [0, np.nan]]) + + result_reduced_series = obj.groupby(0).agg(reduction_func) + result_reduced_frame = obj.groupby(0).agg({1: reduction_func}) + + if reduction_func in ["size", "ngroup"]: + # names are different: None / 1 + tm.assert_series_equal( + result_reduced_series, result_reduced_frame[1], check_names=False + ) + else: + tm.assert_frame_equal(result_reduced_series, result_reduced_frame) + tm.assert_series_equal( + result_reduced_series.dtypes, result_reduced_frame.dtypes + ) + + +def test_group_mean_timedelta_nat(): + # GH43132 + data = Series(["1 day", "3 days", "NaT"], dtype="timedelta64[ns]") + expected = Series(["2 days"], dtype="timedelta64[ns]", index=np.array([0])) + + result = data.groupby([0, 0, 0]).mean() + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "input_data, expected_output", + [ + ( # no timezone + ["2021-01-01T00:00", "NaT", "2021-01-01T02:00"], + ["2021-01-01T01:00"], + ), + ( # timezone + ["2021-01-01T00:00-0100", "NaT", "2021-01-01T02:00-0100"], + ["2021-01-01T01:00-0100"], + ), + ], +) +def test_group_mean_datetime64_nat(input_data, expected_output): + # GH43132 + data = to_datetime(Series(input_data)) + expected = to_datetime(Series(expected_output, index=np.array([0]))) + + result = data.groupby([0, 0, 0]).mean() + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "func, output", [("mean", [8 + 18j, 10 + 22j]), ("sum", [40 + 90j, 50 + 110j])] +) +def test_groupby_complex(func, output): + # GH#43701 + data = Series(np.arange(20).reshape(10, 2).dot([1, 2j])) + result = data.groupby(data.index % 2).agg(func) + expected = Series(output) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("func", ["min", "max", "var"]) +def test_groupby_complex_raises(func): + # GH#43701 + data = Series(np.arange(20).reshape(10, 2).dot([1, 2j])) + msg = "No matching signature found" + with pytest.raises(TypeError, match=msg): + data.groupby(data.index % 2).agg(func) + + +@pytest.mark.parametrize( + "func", [["min"], ["mean", "max"], {"b": "sum"}, {"b": "prod", "c": "median"}] +) +def test_multi_axis_1_raises(func): + # GH#46995 + df = DataFrame({"a": [1, 1, 2], "b": [3, 4, 5], "c": [6, 7, 8]}) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby("a", axis=1) + with pytest.raises(NotImplementedError, match="axis other than 0 is not supported"): + gb.agg(func) + + +@pytest.mark.parametrize( + "test, constant", + [ + ([[20, "A"], [20, "B"], [10, "C"]], {0: [10, 20], 1: ["C", ["A", "B"]]}), + ([[20, "A"], [20, "B"], [30, "C"]], {0: [20, 30], 1: [["A", "B"], "C"]}), + ([["a", 1], ["a", 1], ["b", 2], ["b", 3]], {0: ["a", "b"], 1: [1, [2, 3]]}), + pytest.param( + [["a", 1], ["a", 2], ["b", 3], ["b", 3]], + {0: ["a", "b"], 1: [[1, 2], 3]}, + marks=pytest.mark.xfail, + ), + ], +) +def test_agg_of_mode_list(test, constant): + # GH#25581 + df1 = DataFrame(test) + result = df1.groupby(0).agg(Series.mode) + # Mode usually only returns 1 value, but can return a list in the case of a tie. + + expected = DataFrame(constant) + expected = expected.set_index(0) + + tm.assert_frame_equal(result, expected) + + +def test_dataframe_groupy_agg_list_like_func_with_args(): + # GH#50624 + df = DataFrame({"x": [1, 2, 3], "y": ["a", "b", "c"]}) + gb = df.groupby("y") + + def foo1(x, a=1, c=0): + return x.sum() + a + c + + def foo2(x, b=2, c=0): + return x.sum() + b + c + + msg = r"foo1\(\) got an unexpected keyword argument 'b'" + with pytest.raises(TypeError, match=msg): + gb.agg([foo1, foo2], 3, b=3, c=4) + + result = gb.agg([foo1, foo2], 3, c=4) + expected = DataFrame( + [[8, 8], [9, 9], [10, 10]], + index=Index(["a", "b", "c"], name="y"), + columns=MultiIndex.from_tuples([("x", "foo1"), ("x", "foo2")]), + ) + tm.assert_frame_equal(result, expected) + + +def test_series_groupy_agg_list_like_func_with_args(): + # GH#50624 + s = Series([1, 2, 3]) + sgb = s.groupby(s) + + def foo1(x, a=1, c=0): + return x.sum() + a + c + + def foo2(x, b=2, c=0): + return x.sum() + b + c + + msg = r"foo1\(\) got an unexpected keyword argument 'b'" + with pytest.raises(TypeError, match=msg): + sgb.agg([foo1, foo2], 3, b=3, c=4) + + result = sgb.agg([foo1, foo2], 3, c=4) + expected = DataFrame( + [[8, 8], [9, 9], [10, 10]], index=Index([1, 2, 3]), columns=["foo1", "foo2"] + ) + tm.assert_frame_equal(result, expected) + + +def test_agg_groupings_selection(): + # GH#51186 - a selected grouping should be in the output of agg + df = DataFrame({"a": [1, 1, 2], "b": [3, 3, 4], "c": [5, 6, 7]}) + gb = df.groupby(["a", "b"]) + selected_gb = gb[["b", "c"]] + result = selected_gb.agg(lambda x: x.sum()) + index = MultiIndex( + levels=[[1, 2], [3, 4]], codes=[[0, 1], [0, 1]], names=["a", "b"] + ) + expected = DataFrame({"b": [6, 4], "c": [11, 7]}, index=index) + tm.assert_frame_equal(result, expected) + + +def test_agg_multiple_with_as_index_false_subset_to_a_single_column(): + # GH#50724 + df = DataFrame({"a": [1, 1, 2], "b": [3, 4, 5]}) + gb = df.groupby("a", as_index=False)["b"] + result = gb.agg(["sum", "mean"]) + expected = DataFrame({"a": [1, 2], "sum": [7, 5], "mean": [3.5, 5.0]}) + tm.assert_frame_equal(result, expected) + + +def test_agg_with_as_index_false_with_list(): + # GH#52849 + df = DataFrame({"a1": [0, 0, 1], "a2": [2, 3, 3], "b": [4, 5, 6]}) + gb = df.groupby(by=["a1", "a2"], as_index=False) + result = gb.agg(["sum"]) + + expected = DataFrame( + data=[[0, 2, 4], [0, 3, 5], [1, 3, 6]], + columns=MultiIndex.from_tuples([("a1", ""), ("a2", ""), ("b", "sum")]), + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_agg_extension_timedelta_cumsum_with_named_aggregation(): + # GH#41720 + expected = DataFrame( + { + "td": { + 0: pd.Timedelta("0 days 01:00:00"), + 1: pd.Timedelta("0 days 01:15:00"), + 2: pd.Timedelta("0 days 01:15:00"), + } + } + ) + df = DataFrame( + { + "td": Series( + ["0 days 01:00:00", "0 days 00:15:00", "0 days 01:15:00"], + dtype="timedelta64[ns]", + ), + "grps": ["a", "a", "b"], + } + ) + gb = df.groupby("grps") + result = gb.agg(td=("td", "cumsum")) + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregation_empty_group(): + # https://github.com/pandas-dev/pandas/issues/18869 + def func(x): + if len(x) == 0: + raise ValueError("length must not be 0") + return len(x) + + df = DataFrame( + {"A": pd.Categorical(["a", "a"], categories=["a", "b", "c"]), "B": [1, 1]} + ) + msg = "length must not be 0" + with pytest.raises(ValueError, match=msg): + df.groupby("A", observed=False).agg(func) diff --git a/shared/package-files/71/71147a23e948b1e7c6f79bc465bf13b9776f9b0ee974f15e76906778b54a046f/test_cumulative.py b/shared/package-files/71/71147a23e948b1e7c6f79bc465bf13b9776f9b0ee974f15e76906778b54a046f/test_cumulative.py new file mode 100644 index 0000000000000000000000000000000000000000..2d8fe65f807e431d788e526eee058780b5bf979c --- /dev/null +++ b/shared/package-files/71/71147a23e948b1e7c6f79bc465bf13b9776f9b0ee974f15e76906778b54a046f/test_cumulative.py @@ -0,0 +1,20 @@ +import pytest + +import pandas._testing as tm +from pandas.core.arrays import TimedeltaArray + + +class TestAccumulator: + def test_accumulators_disallowed(self): + # GH#50297 + arr = TimedeltaArray._from_sequence(["1D", "2D"], dtype="m8[ns]") + with pytest.raises(TypeError, match="cumprod not supported"): + arr._accumulate("cumprod") + + def test_cumsum(self, unit): + # GH#50297 + dtype = f"m8[{unit}]" + arr = TimedeltaArray._from_sequence(["1D", "2D"], dtype=dtype) + result = arr._accumulate("cumsum") + expected = TimedeltaArray._from_sequence(["1D", "3D"], dtype=dtype) + tm.assert_timedelta_array_equal(result, expected) diff --git a/shared/package-files/71/71148166f66fd4236e7d3161d549b073a90f7592fc5c175e5bffdde6c5b3932a/__init__.py b/shared/package-files/71/71148166f66fd4236e7d3161d549b073a90f7592fc5c175e5bffdde6c5b3932a/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0c63f283f3859bd4d368a431a62fc2fc45827046 --- /dev/null +++ b/shared/package-files/71/71148166f66fd4236e7d3161d549b073a90f7592fc5c175e5bffdde6c5b3932a/__init__.py @@ -0,0 +1,15 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from logging import getLogger + +from ..compat import on_win + +if on_win: + from .windows import get_free_space_on_windows as get_free_space + from .windows import is_admin_on_windows as is_admin +else: + from .unix import get_free_space_on_unix as get_free_space # noqa + from .unix import is_admin_on_unix as is_admin # noqa + + +log = getLogger(__name__) diff --git a/shared/package-files/71/7117929558e09e84fbe309ad367fa81086622544df457ee58e396a262ef5e884/test_callback.py b/shared/package-files/71/7117929558e09e84fbe309ad367fa81086622544df457ee58e396a262ef5e884/test_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..5b6c294d33fcff10c5c1b5488c0124f42d9c1b70 --- /dev/null +++ b/shared/package-files/71/7117929558e09e84fbe309ad367fa81086622544df457ee58e396a262ef5e884/test_callback.py @@ -0,0 +1,243 @@ +import math +import textwrap +import sys +import pytest +import threading +import traceback +import time + +import numpy as np +from numpy.testing import IS_PYPY +from . import util + + +class TestF77Callback(util.F2PyTest): + sources = [util.getpath("tests", "src", "callback", "foo.f")] + + @pytest.mark.parametrize("name", "t,t2".split(",")) + def test_all(self, name): + self.check_function(name) + + @pytest.mark.xfail(IS_PYPY, + reason="PyPy cannot modify tp_doc after PyType_Ready") + def test_docstring(self): + expected = textwrap.dedent("""\ + a = t(fun,[fun_extra_args]) + + Wrapper for ``t``. + + Parameters + ---------- + fun : call-back function + + Other Parameters + ---------------- + fun_extra_args : input tuple, optional + Default: () + + Returns + ------- + a : int + + Notes + ----- + Call-back functions:: + + def fun(): return a + Return objects: + a : int + """) + assert self.module.t.__doc__ == expected + + def check_function(self, name): + t = getattr(self.module, name) + r = t(lambda: 4) + assert r == 4 + r = t(lambda a: 5, fun_extra_args=(6, )) + assert r == 5 + r = t(lambda a: a, fun_extra_args=(6, )) + assert r == 6 + r = t(lambda a: 5 + a, fun_extra_args=(7, )) + assert r == 12 + r = t(lambda a: math.degrees(a), fun_extra_args=(math.pi, )) + assert r == 180 + r = t(math.degrees, fun_extra_args=(math.pi, )) + assert r == 180 + + r = t(self.module.func, fun_extra_args=(6, )) + assert r == 17 + r = t(self.module.func0) + assert r == 11 + r = t(self.module.func0._cpointer) + assert r == 11 + + class A: + def __call__(self): + return 7 + + def mth(self): + return 9 + + a = A() + r = t(a) + assert r == 7 + r = t(a.mth) + assert r == 9 + + @pytest.mark.skipif(sys.platform == 'win32', + reason='Fails with MinGW64 Gfortran (Issue #9673)') + def test_string_callback(self): + def callback(code): + if code == "r": + return 0 + else: + return 1 + + f = getattr(self.module, "string_callback") + r = f(callback) + assert r == 0 + + @pytest.mark.skipif(sys.platform == 'win32', + reason='Fails with MinGW64 Gfortran (Issue #9673)') + def test_string_callback_array(self): + # See gh-10027 + cu1 = np.zeros((1, ), "S8") + cu2 = np.zeros((1, 8), "c") + cu3 = np.array([""], "S8") + + def callback(cu, lencu): + if cu.shape != (lencu,): + return 1 + if cu.dtype != "S8": + return 2 + if not np.all(cu == b""): + return 3 + return 0 + + f = getattr(self.module, "string_callback_array") + for cu in [cu1, cu2, cu3]: + res = f(callback, cu, cu.size) + assert res == 0 + + def test_threadsafety(self): + # Segfaults if the callback handling is not threadsafe + + errors = [] + + def cb(): + # Sleep here to make it more likely for another thread + # to call their callback at the same time. + time.sleep(1e-3) + + # Check reentrancy + r = self.module.t(lambda: 123) + assert r == 123 + + return 42 + + def runner(name): + try: + for j in range(50): + r = self.module.t(cb) + assert r == 42 + self.check_function(name) + except Exception: + errors.append(traceback.format_exc()) + + threads = [ + threading.Thread(target=runner, args=(arg, )) + for arg in ("t", "t2") for n in range(20) + ] + + for t in threads: + t.start() + + for t in threads: + t.join() + + errors = "\n\n".join(errors) + if errors: + raise AssertionError(errors) + + def test_hidden_callback(self): + try: + self.module.hidden_callback(2) + except Exception as msg: + assert str(msg).startswith("Callback global_f not defined") + + try: + self.module.hidden_callback2(2) + except Exception as msg: + assert str(msg).startswith("cb: Callback global_f not defined") + + self.module.global_f = lambda x: x + 1 + r = self.module.hidden_callback(2) + assert r == 3 + + self.module.global_f = lambda x: x + 2 + r = self.module.hidden_callback(2) + assert r == 4 + + del self.module.global_f + try: + self.module.hidden_callback(2) + except Exception as msg: + assert str(msg).startswith("Callback global_f not defined") + + self.module.global_f = lambda x=0: x + 3 + r = self.module.hidden_callback(2) + assert r == 5 + + # reproducer of gh18341 + r = self.module.hidden_callback2(2) + assert r == 3 + + +class TestF77CallbackPythonTLS(TestF77Callback): + """ + Callback tests using Python thread-local storage instead of + compiler-provided + """ + + options = ["-DF2PY_USE_PYTHON_TLS"] + + +class TestF90Callback(util.F2PyTest): + sources = [util.getpath("tests", "src", "callback", "gh17797.f90")] + + def test_gh17797(self): + def incr(x): + return x + 123 + + y = np.array([1, 2, 3], dtype=np.int64) + r = self.module.gh17797(incr, y) + assert r == 123 + 1 + 2 + 3 + + +class TestGH18335(util.F2PyTest): + """The reproduction of the reported issue requires specific input that + extensions may break the issue conditions, so the reproducer is + implemented as a separate test class. Do not extend this test with + other tests! + """ + sources = [util.getpath("tests", "src", "callback", "gh18335.f90")] + + def test_gh18335(self): + def foo(x): + x[0] += 1 + + r = self.module.gh18335(foo) + assert r == 123 + 1 + + +class TestGH25211(util.F2PyTest): + sources = [util.getpath("tests", "src", "callback", "gh25211.f"), + util.getpath("tests", "src", "callback", "gh25211.pyf")] + module_name = "callback2" + + def test_gh18335(self): + def bar(x): + return x*x + + res = self.module.foo(bar) + assert res == 110 diff --git a/shared/package-files/71/711d0b4c6b4c9e610a58a2700b5c72769f658eeb67f4c3d33e509fb79e061c88/throughput_benchmark-inl.h b/shared/package-files/71/711d0b4c6b4c9e610a58a2700b5c72769f658eeb67f4c3d33e509fb79e061c88/throughput_benchmark-inl.h new file mode 100644 index 0000000000000000000000000000000000000000..4334a58683bb8a971abe117d7ce9b0edbda2db53 --- /dev/null +++ b/shared/package-files/71/711d0b4c6b4c9e610a58a2700b5c72769f658eeb67f4c3d33e509fb79e061c88/throughput_benchmark-inl.h @@ -0,0 +1,161 @@ +#pragma once + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +namespace torch { +namespace throughput_benchmark { +namespace detail { + +template +BenchmarkExecutionStats BenchmarkHelper::benchmark( + const BenchmarkConfig& config) const { + CHECK(initialized_); + TORCH_CHECK( + config.num_worker_threads == 1, + "Only parallelization by callers is supported"); + + LOG(INFO) << at::get_parallel_info(); + + // We pre-generate inputs here for each of the threads. This allows us to + // safely move inputs out for each of the threads independently and thus avoid + // overhead from the benchmark runner itself + std::vector> thread_inputs(config.num_calling_threads); + std::vector input_iters(config.num_calling_threads); + { + std::random_device seeder; + std::mt19937 engine(seeder()); + TORCH_CHECK( + !inputs_.empty(), + "Please provide benchmark inputs." + "Did you forget to call add_input()? "); + std::uniform_int_distribution dist(0, inputs_.size() - 1); + + for (const auto thread_id : c10::irange(config.num_calling_threads)) { + // Just in case we generate num_iters inputs for each of the threads + // This was if one thread does all the work we will be fine + for (const auto i [[maybe_unused]] : + c10::irange(config.num_iters + config.num_warmup_iters)) { + thread_inputs[thread_id].push_back(cloneInput(inputs_[dist(engine)])); + } + input_iters[thread_id] = 0; + } + } + + std::mutex m; + std::condition_variable worker_main_cv; + std::condition_variable main_worker_cv; + // TODO: add GUARDED_BY once it is available + int64_t initialized{0}; + int64_t finished{0}; + bool start{false}; + std::atomic num_attempted_iters{0}; + std::vector callers; + + callers.reserve(config.num_calling_threads); + + bool tls_grad_enabled = c10::GradMode::is_enabled(); + c10::impl::LocalDispatchKeySet tls_key_set = + c10::impl::tls_local_dispatch_key_set(); + + for (const auto thread_id : c10::irange(config.num_calling_threads)) { + callers.emplace_back([&, thread_id]() { + // We use conditional variable as a barrier to make sure each thread + // performs required warmeup iterations before we start measuring + c10::GradMode::set_enabled(tls_grad_enabled); + c10::impl::_force_tls_local_dispatch_key_set(tls_key_set); + + for (const auto j : c10::irange(config.num_warmup_iters)) { + (void)j; + runOnce(std::move(thread_inputs[thread_id][input_iters[thread_id]])); + ++input_iters[thread_id]; + } + { + std::unique_lock lock(m); + ++initialized; + worker_main_cv.notify_one(); + // NOLINTNEXTLINE(bugprone-infinite-loop) + while (!start) { + main_worker_cv.wait(lock); + } + } + LOG(INFO) << "Starting forward thread " << thread_id; + while (num_attempted_iters.fetch_add(1) < config.num_iters) { + runOnce(std::move(thread_inputs[thread_id][input_iters[thread_id]])); + ++input_iters[thread_id]; + } + + { + std::unique_lock lock(m); + ++finished; + worker_main_cv.notify_one(); + LOG(INFO) << "Shutting down forward thread " << thread_id + << ". Total number of finished threads: " << finished; + } + }); + } + + using Clock = std::chrono::high_resolution_clock; + using RecordProfile = torch::autograd::profiler::RecordProfile; + using TimePoint = std::chrono::time_point; + TimePoint start_time; + + std::unique_ptr profiler_guard; + { + std::unique_lock lock(m); + while (initialized != config.num_calling_threads) { + worker_main_cv.wait(lock); + } + if (!config.profiler_output_path.empty()) { + LOG(INFO) << "Using Autograd profiler. Trace will be saved to " + << config.profiler_output_path; + profiler_guard = + std::make_unique(config.profiler_output_path); + } + LOG(INFO) << "Starting threads"; + start = true; + start_time = Clock::now(); + } + + main_worker_cv.notify_all(); + { + std::unique_lock lock(m); + worker_main_cv.wait( + lock, [&]() { return finished == config.num_calling_threads; }); + } + auto end_time = std::chrono::high_resolution_clock::now(); + profiler_guard.reset(); + LOG(INFO) << "Finished benchmark"; + + BenchmarkExecutionStats stats; + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + float total_time_ms = std::chrono::duration_cast( + end_time - start_time) + .count() / + 1000.0 / 1000.0; + // We use config.num_iters instead of num_attempted_iters as it is + // repsesatative of the real work done. Last attempted iteration on each + // calling threads doesn't represent the real work (i.e. running the model) + stats.latency_avg_ms = + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + total_time_ms * config.num_calling_threads / config.num_iters; + stats.num_iters = config.num_iters; + + for (auto& t : callers) { + t.join(); + } + return stats; +} + +} // namespace detail +} // namespace throughput_benchmark +} // namespace torch diff --git a/shared/package-files/71/71212518811fbebc2a2b58bab6012edd91216da9eaa95ad89b975d7857deaddb/test_embed.py b/shared/package-files/71/71212518811fbebc2a2b58bab6012edd91216da9eaa95ad89b975d7857deaddb/test_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..3f0885e73ccd6e3e1ab848ea503499ebf867f214 --- /dev/null +++ b/shared/package-files/71/71212518811fbebc2a2b58bab6012edd91216da9eaa95ad89b975d7857deaddb/test_embed.py @@ -0,0 +1,138 @@ +"""Test embedding of IPython""" + +#----------------------------------------------------------------------------- +# Copyright (C) 2013 The IPython Development Team +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING, distributed as part of this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +import os +import subprocess +import sys + +from IPython.utils.tempdir import NamedFileInTemporaryDirectory +from IPython.testing.decorators import skip_win32 +from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE + +#----------------------------------------------------------------------------- +# Tests +#----------------------------------------------------------------------------- + + +_sample_embed = b""" +import IPython + +a = 3 +b = 14 +print(a, '.', b) + +IPython.embed() + +print('bye!') +""" + +_exit = b"exit\r" + +def test_ipython_embed(): + """test that `IPython.embed()` works""" + with NamedFileInTemporaryDirectory('file_with_embed.py') as f: + f.write(_sample_embed) + f.flush() + f.close() # otherwise msft won't be able to read the file + + # run `python file_with_embed.py` + cmd = [sys.executable, f.name] + env = os.environ.copy() + env['IPY_TEST_SIMPLE_PROMPT'] = '1' + + p = subprocess.Popen(cmd, env=env, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + out, err = p.communicate(_exit) + std = out.decode('UTF-8') + + assert p.returncode == 0 + assert "3 . 14" in std + if os.name != "nt": + # TODO: Fix up our different stdout references, see issue gh-14 + assert "IPython" in std + assert "bye!" in std + + +@skip_win32 +def test_nest_embed(): + """test that `IPython.embed()` is nestable""" + import pexpect + ipy_prompt = r']:' #ansi color codes give problems matching beyond this + env = os.environ.copy() + env['IPY_TEST_SIMPLE_PROMPT'] = '1' + + + child = pexpect.spawn(sys.executable, ['-m', 'IPython', '--colors=nocolor'], + env=env) + child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE + child.expect(ipy_prompt) + child.timeout = 5 * IPYTHON_TESTING_TIMEOUT_SCALE + child.sendline("import IPython") + child.expect(ipy_prompt) + child.sendline("ip0 = get_ipython()") + #enter first nested embed + child.sendline("IPython.embed()") + #skip the banner until we get to a prompt + try: + prompted = -1 + while prompted != 0: + prompted = child.expect([ipy_prompt, '\r\n']) + except pexpect.TIMEOUT as e: + print(e) + #child.interact() + child.sendline("embed1 = get_ipython()") + child.expect(ipy_prompt) + child.sendline("print('true' if embed1 is not ip0 else 'false')") + assert(child.expect(['true\r\n', 'false\r\n']) == 0) + child.expect(ipy_prompt) + child.sendline("print('true' if IPython.get_ipython() is embed1 else 'false')") + assert(child.expect(['true\r\n', 'false\r\n']) == 0) + child.expect(ipy_prompt) + #enter second nested embed + child.sendline("IPython.embed()") + #skip the banner until we get to a prompt + try: + prompted = -1 + while prompted != 0: + prompted = child.expect([ipy_prompt, '\r\n']) + except pexpect.TIMEOUT as e: + print(e) + #child.interact() + child.sendline("embed2 = get_ipython()") + child.expect(ipy_prompt) + child.sendline("print('true' if embed2 is not embed1 else 'false')") + assert(child.expect(['true\r\n', 'false\r\n']) == 0) + child.expect(ipy_prompt) + child.sendline("print('true' if embed2 is IPython.get_ipython() else 'false')") + assert(child.expect(['true\r\n', 'false\r\n']) == 0) + child.expect(ipy_prompt) + child.sendline('exit') + #back at first embed + child.expect(ipy_prompt) + child.sendline("print('true' if get_ipython() is embed1 else 'false')") + assert(child.expect(['true\r\n', 'false\r\n']) == 0) + child.expect(ipy_prompt) + child.sendline("print('true' if IPython.get_ipython() is embed1 else 'false')") + assert(child.expect(['true\r\n', 'false\r\n']) == 0) + child.expect(ipy_prompt) + child.sendline('exit') + #back at launching scope + child.expect(ipy_prompt) + child.sendline("print('true' if get_ipython() is ip0 else 'false')") + assert(child.expect(['true\r\n', 'false\r\n']) == 0) + child.expect(ipy_prompt) + child.sendline("print('true' if IPython.get_ipython() is ip0 else 'false')") + assert(child.expect(['true\r\n', 'false\r\n']) == 0) + child.expect(ipy_prompt) + child.sendline('exit') + child.close() diff --git a/shared/package-files/71/7122b0ff2f9f00f05623692c80b7bc48d4ce87494f334b336be233bff1a19d35/special_erfcx_ops.h b/shared/package-files/71/7122b0ff2f9f00f05623692c80b7bc48d4ce87494f334b336be233bff1a19d35/special_erfcx_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..2e983cc463f272a408cfd4d1dbae04cdbd46713a --- /dev/null +++ b/shared/package-files/71/7122b0ff2f9f00f05623692c80b7bc48d4ce87494f334b336be233bff1a19d35/special_erfcx_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API special_erfcx { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::special_erfcx") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_erfcx(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API special_erfcx_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::special_erfcx") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_erfcx.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/71/71248216fb1cc2b9a0a1faa305daa8c680d9c637141cb2db283e407684209cab/_compat_pickle.py b/shared/package-files/71/71248216fb1cc2b9a0a1faa305daa8c680d9c637141cb2db283e407684209cab/_compat_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..f68496ae639f5f880ae5f4ca0a220a29d2e354be --- /dev/null +++ b/shared/package-files/71/71248216fb1cc2b9a0a1faa305daa8c680d9c637141cb2db283e407684209cab/_compat_pickle.py @@ -0,0 +1,251 @@ +# This module is used to map the old Python 2 names to the new names used in +# Python 3 for the pickle module. This needed to make pickle streams +# generated with Python 2 loadable by Python 3. + +# This is a copy of lib2to3.fixes.fix_imports.MAPPING. We cannot import +# lib2to3 and use the mapping defined there, because lib2to3 uses pickle. +# Thus, this could cause the module to be imported recursively. +IMPORT_MAPPING = { + '__builtin__' : 'builtins', + 'copy_reg': 'copyreg', + 'Queue': 'queue', + 'SocketServer': 'socketserver', + 'ConfigParser': 'configparser', + 'repr': 'reprlib', + 'tkFileDialog': 'tkinter.filedialog', + 'tkSimpleDialog': 'tkinter.simpledialog', + 'tkColorChooser': 'tkinter.colorchooser', + 'tkCommonDialog': 'tkinter.commondialog', + 'Dialog': 'tkinter.dialog', + 'Tkdnd': 'tkinter.dnd', + 'tkFont': 'tkinter.font', + 'tkMessageBox': 'tkinter.messagebox', + 'ScrolledText': 'tkinter.scrolledtext', + 'Tkconstants': 'tkinter.constants', + 'Tix': 'tkinter.tix', + 'ttk': 'tkinter.ttk', + 'Tkinter': 'tkinter', + 'markupbase': '_markupbase', + '_winreg': 'winreg', + 'thread': '_thread', + 'dummy_thread': '_dummy_thread', + 'dbhash': 'dbm.bsd', + 'dumbdbm': 'dbm.dumb', + 'dbm': 'dbm.ndbm', + 'gdbm': 'dbm.gnu', + 'xmlrpclib': 'xmlrpc.client', + 'SimpleXMLRPCServer': 'xmlrpc.server', + 'httplib': 'http.client', + 'htmlentitydefs' : 'html.entities', + 'HTMLParser' : 'html.parser', + 'Cookie': 'http.cookies', + 'cookielib': 'http.cookiejar', + 'BaseHTTPServer': 'http.server', + 'test.test_support': 'test.support', + 'commands': 'subprocess', + 'urlparse' : 'urllib.parse', + 'robotparser' : 'urllib.robotparser', + 'urllib2': 'urllib.request', + 'anydbm': 'dbm', + '_abcoll' : 'collections.abc', +} + + +# This contains rename rules that are easy to handle. We ignore the more +# complex stuff (e.g. mapping the names in the urllib and types modules). +# These rules should be run before import names are fixed. +NAME_MAPPING = { + ('__builtin__', 'xrange'): ('builtins', 'range'), + ('__builtin__', 'reduce'): ('functools', 'reduce'), + ('__builtin__', 'intern'): ('sys', 'intern'), + ('__builtin__', 'unichr'): ('builtins', 'chr'), + ('__builtin__', 'unicode'): ('builtins', 'str'), + ('__builtin__', 'long'): ('builtins', 'int'), + ('itertools', 'izip'): ('builtins', 'zip'), + ('itertools', 'imap'): ('builtins', 'map'), + ('itertools', 'ifilter'): ('builtins', 'filter'), + ('itertools', 'ifilterfalse'): ('itertools', 'filterfalse'), + ('itertools', 'izip_longest'): ('itertools', 'zip_longest'), + ('UserDict', 'IterableUserDict'): ('collections', 'UserDict'), + ('UserList', 'UserList'): ('collections', 'UserList'), + ('UserString', 'UserString'): ('collections', 'UserString'), + ('whichdb', 'whichdb'): ('dbm', 'whichdb'), + ('_socket', 'fromfd'): ('socket', 'fromfd'), + ('_multiprocessing', 'Connection'): ('multiprocessing.connection', 'Connection'), + ('multiprocessing.process', 'Process'): ('multiprocessing.context', 'Process'), + ('multiprocessing.forking', 'Popen'): ('multiprocessing.popen_fork', 'Popen'), + ('urllib', 'ContentTooShortError'): ('urllib.error', 'ContentTooShortError'), + ('urllib', 'getproxies'): ('urllib.request', 'getproxies'), + ('urllib', 'pathname2url'): ('urllib.request', 'pathname2url'), + ('urllib', 'quote_plus'): ('urllib.parse', 'quote_plus'), + ('urllib', 'quote'): ('urllib.parse', 'quote'), + ('urllib', 'unquote_plus'): ('urllib.parse', 'unquote_plus'), + ('urllib', 'unquote'): ('urllib.parse', 'unquote'), + ('urllib', 'url2pathname'): ('urllib.request', 'url2pathname'), + ('urllib', 'urlcleanup'): ('urllib.request', 'urlcleanup'), + ('urllib', 'urlencode'): ('urllib.parse', 'urlencode'), + ('urllib', 'urlopen'): ('urllib.request', 'urlopen'), + ('urllib', 'urlretrieve'): ('urllib.request', 'urlretrieve'), + ('urllib2', 'HTTPError'): ('urllib.error', 'HTTPError'), + ('urllib2', 'URLError'): ('urllib.error', 'URLError'), +} + +PYTHON2_EXCEPTIONS = ( + "ArithmeticError", + "AssertionError", + "AttributeError", + "BaseException", + "BufferError", + "BytesWarning", + "DeprecationWarning", + "EOFError", + "EnvironmentError", + "Exception", + "FloatingPointError", + "FutureWarning", + "GeneratorExit", + "IOError", + "ImportError", + "ImportWarning", + "IndentationError", + "IndexError", + "KeyError", + "KeyboardInterrupt", + "LookupError", + "MemoryError", + "NameError", + "NotImplementedError", + "OSError", + "OverflowError", + "PendingDeprecationWarning", + "ReferenceError", + "RuntimeError", + "RuntimeWarning", + # StandardError is gone in Python 3, so we map it to Exception + "StopIteration", + "SyntaxError", + "SyntaxWarning", + "SystemError", + "SystemExit", + "TabError", + "TypeError", + "UnboundLocalError", + "UnicodeDecodeError", + "UnicodeEncodeError", + "UnicodeError", + "UnicodeTranslateError", + "UnicodeWarning", + "UserWarning", + "ValueError", + "Warning", + "ZeroDivisionError", +) + +try: + WindowsError +except NameError: + pass +else: + PYTHON2_EXCEPTIONS += ("WindowsError",) + +for excname in PYTHON2_EXCEPTIONS: + NAME_MAPPING[("exceptions", excname)] = ("builtins", excname) + +MULTIPROCESSING_EXCEPTIONS = ( + 'AuthenticationError', + 'BufferTooShort', + 'ProcessError', + 'TimeoutError', +) + +for excname in MULTIPROCESSING_EXCEPTIONS: + NAME_MAPPING[("multiprocessing", excname)] = ("multiprocessing.context", excname) + +# Same, but for 3.x to 2.x +REVERSE_IMPORT_MAPPING = dict((v, k) for (k, v) in IMPORT_MAPPING.items()) +assert len(REVERSE_IMPORT_MAPPING) == len(IMPORT_MAPPING) +REVERSE_NAME_MAPPING = dict((v, k) for (k, v) in NAME_MAPPING.items()) +assert len(REVERSE_NAME_MAPPING) == len(NAME_MAPPING) + +# Non-mutual mappings. + +IMPORT_MAPPING.update({ + 'cPickle': 'pickle', + '_elementtree': 'xml.etree.ElementTree', + 'FileDialog': 'tkinter.filedialog', + 'SimpleDialog': 'tkinter.simpledialog', + 'DocXMLRPCServer': 'xmlrpc.server', + 'SimpleHTTPServer': 'http.server', + 'CGIHTTPServer': 'http.server', + # For compatibility with broken pickles saved in old Python 3 versions + 'UserDict': 'collections', + 'UserList': 'collections', + 'UserString': 'collections', + 'whichdb': 'dbm', + 'StringIO': 'io', + 'cStringIO': 'io', +}) + +REVERSE_IMPORT_MAPPING.update({ + '_bz2': 'bz2', + '_dbm': 'dbm', + '_functools': 'functools', + '_gdbm': 'gdbm', + '_pickle': 'pickle', +}) + +NAME_MAPPING.update({ + ('__builtin__', 'basestring'): ('builtins', 'str'), + ('exceptions', 'StandardError'): ('builtins', 'Exception'), + ('UserDict', 'UserDict'): ('collections', 'UserDict'), + ('socket', '_socketobject'): ('socket', 'SocketType'), +}) + +REVERSE_NAME_MAPPING.update({ + ('_functools', 'reduce'): ('__builtin__', 'reduce'), + ('tkinter.filedialog', 'FileDialog'): ('FileDialog', 'FileDialog'), + ('tkinter.filedialog', 'LoadFileDialog'): ('FileDialog', 'LoadFileDialog'), + ('tkinter.filedialog', 'SaveFileDialog'): ('FileDialog', 'SaveFileDialog'), + ('tkinter.simpledialog', 'SimpleDialog'): ('SimpleDialog', 'SimpleDialog'), + ('xmlrpc.server', 'ServerHTMLDoc'): ('DocXMLRPCServer', 'ServerHTMLDoc'), + ('xmlrpc.server', 'XMLRPCDocGenerator'): + ('DocXMLRPCServer', 'XMLRPCDocGenerator'), + ('xmlrpc.server', 'DocXMLRPCRequestHandler'): + ('DocXMLRPCServer', 'DocXMLRPCRequestHandler'), + ('xmlrpc.server', 'DocXMLRPCServer'): + ('DocXMLRPCServer', 'DocXMLRPCServer'), + ('xmlrpc.server', 'DocCGIXMLRPCRequestHandler'): + ('DocXMLRPCServer', 'DocCGIXMLRPCRequestHandler'), + ('http.server', 'SimpleHTTPRequestHandler'): + ('SimpleHTTPServer', 'SimpleHTTPRequestHandler'), + ('http.server', 'CGIHTTPRequestHandler'): + ('CGIHTTPServer', 'CGIHTTPRequestHandler'), + ('_socket', 'socket'): ('socket', '_socketobject'), +}) + +PYTHON3_OSERROR_EXCEPTIONS = ( + 'BrokenPipeError', + 'ChildProcessError', + 'ConnectionAbortedError', + 'ConnectionError', + 'ConnectionRefusedError', + 'ConnectionResetError', + 'FileExistsError', + 'FileNotFoundError', + 'InterruptedError', + 'IsADirectoryError', + 'NotADirectoryError', + 'PermissionError', + 'ProcessLookupError', + 'TimeoutError', +) + +for excname in PYTHON3_OSERROR_EXCEPTIONS: + REVERSE_NAME_MAPPING[('builtins', excname)] = ('exceptions', 'OSError') + +PYTHON3_IMPORTERROR_EXCEPTIONS = ( + 'ModuleNotFoundError', +) + +for excname in PYTHON3_IMPORTERROR_EXCEPTIONS: + REVERSE_NAME_MAPPING[('builtins', excname)] = ('exceptions', 'ImportError') diff --git a/shared/package-files/71/712558c3f93efb2147ff63a5b9fd56f84ce752f85a1651a2ad939189492776f1/frontend.py b/shared/package-files/71/712558c3f93efb2147ff63a5b9fd56f84ce752f85a1651a2ad939189492776f1/frontend.py new file mode 100644 index 0000000000000000000000000000000000000000..37237af33d4846fab483c88104c1ed05193c4eba --- /dev/null +++ b/shared/package-files/71/712558c3f93efb2147ff63a5b9fd56f84ce752f85a1651a2ad939189492776f1/frontend.py @@ -0,0 +1,1266 @@ +import ast +import dataclasses +import inspect +import re +import string +import sys +from collections import namedtuple +from textwrap import dedent +from typing import List, Tuple # noqa: F401 + +import torch +import torch.jit.annotations +from torch import _jit_internal +from torch._C._jit_tree_views import ( + Apply, + Assert, + Assign, + Attribute, + AugAssign, + BinOp, + Break, + ClassDef, + Const, + Continue, + Decl, + Def, + Delete, + DictComp, + DictLiteral, + Dots, + EmptyTypeAnnotation, + ExprStmt, + FalseLiteral, + For, + Ident, + If, + ListComp, + ListLiteral, + NoneLiteral, + Param, + Pass, + Property, + Raise, + Return, + Select, + SliceExpr, + Starred, + Stmt, + StringLiteral, + Subscript, + TernaryIf, + TrueLiteral, + TupleLiteral, + UnaryOp, + Var, + While, + With, + WithItem, +) +from torch._jit_internal import ( # noqa: F401 + _is_drop_fn, + FunctionModifiers, + is_static_fn, + should_drop, +) +from torch._sources import ( + get_source_lines_and_file, + make_source_context, + parse_def, + ParsedDef as _ParsedDef, +) +from torch.jit._dataclass_impls import DATACLASS_MAGIC_METHODS +from torch.jit._monkeytype_config import get_qualified_name, monkeytype_trace + +_IS_ASTUNPARSE_INSTALLED = False +try: + import astunparse # type: ignore[import] + + _IS_ASTUNPARSE_INSTALLED = True +except ImportError: + pass + +# Borrowed from cPython implementation +# https://github.com/python/cpython/blob/561612d8456cfab5672c9b445521113b847bd6b3/Lib/textwrap.py#L411# + +_reserved_prefix = "__jit" +_reserved_names = {"print"} +_identifier_chars = set(string.ascii_lowercase + string.ascii_uppercase + string.digits) + + +def is_reserved_name(name): + return name.startswith(_reserved_prefix) or name in _reserved_names + + +pretty_node_names = { + ast.FunctionDef: "function definitions", + ast.For: "for loops", + ast.Delete: "del statements", + ast.ClassDef: "class definitions", + ast.With: "with statements", + ast.Raise: "raise statements", + ast.Assert: "assertions", + ast.Import: "import statements", + ast.ImportFrom: "import statements", + ast.Global: "global variables", + ast.Break: "break statements", + ast.Continue: "continue statements", +} + +node_start_tokens = { + ast.FunctionDef: "def", + ast.For: "for", + ast.Delete: "del", + ast.ClassDef: "class", + ast.With: "with", + ast.Raise: "raise", + ast.Assert: "assert", + ast.Import: "import", + ast.ImportFrom: "from", + ast.Global: "global", + ast.Break: "break", + ast.Continue: "continue", +} + +pretty_node_names.update( + { + ast.AsyncFunctionDef: "async function definitions", + ast.AsyncFor: "async for loops", + ast.AsyncWith: "async with statements", + ast.Try: "try blocks", + ast.Nonlocal: "nonlocal variables", + } +) + +node_start_tokens.update( + { + ast.AsyncFunctionDef: "async def", + ast.AsyncFor: "async for", + ast.AsyncWith: "async with", + ast.Try: "try", + ast.Nonlocal: "nonlocal", + } +) + +pretty_node_names.update( + { + ast.AnnAssign: "annotated assignments", + } +) +# NB: no specific token for AnnAssign + + +class FrontendError(Exception): + def __init__(self, source_range, msg): + self.source_range = source_range + self.msg = msg + + # This has to be instantiated here so the ErrorReport is accurate to the + # call stack when the FrontendError was raised + self.error_report = torch._C.ErrorReport(self.source_range) + + def __str__(self): + return self.msg + self.error_report.what().lstrip() + + +class NotSupportedError(FrontendError): + pass + + +class UnsupportedNodeError(NotSupportedError): + def __init__(self, ctx, offending_node, reason=""): + # If we don't have a specific token, we default to length of 1 + node_type = type(offending_node) + range_len = len(node_start_tokens.get(node_type, " ")) + source_range = ctx.make_range( + offending_node.lineno, + offending_node.col_offset, + offending_node.col_offset + range_len, + ) + feature_name = pretty_node_names.get(node_type, node_type.__name__) + msg = f"{feature_name} {reason + ' ' if reason else ''}aren't supported" + super().__init__(source_range, msg) + + +class FrontendTypeError(FrontendError): + pass + + +def build_withitems(ctx, items): + items = [build_withitem(ctx, i) for i in items] + return list(items) + + +def build_stmts(ctx, stmts): + stmts = [build_stmt(ctx, s) for s in stmts] + return list(filter(None, stmts)) + + +def get_class_properties(cls, self_name): + """ + Get a list of Property objects representing the properties of a class. + + Args: + cls: The class to get properties of. + self_name: The name of the class that the properties should belong to. + Returns: + A list of Property objects corresponding to the properties of cls. Property + here refers to the subclass of TreeView. + """ + props = inspect.getmembers(cls, predicate=lambda m: isinstance(m, property)) + # Any property that should not compiled must be in this list on the Module. + unused_properties = getattr(cls, "__jit_unused_properties__", []) + + # Create Property TreeView objects from inspected property objects. + properties = [] + for prop in props: + if prop[0] not in unused_properties and not should_drop(prop[1].fget): + getter = get_jit_def( + prop[1].fget, f"__{prop[0]}_getter", self_name=self_name + ) + setter = ( + get_jit_def(prop[1].fset, f"__{prop[0]}_setter", self_name=self_name) + if prop[1].fset + else None + ) + properties.append( + Property(getter.range(), Ident(getter.range(), prop[0]), getter, setter) + ) + + return properties + + +def get_class_assigns(ctx, cls_ast): + assigns = [] + + def maybe_build_assign(builder, entry): + nonlocal assigns + try: + assigns.append(builder(ctx, entry)) + except NotSupportedError: + pass + + for entry in cls_ast.body: + if isinstance(entry, ast.Assign): + maybe_build_assign(StmtBuilder.build_Assign, entry) + elif isinstance(entry, ast.AnnAssign): + maybe_build_assign(StmtBuilder.build_AnnAssign, entry) + return assigns + + +def get_jit_class_def(cls, self_name): + # Get defs for each method within the current class independently + # TODO: proper overriding analysis when implementing class inheritance + methods = inspect.getmembers( + cls, + predicate=lambda m: (inspect.ismethod(m) or inspect.isfunction(m)) + and not is_static_fn(cls, m.__name__) + and m.__name__ in cls.__dict__ + and not _is_drop_fn(m), + ) + + def is_classmethod(fn): + return inspect.ismethod(fn) and getattr(fn, "__self__", None) == cls + + # Get and parse the source code for this class + sourcelines, file_lineno, filename = get_source_lines_and_file( + cls, torch._C.ErrorReport.call_stack() + ) + source = "".join(sourcelines) + + dedent_src = dedent(source) + py_ast = ast.parse(dedent_src) + + class_ast = py_ast.body[0] + assert isinstance(class_ast, ast.ClassDef) + + # Special case for dataclasses. In general we need access to the source code for + # an object in order to JIT compile it. But the dataclasses module dynamically synthesizes + # magic methods for classes, and we can't get the source code for these methods. As a + # workaround, we synthesize TorchScript-friendly implementations ourselves. + if dataclasses.is_dataclass(cls): + # Detect whether the user manually implemented any of the magic methods. If they did, + # we don't want to synthesize/override them. + overrides = { + method.name + for method in class_ast.body + if isinstance(method, ast.FunctionDef) + and method.name in DATACLASS_MAGIC_METHODS + } + for i, (name, _) in enumerate(methods): + # Is this a magic method we can synthesize? + synthesizer_fn = DATACLASS_MAGIC_METHODS.get(name) + if synthesizer_fn and name not in overrides: + parsed_def = synthesizer_fn(cls) + methods[i] = name, parsed_def + func = getattr(cls, name) + _jit_internal.loader.cache(func, parsed_def.source) + + method_defs = [ + get_jit_def(obj, name, self_name=self_name, is_classmethod=is_classmethod(obj)) + for (name, obj) in methods + ] + properties = get_class_properties(cls, self_name) + + leading_whitespace_len = len(source.split("\n", 1)[0]) - len( + dedent_src.split("\n", 1)[0] + ) + ctx = make_source_context( + source, filename, file_lineno, leading_whitespace_len, False + ) + assigns = get_class_assigns(ctx, class_ast) + + return build_class_def(ctx, class_ast, method_defs, properties, self_name, assigns) + + +def get_jit_def(fn, def_name, self_name=None, is_classmethod=False): + """ + Build a JIT AST (TreeView) from the given function. + + Args: + fn: A function object to compile or a pre-parsed ParsedDef object + def_name: The name to give to the resulting AST object. This is not + always the same as `fn.__name__`, for example: + def _forward(self): + ... + forward = _forward + In this case, the `__name__` attribute of the function object is "_forward", + but we want the result AST to have the name "forward". + self_name: If this function is a method, what the type name of `self` is. + """ + parsed_def = parse_def(fn) if not isinstance(fn, _ParsedDef) else fn + type_line = torch.jit.annotations.get_type_line(parsed_def.source) + fn_def = parsed_def.ast.body[0] + + if is_classmethod: + arg_name = fn_def.args.args[0].arg + # Insert a statement that assigns the first argument to the class + assign_stmt = ast.parse(f"{arg_name} = {self_name}").body[0] + fn_def.body.insert(0, assign_stmt) + + # Swap out the function signature and body if it is unused + if should_drop(fn): + unused_fn_def = ast.parse( + 'def unused_fn(self: Any):\n\traise RuntimeError("Cannot call @unused methods")' + ) + if len(unused_fn_def.body) != 1 or not isinstance( + unused_fn_def.body[0], ast.FunctionDef + ): + raise RuntimeError( + f"Expected a single top-level function: {parsed_def.filename}:{parsed_def.file_lineno}" + ) + unused_def = unused_fn_def.body[0] + fn_def.body = unused_def.body + # kwarg/vararg not supported by `build_def` + fn_def.args.kwarg = fn_def.args.vararg = None + for arg in fn_def.args.args + fn_def.args.kwonlyargs: + # Replace potentially unsupported type annotations by "Any" + arg.annotation = unused_def.args.args[0].annotation + if _is_drop_fn(fn): + # Dropping potentially unsupported return type annotation for jit._drop + fn_def.returns = None + fn_def.type_comment = None + + # If MonkeyType is installed, get all the consolidated type traces + # for the arguments from type_trace_db + type_trace_db = torch.jit._script._get_type_trace_db() + pdt_arg_types = None + if monkeytype_trace and not isinstance(fn, _ParsedDef): # type: ignore[truthy-function] + qualname = get_qualified_name(fn) + pdt_arg_types = type_trace_db.get_args_types(qualname) + + return build_def( + parsed_def.ctx, + fn_def, + type_line, + def_name, + self_name=self_name, + pdt_arg_types=pdt_arg_types, + ) + + +# TODO: more robust handling of recognizing ignore context manager +def is_torch_jit_ignore_context_manager(stmt): + # checks if the statement is torch.jit.ignore context manager + if isinstance(stmt.items[0].context_expr, ast.Call): + # extract torch part + function = stmt.items[0].context_expr.func + if isinstance(function, ast.Attribute): + attr_name = function.attr + attr_value = function.value + if attr_name == "_IgnoreContextManager" and isinstance( + attr_value, ast.Attribute + ): + # there should be at most two nested attributes (e.g torch.jit._IgnoreContextManager) + if attr_value.attr == "jit" and isinstance(attr_value.value, ast.Name): + if attr_value.value.id == "torch": + return True + return False + + +class Builder: + def __call__(self, ctx, node): + method = getattr(self, "build_" + node.__class__.__name__, None) + if method is None: + raise UnsupportedNodeError(ctx, node) + return method(ctx, node) + + +def build_class_def(ctx, py_def, methods, properties, self_name, assigns): + r = ctx.make_range( + py_def.lineno, py_def.col_offset, py_def.col_offset + len("class") + ) + return ClassDef( + Ident(r, self_name), [Stmt(method) for method in methods], properties, assigns + ) + + +def build_def(ctx, py_def, type_line, def_name, self_name=None, pdt_arg_types=None): + body = py_def.body + r = ctx.make_range(py_def.lineno, py_def.col_offset, py_def.col_offset + len("def")) + + param_list = build_param_list(ctx, py_def.args, self_name, pdt_arg_types) + return_type = None + if getattr(py_def, "returns", None) is not None: + return_type = build_expr(ctx, py_def.returns) + + decl = Decl(r, param_list, return_type) + is_method = self_name is not None + if type_line is not None: + type_comment_decl = torch._C.parse_type_comment(type_line) + decl = torch._C.merge_type_from_type_comment(decl, type_comment_decl, is_method) + + return Def(Ident(r, def_name), decl, build_stmts(ctx, body)) + + +_vararg_kwarg_err = ( + "Compiled functions can't take variable number of arguments " + "or use keyword-only arguments with defaults" +) + + +def build_param_list(ctx, py_args, self_name, pdt_arg_types=None): + if py_args.kwarg is not None: + expr = py_args.kwarg + ctx_range = ctx.make_range( + expr.lineno, expr.col_offset - 1, expr.col_offset + len(expr.arg) + ) + raise NotSupportedError(ctx_range, _vararg_kwarg_err) + if py_args.vararg is not None: + expr = py_args.vararg + ctx_range = ctx.make_range( + expr.lineno, expr.col_offset - 1, expr.col_offset + len(expr.arg) + ) + raise NotSupportedError(ctx_range, _vararg_kwarg_err) + if len(py_args.kw_defaults) > 0: + # kw_defaults is a list of the values for the kwargs (which default to None), + # so they don't actually have line numbers. + for arg in py_args.kw_defaults: + if arg is not None: + ctx_range = build_expr(ctx, arg).range() + raise NotSupportedError(ctx_range, _vararg_kwarg_err) + + # List of Tuple of args and type as inferred by profile directed typing + arg_and_types = [ + ( + arg, + pdt_arg_types[arg.arg] + if pdt_arg_types and bool(pdt_arg_types[arg.arg]) + else None, + ) + for arg in py_args.args + ] + arg_and_types_kwonlyargs = [ + ( + arg, + pdt_arg_types[arg.arg] + if pdt_arg_types and bool(pdt_arg_types[arg.arg]) + else None, + ) + for arg in py_args.kwonlyargs + ] + + result = [ + build_param(ctx, arg, self_name, kwarg_only=False, pdt_arg_type=arg_type) + for arg, arg_type in arg_and_types + ] + result += [ + build_param(ctx, arg, self_name, kwarg_only=True, pdt_arg_type=arg_type) + for arg, arg_type in arg_and_types_kwonlyargs + ] + return result + + +def build_param(ctx, py_arg, self_name, kwarg_only, pdt_arg_type=None): + # NB: In Python3 py_arg is a pair of (str arg, expr? annotation) + name = py_arg.arg + r = ctx.make_range(py_arg.lineno, py_arg.col_offset, py_arg.col_offset + len(name)) + if getattr(py_arg, "annotation", None) is not None: + annotation_expr = build_expr(ctx, py_arg.annotation) + elif pdt_arg_type: + annotation_expr = Var(Ident(r, pdt_arg_type)) + elif self_name is not None and name == "self": + annotation_expr = Var(Ident(r, self_name)) + else: + annotation_expr = EmptyTypeAnnotation(r) + return Param(annotation_expr, Ident(r, name), kwarg_only) + + +def build_ignore_context_manager(ctx, stmt): + InputType = namedtuple("InputType", ["name", "ann"]) + OutputType = namedtuple("OutputType", ["name", "ann"]) + + def process_ins_outs(args): + # parse the context manager to figure out inputs and outputs + # with their annotated types + # TODO: add input, output validator + inputs = [] + outputs = [] + for arg in args: + var_name = arg.arg + var_ann = arg.value.value + var_decl_type, var_ann = var_ann.split(":") + if var_decl_type == "inp": + inputs.append(InputType(var_name, var_ann)) + if var_decl_type == "out": + outputs.append(OutputType(var_name, var_ann)) + return inputs, outputs + + def create_unique_name_ext(ctx, stmt): + # extension will be based on the full path filename plus + # the line number of original context manager + fn = re.sub(r"[^a-zA-Z0-9_]", "_", ctx.filename) + return f"{fn}_{stmt.lineno}" + + def build_return_ann_stmt(outputs): + return_type_ann = "" + return_statement_str = "return " + if len(outputs) == 0: + return_type_ann += " -> None" + if len(outputs) == 1: + return_type_ann = " -> " + outputs[0].ann + return_statement_str += outputs[0].name + if len(outputs) > 1: + return_type_ann = " -> Tuple" + return_type_ann += "[" + ", ".join([var.ann for var in outputs]) + "]" + return_statement_str += ", ".join([var.name for var in outputs]) + return return_type_ann, return_statement_str + + def build_args(args): + return ", ".join([arg.name for arg in args]) + + inputs, outputs = process_ins_outs(stmt.items[0].context_expr.keywords) + + # build the replacement function str with given inputs and outputs + ignore_function_name = "func_ignore_" + create_unique_name_ext(ctx, stmt) + ignore_function_str = "\ndef " + ignore_function_name + ignore_function_str += ( + "(" + ", ".join([var.name + " :" + var.ann for var in inputs]) + ")" + ) + + return_ann, return_stmt = build_return_ann_stmt(outputs) + ignore_function_str += return_ann + ": pass" + + # first create the functionDef object from just declaration + ignore_function = ast.parse(ignore_function_str).body[0] + + # dump the body of context manager to dummy function + ignore_function.body = stmt.body # type: ignore[attr-defined] + + # insert return statement to the function + return_stmt = ast.parse(return_stmt).body[0] + ignore_function.body.append(return_stmt) # type: ignore[attr-defined] + + # registers the custom function in the global context + ignore_func_str = "@torch.jit.ignore\n" + astunparse.unparse(ignore_function) + ignore_func_str += f'\nglobals()["{ignore_function_name}"] = {ignore_function_name}' + exec(ignore_func_str) # noqa: P204 + + # build the statements as: + # , , ... = torch.jit.frontend.(, ) + assign_str_lhs = build_args(outputs) + # this function will be registered in torch.jit.frontend module by default + assign_str_rhs = ( + f"torch.jit.frontend.{ignore_function_name}(" + build_args(inputs) + ")" + ) + + if len(outputs) > 0: + assign_str = assign_str_lhs + " = " + assign_str_rhs + else: + assign_str = assign_str_rhs + assign_ast = ast.parse(assign_str).body[0] + return assign_ast + + +def get_default_args(fn): + if fn is None: + return {} + + signature = inspect.signature(fn) + + return { + k: v.default + for k, v in signature.parameters.items() + if v.default is not inspect.Parameter.empty + } + + +def get_default_args_for_class(cls): + """ + Get default arguments for all methods in a class (except for static methods). + + Args: + cls: type - The class type to inspect for default arguments. + Returns: + A Dict[str, Dict[str, Any]] which maps each method name to a Dict[str, Any] + that maps each argument name to its default value. + """ + # Get methods (except static methods because those are compiled separately as + # if they were independent script functions). + methods = inspect.getmembers( + cls, + predicate=lambda m: (inspect.ismethod(m) or inspect.isfunction(m)) + and not is_static_fn(cls, m.__name__) + and m.__name__ in cls.__dict__, + ) + + # Get method defaults. Property defaults do not need to be considered + # because setters cannot be invoked without a value. + defaults = { + method_name: get_default_args(method_impl) + for method_name, method_impl in methods + } + + return defaults + + +class WithItemBuilder(Builder): + @staticmethod + def build_withitem(ctx, item): + lineno = item.context_expr.lineno + start = item.context_expr.col_offset + end = start + len(pretty_node_names[ast.With]) + op_vars = item.optional_vars + r = ctx.make_range(lineno, start, end) + + return WithItem( + r, + build_expr(ctx, item.context_expr), + build_expr(ctx, op_vars) if op_vars else None, + ) + + +class StmtBuilder(Builder): + augassign_map = { + ast.Add: "+", + ast.Sub: "-", + ast.Mult: "*", + ast.Div: "/", + ast.Mod: "%", + ast.BitOr: "|", + ast.BitAnd: "&", + ast.BitXor: "^", + ast.LShift: "<<", + ast.RShift: ">>", + ast.Pow: "**", + } + + @staticmethod + def build_Expr(ctx, stmt): + value = stmt.value + if value.__class__.__name__ == "Str": + # If a statement is a string literal expression, + # then it is a docstring. Just ignore it. + return None + else: + return ExprStmt(build_expr(ctx, value)) + + @staticmethod + def build_Assign(ctx, stmt): + rhs = build_expr(ctx, stmt.value) + lhs = [build_expr(ctx, x) for x in stmt.targets] + return Assign(lhs, rhs) + + @staticmethod + def build_AnnAssign(ctx, stmt): + if stmt.value is None: + raise UnsupportedNodeError(ctx, stmt, reason="without assigned value") + + # Disallow type annotations on instance attributes outside of __init__ + if ( + type(stmt.target) == ast.Attribute + and stmt.target.value.id == "self" # type: ignore[attr-defined] + and ctx.funcname != "__init__" + ): + start = stmt.col_offset + end = start + len(f"self.{stmt.target.attr}") + if hasattr(stmt.annotation, "id"): + end += len(f": {stmt.annotation.id}") + sr = ctx.make_range(stmt.lineno, start, end) + raise ValueError( + "Type annotations on instance attributes must be declared in " + f"__init__, not '{ctx.funcname}': {sr}" + ) + + rhs = build_expr(ctx, stmt.value) + lhs = build_expr(ctx, stmt.target) + the_type = build_expr(ctx, stmt.annotation) + return Assign([lhs], rhs, the_type) + + @staticmethod + def build_Delete(ctx, stmt): + r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("del")) + + return Delete(r, [build_expr(ctx, target) for target in stmt.targets]) + + @staticmethod + def build_Return(ctx, stmt): + r = ctx.make_range( + stmt.lineno, stmt.col_offset, stmt.col_offset + len("return") + ) + return Return(r, None if stmt.value is None else build_expr(ctx, stmt.value)) + + @staticmethod + def build_Raise(ctx, stmt): + r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("raise")) + expr = build_expr(ctx, stmt.exc) + return Raise(r, expr) + + @staticmethod + def build_Assert(ctx, stmt): + r = ctx.make_range( + stmt.lineno, stmt.col_offset, stmt.col_offset + len("assert") + ) + test = build_expr(ctx, stmt.test) + msg = build_expr(ctx, stmt.msg) if stmt.msg is not None else None + return Assert(r, test, msg) + + @staticmethod + def build_AugAssign(ctx, stmt): + lhs = build_expr(ctx, stmt.target) + rhs = build_expr(ctx, stmt.value) + op = type(stmt.op) + if op in StmtBuilder.augassign_map: + op_token = StmtBuilder.augassign_map[op] + else: + raise NotSupportedError( + find_before(ctx, rhs.range().start, "=", offsets=(-1, 0)), + "unsupported kind of augmented assignment: " + op.__name__, + ) + return AugAssign(lhs, op_token, rhs) + + @staticmethod + def build_While(ctx, stmt): + if stmt.orelse: + # TODO: try to recover the location of else:? Python doesn't give us useful + # annotations in this case + raise NotSupportedError( + None, "else branches of while loops aren't supported" + ) + r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("while")) + return While(r, build_expr(ctx, stmt.test), build_stmts(ctx, stmt.body)) + + @staticmethod + def build_For(ctx, stmt): + r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("for")) + if stmt.orelse: + raise NotSupportedError(r, "else branches of for loops aren't supported") + + return For( + r, + [build_expr(ctx, stmt.target)], + [build_expr(ctx, stmt.iter)], + build_stmts(ctx, stmt.body), + ) + + @staticmethod + def build_If(ctx, stmt): + r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("if")) + return If( + r, + build_expr(ctx, stmt.test), + build_stmts(ctx, stmt.body), + build_stmts(ctx, stmt.orelse), + ) + + @staticmethod + def build_Print(ctx, stmt): + r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("print")) + if stmt.dest: + raise NotSupportedError( + r, "print statements with non-default destinations aren't supported" + ) + args = [build_expr(ctx, val) for val in stmt.values] + return ExprStmt(Apply(Var(Ident(r, "print")), args, [])) + + @staticmethod + def build_Pass(ctx, stmt): + r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("pass")) + return Pass(r) + + @staticmethod + def build_Break(ctx, stmt): + r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("break")) + return Break(r) + + @staticmethod + def build_Continue(ctx, stmt): + r = ctx.make_range( + stmt.lineno, stmt.col_offset, stmt.col_offset + len("continue") + ) + return Continue(r) + + @staticmethod + def build_With(ctx, stmt): + r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("with")) + # Handle ignore context manager + if is_torch_jit_ignore_context_manager(stmt): + if not _IS_ASTUNPARSE_INSTALLED: + raise RuntimeError( + "torch.jit._IgnoreContextManager requires installing Python library `astunparse`, \ + please install it in your Python environment" + ) + assign_ast = build_ignore_context_manager(ctx, stmt) + return build_stmt(ctx, assign_ast) + return With(r, build_withitems(ctx, stmt.items), build_stmts(ctx, stmt.body)) + + +class ExprBuilder(Builder): + binop_map = { + ast.Add: "+", + ast.Sub: "-", + ast.Mult: "*", + ast.Div: "/", + ast.Pow: "**", + ast.Mod: "%", + ast.FloorDiv: "//", + ast.BitAnd: "&", + ast.BitXor: "^", + ast.BitOr: "|", + ast.LShift: "<<", + ast.RShift: ">>", + } + + binop_map[ast.MatMult] = "@" + + unop_map = { + ast.Not: "not", + ast.USub: "-", + ast.Invert: "~", + } + + boolop_map = { + ast.And: "and", + ast.Or: "or", + } + + cmpop_map = { + ast.Eq: "==", + ast.NotEq: "!=", + ast.LtE: "<=", + ast.Lt: "<", + ast.GtE: ">=", + ast.Gt: ">", + ast.Is: "is", + ast.IsNot: "is not", + ast.In: "in", + ast.NotIn: "not in", + } + + @staticmethod + def build_Attribute(ctx, expr): + base = build_expr(ctx, expr.value) + # expr.attr is just a string, so it's not annotated in any way, so we have + # to build the range manually + source = ctx.source.encode("utf-8") + + def get_char(index): + return chr(source[index]) + + start_pos = base.range().end + 1 + while get_char(start_pos) in string.whitespace: # Skip whitespace + start_pos += 1 + end_pos = start_pos + len(expr.attr) + name_range = ctx.make_raw_range(start_pos, end_pos) + return Select(base, Ident(name_range, expr.attr)) + + @staticmethod + def build_Call(ctx, expr): + func = build_expr(ctx, expr.func) + args = [build_expr(ctx, py_arg) for py_arg in expr.args] + if hasattr(expr, "starargs") and expr.starargs: + stararg_expr = build_expr(ctx, expr.starargs) + args += [Starred(stararg_expr.range(), stararg_expr)] + kwargs = [] + for kw in expr.keywords: + kw_expr = build_expr(ctx, kw.value) + # XXX: we could do a better job at figuring out the range for the name here + if not kw.arg: + raise NotSupportedError( + kw_expr.range(), "keyword-arg expansion is not supported" + ) + kwargs.append(Attribute(Ident(kw_expr.range(), kw.arg), kw_expr)) + return Apply(func, args, kwargs) + + @staticmethod + def build_Ellipsis(ctx, expr): + r = ctx.make_range( + expr.lineno, expr.col_offset, expr.col_offset + 3 + ) # len("...") == 3 + return Dots(r) + + @staticmethod + def build_Name(ctx, expr): + r = ctx.make_range(expr.lineno, expr.col_offset, expr.col_offset + len(expr.id)) + if expr.id.startswith(_reserved_prefix): + raise NotSupportedError( + r, + "names of variables used in JIT-ed functions " + "can't start with " + _reserved_prefix, + ) + if expr.id == "True": + return TrueLiteral(r) + elif expr.id == "False": + return FalseLiteral(r) + elif expr.id == "None": + return NoneLiteral(r) + elif expr.id == "Ellipsis": + return Dots(r) + return Var(Ident(r, expr.id)) + + @staticmethod + def build_NameConstant(ctx, expr): + r = ctx.make_range( + expr.lineno, expr.col_offset, expr.col_offset + len(str(expr.value)) + ) + if expr.value is True: + return TrueLiteral(r) + elif expr.value is False: + return FalseLiteral(r) + elif expr.value is None: + return NoneLiteral(r) + elif expr.value == Ellipsis: + return Dots(r) + else: + raise ValueError("Name constant value unsupported: " + str(expr.value)) + + @staticmethod + def build_BinOp(ctx, expr): + lhs = build_expr(ctx, expr.left) + rhs = build_expr(ctx, expr.right) + op = type(expr.op) + + if op == ast.Div and not ctx.uses_true_division: + err_range = ctx.make_raw_range(lhs.range().end, rhs.range().start) + raise FrontendError( + err_range, + "Division of ints in TorchScript uses Python 3 true " + "division semantics. Please put `from __future__ " + "import division` at the top of your file", + ) + op_token = ExprBuilder.binop_map.get(op) + if op_token is None: + err_range = ctx.make_raw_range(lhs.range().end, rhs.range().start) + raise NotSupportedError( + err_range, "unsupported binary operator: " + op.__name__ + ) + return BinOp(op_token, lhs, rhs) + + @staticmethod + def build_UnaryOp(ctx, expr): + sub_expr = build_expr(ctx, expr.operand) + op = type(expr.op) + op_token = ExprBuilder.unop_map.get(op) + if op_token is None: + raise NotSupportedError( + expr.range(), "unsupported unary operator: " + op.__name__ + ) + r = ctx.make_range( + expr.lineno, expr.col_offset, expr.col_offset + len(op_token) + ) + return UnaryOp(r, op_token, sub_expr) + + @staticmethod + def build_BoolOp(ctx, expr): + if len(expr.values) < 2: + raise AssertionError( + "expected at least 2 values in BoolOp, but got " + str(len(expr.values)) + ) + sub_exprs = [build_expr(ctx, sub_expr) for sub_expr in expr.values] + op = type(expr.op) + op_token = ExprBuilder.boolop_map.get(op) + if op_token is None: + err_range = ctx.make_raw_range( + sub_exprs[0].range().end, sub_exprs[1].range().start + ) + raise NotSupportedError( + err_range, "unsupported boolean operator: " + op.__name__ + ) + lhs = sub_exprs[0] + for rhs in sub_exprs[1:]: + lhs = BinOp(op_token, lhs, rhs) + return lhs + + @staticmethod + def build_IfExp(ctx, expr): + return TernaryIf( + build_expr(ctx, expr.test), + build_expr(ctx, expr.body), + build_expr(ctx, expr.orelse), + ) + + @staticmethod + def build_Compare(ctx, expr): + operands = [build_expr(ctx, e) for e in [expr.left] + list(expr.comparators)] + result = None + for lhs, op_, rhs in zip(operands, expr.ops, operands[1:]): + op = type(op_) + op_token = ExprBuilder.cmpop_map.get(op) + r = ctx.make_raw_range(lhs.range().end, rhs.range().start) + if op_token is None: + raise NotSupportedError( + r, "unsupported comparison operator: " + op.__name__ + ) + + if op == ast.NotIn: + # NB: `not in` is just `not( in )`, so we don't introduce new tree view + # but just make it a nested call in our tree view structure + in_expr = BinOp("in", lhs, rhs) + cmp_expr = UnaryOp(r, "not", in_expr) + else: + cmp_expr = BinOp(op_token, lhs, rhs) + + if result is None: + result = cmp_expr + else: + result = BinOp("and", result, cmp_expr) + return result + + @staticmethod + def build_Subscript(ctx, expr): + def build_SliceExpr(ctx, base, slice_expr): + lower = ( + build_expr(ctx, slice_expr.lower) + if slice_expr.lower is not None + else None + ) + upper = ( + build_expr(ctx, slice_expr.upper) + if slice_expr.upper is not None + else None + ) + step = ( + build_expr(ctx, slice_expr.step) + if slice_expr.step is not None + else None + ) + return SliceExpr(base.range(), lower, upper, step) + + def build_Index(ctx, base, index_expr): + if isinstance(index_expr.value, ast.Tuple): + raise NotSupportedError( + base.range(), + "slicing multiple dimensions with tuples not supported yet", + ) + return build_expr(ctx, index_expr.value) + + def build_ExtSlice(ctx, base, extslice): + sub_exprs = [] + for expr in extslice.dims: + sub_type = type(expr) + if sub_type is ast.Index: + sub_exprs.append(build_Index(ctx, base, expr)) + elif sub_type is ast.Slice: + sub_exprs.append(build_SliceExpr(ctx, base, expr)) + elif sub_type is ast.Ellipsis: + sub_exprs.append(Dots(base.range())) + else: + raise NotSupportedError( + base.range(), + f"slicing multiple dimensions with {sub_type} not supported", + ) + return sub_exprs + + base = build_expr(ctx, expr.value) + sub_type = type(expr.slice) + if sub_type is ast.Index: + if isinstance(expr.slice.value, ast.Tuple): + # N-dimensional indexing using Tuple: x[(i, j, k)] is equivalent to x[i, j, k] + # XXX: Indexing using a list is **different**! It triggers advanced indexing. + indices = [ + build_expr(ctx, index_expr) for index_expr in expr.slice.value.elts + ] + if not indices: + # `col_offset` is an int, but `end_col_offset` is + # `Optional[int]`. The magic number is here to make + # sure we can parse `()` on any machine + r = ctx.make_range( + expr.lineno, + expr.slice.value.col_offset, + expr.slice.value.col_offset + 2, + ) + tup = TupleLiteral(r, []) + indices.append(tup) + return Subscript(base, indices) + else: + return Subscript(base, [build_expr(ctx, expr.slice.value)]) + elif sub_type is ast.Slice: + return Subscript(base, [build_SliceExpr(ctx, base, expr.slice)]) + elif sub_type is ast.ExtSlice: + return Subscript(base, build_ExtSlice(ctx, base, expr.slice)) + elif sys.version_info >= ( + 3, + 9, + ): # In Python3.9 array indicies are not wrapped in ast.Index + if sub_type is ast.Tuple: + # N-dimensional indexing using Tuple: x[(i, j, k)] is equivalent to x[i, j, k] + indices = [] + for index_expr in expr.slice.elts: + if isinstance(index_expr, ast.Slice): + indices.append(build_SliceExpr(ctx, base, index_expr)) + else: + indices.append(build_expr(ctx, index_expr)) + # Special-case logic for `typing.Tuple[()]` + if not indices: + # See note above r.e. magic number + r = ctx.make_range( + expr.lineno, expr.slice.col_offset, expr.slice.col_offset + 2 + ) + tup = TupleLiteral(r, []) + indices.append(tup) + return Subscript(base, indices) + return Subscript(base, [build_expr(ctx, expr.slice)]) + else: # Ellipsis (can only happen in Python 2) + raise NotSupportedError(base.range(), "ellipsis is not supported") + + @staticmethod + def build_List(ctx, expr): + return ListLiteral( + ctx.make_range(expr.lineno, expr.col_offset, expr.col_offset + 1), + [build_expr(ctx, e) for e in expr.elts], + ) + + @staticmethod + def build_Tuple(ctx, expr): + return TupleLiteral( + ctx.make_range(expr.lineno, expr.col_offset, expr.col_offset + 1), + [build_expr(ctx, e) for e in expr.elts], + ) + + @staticmethod + def build_Dict(ctx, expr): + range = ctx.make_range(expr.lineno, expr.col_offset, expr.col_offset + 1) + if expr.keys and not expr.keys[0]: + raise NotSupportedError( + range, "Dict expansion (e.g. `{**dict}`) is not supported" + ) + return DictLiteral( + range, + [build_expr(ctx, e) for e in expr.keys], + [build_expr(ctx, e) for e in expr.values], + ) + + @staticmethod + def build_Num(ctx, expr): + value = str(expr.value) + r = ctx.make_range(expr.lineno, expr.col_offset, expr.col_offset + len(value)) + return Const(r, value) + + @staticmethod + def build_Constant(ctx, expr): + value = expr.value + if value is None or isinstance(value, bool): + # NB: this check has to happen before the int check because bool is + # a subclass of int + return ExprBuilder.build_NameConstant(ctx, expr) + if isinstance(value, (int, float, complex)): + return ExprBuilder.build_Num(ctx, expr) + elif isinstance(value, str): + return ExprBuilder.build_Str(ctx, expr) + elif isinstance(value, type(Ellipsis)): + return ExprBuilder.build_Ellipsis(ctx, expr) + else: + error_range = ctx.make_range( + expr.lineno, expr.col_offset, expr.col_offset + len(str(value)) + ) + raise FrontendError(error_range, "Unknown Constant expression type") + + @staticmethod + def build_Str(ctx, expr): + value = str(expr.value) + r = ctx.make_range( + expr.lineno, expr.col_offset, expr.col_offset + len(value) + 1 + ) + return StringLiteral(r, value) + + @staticmethod + def build_JoinedStr(ctx, expr): + s = "" + args = [] + for value in expr.values: + r = ctx.make_range(value.lineno, value.col_offset, value.col_offset + 1) + if isinstance(value, ast.FormattedValue): + if value.conversion != -1: + raise NotSupportedError(r, "Don't support conversion in JoinedStr") + if value.format_spec is not None: + raise NotSupportedError(r, "Don't support formatting in JoinedStr") + s += "{}" + args.append(build_expr(ctx, value.value)) + elif isinstance(value, ast.Str): + s += value.s + else: + raise NotSupportedError(r, "Unsupported value in JoinedStr") + + r = ctx.make_range(expr.lineno, expr.col_offset, expr.col_offset + 1) + return Apply(Select(StringLiteral(r, s), Ident(r, "format")), args, []) + + @staticmethod + def build_ListComp(ctx, stmt): + r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset) + if len(stmt.generators) != 1: + raise NotSupportedError(r, "Only a single generator is currently supported") + + if len(stmt.generators[0].ifs) != 0: + raise NotSupportedError(r, "Comprehension ifs are not supported yet") + + elt_expr = build_expr(ctx, stmt.elt) + target_expr = build_expr(ctx, stmt.generators[0].target) + iter_expr = build_expr(ctx, stmt.generators[0].iter) + + return ListComp(r, elt_expr, target_expr, iter_expr) + + @staticmethod + def build_GeneratorExp(ctx, stmt): + # Convert Generator expression to ListComp + return ExprBuilder.build_ListComp(ctx, stmt) + + @staticmethod + def build_DictComp(ctx, stmt): + r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset) + if len(stmt.generators) != 1: + raise NotSupportedError(r, "Only a single generator is currently supported") + + if len(stmt.generators[0].ifs) != 0: + raise NotSupportedError(r, "Comprehension ifs are not supported yet") + + key_expr = build_expr(ctx, stmt.key) + value_expr = build_expr(ctx, stmt.value) + target_expr = build_expr(ctx, stmt.generators[0].target) + iter_expr = build_expr(ctx, stmt.generators[0].iter) + + return DictComp(r, key_expr, value_expr, target_expr, iter_expr) + + @staticmethod + def build_Starred(ctx, expr): + r = ctx.make_range(expr.lineno, expr.col_offset, expr.col_offset + 1) + return Starred(r, build_expr(ctx, expr.value)) + + +build_expr = ExprBuilder() +build_stmt = StmtBuilder() +build_withitem = WithItemBuilder() + + +def find_before(ctx, pos, substr, offsets=(0, 0)): + new_pos = ctx.source[:pos].rindex(substr) + return ctx.make_raw_range(new_pos + offsets[0], new_pos + len(substr) + offsets[1]) diff --git a/shared/package-files/71/71268d4969681c008e765f380caee203efb80e68aa4ad972458349b54d3cb216/sb2 b/shared/package-files/71/71268d4969681c008e765f380caee203efb80e68aa4ad972458349b54d3cb216/sb2 new file mode 100644 index 0000000000000000000000000000000000000000..21b7e178bf1a3ac8e15e5f1a9fe4982fc4794adb Binary files /dev/null and b/shared/package-files/71/71268d4969681c008e765f380caee203efb80e68aa4ad972458349b54d3cb216/sb2 differ diff --git a/shared/package-files/71/71268d4969681c008e765f380caee203efb80e68aa4ad972458349b54d3cb216/sb3 b/shared/package-files/71/71268d4969681c008e765f380caee203efb80e68aa4ad972458349b54d3cb216/sb3 new file mode 100644 index 0000000000000000000000000000000000000000..21b7e178bf1a3ac8e15e5f1a9fe4982fc4794adb Binary files /dev/null and b/shared/package-files/71/71268d4969681c008e765f380caee203efb80e68aa4ad972458349b54d3cb216/sb3 differ diff --git a/shared/package-files/71/71295caa6c9a285a5d9a116e676ce3c48cb295c8e273baa2ea354c627d2b1c5e/direct_url.json b/shared/package-files/71/71295caa6c9a285a5d9a116e676ce3c48cb295c8e273baa2ea354c627d2b1c5e/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..7ed83c92ed1d020dad95a19aba850de63c246648 --- /dev/null +++ b/shared/package-files/71/71295caa6c9a285a5d9a116e676ce3c48cb295c8e273baa2ea354c627d2b1c5e/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///croot/pycosat_1696536503704/work"} \ No newline at end of file diff --git a/shared/package-files/71/712c7657759a6611284a731e077aea1efb198f8d4d74d1fc721fa3e616c8efc1/_assert_tensor_metadata_compositeimplicitautograd_dispatch.h b/shared/package-files/71/712c7657759a6611284a731e077aea1efb198f8d4d74d1fc721fa3e616c8efc1/_assert_tensor_metadata_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..636174f01d346241c842026e475b056d375813dd --- /dev/null +++ b/shared/package-files/71/712c7657759a6611284a731e077aea1efb198f8d4d74d1fc721fa3e616c8efc1/_assert_tensor_metadata_compositeimplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API void _assert_tensor_metadata(const at::Tensor & a, at::OptionalIntArrayRef size=c10::nullopt, at::OptionalIntArrayRef stride=c10::nullopt, c10::optional dtype=c10::nullopt); +TORCH_API void _assert_tensor_metadata_symint(const at::Tensor & a, at::OptionalSymIntArrayRef size=c10::nullopt, at::OptionalSymIntArrayRef stride=c10::nullopt, c10::optional dtype=c10::nullopt); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/71/712e41916c40db1fb90d38db541b48752aced6754cc6cb32785c5535911a6b28/_reshape_alias_copy_compositeexplicitautograd_dispatch.h b/shared/package-files/71/712e41916c40db1fb90d38db541b48752aced6754cc6cb32785c5535911a6b28/_reshape_alias_copy_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9f458d70733b0a423c6361bf8ec6f6b8d619a671 --- /dev/null +++ b/shared/package-files/71/712e41916c40db1fb90d38db541b48752aced6754cc6cb32785c5535911a6b28/_reshape_alias_copy_compositeexplicitautograd_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & _reshape_alias_copy_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride); +TORCH_API at::Tensor & _reshape_alias_copy_outf(const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride, at::Tensor & out); +TORCH_API at::Tensor & _reshape_alias_copy_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride); +TORCH_API at::Tensor & _reshape_alias_copy_symint_outf(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/71/71302ad0adc69cb0623640a064d56bf6b2edf07debae7ca11da78b73f6130689/dense.py b/shared/package-files/71/71302ad0adc69cb0623640a064d56bf6b2edf07debae7ca11da78b73f6130689/dense.py new file mode 100644 index 0000000000000000000000000000000000000000..4b2f2d768471a5a65edd2c6e7793c975188a490c --- /dev/null +++ b/shared/package-files/71/71302ad0adc69cb0623640a064d56bf6b2edf07debae7ca11da78b73f6130689/dense.py @@ -0,0 +1,1090 @@ +import random + +from sympy.core.basic import Basic +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.sympify import sympify +from sympy.functions.elementary.trigonometric import cos, sin +from sympy.utilities.decorator import doctest_depends_on +from sympy.utilities.exceptions import sympy_deprecation_warning +from sympy.utilities.iterables import is_sequence + +from .common import ShapeError +from .decompositions import _cholesky, _LDLdecomposition +from .matrices import MatrixBase +from .repmatrix import MutableRepMatrix, RepMatrix +from .solvers import _lower_triangular_solve, _upper_triangular_solve + + +def _iszero(x): + """Returns True if x is zero.""" + return x.is_zero + + +class DenseMatrix(RepMatrix): + """Matrix implementation based on DomainMatrix as the internal representation""" + + # + # DenseMatrix is a superclass for both MutableDenseMatrix and + # ImmutableDenseMatrix. Methods shared by both classes but not for the + # Sparse classes should be implemented here. + # + + is_MatrixExpr = False # type: bool + + _op_priority = 10.01 + _class_priority = 4 + + @property + def _mat(self): + sympy_deprecation_warning( + """ + The private _mat attribute of Matrix is deprecated. Use the + .flat() method instead. + """, + deprecated_since_version="1.9", + active_deprecations_target="deprecated-private-matrix-attributes" + ) + + return self.flat() + + def _eval_inverse(self, **kwargs): + return self.inv(method=kwargs.get('method', 'GE'), + iszerofunc=kwargs.get('iszerofunc', _iszero), + try_block_diag=kwargs.get('try_block_diag', False)) + + def as_immutable(self): + """Returns an Immutable version of this Matrix + """ + from .immutable import ImmutableDenseMatrix as cls + return cls._fromrep(self._rep.copy()) + + def as_mutable(self): + """Returns a mutable version of this matrix + + Examples + ======== + + >>> from sympy import ImmutableMatrix + >>> X = ImmutableMatrix([[1, 2], [3, 4]]) + >>> Y = X.as_mutable() + >>> Y[1, 1] = 5 # Can set values in Y + >>> Y + Matrix([ + [1, 2], + [3, 5]]) + """ + return Matrix(self) + + def cholesky(self, hermitian=True): + return _cholesky(self, hermitian=hermitian) + + def LDLdecomposition(self, hermitian=True): + return _LDLdecomposition(self, hermitian=hermitian) + + def lower_triangular_solve(self, rhs): + return _lower_triangular_solve(self, rhs) + + def upper_triangular_solve(self, rhs): + return _upper_triangular_solve(self, rhs) + + cholesky.__doc__ = _cholesky.__doc__ + LDLdecomposition.__doc__ = _LDLdecomposition.__doc__ + lower_triangular_solve.__doc__ = _lower_triangular_solve.__doc__ + upper_triangular_solve.__doc__ = _upper_triangular_solve.__doc__ + + +def _force_mutable(x): + """Return a matrix as a Matrix, otherwise return x.""" + if getattr(x, 'is_Matrix', False): + return x.as_mutable() + elif isinstance(x, Basic): + return x + elif hasattr(x, '__array__'): + a = x.__array__() + if len(a.shape) == 0: + return sympify(a) + return Matrix(x) + return x + + +class MutableDenseMatrix(DenseMatrix, MutableRepMatrix): + + def simplify(self, **kwargs): + """Applies simplify to the elements of a matrix in place. + + This is a shortcut for M.applyfunc(lambda x: simplify(x, ratio, measure)) + + See Also + ======== + + sympy.simplify.simplify.simplify + """ + from sympy.simplify.simplify import simplify as _simplify + for (i, j), element in self.todok().items(): + self[i, j] = _simplify(element, **kwargs) + + +MutableMatrix = Matrix = MutableDenseMatrix + +########### +# Numpy Utility Functions: +# list2numpy, matrix2numpy, symmarray +########### + + +def list2numpy(l, dtype=object): # pragma: no cover + """Converts Python list of SymPy expressions to a NumPy array. + + See Also + ======== + + matrix2numpy + """ + from numpy import empty + a = empty(len(l), dtype) + for i, s in enumerate(l): + a[i] = s + return a + + +def matrix2numpy(m, dtype=object): # pragma: no cover + """Converts SymPy's matrix to a NumPy array. + + See Also + ======== + + list2numpy + """ + from numpy import empty + a = empty(m.shape, dtype) + for i in range(m.rows): + for j in range(m.cols): + a[i, j] = m[i, j] + return a + + +########### +# Rotation matrices: +# rot_givens, rot_axis[123], rot_ccw_axis[123] +########### + + +def rot_givens(i, j, theta, dim=3): + r"""Returns a a Givens rotation matrix, a a rotation in the + plane spanned by two coordinates axes. + + Explanation + =========== + + The Givens rotation corresponds to a generalization of rotation + matrices to any number of dimensions, given by: + + .. math:: + G(i, j, \theta) = + \begin{bmatrix} + 1 & \cdots & 0 & \cdots & 0 & \cdots & 0 \\ + \vdots & \ddots & \vdots & & \vdots & & \vdots \\ + 0 & \cdots & c & \cdots & -s & \cdots & 0 \\ + \vdots & & \vdots & \ddots & \vdots & & \vdots \\ + 0 & \cdots & s & \cdots & c & \cdots & 0 \\ + \vdots & & \vdots & & \vdots & \ddots & \vdots \\ + 0 & \cdots & 0 & \cdots & 0 & \cdots & 1 + \end{bmatrix} + + Where $c = \cos(\theta)$ and $s = \sin(\theta)$ appear at the intersections + ``i``\th and ``j``\th rows and columns. + + For fixed ``i > j``\, the non-zero elements of a Givens matrix are + given by: + + - $g_{kk} = 1$ for $k \ne i,\,j$ + - $g_{kk} = c$ for $k = i,\,j$ + - $g_{ji} = -g_{ij} = -s$ + + Parameters + ========== + + i : int between ``0`` and ``dim - 1`` + Represents first axis + j : int between ``0`` and ``dim - 1`` + Represents second axis + dim : int bigger than 1 + Number of dimentions. Defaults to 3. + + Examples + ======== + + >>> from sympy import pi, rot_givens + + A counterclockwise rotation of pi/3 (60 degrees) around + the third axis (z-axis): + + >>> rot_givens(1, 0, pi/3) + Matrix([ + [ 1/2, -sqrt(3)/2, 0], + [sqrt(3)/2, 1/2, 0], + [ 0, 0, 1]]) + + If we rotate by pi/2 (90 degrees): + + >>> rot_givens(1, 0, pi/2) + Matrix([ + [0, -1, 0], + [1, 0, 0], + [0, 0, 1]]) + + This can be generalized to any number + of dimensions: + + >>> rot_givens(1, 0, pi/2, dim=4) + Matrix([ + [0, -1, 0, 0], + [1, 0, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1]]) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Givens_rotation + + See Also + ======== + + rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis (clockwise around the x axis) + rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis (clockwise around the y axis) + rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis (clockwise around the z axis) + rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis (counterclockwise around the x axis) + rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis (counterclockwise around the y axis) + rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis (counterclockwise around the z axis) + """ + if not isinstance(dim, int) or dim < 2: + raise ValueError('dim must be an integer biggen than one, ' + 'got {}.'.format(dim)) + + if i == j: + raise ValueError('i and j must be different, ' + 'got ({}, {})'.format(i, j)) + + for ij in [i, j]: + if not isinstance(ij, int) or ij < 0 or ij > dim - 1: + raise ValueError('i and j must be integers between 0 and ' + '{}, got i={} and j={}.'.format(dim-1, i, j)) + + theta = sympify(theta) + c = cos(theta) + s = sin(theta) + M = eye(dim) + M[i, i] = c + M[j, j] = c + M[i, j] = s + M[j, i] = -s + return M + + +def rot_axis3(theta): + r"""Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis. + + Explanation + =========== + + For a right-handed coordinate system, this corresponds to a + clockwise rotation around the `z`-axis, given by: + + .. math:: + + R = \begin{bmatrix} + \cos(\theta) & \sin(\theta) & 0 \\ + -\sin(\theta) & \cos(\theta) & 0 \\ + 0 & 0 & 1 + \end{bmatrix} + + Examples + ======== + + >>> from sympy import pi, rot_axis3 + + A rotation of pi/3 (60 degrees): + + >>> theta = pi/3 + >>> rot_axis3(theta) + Matrix([ + [ 1/2, sqrt(3)/2, 0], + [-sqrt(3)/2, 1/2, 0], + [ 0, 0, 1]]) + + If we rotate by pi/2 (90 degrees): + + >>> rot_axis3(pi/2) + Matrix([ + [ 0, 1, 0], + [-1, 0, 0], + [ 0, 0, 1]]) + + See Also + ======== + + rot_givens: Returns a Givens rotation matrix (generalized rotation for + any number of dimensions) + rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis (counterclockwise around the z axis) + rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis (clockwise around the x axis) + rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis (clockwise around the y axis) + """ + return rot_givens(0, 1, theta, dim=3) + + +def rot_axis2(theta): + r"""Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis. + + Explanation + =========== + + For a right-handed coordinate system, this corresponds to a + clockwise rotation around the `y`-axis, given by: + + .. math:: + + R = \begin{bmatrix} + \cos(\theta) & 0 & -\sin(\theta) \\ + 0 & 1 & 0 \\ + \sin(\theta) & 0 & \cos(\theta) + \end{bmatrix} + + Examples + ======== + + >>> from sympy import pi, rot_axis2 + + A rotation of pi/3 (60 degrees): + + >>> theta = pi/3 + >>> rot_axis2(theta) + Matrix([ + [ 1/2, 0, -sqrt(3)/2], + [ 0, 1, 0], + [sqrt(3)/2, 0, 1/2]]) + + If we rotate by pi/2 (90 degrees): + + >>> rot_axis2(pi/2) + Matrix([ + [0, 0, -1], + [0, 1, 0], + [1, 0, 0]]) + + See Also + ======== + + rot_givens: Returns a Givens rotation matrix (generalized rotation for + any number of dimensions) + rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis (clockwise around the y axis) + rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis (counterclockwise around the x axis) + rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis (counterclockwise around the z axis) + """ + return rot_givens(2, 0, theta, dim=3) + + +def rot_axis1(theta): + r"""Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis. + + Explanation + =========== + + For a right-handed coordinate system, this corresponds to a + clockwise rotation around the `x`-axis, given by: + + .. math:: + + R = \begin{bmatrix} + 1 & 0 & 0 \\ + 0 & \cos(\theta) & \sin(\theta) \\ + 0 & -\sin(\theta) & \cos(\theta) + \end{bmatrix} + + Examples + ======== + + >>> from sympy import pi, rot_axis1 + + A rotation of pi/3 (60 degrees): + + >>> theta = pi/3 + >>> rot_axis1(theta) + Matrix([ + [1, 0, 0], + [0, 1/2, sqrt(3)/2], + [0, -sqrt(3)/2, 1/2]]) + + If we rotate by pi/2 (90 degrees): + + >>> rot_axis1(pi/2) + Matrix([ + [1, 0, 0], + [0, 0, 1], + [0, -1, 0]]) + + See Also + ======== + + rot_givens: Returns a Givens rotation matrix (generalized rotation for + any number of dimensions) + rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis (counterclockwise around the x axis) + rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis (clockwise around the y axis) + rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis (clockwise around the z axis) + """ + return rot_givens(1, 2, theta, dim=3) + + +def rot_ccw_axis3(theta): + r"""Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis. + + Explanation + =========== + + For a right-handed coordinate system, this corresponds to a + counterclockwise rotation around the `z`-axis, given by: + + .. math:: + + R = \begin{bmatrix} + \cos(\theta) & -\sin(\theta) & 0 \\ + \sin(\theta) & \cos(\theta) & 0 \\ + 0 & 0 & 1 + \end{bmatrix} + + Examples + ======== + + >>> from sympy import pi, rot_ccw_axis3 + + A rotation of pi/3 (60 degrees): + + >>> theta = pi/3 + >>> rot_ccw_axis3(theta) + Matrix([ + [ 1/2, -sqrt(3)/2, 0], + [sqrt(3)/2, 1/2, 0], + [ 0, 0, 1]]) + + If we rotate by pi/2 (90 degrees): + + >>> rot_ccw_axis3(pi/2) + Matrix([ + [0, -1, 0], + [1, 0, 0], + [0, 0, 1]]) + + See Also + ======== + + rot_givens: Returns a Givens rotation matrix (generalized rotation for + any number of dimensions) + rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis (clockwise around the z axis) + rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis (counterclockwise around the x axis) + rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis (counterclockwise around the y axis) + """ + return rot_givens(1, 0, theta, dim=3) + + +def rot_ccw_axis2(theta): + r"""Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis. + + Explanation + =========== + + For a right-handed coordinate system, this corresponds to a + counterclockwise rotation around the `y`-axis, given by: + + .. math:: + + R = \begin{bmatrix} + \cos(\theta) & 0 & \sin(\theta) \\ + 0 & 1 & 0 \\ + -\sin(\theta) & 0 & \cos(\theta) + \end{bmatrix} + + Examples + ======== + + >>> from sympy import pi, rot_ccw_axis2 + + A rotation of pi/3 (60 degrees): + + >>> theta = pi/3 + >>> rot_ccw_axis2(theta) + Matrix([ + [ 1/2, 0, sqrt(3)/2], + [ 0, 1, 0], + [-sqrt(3)/2, 0, 1/2]]) + + If we rotate by pi/2 (90 degrees): + + >>> rot_ccw_axis2(pi/2) + Matrix([ + [ 0, 0, 1], + [ 0, 1, 0], + [-1, 0, 0]]) + + See Also + ======== + + rot_givens: Returns a Givens rotation matrix (generalized rotation for + any number of dimensions) + rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis (clockwise around the y axis) + rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis (counterclockwise around the x axis) + rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis (counterclockwise around the z axis) + """ + return rot_givens(0, 2, theta, dim=3) + + +def rot_ccw_axis1(theta): + r"""Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis. + + Explanation + =========== + + For a right-handed coordinate system, this corresponds to a + counterclockwise rotation around the `x`-axis, given by: + + .. math:: + + R = \begin{bmatrix} + 1 & 0 & 0 \\ + 0 & \cos(\theta) & -\sin(\theta) \\ + 0 & \sin(\theta) & \cos(\theta) + \end{bmatrix} + + Examples + ======== + + >>> from sympy import pi, rot_ccw_axis1 + + A rotation of pi/3 (60 degrees): + + >>> theta = pi/3 + >>> rot_ccw_axis1(theta) + Matrix([ + [1, 0, 0], + [0, 1/2, -sqrt(3)/2], + [0, sqrt(3)/2, 1/2]]) + + If we rotate by pi/2 (90 degrees): + + >>> rot_ccw_axis1(pi/2) + Matrix([ + [1, 0, 0], + [0, 0, -1], + [0, 1, 0]]) + + See Also + ======== + + rot_givens: Returns a Givens rotation matrix (generalized rotation for + any number of dimensions) + rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis (clockwise around the x axis) + rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis (counterclockwise around the y axis) + rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis (counterclockwise around the z axis) + """ + return rot_givens(2, 1, theta, dim=3) + + +@doctest_depends_on(modules=('numpy',)) +def symarray(prefix, shape, **kwargs): # pragma: no cover + r"""Create a numpy ndarray of symbols (as an object array). + + The created symbols are named ``prefix_i1_i2_``... You should thus provide a + non-empty prefix if you want your symbols to be unique for different output + arrays, as SymPy symbols with identical names are the same object. + + Parameters + ---------- + + prefix : string + A prefix prepended to the name of every symbol. + + shape : int or tuple + Shape of the created array. If an int, the array is one-dimensional; for + more than one dimension the shape must be a tuple. + + \*\*kwargs : dict + keyword arguments passed on to Symbol + + Examples + ======== + These doctests require numpy. + + >>> from sympy import symarray + >>> symarray('', 3) + [_0 _1 _2] + + If you want multiple symarrays to contain distinct symbols, you *must* + provide unique prefixes: + + >>> a = symarray('', 3) + >>> b = symarray('', 3) + >>> a[0] == b[0] + True + >>> a = symarray('a', 3) + >>> b = symarray('b', 3) + >>> a[0] == b[0] + False + + Creating symarrays with a prefix: + + >>> symarray('a', 3) + [a_0 a_1 a_2] + + For more than one dimension, the shape must be given as a tuple: + + >>> symarray('a', (2, 3)) + [[a_0_0 a_0_1 a_0_2] + [a_1_0 a_1_1 a_1_2]] + >>> symarray('a', (2, 3, 2)) + [[[a_0_0_0 a_0_0_1] + [a_0_1_0 a_0_1_1] + [a_0_2_0 a_0_2_1]] + + [[a_1_0_0 a_1_0_1] + [a_1_1_0 a_1_1_1] + [a_1_2_0 a_1_2_1]]] + + For setting assumptions of the underlying Symbols: + + >>> [s.is_real for s in symarray('a', 2, real=True)] + [True, True] + """ + from numpy import empty, ndindex + arr = empty(shape, dtype=object) + for index in ndindex(shape): + arr[index] = Symbol('%s_%s' % (prefix, '_'.join(map(str, index))), + **kwargs) + return arr + + +############### +# Functions +############### + +def casoratian(seqs, n, zero=True): + """Given linear difference operator L of order 'k' and homogeneous + equation Ly = 0 we want to compute kernel of L, which is a set + of 'k' sequences: a(n), b(n), ... z(n). + + Solutions of L are linearly independent iff their Casoratian, + denoted as C(a, b, ..., z), do not vanish for n = 0. + + Casoratian is defined by k x k determinant:: + + + a(n) b(n) . . . z(n) + + | a(n+1) b(n+1) . . . z(n+1) | + | . . . . | + | . . . . | + | . . . . | + + a(n+k-1) b(n+k-1) . . . z(n+k-1) + + + It proves very useful in rsolve_hyper() where it is applied + to a generating set of a recurrence to factor out linearly + dependent solutions and return a basis: + + >>> from sympy import Symbol, casoratian, factorial + >>> n = Symbol('n', integer=True) + + Exponential and factorial are linearly independent: + + >>> casoratian([2**n, factorial(n)], n) != 0 + True + + """ + + seqs = list(map(sympify, seqs)) + + if not zero: + f = lambda i, j: seqs[j].subs(n, n + i) + else: + f = lambda i, j: seqs[j].subs(n, i) + + k = len(seqs) + + return Matrix(k, k, f).det() + + +def eye(*args, **kwargs): + """Create square identity matrix n x n + + See Also + ======== + + diag + zeros + ones + """ + + return Matrix.eye(*args, **kwargs) + + +def diag(*values, strict=True, unpack=False, **kwargs): + """Returns a matrix with the provided values placed on the + diagonal. If non-square matrices are included, they will + produce a block-diagonal matrix. + + Examples + ======== + + This version of diag is a thin wrapper to Matrix.diag that differs + in that it treats all lists like matrices -- even when a single list + is given. If this is not desired, either put a `*` before the list or + set `unpack=True`. + + >>> from sympy import diag + + >>> diag([1, 2, 3], unpack=True) # = diag(1,2,3) or diag(*[1,2,3]) + Matrix([ + [1, 0, 0], + [0, 2, 0], + [0, 0, 3]]) + + >>> diag([1, 2, 3]) # a column vector + Matrix([ + [1], + [2], + [3]]) + + See Also + ======== + .common.MatrixCommon.eye + .common.MatrixCommon.diagonal + .common.MatrixCommon.diag + .expressions.blockmatrix.BlockMatrix + """ + return Matrix.diag(*values, strict=strict, unpack=unpack, **kwargs) + + +def GramSchmidt(vlist, orthonormal=False): + """Apply the Gram-Schmidt process to a set of vectors. + + Parameters + ========== + + vlist : List of Matrix + Vectors to be orthogonalized for. + + orthonormal : Bool, optional + If true, return an orthonormal basis. + + Returns + ======= + + vlist : List of Matrix + Orthogonalized vectors + + Notes + ===== + + This routine is mostly duplicate from ``Matrix.orthogonalize``, + except for some difference that this always raises error when + linearly dependent vectors are found, and the keyword ``normalize`` + has been named as ``orthonormal`` in this function. + + See Also + ======== + + .matrices.MatrixSubspaces.orthogonalize + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process + """ + return MutableDenseMatrix.orthogonalize( + *vlist, normalize=orthonormal, rankcheck=True + ) + + +def hessian(f, varlist, constraints=()): + """Compute Hessian matrix for a function f wrt parameters in varlist + which may be given as a sequence or a row/column vector. A list of + constraints may optionally be given. + + Examples + ======== + + >>> from sympy import Function, hessian, pprint + >>> from sympy.abc import x, y + >>> f = Function('f')(x, y) + >>> g1 = Function('g')(x, y) + >>> g2 = x**2 + 3*y + >>> pprint(hessian(f, (x, y), [g1, g2])) + [ d d ] + [ 0 0 --(g(x, y)) --(g(x, y)) ] + [ dx dy ] + [ ] + [ 0 0 2*x 3 ] + [ ] + [ 2 2 ] + [d d d ] + [--(g(x, y)) 2*x ---(f(x, y)) -----(f(x, y))] + [dx 2 dy dx ] + [ dx ] + [ ] + [ 2 2 ] + [d d d ] + [--(g(x, y)) 3 -----(f(x, y)) ---(f(x, y)) ] + [dy dy dx 2 ] + [ dy ] + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Hessian_matrix + + See Also + ======== + + sympy.matrices.matrices.MatrixCalculus.jacobian + wronskian + """ + # f is the expression representing a function f, return regular matrix + if isinstance(varlist, MatrixBase): + if 1 not in varlist.shape: + raise ShapeError("`varlist` must be a column or row vector.") + if varlist.cols == 1: + varlist = varlist.T + varlist = varlist.tolist()[0] + if is_sequence(varlist): + n = len(varlist) + if not n: + raise ShapeError("`len(varlist)` must not be zero.") + else: + raise ValueError("Improper variable list in hessian function") + if not getattr(f, 'diff'): + # check differentiability + raise ValueError("Function `f` (%s) is not differentiable" % f) + m = len(constraints) + N = m + n + out = zeros(N) + for k, g in enumerate(constraints): + if not getattr(g, 'diff'): + # check differentiability + raise ValueError("Function `f` (%s) is not differentiable" % f) + for i in range(n): + out[k, i + m] = g.diff(varlist[i]) + for i in range(n): + for j in range(i, n): + out[i + m, j + m] = f.diff(varlist[i]).diff(varlist[j]) + for i in range(N): + for j in range(i + 1, N): + out[j, i] = out[i, j] + return out + + +def jordan_cell(eigenval, n): + """ + Create a Jordan block: + + Examples + ======== + + >>> from sympy import jordan_cell + >>> from sympy.abc import x + >>> jordan_cell(x, 4) + Matrix([ + [x, 1, 0, 0], + [0, x, 1, 0], + [0, 0, x, 1], + [0, 0, 0, x]]) + """ + + return Matrix.jordan_block(size=n, eigenvalue=eigenval) + + +def matrix_multiply_elementwise(A, B): + """Return the Hadamard product (elementwise product) of A and B + + >>> from sympy import Matrix, matrix_multiply_elementwise + >>> A = Matrix([[0, 1, 2], [3, 4, 5]]) + >>> B = Matrix([[1, 10, 100], [100, 10, 1]]) + >>> matrix_multiply_elementwise(A, B) + Matrix([ + [ 0, 10, 200], + [300, 40, 5]]) + + See Also + ======== + + sympy.matrices.common.MatrixCommon.__mul__ + """ + return A.multiply_elementwise(B) + + +def ones(*args, **kwargs): + """Returns a matrix of ones with ``rows`` rows and ``cols`` columns; + if ``cols`` is omitted a square matrix will be returned. + + See Also + ======== + + zeros + eye + diag + """ + + if 'c' in kwargs: + kwargs['cols'] = kwargs.pop('c') + + return Matrix.ones(*args, **kwargs) + + +def randMatrix(r, c=None, min=0, max=99, seed=None, symmetric=False, + percent=100, prng=None): + """Create random matrix with dimensions ``r`` x ``c``. If ``c`` is omitted + the matrix will be square. If ``symmetric`` is True the matrix must be + square. If ``percent`` is less than 100 then only approximately the given + percentage of elements will be non-zero. + + The pseudo-random number generator used to generate matrix is chosen in the + following way. + + * If ``prng`` is supplied, it will be used as random number generator. + It should be an instance of ``random.Random``, or at least have + ``randint`` and ``shuffle`` methods with same signatures. + * if ``prng`` is not supplied but ``seed`` is supplied, then new + ``random.Random`` with given ``seed`` will be created; + * otherwise, a new ``random.Random`` with default seed will be used. + + Examples + ======== + + >>> from sympy import randMatrix + >>> randMatrix(3) # doctest:+SKIP + [25, 45, 27] + [44, 54, 9] + [23, 96, 46] + >>> randMatrix(3, 2) # doctest:+SKIP + [87, 29] + [23, 37] + [90, 26] + >>> randMatrix(3, 3, 0, 2) # doctest:+SKIP + [0, 2, 0] + [2, 0, 1] + [0, 0, 1] + >>> randMatrix(3, symmetric=True) # doctest:+SKIP + [85, 26, 29] + [26, 71, 43] + [29, 43, 57] + >>> A = randMatrix(3, seed=1) + >>> B = randMatrix(3, seed=2) + >>> A == B + False + >>> A == randMatrix(3, seed=1) + True + >>> randMatrix(3, symmetric=True, percent=50) # doctest:+SKIP + [77, 70, 0], + [70, 0, 0], + [ 0, 0, 88] + """ + # Note that ``Random()`` is equivalent to ``Random(None)`` + prng = prng or random.Random(seed) + + if c is None: + c = r + + if symmetric and r != c: + raise ValueError('For symmetric matrices, r must equal c, but %i != %i' % (r, c)) + + ij = range(r * c) + if percent != 100: + ij = prng.sample(ij, int(len(ij)*percent // 100)) + + m = zeros(r, c) + + if not symmetric: + for ijk in ij: + i, j = divmod(ijk, c) + m[i, j] = prng.randint(min, max) + else: + for ijk in ij: + i, j = divmod(ijk, c) + if i <= j: + m[i, j] = m[j, i] = prng.randint(min, max) + + return m + + +def wronskian(functions, var, method='bareiss'): + """ + Compute Wronskian for [] of functions + + :: + + | f1 f2 ... fn | + | f1' f2' ... fn' | + | . . . . | + W(f1, ..., fn) = | . . . . | + | . . . . | + | (n) (n) (n) | + | D (f1) D (f2) ... D (fn) | + + see: https://en.wikipedia.org/wiki/Wronskian + + See Also + ======== + + sympy.matrices.matrices.MatrixCalculus.jacobian + hessian + """ + + functions = [sympify(f) for f in functions] + n = len(functions) + if n == 0: + return S.One + W = Matrix(n, n, lambda i, j: functions[i].diff(var, j)) + return W.det(method) + + +def zeros(*args, **kwargs): + """Returns a matrix of zeros with ``rows`` rows and ``cols`` columns; + if ``cols`` is omitted a square matrix will be returned. + + See Also + ======== + + ones + eye + diag + """ + + if 'c' in kwargs: + kwargs['cols'] = kwargs.pop('c') + + return Matrix.zeros(*args, **kwargs) diff --git a/shared/package-files/71/713a5ca86123db1043a2bc262c254799d63ed7ddf8d252f31ce36f98512655eb/gen_annotated_fn_args.py b/shared/package-files/71/713a5ca86123db1043a2bc262c254799d63ed7ddf8d252f31ce36f98512655eb/gen_annotated_fn_args.py new file mode 100644 index 0000000000000000000000000000000000000000..f935a9adf4c6f126fe45999613ed9871280aac61 --- /dev/null +++ b/shared/package-files/71/713a5ca86123db1043a2bc262c254799d63ed7ddf8d252f31ce36f98512655eb/gen_annotated_fn_args.py @@ -0,0 +1,129 @@ +""" +For procedural tests needed for __torch_function__, we use this function +to export method names and signatures as needed by the tests in +test/test_overrides.py. + +python -m tools.autograd.gen_annotated_fn_args \ + aten/src/ATen/native/native_functions.yaml \ + aten/src/ATen/native/tags.yaml \ + $OUTPUT_DIR \ + tools/autograd + +Where $OUTPUT_DIR is where you would like the files to be +generated. In the full build system, OUTPUT_DIR is +torch/testing/_internal/generated +""" + +import argparse +import os +import textwrap +from collections import defaultdict + +from typing import Any, Dict, List, Sequence + +import torchgen.api.python as python +from torchgen.context import with_native_function + +from torchgen.gen import parse_native_yaml +from torchgen.model import Argument, BaseOperatorName, NativeFunction +from torchgen.utils import FileManager + +from .gen_python_functions import ( + is_py_fft_function, + is_py_linalg_function, + is_py_nn_function, + is_py_special_function, + is_py_torch_function, + is_py_variable_method, + should_generate_py_binding, +) + + +def gen_annotated( + native_yaml_path: str, tags_yaml_path: str, out: str, autograd_dir: str +) -> None: + native_functions = parse_native_yaml( + native_yaml_path, tags_yaml_path + ).native_functions + mappings = ( + (is_py_torch_function, "torch._C._VariableFunctions"), + (is_py_nn_function, "torch._C._nn"), + (is_py_linalg_function, "torch._C._linalg"), + (is_py_special_function, "torch._C._special"), + (is_py_fft_function, "torch._C._fft"), + (is_py_variable_method, "torch.Tensor"), + ) + annotated_args: List[str] = [] + for pred, namespace in mappings: + groups: Dict[BaseOperatorName, List[NativeFunction]] = defaultdict(list) + for f in native_functions: + if not should_generate_py_binding(f) or not pred(f): + continue + groups[f.func.name.name].append(f) + for group in groups.values(): + for f in group: + annotated_args.append(f"{namespace}.{gen_annotated_args(f)}") + + template_path = os.path.join(autograd_dir, "templates") + fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False) + fm.write_with_template( + "annotated_fn_args.py", + "annotated_fn_args.py.in", + lambda: { + "annotated_args": textwrap.indent("\n".join(annotated_args), " "), + }, + ) + + +@with_native_function +def gen_annotated_args(f: NativeFunction) -> str: + def _get_kwargs_func_exclusion_list() -> List[str]: + # functions that currently don't work with kwargs in test_overrides.py + return [ + "diagonal", + "round_", + "round", + "scatter_", + ] + + def _add_out_arg( + out_args: List[Dict[str, Any]], args: Sequence[Argument], *, is_kwarg_only: bool + ) -> None: + for arg in args: + if arg.default is not None: + continue + out_arg: Dict[str, Any] = {} + out_arg["is_kwarg_only"] = str(is_kwarg_only) + out_arg["name"] = arg.name + out_arg["simple_type"] = python.argument_type_str( + arg.type, simple_type=True + ) + size_t = python.argument_type_size(arg.type) + if size_t: + out_arg["size"] = size_t + out_args.append(out_arg) + + out_args: List[Dict[str, Any]] = [] + _add_out_arg(out_args, f.func.arguments.flat_positional, is_kwarg_only=False) + if f"{f.func.name.name}" not in _get_kwargs_func_exclusion_list(): + _add_out_arg(out_args, f.func.arguments.flat_kwarg_only, is_kwarg_only=True) + + return f"{f.func.name.name}: {repr(out_args)}," + + +def main() -> None: + parser = argparse.ArgumentParser(description="Generate annotated_fn_args script") + parser.add_argument( + "native_functions", metavar="NATIVE", help="path to native_functions.yaml" + ) + parser.add_argument("tags", metavar="TAGS", help="path to tags.yaml") + parser.add_argument("out", metavar="OUT", help="path to output directory") + parser.add_argument( + "autograd", metavar="AUTOGRAD", help="path to template directory" + ) + args = parser.parse_args() + gen_annotated(args.native_functions, args.tags, args.out, args.autograd) + + +if __name__ == "__main__": + main() diff --git a/shared/package-files/71/713eb8d7d1539eb1959b8a49787ddb39e9d0abb2c71808fe186aedbed4f38386/cli.py b/shared/package-files/71/713eb8d7d1539eb1959b8a49787ddb39e9d0abb2c71808fe186aedbed4f38386/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..eacc9df78fae2b0e5bec7c610bf630bf36db8958 --- /dev/null +++ b/shared/package-files/71/713eb8d7d1539eb1959b8a49787ddb39e9d0abb2c71808fe186aedbed4f38386/cli.py @@ -0,0 +1,198 @@ +import os +import argparse +import logging +import shutil +import multiprocessing as mp +from contextlib import closing +from functools import partial + +import fontTools +from .ufo import font_to_quadratic, fonts_to_quadratic + +ufo_module = None +try: + import ufoLib2 as ufo_module +except ImportError: + try: + import defcon as ufo_module + except ImportError as e: + pass + + +logger = logging.getLogger("fontTools.cu2qu") + + +def _cpu_count(): + try: + return mp.cpu_count() + except NotImplementedError: # pragma: no cover + return 1 + + +def open_ufo(path): + if hasattr(ufo_module.Font, "open"): # ufoLib2 + return ufo_module.Font.open(path) + return ufo_module.Font(path) # defcon + + +def _font_to_quadratic(input_path, output_path=None, **kwargs): + ufo = open_ufo(input_path) + logger.info("Converting curves for %s", input_path) + if font_to_quadratic(ufo, **kwargs): + logger.info("Saving %s", output_path) + if output_path: + ufo.save(output_path) + else: + ufo.save() # save in-place + elif output_path: + _copytree(input_path, output_path) + + +def _samepath(path1, path2): + # TODO on python3+, there's os.path.samefile + path1 = os.path.normcase(os.path.abspath(os.path.realpath(path1))) + path2 = os.path.normcase(os.path.abspath(os.path.realpath(path2))) + return path1 == path2 + + +def _copytree(input_path, output_path): + if _samepath(input_path, output_path): + logger.debug("input and output paths are the same file; skipped copy") + return + if os.path.exists(output_path): + shutil.rmtree(output_path) + shutil.copytree(input_path, output_path) + + +def _main(args=None): + """Convert a UFO font from cubic to quadratic curves""" + parser = argparse.ArgumentParser(prog="cu2qu") + parser.add_argument("--version", action="version", version=fontTools.__version__) + parser.add_argument( + "infiles", + nargs="+", + metavar="INPUT", + help="one or more input UFO source file(s).", + ) + parser.add_argument("-v", "--verbose", action="count", default=0) + parser.add_argument( + "-e", + "--conversion-error", + type=float, + metavar="ERROR", + default=None, + help="maximum approximation error measured in EM (default: 0.001)", + ) + parser.add_argument( + "-m", + "--mixed", + default=False, + action="store_true", + help="whether to used mixed quadratic and cubic curves", + ) + parser.add_argument( + "--keep-direction", + dest="reverse_direction", + action="store_false", + help="do not reverse the contour direction", + ) + + mode_parser = parser.add_mutually_exclusive_group() + mode_parser.add_argument( + "-i", + "--interpolatable", + action="store_true", + help="whether curve conversion should keep interpolation compatibility", + ) + mode_parser.add_argument( + "-j", + "--jobs", + type=int, + nargs="?", + default=1, + const=_cpu_count(), + metavar="N", + help="convert using N multiple processes (default: %(default)s)", + ) + + output_parser = parser.add_mutually_exclusive_group() + output_parser.add_argument( + "-o", + "--output-file", + default=None, + metavar="OUTPUT", + help=( + "output filename for the converted UFO. By default fonts are " + "modified in place. This only works with a single input." + ), + ) + output_parser.add_argument( + "-d", + "--output-dir", + default=None, + metavar="DIRECTORY", + help="output directory where to save converted UFOs", + ) + + options = parser.parse_args(args) + + if ufo_module is None: + parser.error("Either ufoLib2 or defcon are required to run this script.") + + if not options.verbose: + level = "WARNING" + elif options.verbose == 1: + level = "INFO" + else: + level = "DEBUG" + logging.basicConfig(level=level) + + if len(options.infiles) > 1 and options.output_file: + parser.error("-o/--output-file can't be used with multile inputs") + + if options.output_dir: + output_dir = options.output_dir + if not os.path.exists(output_dir): + os.mkdir(output_dir) + elif not os.path.isdir(output_dir): + parser.error("'%s' is not a directory" % output_dir) + output_paths = [ + os.path.join(output_dir, os.path.basename(p)) for p in options.infiles + ] + elif options.output_file: + output_paths = [options.output_file] + else: + # save in-place + output_paths = [None] * len(options.infiles) + + kwargs = dict( + dump_stats=options.verbose > 0, + max_err_em=options.conversion_error, + reverse_direction=options.reverse_direction, + all_quadratic=False if options.mixed else True, + ) + + if options.interpolatable: + logger.info("Converting curves compatibly") + ufos = [open_ufo(infile) for infile in options.infiles] + if fonts_to_quadratic(ufos, **kwargs): + for ufo, output_path in zip(ufos, output_paths): + logger.info("Saving %s", output_path) + if output_path: + ufo.save(output_path) + else: + ufo.save() + else: + for input_path, output_path in zip(options.infiles, output_paths): + if output_path: + _copytree(input_path, output_path) + else: + jobs = min(len(options.infiles), options.jobs) if options.jobs > 1 else 1 + if jobs > 1: + func = partial(_font_to_quadratic, **kwargs) + logger.info("Running %d parallel processes", jobs) + with closing(mp.Pool(jobs)) as pool: + pool.starmap(func, zip(options.infiles, output_paths)) + else: + for input_path, output_path in zip(options.infiles, output_paths): + _font_to_quadratic(input_path, output_path, **kwargs) diff --git a/shared/package-files/71/713ec6e219fedc0fd9765587d533c7f0afd0f5b0282945238cb940c05bc53eba/file.pyi b/shared/package-files/71/713ec6e219fedc0fd9765587d533c7f0afd0f5b0282945238cb940c05bc53eba/file.pyi new file mode 100644 index 0000000000000000000000000000000000000000..96e20463adda0381c3a76eb1bd9f26240cebb485 --- /dev/null +++ b/shared/package-files/71/713ec6e219fedc0fd9765587d533c7f0afd0f5b0282945238cb940c05bc53eba/file.pyi @@ -0,0 +1,9 @@ +from typing import Optional + +from django.contrib.sessions.backends.base import SessionBase + +class SessionStore(SessionBase): + storage_path: str = ... + file_prefix: str = ... + def __init__(self, session_key: Optional[str] = ...) -> None: ... + def clean(self) -> None: ... diff --git a/shared/package-files/71/7140613066b986ccde56a3a6d8aa4e75e261f8bb22a84ed135dc8850f676bcef/ttGlyphSet.py b/shared/package-files/71/7140613066b986ccde56a3a6d8aa4e75e261f8bb22a84ed135dc8850f676bcef/ttGlyphSet.py new file mode 100644 index 0000000000000000000000000000000000000000..3a9a0cb9960434d28fd98bd6bf9fdd128522d89f --- /dev/null +++ b/shared/package-files/71/7140613066b986ccde56a3a6d8aa4e75e261f8bb22a84ed135dc8850f676bcef/ttGlyphSet.py @@ -0,0 +1,490 @@ +"""GlyphSets returned by a TTFont.""" + +from abc import ABC, abstractmethod +from collections.abc import Mapping +from contextlib import contextmanager +from copy import copy, deepcopy +from types import SimpleNamespace +from fontTools.misc.vector import Vector +from fontTools.misc.fixedTools import otRound, fixedToFloat as fi2fl +from fontTools.misc.loggingTools import deprecateFunction +from fontTools.misc.transform import Transform, DecomposedTransform +from fontTools.pens.transformPen import TransformPen, TransformPointPen +from fontTools.pens.recordingPen import ( + DecomposingRecordingPen, + lerpRecordings, + replayRecording, +) + + +class _TTGlyphSet(Mapping): + """Generic dict-like GlyphSet class that pulls metrics from hmtx and + glyph shape from TrueType or CFF. + """ + + def __init__(self, font, location, glyphsMapping, *, recalcBounds=True): + self.recalcBounds = recalcBounds + self.font = font + self.defaultLocationNormalized = ( + {axis.axisTag: 0 for axis in self.font["fvar"].axes} + if "fvar" in self.font + else {} + ) + self.location = location if location is not None else {} + self.rawLocation = {} # VarComponent-only location + self.originalLocation = location if location is not None else {} + self.depth = 0 + self.locationStack = [] + self.rawLocationStack = [] + self.glyphsMapping = glyphsMapping + self.hMetrics = font["hmtx"].metrics + self.vMetrics = getattr(font.get("vmtx"), "metrics", None) + self.hvarTable = None + if location: + from fontTools.varLib.varStore import VarStoreInstancer + + self.hvarTable = getattr(font.get("HVAR"), "table", None) + if self.hvarTable is not None: + self.hvarInstancer = VarStoreInstancer( + self.hvarTable.VarStore, font["fvar"].axes, location + ) + # TODO VVAR, VORG + + @contextmanager + def pushLocation(self, location, reset: bool): + self.locationStack.append(self.location) + self.rawLocationStack.append(self.rawLocation) + if reset: + self.location = self.originalLocation.copy() + self.rawLocation = self.defaultLocationNormalized.copy() + else: + self.location = self.location.copy() + self.rawLocation = {} + self.location.update(location) + self.rawLocation.update(location) + + try: + yield None + finally: + self.location = self.locationStack.pop() + self.rawLocation = self.rawLocationStack.pop() + + @contextmanager + def pushDepth(self): + try: + depth = self.depth + self.depth += 1 + yield depth + finally: + self.depth -= 1 + + def __contains__(self, glyphName): + return glyphName in self.glyphsMapping + + def __iter__(self): + return iter(self.glyphsMapping.keys()) + + def __len__(self): + return len(self.glyphsMapping) + + @deprecateFunction( + "use 'glyphName in glyphSet' instead", category=DeprecationWarning + ) + def has_key(self, glyphName): + return glyphName in self.glyphsMapping + + +class _TTGlyphSetGlyf(_TTGlyphSet): + def __init__(self, font, location, recalcBounds=True): + self.glyfTable = font["glyf"] + super().__init__(font, location, self.glyfTable, recalcBounds=recalcBounds) + self.gvarTable = font.get("gvar") + + def __getitem__(self, glyphName): + return _TTGlyphGlyf(self, glyphName, recalcBounds=self.recalcBounds) + + +class _TTGlyphSetCFF(_TTGlyphSet): + def __init__(self, font, location): + tableTag = "CFF2" if "CFF2" in font else "CFF " + self.charStrings = list(font[tableTag].cff.values())[0].CharStrings + super().__init__(font, location, self.charStrings) + self.setLocation(location) + + def __getitem__(self, glyphName): + return _TTGlyphCFF(self, glyphName) + + def setLocation(self, location): + self.blender = None + if location: + # TODO Optimize by using instancer.setLocation() + + from fontTools.varLib.varStore import VarStoreInstancer + + varStore = getattr(self.charStrings, "varStore", None) + if varStore is not None: + instancer = VarStoreInstancer( + varStore.otVarStore, self.font["fvar"].axes, location + ) + self.blender = instancer.interpolateFromDeltas + else: + self.blender = None + + @contextmanager + def pushLocation(self, location, reset: bool): + self.setLocation(location) + with _TTGlyphSet.pushLocation(self, location, reset) as value: + try: + yield value + finally: + self.setLocation(self.location) + + +class _TTGlyphSetVARC(_TTGlyphSet): + def __init__(self, font, location, glyphSet): + self.glyphSet = glyphSet + super().__init__(font, location, glyphSet) + self.varcTable = font["VARC"].table + + def __getitem__(self, glyphName): + varc = self.varcTable + if glyphName not in varc.Coverage.glyphs: + return self.glyphSet[glyphName] + return _TTGlyphVARC(self, glyphName) + + +class _TTGlyph(ABC): + """Glyph object that supports the Pen protocol, meaning that it has + .draw() and .drawPoints() methods that take a pen object as their only + argument. Additionally there are 'width' and 'lsb' attributes, read from + the 'hmtx' table. + + If the font contains a 'vmtx' table, there will also be 'height' and 'tsb' + attributes. + """ + + def __init__(self, glyphSet, glyphName, *, recalcBounds=True): + self.glyphSet = glyphSet + self.name = glyphName + self.recalcBounds = recalcBounds + self.width, self.lsb = glyphSet.hMetrics[glyphName] + if glyphSet.vMetrics is not None: + self.height, self.tsb = glyphSet.vMetrics[glyphName] + else: + self.height, self.tsb = None, None + if glyphSet.location and glyphSet.hvarTable is not None: + varidx = ( + glyphSet.font.getGlyphID(glyphName) + if glyphSet.hvarTable.AdvWidthMap is None + else glyphSet.hvarTable.AdvWidthMap.mapping[glyphName] + ) + self.width += glyphSet.hvarInstancer[varidx] + # TODO: VVAR/VORG + + @abstractmethod + def draw(self, pen): + """Draw the glyph onto ``pen``. See fontTools.pens.basePen for details + how that works. + """ + raise NotImplementedError + + def drawPoints(self, pen): + """Draw the glyph onto ``pen``. See fontTools.pens.pointPen for details + how that works. + """ + from fontTools.pens.pointPen import SegmentToPointPen + + self.draw(SegmentToPointPen(pen)) + + +class _TTGlyphGlyf(_TTGlyph): + def draw(self, pen): + """Draw the glyph onto ``pen``. See fontTools.pens.basePen for details + how that works. + """ + glyph, offset = self._getGlyphAndOffset() + + with self.glyphSet.pushDepth() as depth: + if depth: + offset = 0 # Offset should only apply at top-level + + glyph.draw(pen, self.glyphSet.glyfTable, offset) + + def drawPoints(self, pen): + """Draw the glyph onto ``pen``. See fontTools.pens.pointPen for details + how that works. + """ + glyph, offset = self._getGlyphAndOffset() + + with self.glyphSet.pushDepth() as depth: + if depth: + offset = 0 # Offset should only apply at top-level + + glyph.drawPoints(pen, self.glyphSet.glyfTable, offset) + + def _getGlyphAndOffset(self): + if self.glyphSet.location and self.glyphSet.gvarTable is not None: + glyph = self._getGlyphInstance() + else: + glyph = self.glyphSet.glyfTable[self.name] + + offset = self.lsb - glyph.xMin if hasattr(glyph, "xMin") else 0 + return glyph, offset + + def _getGlyphInstance(self): + from fontTools.varLib.iup import iup_delta + from fontTools.ttLib.tables._g_l_y_f import GlyphCoordinates + from fontTools.varLib.models import supportScalar + + glyphSet = self.glyphSet + glyfTable = glyphSet.glyfTable + variations = glyphSet.gvarTable.variations[self.name] + hMetrics = glyphSet.hMetrics + vMetrics = glyphSet.vMetrics + coordinates, _ = glyfTable._getCoordinatesAndControls( + self.name, hMetrics, vMetrics + ) + origCoords, endPts = None, None + for var in variations: + scalar = supportScalar(glyphSet.location, var.axes) + if not scalar: + continue + delta = var.coordinates + if None in delta: + if origCoords is None: + origCoords, control = glyfTable._getCoordinatesAndControls( + self.name, hMetrics, vMetrics + ) + endPts = ( + control[1] if control[0] >= 1 else list(range(len(control[1]))) + ) + delta = iup_delta(delta, origCoords, endPts) + coordinates += GlyphCoordinates(delta) * scalar + + glyph = copy(glyfTable[self.name]) # Shallow copy + width, lsb, height, tsb = _setCoordinates( + glyph, coordinates, glyfTable, recalcBounds=self.recalcBounds + ) + self.lsb = lsb + self.tsb = tsb + if glyphSet.hvarTable is None: + # no HVAR: let's set metrics from the phantom points + self.width = width + self.height = height + return glyph + + +class _TTGlyphCFF(_TTGlyph): + def draw(self, pen): + """Draw the glyph onto ``pen``. See fontTools.pens.basePen for details + how that works. + """ + self.glyphSet.charStrings[self.name].draw(pen, self.glyphSet.blender) + + +def _evaluateCondition(condition, fvarAxes, location, instancer): + if condition.Format == 1: + # ConditionAxisRange + axisIndex = condition.AxisIndex + axisTag = fvarAxes[axisIndex].axisTag + axisValue = location.get(axisTag, 0) + minValue = condition.FilterRangeMinValue + maxValue = condition.FilterRangeMaxValue + return minValue <= axisValue <= maxValue + elif condition.Format == 2: + # ConditionValue + value = condition.DefaultValue + value += instancer[condition.VarIdx][0] + return value > 0 + elif condition.Format == 3: + # ConditionAnd + for subcondition in condition.ConditionTable: + if not _evaluateCondition(subcondition, fvarAxes, location, instancer): + return False + return True + elif condition.Format == 4: + # ConditionOr + for subcondition in condition.ConditionTable: + if _evaluateCondition(subcondition, fvarAxes, location, instancer): + return True + return False + elif condition.Format == 5: + # ConditionNegate + return not _evaluateCondition( + condition.conditionTable, fvarAxes, location, instancer + ) + else: + return False # Unkonwn condition format + + +class _TTGlyphVARC(_TTGlyph): + def _draw(self, pen, isPointPen): + """Draw the glyph onto ``pen``. See fontTools.pens.basePen for details + how that works. + """ + from fontTools.ttLib.tables.otTables import ( + VarComponentFlags, + NO_VARIATION_INDEX, + ) + + glyphSet = self.glyphSet + varc = glyphSet.varcTable + idx = varc.Coverage.glyphs.index(self.name) + glyph = varc.VarCompositeGlyphs.VarCompositeGlyph[idx] + + from fontTools.varLib.multiVarStore import MultiVarStoreInstancer + from fontTools.varLib.varStore import VarStoreInstancer + + fvarAxes = glyphSet.font["fvar"].axes + instancer = MultiVarStoreInstancer( + varc.MultiVarStore, fvarAxes, self.glyphSet.location + ) + + for comp in glyph.components: + if comp.flags & VarComponentFlags.HAVE_CONDITION: + condition = varc.ConditionList.ConditionTable[comp.conditionIndex] + if not _evaluateCondition( + condition, fvarAxes, self.glyphSet.location, instancer + ): + continue + + location = {} + if comp.axisIndicesIndex is not None: + axisIndices = varc.AxisIndicesList.Item[comp.axisIndicesIndex] + axisValues = Vector(comp.axisValues) + if comp.axisValuesVarIndex != NO_VARIATION_INDEX: + axisValues += fi2fl(instancer[comp.axisValuesVarIndex], 14) + assert len(axisIndices) == len(axisValues), ( + len(axisIndices), + len(axisValues), + ) + location = { + fvarAxes[i].axisTag: v for i, v in zip(axisIndices, axisValues) + } + + if comp.transformVarIndex != NO_VARIATION_INDEX: + deltas = instancer[comp.transformVarIndex] + comp = deepcopy(comp) + comp.applyTransformDeltas(deltas) + transform = comp.transform + + reset = comp.flags & VarComponentFlags.RESET_UNSPECIFIED_AXES + with self.glyphSet.glyphSet.pushLocation(location, reset): + with self.glyphSet.pushLocation(location, reset): + shouldDecompose = self.name == comp.glyphName + + if not shouldDecompose: + try: + pen.addVarComponent( + comp.glyphName, transform, self.glyphSet.rawLocation + ) + except AttributeError: + shouldDecompose = True + + if shouldDecompose: + t = transform.toTransform() + compGlyphSet = ( + self.glyphSet + if comp.glyphName != self.name + else glyphSet.glyphSet + ) + g = compGlyphSet[comp.glyphName] + if isPointPen: + tPen = TransformPointPen(pen, t) + g.drawPoints(tPen) + else: + tPen = TransformPen(pen, t) + g.draw(tPen) + + def draw(self, pen): + self._draw(pen, False) + + def drawPoints(self, pen): + self._draw(pen, True) + + +def _setCoordinates(glyph, coord, glyfTable, *, recalcBounds=True): + # Handle phantom points for (left, right, top, bottom) positions. + assert len(coord) >= 4 + leftSideX = coord[-4][0] + rightSideX = coord[-3][0] + topSideY = coord[-2][1] + bottomSideY = coord[-1][1] + + for _ in range(4): + del coord[-1] + + if glyph.isComposite(): + assert len(coord) == len(glyph.components) + glyph.components = [copy(comp) for comp in glyph.components] # Shallow copy + for p, comp in zip(coord, glyph.components): + if hasattr(comp, "x"): + comp.x, comp.y = p + elif glyph.numberOfContours == 0: + assert len(coord) == 0 + else: + assert len(coord) == len(glyph.coordinates) + glyph.coordinates = coord + + if recalcBounds: + glyph.recalcBounds(glyfTable) + + horizontalAdvanceWidth = otRound(rightSideX - leftSideX) + verticalAdvanceWidth = otRound(topSideY - bottomSideY) + leftSideBearing = otRound(glyph.xMin - leftSideX) + topSideBearing = otRound(topSideY - glyph.yMax) + return ( + horizontalAdvanceWidth, + leftSideBearing, + verticalAdvanceWidth, + topSideBearing, + ) + + +class LerpGlyphSet(Mapping): + """A glyphset that interpolates between two other glyphsets. + + Factor is typically between 0 and 1. 0 means the first glyphset, + 1 means the second glyphset, and 0.5 means the average of the + two glyphsets. Other values are possible, and can be useful to + extrapolate. Defaults to 0.5. + """ + + def __init__(self, glyphset1, glyphset2, factor=0.5): + self.glyphset1 = glyphset1 + self.glyphset2 = glyphset2 + self.factor = factor + + def __getitem__(self, glyphname): + if glyphname in self.glyphset1 and glyphname in self.glyphset2: + return LerpGlyph(glyphname, self) + raise KeyError(glyphname) + + def __contains__(self, glyphname): + return glyphname in self.glyphset1 and glyphname in self.glyphset2 + + def __iter__(self): + set1 = set(self.glyphset1) + set2 = set(self.glyphset2) + return iter(set1.intersection(set2)) + + def __len__(self): + set1 = set(self.glyphset1) + set2 = set(self.glyphset2) + return len(set1.intersection(set2)) + + +class LerpGlyph: + def __init__(self, glyphname, glyphset): + self.glyphset = glyphset + self.glyphname = glyphname + + def draw(self, pen): + recording1 = DecomposingRecordingPen(self.glyphset.glyphset1) + self.glyphset.glyphset1[self.glyphname].draw(recording1) + recording2 = DecomposingRecordingPen(self.glyphset.glyphset2) + self.glyphset.glyphset2[self.glyphname].draw(recording2) + + factor = self.glyphset.factor + + replayRecording(lerpRecordings(recording1.value, recording2.value, factor), pen) diff --git a/shared/package-files/71/714109ef8521c1e202c1b2af536aba9e865c3600f442504407d09f6a41986aa0/wcwidth.py b/shared/package-files/71/714109ef8521c1e202c1b2af536aba9e865c3600f442504407d09f6a41986aa0/wcwidth.py new file mode 100644 index 0000000000000000000000000000000000000000..23886ff1581a16aa97e5c375e62261622e24c169 --- /dev/null +++ b/shared/package-files/71/714109ef8521c1e202c1b2af536aba9e865c3600f442504407d09f6a41986aa0/wcwidth.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +from functools import lru_cache +import unicodedata + + +@lru_cache(100) +def wcwidth(c: str) -> int: + """Determine how many columns are needed to display a character in a terminal. + + Returns -1 if the character is not printable. + Returns 0, 1 or 2 for other characters. + """ + o = ord(c) + + # ASCII fast path. + if 0x20 <= o < 0x07F: + return 1 + + # Some Cf/Zp/Zl characters which should be zero-width. + if ( + o == 0x0000 + or 0x200B <= o <= 0x200F + or 0x2028 <= o <= 0x202E + or 0x2060 <= o <= 0x2063 + ): + return 0 + + category = unicodedata.category(c) + + # Control characters. + if category == "Cc": + return -1 + + # Combining characters with zero width. + if category in ("Me", "Mn"): + return 0 + + # Full/Wide east asian characters. + if unicodedata.east_asian_width(c) in ("F", "W"): + return 2 + + return 1 + + +def wcswidth(s: str) -> int: + """Determine how many columns are needed to display a string in a terminal. + + Returns -1 if the string contains non-printable characters. + """ + width = 0 + for c in unicodedata.normalize("NFC", s): + wc = wcwidth(c) + if wc < 0: + return -1 + width += wc + return width diff --git a/shared/package-files/71/7142b1120b993d6091197574090fe04be3ea64ffc3ad5a167a4b5e0b42c9f062/koi8-r.enc b/shared/package-files/71/7142b1120b993d6091197574090fe04be3ea64ffc3ad5a167a4b5e0b42c9f062/koi8-r.enc new file mode 100644 index 0000000000000000000000000000000000000000..49bf2ea65cf85811e8f32d219b5ebbfe3792bd71 --- /dev/null +++ b/shared/package-files/71/7142b1120b993d6091197574090fe04be3ea64ffc3ad5a167a4b5e0b42c9f062/koi8-r.enc @@ -0,0 +1,20 @@ +# Encoding file: koi8-r, single-byte +S +003F 0 1 +00 +0000000100020003000400050006000700080009000A000B000C000D000E000F +0010001100120013001400150016001700180019001A001B001C001D001E001F +0020002100220023002400250026002700280029002A002B002C002D002E002F +0030003100320033003400350036003700380039003A003B003C003D003E003F +0040004100420043004400450046004700480049004A004B004C004D004E004F +0050005100520053005400550056005700580059005A005B005C005D005E005F +0060006100620063006400650066006700680069006A006B006C006D006E006F +0070007100720073007400750076007700780079007A007B007C007D007E007F +25002502250C251025142518251C2524252C2534253C258025842588258C2590 +259125922593232025A02219221A22482264226500A0232100B000B200B700F7 +25502551255204512553255425552556255725582559255A255B255C255D255E +255F25602561040125622563256425652566256725682569256A256B256C00A9 +044E0430043104460434043504440433044504380439043A043B043C043D043E +043F044F044004410442044304360432044C044B04370448044D04490447044A +042E0410041104260414041504240413042504180419041A041B041C041D041E +041F042F042004210422042304160412042C042B04170428042D04290427042A diff --git a/shared/package-files/71/71443d8881ca5d68095d8d9087d3355571600ff012c8d41b915938527c20ee8a/static.pyi b/shared/package-files/71/71443d8881ca5d68095d8d9087d3355571600ff012c8d41b915938527c20ee8a/static.pyi new file mode 100644 index 0000000000000000000000000000000000000000..db254c7a0a7e38cce74260e6bbaf0332494852d0 --- /dev/null +++ b/shared/package-files/71/71443d8881ca5d68095d8d9087d3355571600ff012c8d41b915938527c20ee8a/static.pyi @@ -0,0 +1,33 @@ +from typing import Any, Optional + +from django.template.base import FilterExpression, Parser, Token +from django.template.context import Context + +from django import template + +register: Any + +class PrefixNode(template.Node): + varname: Optional[str] = ... + name: str = ... + def __init__(self, varname: Optional[str] = ..., name: str = ...) -> None: ... + @classmethod + def handle_token(cls, parser: Parser, token: Token, name: str) -> PrefixNode: ... + @classmethod + def handle_simple(cls, name: str) -> str: ... + +def get_static_prefix(parser: Parser, token: Token) -> PrefixNode: ... +def get_media_prefix(parser: Parser, token: Token) -> PrefixNode: ... + +class StaticNode(template.Node): + path: FilterExpression = ... + varname: Optional[str] = ... + def __init__(self, varname: Optional[str] = ..., path: FilterExpression = ...) -> None: ... + def url(self, context: Context) -> str: ... + @classmethod + def handle_simple(cls, path: str) -> str: ... + @classmethod + def handle_token(cls, parser: Parser, token: Token) -> StaticNode: ... + +def do_static(parser: Parser, token: Token) -> StaticNode: ... +def static(path: str) -> str: ... diff --git a/shared/package-files/71/71448b4e02dfe3b5d220b71d79c1f68565f1d2107b9658a4fb93d8d80afc67dd/unflatten_dense_tensors_compositeimplicitautograd_dispatch.h b/shared/package-files/71/71448b4e02dfe3b5d220b71d79c1f68565f1d2107b9658a4fb93d8d80afc67dd/unflatten_dense_tensors_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..7e4f17fae2975f8b39749708e7ec0fdb386a5b1d --- /dev/null +++ b/shared/package-files/71/71448b4e02dfe3b5d220b71d79c1f68565f1d2107b9658a4fb93d8d80afc67dd/unflatten_dense_tensors_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API ::std::vector unflatten_dense_tensors(const at::Tensor & flat, at::TensorList tensors); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/71/71454698c44182595fb982775f4074ce0d017fe2cfa3d97b2dee63bbcf36771e/Kiritimati b/shared/package-files/71/71454698c44182595fb982775f4074ce0d017fe2cfa3d97b2dee63bbcf36771e/Kiritimati new file mode 100644 index 0000000000000000000000000000000000000000..2f676d3bf5c8599994bcabd402ca30efa4cde5dd Binary files /dev/null and b/shared/package-files/71/71454698c44182595fb982775f4074ce0d017fe2cfa3d97b2dee63bbcf36771e/Kiritimati differ diff --git a/shared/package-files/71/7145b57ac5c074bca968580b337c04a71bbd6efb93afaf291c1361fd700dc791/fo_fo.msg b/shared/package-files/71/7145b57ac5c074bca968580b337c04a71bbd6efb93afaf291c1361fd700dc791/fo_fo.msg new file mode 100644 index 0000000000000000000000000000000000000000..2392b8e6734d6f811cadb5c4ed6aa62147829309 --- /dev/null +++ b/shared/package-files/71/7145b57ac5c074bca968580b337c04a71bbd6efb93afaf291c1361fd700dc791/fo_fo.msg @@ -0,0 +1,7 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset fo_FO DATE_FORMAT "%d/%m-%Y" + ::msgcat::mcset fo_FO TIME_FORMAT "%T" + ::msgcat::mcset fo_FO TIME_FORMAT_12 "%T" + ::msgcat::mcset fo_FO DATE_TIME_FORMAT "%a %d %b %Y %T %z" +} diff --git a/shared/package-files/71/71469eabac93ed337768afa810bdfa20bc0a60c09360ebf5403ea89b6792473d/pairwise_distance.h b/shared/package-files/71/71469eabac93ed337768afa810bdfa20bc0a60c09360ebf5403ea89b6792473d/pairwise_distance.h new file mode 100644 index 0000000000000000000000000000000000000000..b48a625a1973bdfdb0f8f51fa60c55f73acbd27d --- /dev/null +++ b/shared/package-files/71/71469eabac93ed337768afa810bdfa20bc0a60c09360ebf5403ea89b6792473d/pairwise_distance.h @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::pairwise_distance(Tensor x1, Tensor x2, float p=2, float eps=1e-06, bool keepdim=False) -> Tensor +inline at::Tensor pairwise_distance(const at::Tensor & x1, const at::Tensor & x2, double p=2, double eps=1e-06, bool keepdim=false) { + return at::_ops::pairwise_distance::call(x1, x2, p, eps, keepdim); +} + +} diff --git a/shared/package-files/71/7149cdb2b75d75d27f6265e7181f0d31f811b9630c75db5e5737e145a03944e4/pinverse_native.h b/shared/package-files/71/7149cdb2b75d75d27f6265e7181f0d31f811b9630c75db5e5737e145a03944e4/pinverse_native.h new file mode 100644 index 0000000000000000000000000000000000000000..117965384d5be1f161aca3a2cddd908174d3d4fe --- /dev/null +++ b/shared/package-files/71/7149cdb2b75d75d27f6265e7181f0d31f811b9630c75db5e5737e145a03944e4/pinverse_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor pinverse(const at::Tensor & self, double rcond=1e-15); +} // namespace native +} // namespace at diff --git a/shared/package-files/71/714a95c39bc31cd499a1a3b827479b6547f94ab24fdfaefbe5a6eced1f417258/embedding_in_wx3.xrc b/shared/package-files/71/714a95c39bc31cd499a1a3b827479b6547f94ab24fdfaefbe5a6eced1f417258/embedding_in_wx3.xrc new file mode 100644 index 0000000000000000000000000000000000000000..220656d735346d99363d97721fe738d8fcb4feeb --- /dev/null +++ b/shared/package-files/71/714a95c39bc31cd499a1a3b827479b6547f94ab24fdfaefbe5a6eced1f417258/embedding_in_wx3.xrc @@ -0,0 +1,65 @@ + + + + embedding_in_wx3 + + + wxVERTICAL + + + + + + + wxALL|wxEXPAND + 5 + + + + wxHORIZONTAL + + + + + + wxALL|wxEXPAND + 2 + + + + + + + wxALL|wxEXPAND + 2 + + + + + + + + wxALL|wxEXPAND + 2 + + + + 0 + + + wxEXPAND + + + + wxLEFT|wxRIGHT|wxEXPAND + 5 + + + + + wxEXPAND + + + + + \ No newline at end of file diff --git a/shared/package-files/71/714c17e13a79842d52eb6172a4b8551a48ac7db8d0f969b6ece8f335dda3d9c7/CPUAllocator.h b/shared/package-files/71/714c17e13a79842d52eb6172a4b8551a48ac7db8d0f969b6ece8f335dda3d9c7/CPUAllocator.h new file mode 100644 index 0000000000000000000000000000000000000000..98debb9db50ddffbca6ff4fc567e895d482d27c9 --- /dev/null +++ b/shared/package-files/71/714c17e13a79842d52eb6172a4b8551a48ac7db8d0f969b6ece8f335dda3d9c7/CPUAllocator.h @@ -0,0 +1,59 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +// TODO: rename to c10 +C10_DECLARE_bool(caffe2_report_cpu_memory_usage); + +namespace c10 { + +using MemoryDeleter = void (*)(void*); + +// A helper function that is basically doing nothing. +C10_API void NoDelete(void*); + +// A simple struct that is used to report C10's memory allocation, +// deallocation status and out-of-memory events to the profiler +class C10_API ProfiledCPUMemoryReporter { + public: + ProfiledCPUMemoryReporter() = default; + void New(void* ptr, size_t nbytes); + void OutOfMemory(size_t nbytes); + void Delete(void* ptr); + + private: + std::mutex mutex_; + std::unordered_map size_table_; + size_t allocated_ = 0; + size_t log_cnt_ = 0; +}; + +C10_API ProfiledCPUMemoryReporter& profiledCPUMemoryReporter(); + +// Get the CPU Allocator. +C10_API at::Allocator* GetCPUAllocator(); +// Sets the CPU allocator to the given allocator: the caller gives away the +// ownership of the pointer. +C10_API void SetCPUAllocator(at::Allocator* alloc, uint8_t priority = 0); + +// Get the Default CPU Allocator +C10_API at::Allocator* GetDefaultCPUAllocator(); + +// Get the Default Mobile CPU Allocator +C10_API at::Allocator* GetDefaultMobileCPUAllocator(); + +// The CPUCachingAllocator is experimental and might disappear in the future. +// The only place that uses it is in StaticRuntime. +// Set the CPU Caching Allocator +C10_API void SetCPUCachingAllocator(Allocator* alloc, uint8_t priority = 0); +// Get the CPU Caching Allocator +C10_API Allocator* GetCPUCachingAllocator(); + +} // namespace c10 diff --git a/shared/package-files/71/7150ced9af62aa88c8cde528544505ba148be0c479c088124b21e3312af1f7e2/profiling_graph_executor_impl.h b/shared/package-files/71/7150ced9af62aa88c8cde528544505ba148be0c479c088124b21e3312af1f7e2/profiling_graph_executor_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..45da1f030e96283abf6bd68c7038435c16c1b7fa --- /dev/null +++ b/shared/package-files/71/7150ced9af62aa88c8cde528544505ba148be0c479c088124b21e3312af1f7e2/profiling_graph_executor_impl.h @@ -0,0 +1,73 @@ +#pragma once +#include +#include +#include + +C10_DECLARE_bool(torch_jit_static_then_dynamic); + +C10_DECLARE_bool(torch_jit_always_dynamic); + +namespace torch::jit { + +TORCH_API void runNooptPassPipeline(std::shared_ptr& graph); + +struct TORCH_API ProfilingGraphExecutorImpl : public GraphExecutorImplBase { + ProfilingGraphExecutorImpl( + const std::shared_ptr& graph, + std::string function_name); + + const ExecutionPlan& getPlanFor( + Stack& stack, + c10::optional remaining_bailout_depth) override; + GraphExecutorState getDebugState() override; + ~ProfilingGraphExecutorImpl() override = default; + + void debugFlushCompilationCache(); + + bool isOptimized() const override { + return optimized_plan_.has_value(); + } + + private: + const ExecutionPlan& getOptimizedPlanFor( + Stack& stack, + c10::optional remaining_bailout_depth); + void runProfilingInsensitiveOptimizations(std::shared_ptr& graph); + void runProfilingOptimizations( + std::shared_ptr& graph, + size_t remaining_depth); + void replaceFallbackGraphWithFallbackFunction(Block* b); + FusionBehavior getCurrentBehavior(size_t remaining_depth); + size_t getInstantiatedBailoutDepth(); + void runNoGradOptimizations( + std::shared_ptr& graph, + size_t remaining_bailout_depth); + void runFinalOptimizations(std::shared_ptr& graph); + + void clearTheGraphCompilationIntermediateGraphs(); + + std::unique_ptr pr_; + c10::optional + profiling_plan_; // plan to run in order to profiling the code + c10::optional optimized_plan_; + FusionStrategy fusion_strategy_; + + // this plan is used if getGraphExecutorOptimize is unset + c10::optional fallback_plan_; + // fallback functions are inserted for tensorexpr fusion groups + // and by specialize_autogradzero. Whenever, at runtime, input + // tensor don't match profiled properties, fallback functions are called + // They are the deoptimized version of the logic in fusion groups + // and/or autograd. + // The fallback functions are owned by a GraphExecutor instance + // They only exist in the optimized graph which is a private property + // of the GraphExecutor and only shared with InterpreterState + std::vector> fallback_functions_; + c10::optional remaining_bailout_depth_; + // The time the optimized_plan_ is created. + int32_t time_optimized_plan_created_ = 0; + // Has the extra memory used by the graph for profiling is released? + bool is_graph_extra_memory_released_ = false; +}; + +} // namespace torch::jit diff --git a/shared/package-files/71/71512dbe826d6f6f37117b397d22087c8c412156090d07780113e9082c910f48/expand_as_compositeimplicitautograd_dispatch.h b/shared/package-files/71/71512dbe826d6f6f37117b397d22087c8c412156090d07780113e9082c910f48/expand_as_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..2198ce01f90ba6fa51f1c4c601e619c2b465870c --- /dev/null +++ b/shared/package-files/71/71512dbe826d6f6f37117b397d22087c8c412156090d07780113e9082c910f48/expand_as_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor expand_as(const at::Tensor & self, const at::Tensor & other); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/71/7155c6318fbb6e79acddefb319fd14f8bc3f5a24b9a20cc4c345dc26f2e6115a/_values.h b/shared/package-files/71/7155c6318fbb6e79acddefb319fd14f8bc3f5a24b9a20cc4c345dc26f2e6115a/_values.h new file mode 100644 index 0000000000000000000000000000000000000000..29e03d001a2cf893c19d70bf7e7c8ad88a493982 --- /dev/null +++ b/shared/package-files/71/7155c6318fbb6e79acddefb319fd14f8bc3f5a24b9a20cc4c345dc26f2e6115a/_values.h @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + + +} diff --git a/shared/package-files/71/71566d8c1e08f7f3b2d998a71bedc155afbc70c943b9f945aa93ca596d18d805/signal_handler.h b/shared/package-files/71/71566d8c1e08f7f3b2d998a71bedc155afbc70c943b9f945aa93ca596d18d805/signal_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..122d3598424ec43cc815d28378752ecfff952f39 --- /dev/null +++ b/shared/package-files/71/71566d8c1e08f7f3b2d998a71bedc155afbc70c943b9f945aa93ca596d18d805/signal_handler.h @@ -0,0 +1,110 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include + +#if defined(__APPLE__) +#define C10_SUPPORTS_SIGNAL_HANDLER +#elif defined(__linux__) && !defined(C10_DISABLE_SIGNAL_HANDLERS) +#define C10_SUPPORTS_FATAL_SIGNAL_HANDLERS +#define C10_SUPPORTS_SIGNAL_HANDLER +#endif + +#if defined(C10_SUPPORTS_FATAL_SIGNAL_HANDLERS) +#include +#endif + +namespace c10 { + +class C10_API SignalHandler { + public: + enum class Action { NONE, STOP }; + + // Constructor. Specify what action to take when a signal is received. + SignalHandler(Action SIGINT_action, Action SIGHUP_action); + ~SignalHandler(); + + Action CheckForSignals(); + + bool GotSIGINT(); + bool GotSIGHUP(); + + Action SIGINT_action_; + Action SIGHUP_action_; + std::atomic my_sigint_count_; + std::atomic my_sighup_count_; +}; + +#if defined(C10_SUPPORTS_FATAL_SIGNAL_HANDLERS) +class C10_API FatalSignalHandler { + // This works by setting up certain fatal signal handlers. Previous fatal + // signal handlers will still be called when the signal is raised. Defaults + // to being off. + public: + C10_API void setPrintStackTracesOnFatalSignal(bool print); + C10_API bool printStackTracesOnFatalSignal(); + static FatalSignalHandler& getInstance(); + virtual ~FatalSignalHandler(); + + protected: + explicit FatalSignalHandler(); + + private: + void installFatalSignalHandlers(); + void uninstallFatalSignalHandlers(); + static void fatalSignalHandlerStatic(int signum); + void fatalSignalHandler(int signum); + virtual void fatalSignalHandlerPostProcess(); + struct sigaction* getPreviousSigaction(int signum); + const char* getSignalName(int signum); + void callPreviousSignalHandler( + struct sigaction* action, + int signum, + siginfo_t* info, + void* ctx); + void stacktraceSignalHandler(bool needsLock); + static void stacktraceSignalHandlerStatic( + int signum, + siginfo_t* info, + void* ctx); + void stacktraceSignalHandler(int signum, siginfo_t* info, void* ctx); + + // The mutex protects the bool. + std::mutex fatalSignalHandlersInstallationMutex; + bool fatalSignalHandlersInstalled; + // We need to hold a reference to call the previous SIGUSR2 handler in case + // we didn't signal it + struct sigaction previousSigusr2 {}; + // Flag dictating whether the SIGUSR2 handler falls back to previous handlers + // or is intercepted in order to print a stack trace. + std::atomic fatalSignalReceived; + // Global state set when a fatal signal is received so that backtracing + // threads know why they're printing a stacktrace. + const char* fatalSignalName; + int fatalSignum = -1; + // This wait condition is used to wait for other threads to finish writing + // their stack trace when in fatal sig handler (we can't use pthread_join + // because there's no way to convert from a tid to a pthread_t). + std::condition_variable writingCond; + std::mutex writingMutex; + // used to indicate if the other thread responded to the signal + bool signalReceived; + + struct signal_handler { + const char* name; + int signum; + struct sigaction previous; + }; + + // NOLINTNEXTLINE(*c-arrays*) + static signal_handler kSignalHandlers[]; +}; + +#endif // defined(C10_SUPPORTS_SIGNAL_HANDLER) + +} // namespace c10 diff --git a/shared/package-files/71/71585eb669923743a200e9bdc560c422ee9c4c9e3753f7a3d9944c098dcb3c27/to_sparse_csr_ops.h b/shared/package-files/71/71585eb669923743a200e9bdc560c422ee9c4c9e3753f7a3d9944c098dcb3c27/to_sparse_csr_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..e548b98f1c83bb08ca818ea3d8dc3b0fc08cbb91 --- /dev/null +++ b/shared/package-files/71/71585eb669923743a200e9bdc560c422ee9c4c9e3753f7a3d9944c098dcb3c27/to_sparse_csr_ops.h @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API to_sparse_csr { + using schema = at::Tensor (const at::Tensor &, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::to_sparse_csr") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, c10::optional dense_dim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional dense_dim); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/71/71596c364bc6d0d12d260b4c3db4675009926be9b91c0ed7804bfa739f60e697/boxplots.py b/shared/package-files/71/71596c364bc6d0d12d260b4c3db4675009926be9b91c0ed7804bfa739f60e697/boxplots.py new file mode 100644 index 0000000000000000000000000000000000000000..59bd78e0c388c9c9778315f51e988e731968eb70 --- /dev/null +++ b/shared/package-files/71/71596c364bc6d0d12d260b4c3db4675009926be9b91c0ed7804bfa739f60e697/boxplots.py @@ -0,0 +1,468 @@ +"""Variations on boxplots""" + +# Author: Ralf Gommers +# Based on code by Flavio Coelho and Teemu Ikonen. + +import numpy as np +from scipy.stats import gaussian_kde + +from statsmodels.tools.rng_qrng import check_random_state +from statsmodels.tools.validation import string_like + +from . import utils + +__all__ = ["beanplot", "violinplot"] + + +def violinplot( + data, + ax=None, + labels=None, + positions=None, + side="both", + show_boxplot=True, + plot_opts=None, +): + """ + Make a violin plot of each dataset in the `data` sequence + + A violin plot is a boxplot combined with a kernel density estimate of the + probability density function per point. + + Parameters + ---------- + data : sequence[array_like] + Data arrays, one array per value in `positions`. + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure being + created. + labels : list[str], optional + Tick labels for the horizontal axis. If not given, integers + ``1..len(data)`` are used. + positions : array_like, optional + Position array, used as the horizontal axis of the plot. If not given, + spacing of the violins will be equidistant. + side : {'both', 'left', 'right'}, optional + How to plot the violin. Default is 'both'. The 'left', 'right' + options can be used to create asymmetric violin plots. + show_boxplot : bool, optional + Whether or not to show normal box plots on top of the violins. + Default is True. + plot_opts : dict, optional + A dictionary with plotting options. Any of the following can be + provided, if not present in `plot_opts` the defaults will be used:: + + - 'violin_fc', MPL color. Fill color for violins. Default is 'y'. + - 'violin_ec', MPL color. Edge color for violins. Default is 'k'. + - 'violin_lw', scalar. Edge linewidth for violins. Default is 1. + - 'violin_alpha', float. Transparency of violins. Default is 0.5. + - 'cutoff', bool. If True, limit violin range to data range. + Default is False. + - 'cutoff_val', scalar. Where to cut off violins if `cutoff` is + True. Default is 1.5 standard deviations. + - 'cutoff_type', {'std', 'abs'}. Whether cutoff value is absolute, + or in standard deviations. Default is 'std'. + - 'violin_width' : float. Relative width of violins. Max available + space is 1, default is 0.8. + - 'label_fontsize', MPL fontsize. Adjusts fontsize only if given. + - 'label_rotation', scalar. Adjusts label rotation only if given. + Specify in degrees. + - 'bw_factor', Adjusts the scipy gaussian_kde kernel. default: None. + Options for scalar or callable. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + See Also + -------- + beanplot : Bean plot, builds on `violinplot`. + matplotlib.pyplot.boxplot : Standard boxplot. + + Notes + ----- + The appearance of violins can be customized with `plot_opts`. If + customization of boxplot elements is required, set `show_boxplot` to False + and plot it on top of the violins by calling the Matplotlib `boxplot` + function directly. For example:: + + violinplot(data, ax=ax, show_boxplot=False) + ax.boxplot(data, sym='cv', whis=2.5) + + It can happen that the axis labels or tick labels fall outside the plot + area, especially with rotated labels on the horizontal axis. With + Matplotlib 1.1 or higher, this can easily be fixed by calling + ``ax.tight_layout()``. With older Matplotlib one has to use ``plt.rc`` or + ``plt.rcParams`` to fix this, for example:: + + plt.rc('figure.subplot', bottom=0.25) + violinplot(data, ax=ax) + + References + ---------- + J.L. Hintze and R.D. Nelson, "Violin Plots: A Box Plot-Density Trace + Synergism", The American Statistician, Vol. 52, pp.181-84, 1998. + + Examples + -------- + We use the American National Election Survey 1996 dataset, which has Party + Identification of respondents as independent variable and (among other + data) age as dependent variable. + + >>> data = sm.datasets.anes96.load_pandas() + >>> party_ID = np.arange(7) + >>> labels = ["Strong Democrat", "Weak Democrat", "Independent-Democrat", + ... "Independent-Independent", "Independent-Republican", + ... "Weak Republican", "Strong Republican"] + + Group age by party ID, and create a violin plot with it: + + >>> plt.rcParams['figure.subplot.bottom'] = 0.23 # keep labels visible + >>> age = [data.exog['age'][data.endog == id] for id in party_ID] + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> sm.graphics.violinplot(age, ax=ax, labels=labels, + ... plot_opts={'cutoff_val':5, 'cutoff_type':'abs', + ... 'label_fontsize':'small', + ... 'label_rotation':30}) + >>> ax.set_xlabel("Party identification of respondent.") + >>> ax.set_ylabel("Age") + >>> plt.show() + + .. plot:: plots/graphics_boxplot_violinplot.py + """ + side = string_like(side, "side", options=("both", "left", "right"), lower=False) + plot_opts = {} if plot_opts is None else plot_opts + if max([np.size(arr) for arr in data]) == 0: + msg = "No Data to make Violin: Try again!" + raise ValueError(msg) + + fig, ax = utils.create_mpl_ax(ax) + + data = list(map(np.asarray, data)) + if positions is None: + positions = np.arange(len(data)) + 1 + + # Determine available horizontal space for each individual violin. + pos_span = np.max(positions) - np.min(positions) + width = np.min( + [0.15 * np.max([pos_span, 1.0]), plot_opts.get("violin_width", 0.8) / 2.0] + ) + + # Plot violins. + for pos_data, pos in zip(data, positions, strict=True): + _single_violin(ax, pos, pos_data, width, side, plot_opts) + + if show_boxplot: + try: + ax.boxplot(data, notch=1, positions=positions, orientation="vertical") + except TypeError: + # Remove after Matplotlib 3.10 is the minimum + ax.boxplot(data, notch=1, positions=positions, vert=1) + + # Set ticks and tick labels of horizontal axis. + _set_ticks_labels(ax, data, labels, positions, plot_opts) + + return fig + + +def _single_violin(ax, pos, pos_data, width, side, plot_opts): + """Draw a single violin onto `ax` at position `pos`""" + bw_factor = plot_opts.get("bw_factor", None) + + def _violin_range(pos_data, plot_opts): + """Return array with correct range, with which violins can be plotted""" + cutoff = plot_opts.get("cutoff", False) + cutoff_type = plot_opts.get("cutoff_type", "std") + cutoff_val = plot_opts.get("cutoff_val", 1.5) + + s = 0.0 + if not cutoff: + if cutoff_type == "std": + s = cutoff_val * np.std(pos_data) + else: + s = cutoff_val + + x_lower = kde.dataset.min() - s + x_upper = kde.dataset.max() + s + return np.linspace(x_lower, x_upper, 100) + + pos_data = np.asarray(pos_data) + # Kernel density estimate for data at this position. + kde = gaussian_kde(pos_data, bw_method=bw_factor) + + # Create violin for pos, scaled to the available space. + xvals = _violin_range(pos_data, plot_opts) + violin = kde.evaluate(xvals) + violin = width * violin / violin.max() + + if side == "both": + envelope_l, envelope_r = (-violin + pos, violin + pos) + elif side == "right": + envelope_l, envelope_r = (pos, violin + pos) + else: # side == "left" + envelope_l, envelope_r = (-violin + pos, pos) + + # Draw the violin. + ax.fill_betweenx( + xvals, + envelope_l, + envelope_r, + facecolor=plot_opts.get("violin_fc", "#66c2a5"), + edgecolor=plot_opts.get("violin_ec", "k"), + lw=plot_opts.get("violin_lw", 1), + alpha=plot_opts.get("violin_alpha", 0.5), + ) + + return xvals, violin + + +def _set_ticks_labels(ax, data, labels, positions, plot_opts): + """Set ticks and labels on horizontal axis""" + + # Set xticks and limits. + ax.set_xlim([np.min(positions) - 0.5, np.max(positions) + 0.5]) + ax.set_xticks(positions) + + label_fontsize = plot_opts.get("label_fontsize") + label_rotation = plot_opts.get("label_rotation") + if label_fontsize or label_rotation: + from matplotlib.artist import setp + + if labels is not None: + if not len(labels) == len(data): + msg = "Length of `labels` should equal length of `data`." + raise ValueError(msg) + + xticknames = ax.set_xticklabels(labels) + if label_fontsize: + setp(xticknames, fontsize=label_fontsize) + + if label_rotation: + setp(xticknames, rotation=label_rotation) + + +def beanplot( + data, + ax=None, + labels=None, + positions=None, + side="both", + jitter=False, + plot_opts=None, + *, + rng=None, +): + """ + Bean plot of each dataset in a sequence + + A bean plot is a combination of a `violinplot` (kernel density estimate of + the probability density function per point) with a line-scatter plot of all + individual data points. + + Parameters + ---------- + data : sequence[array_like] + Data arrays, one array per value in `positions`. + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure being + created. + labels : list[str], optional + Tick labels for the horizontal axis. If not given, integers + ``1..len(data)`` are used. + positions : array_like, optional + Position array, used as the horizontal axis of the plot. If not given, + spacing of the violins will be equidistant. + side : {'both', 'left', 'right'}, optional + How to plot the violin. Default is 'both'. The 'left', 'right' + options can be used to create asymmetric violin plots. + jitter : bool, optional + If True, jitter markers within violin instead of plotting regular lines + around the center. This can be useful if the data is very dense. + plot_opts : dict, optional + A dictionary with plotting options. All the options for `violinplot` + can be specified, they will simply be passed to `violinplot`. Options + specific to `beanplot` are: + + - 'violin_width' : float. Relative width of violins. Max available + space is 1, default is 0.8. + - 'bean_color', MPL color. Color of bean plot lines. Default is 'k'. + Also used for jitter marker edge color if `jitter` is True. + - 'bean_size', scalar. Line length as a fraction of maximum length. + Default is 0.5. + - 'bean_lw', scalar. Linewidth, default is 0.5. + - 'bean_show_mean', bool. If True (default), show mean as a line. + - 'bean_show_median', bool. If True (default), show median as a + marker. + - 'bean_mean_color', MPL color. Color of mean line. Default is 'b'. + - 'bean_mean_lw', scalar. Linewidth of mean line, default is 2. + - 'bean_mean_size', scalar. Line length as a fraction of maximum length. + Default is 0.5. + - 'bean_median_color', MPL color. Color of median marker. Default + is 'r'. + - 'bean_median_marker', MPL marker. Marker type, default is '+'. + - 'jitter_marker', MPL marker. Marker type for ``jitter=True``. + Default is 'o'. + - 'jitter_marker_size', int. Marker size. Default is 4. + - 'jitter_fc', MPL color. Jitter marker face color. Default is None. + - 'bean_legend_text', str. If given, add a legend with given text. + rng : int, array_like of int, numpy.random.Generator, or numpy.random.RandomState, optional + If `rng` is None, a new ``Generator`` is created using fresh + entropy from the operating system. If `rng` is an int or array + of ints, a new ``Generator`` is created, seeded with `rng`. If + `rng` is already a ``Generator`` or ``RandomState`` instance, + that instance is used. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + See Also + -------- + violinplot : Violin plot, also used internally in `beanplot`. + matplotlib.pyplot.boxplot : Standard boxplot. + + References + ---------- + P. Kampstra, "Beanplot: A Boxplot Alternative for Visual Comparison of + Distributions", J. Stat. Soft., Vol. 28, pp. 1-9, 2008. + + Examples + -------- + We use the American National Election Survey 1996 dataset, which has Party + Identification of respondents as independent variable and (among other + data) age as dependent variable. + + >>> data = sm.datasets.anes96.load_pandas() + >>> party_ID = np.arange(7) + >>> labels = ["Strong Democrat", "Weak Democrat", "Independent-Democrat", + ... "Independent-Independent", "Independent-Republican", + ... "Weak Republican", "Strong Republican"] + + Group age by party ID, and create a violin plot with it: + + >>> plt.rcParams['figure.subplot.bottom'] = 0.23 # keep labels visible + >>> age = [data.exog['age'][data.endog == id] for id in party_ID] + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> sm.graphics.beanplot(age, ax=ax, labels=labels, + ... plot_opts={'cutoff_val':5, 'cutoff_type':'abs', + ... 'label_fontsize':'small', + ... 'label_rotation':30}) + >>> ax.set_xlabel("Party identification of respondent.") + >>> ax.set_ylabel("Age") + >>> plt.show() + + .. plot:: plots/graphics_boxplot_beanplot.py + """ + side = string_like(side, "side", options=("both", "left", "right"), lower=False) + plot_opts = {} if plot_opts is None else plot_opts + fig, ax = utils.create_mpl_ax(ax) + + data = list(map(np.asarray, data)) + if positions is None: + positions = np.arange(len(data)) + 1 + + # Determine available horizontal space for each individual violin. + pos_span = np.max(positions) - np.min(positions) + violin_width = np.min( + [0.15 * np.max([pos_span, 1.0]), plot_opts.get("violin_width", 0.8) / 2.0] + ) + bean_width = np.min( + [0.15 * np.max([pos_span, 1.0]), plot_opts.get("bean_size", 0.5) / 2.0] + ) + bean_mean_width = np.min( + [0.15 * np.max([pos_span, 1.0]), plot_opts.get("bean_mean_size", 0.5) / 2.0] + ) + + legend_txt = plot_opts.get("bean_legend_text", None) + for pos_data, pos in zip(data, positions, strict=True): + # Draw violins. + xvals, violin = _single_violin(ax, pos, pos_data, violin_width, side, plot_opts) + + if jitter: + # Draw data points at random coordinates within violin envelope. + rng = check_random_state(rng) + jitter_coord = pos + _jitter_envelope(pos_data, xvals, violin, side, rng) + ax.plot( + jitter_coord, + pos_data, + ls="", + marker=plot_opts.get("jitter_marker", "o"), + ms=plot_opts.get("jitter_marker_size", 4), + mec=plot_opts.get("bean_color", "k"), + mew=1, + mfc=plot_opts.get("jitter_fc", "none"), + label=legend_txt, + ) + else: + # Draw bean lines. + ax.hlines( + pos_data, + pos - bean_width, + pos + bean_width, + lw=plot_opts.get("bean_lw", 0.5), + color=plot_opts.get("bean_color", "k"), + label=legend_txt, + ) + + # Show legend if required. + if legend_txt is not None: + _show_legend(ax) + legend_txt = None # ensure we get one entry per call to beanplot + + # Draw mean line. + if plot_opts.get("bean_show_mean", True): + ax.hlines( + np.mean(pos_data), + pos - bean_mean_width, + pos + bean_mean_width, + lw=plot_opts.get("bean_mean_lw", 2.0), + color=plot_opts.get("bean_mean_color", "b"), + ) + + # Draw median marker. + if plot_opts.get("bean_show_median", True): + ax.plot( + pos, + np.median(pos_data), + marker=plot_opts.get("bean_median_marker", "+"), + color=plot_opts.get("bean_median_color", "r"), + ) + + # Set ticks and tick labels of horizontal axis. + _set_ticks_labels(ax, data, labels, positions, plot_opts) + + return fig + + +def _jitter_envelope(pos_data, xvals, violin, side, rng): + """Determine envelope for jitter markers""" + if side == "both": + low, high = (-1.0, 1.0) + elif side == "right": + low, high = (0, 1.0) + else: # side == "left" + low, high = (-1.0, 0) + + jitter_envelope = np.interp(pos_data, xvals, violin) + jitter_coord = jitter_envelope * rng.uniform(low=low, high=high, size=pos_data.size) + + return jitter_coord + + +def _show_legend(ax): + """Utility function to show legend""" + leg = ax.legend(loc=1, shadow=True, fancybox=True, labelspacing=0.2, borderpad=0.15) + ltext = leg.get_texts() + llines = leg.get_lines() + leg.get_frame() + + from matplotlib.artist import setp + + setp(ltext, fontsize="small") + setp(llines, linewidth=1) diff --git a/shared/package-files/71/715ad56c5f4f8395092c58b6b6f2deb4f906f81380929a836bd86ab253634875/grammar39.txt b/shared/package-files/71/715ad56c5f4f8395092c58b6b6f2deb4f906f81380929a836bd86ab253634875/grammar39.txt new file mode 100644 index 0000000000000000000000000000000000000000..ae46033cf35962d2311f973c34cc3b743617a1a3 --- /dev/null +++ b/shared/package-files/71/715ad56c5f4f8395092c58b6b6f2deb4f906f81380929a836bd86ab253634875/grammar39.txt @@ -0,0 +1,169 @@ +# Grammar for Python + +# NOTE WELL: You should also follow all the steps listed at +# https://devguide.python.org/grammar/ + +# Start symbols for the grammar: +# single_input is a single interactive statement; +# file_input is a module or sequence of commands read from an input file; +# eval_input is the input for the eval() functions. +# NB: compound_stmt in single_input is followed by extra NEWLINE! +single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE +file_input: stmt* ENDMARKER +eval_input: testlist NEWLINE* ENDMARKER + +decorator: '@' namedexpr_test NEWLINE +decorators: decorator+ +decorated: decorators (classdef | funcdef | async_funcdef) + +async_funcdef: 'async' funcdef +funcdef: 'def' NAME parameters ['->' test] ':' suite + +parameters: '(' [typedargslist] ')' +typedargslist: ( + (tfpdef ['=' test] (',' tfpdef ['=' test])* ',' '/' [',' [ tfpdef ['=' test] ( + ',' tfpdef ['=' test])* ([',' [ + '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] + | '**' tfpdef [',']]]) + | '*' [tfpdef] (',' tfpdef ['=' test])* ([',' ['**' tfpdef [',']]]) + | '**' tfpdef [',']]] ) +| (tfpdef ['=' test] (',' tfpdef ['=' test])* [',' [ + '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] + | '**' tfpdef [',']]] + | '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] + | '**' tfpdef [',']) +) +tfpdef: NAME [':' test] +varargslist: vfpdef ['=' test ](',' vfpdef ['=' test])* ',' '/' [',' [ (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' [ + '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]] + | '**' vfpdef [',']]] + | '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]] + | '**' vfpdef [',']) ]] | (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' [ + '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]] + | '**' vfpdef [',']]] + | '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]] + | '**' vfpdef [','] +) +vfpdef: NAME + +stmt: simple_stmt | compound_stmt | NEWLINE +simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE +small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt | + import_stmt | global_stmt | nonlocal_stmt | assert_stmt) +expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) | + ('=' (yield_expr|testlist_star_expr))*) +annassign: ':' test ['=' (yield_expr|testlist_star_expr)] +testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [','] +augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | + '<<=' | '>>=' | '**=' | '//=') +# For normal and annotated assignments, additional restrictions enforced by the interpreter +del_stmt: 'del' exprlist +pass_stmt: 'pass' +flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt +break_stmt: 'break' +continue_stmt: 'continue' +return_stmt: 'return' [testlist_star_expr] +yield_stmt: yield_expr +raise_stmt: 'raise' [test ['from' test]] +import_stmt: import_name | import_from +import_name: 'import' dotted_as_names +# note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS +import_from: ('from' (('.' | '...')* dotted_name | ('.' | '...')+) + 'import' ('*' | '(' import_as_names ')' | import_as_names)) +import_as_name: NAME ['as' NAME] +dotted_as_name: dotted_name ['as' NAME] +import_as_names: import_as_name (',' import_as_name)* [','] +dotted_as_names: dotted_as_name (',' dotted_as_name)* +dotted_name: NAME ('.' NAME)* +global_stmt: 'global' NAME (',' NAME)* +nonlocal_stmt: 'nonlocal' NAME (',' NAME)* +assert_stmt: 'assert' test [',' test] + +compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated | async_stmt +async_stmt: 'async' (funcdef | with_stmt | for_stmt) +if_stmt: 'if' namedexpr_test ':' suite ('elif' namedexpr_test ':' suite)* ['else' ':' suite] +while_stmt: 'while' namedexpr_test ':' suite ['else' ':' suite] +for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] +try_stmt: ('try' ':' suite + ((except_clause ':' suite)+ + ['else' ':' suite] + ['finally' ':' suite] | + 'finally' ':' suite)) +with_stmt: 'with' with_item (',' with_item)* ':' suite +with_item: test ['as' expr] +# NB compile.c makes sure that the default except clause is last +except_clause: 'except' [test ['as' NAME]] +suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT + +namedexpr_test: test [':=' test] +test: or_test ['if' or_test 'else' test] | lambdef +lambdef: 'lambda' [varargslist] ':' test +or_test: and_test ('or' and_test)* +and_test: not_test ('and' not_test)* +not_test: 'not' not_test | comparison +comparison: expr (comp_op expr)* +# <> isn't actually a valid comparison operator in Python. It's here for the +# sake of a __future__ import described in PEP 401 (which really works :-) +comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' +star_expr: '*' expr +expr: xor_expr ('|' xor_expr)* +xor_expr: and_expr ('^' and_expr)* +and_expr: shift_expr ('&' shift_expr)* +shift_expr: arith_expr (('<<'|'>>') arith_expr)* +arith_expr: term (('+'|'-') term)* +term: factor (('*'|'@'|'/'|'%'|'//') factor)* +factor: ('+'|'-'|'~') factor | power +power: atom_expr ['**' factor] +atom_expr: ['await'] atom trailer* +atom: ('(' [yield_expr|testlist_comp] ')' | + '[' [testlist_comp] ']' | + '{' [dictorsetmaker] '}' | + NAME | NUMBER | strings | '...' | 'None' | 'True' | 'False') +testlist_comp: (namedexpr_test|star_expr) ( comp_for | (',' (namedexpr_test|star_expr))* [','] ) +trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME +subscriptlist: subscript (',' subscript)* [','] +subscript: test | [test] ':' [test] [sliceop] +sliceop: ':' [test] +exprlist: (expr|star_expr) (',' (expr|star_expr))* [','] +testlist: test (',' test)* [','] +dictorsetmaker: ( ((test ':' test | '**' expr) + (comp_for | (',' (test ':' test | '**' expr))* [','])) | + ((test [':=' test] | star_expr) + (comp_for | (',' (test [':=' test] | star_expr))* [','])) ) + +classdef: 'class' NAME ['(' [arglist] ')'] ':' suite + +arglist: argument (',' argument)* [','] + +# The reason that keywords are test nodes instead of NAME is that using NAME +# results in an ambiguity. ast.c makes sure it's a NAME. +# "test '=' test" is really "keyword '=' test", but we have no such token. +# These need to be in a single rule to avoid grammar that is ambiguous +# to our LL(1) parser. Even though 'test' includes '*expr' in star_expr, +# we explicitly match '*' here, too, to give it proper precedence. +# Illegal combinations and orderings are blocked in ast.c: +# multiple (test comp_for) arguments are blocked; keyword unpackings +# that precede iterable unpackings are blocked; etc. +argument: ( test [comp_for] | + test ':=' test | + test '=' test | + '**' test | + '*' test ) + +comp_iter: comp_for | comp_if +sync_comp_for: 'for' exprlist 'in' or_test [comp_iter] +comp_for: ['async'] sync_comp_for +comp_if: 'if' or_test [comp_iter] + +# not used in grammar, but may appear in "node" passed from Parser to Compiler +encoding_decl: NAME + +yield_expr: 'yield' [yield_arg] +yield_arg: 'from' test | testlist_star_expr + +strings: (STRING | fstring)+ +fstring: FSTRING_START fstring_content* FSTRING_END +fstring_content: FSTRING_STRING | fstring_expr +fstring_conversion: '!' NAME +fstring_expr: '{' (testlist_comp | yield_expr) ['='] [ fstring_conversion ] [ fstring_format_spec ] '}' +fstring_format_spec: ':' fstring_content* diff --git a/shared/package-files/71/715d01472a8db087d42f37fd5d40cdf27e6f7a95656b1c6bbdc3fa0b956c1886/SymInt.h b/shared/package-files/71/715d01472a8db087d42f37fd5d40cdf27e6f7a95656b1c6bbdc3fa0b956c1886/SymInt.h new file mode 100644 index 0000000000000000000000000000000000000000..79ce4054b8640eda06b3985296b13fe7b995d33e --- /dev/null +++ b/shared/package-files/71/715d01472a8db087d42f37fd5d40cdf27e6f7a95656b1c6bbdc3fa0b956c1886/SymInt.h @@ -0,0 +1,423 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace c10 { + +class SymFloat; + +// SymInt represents either a regular int64_t, or a symbolic integer +// (represented in a type erased way as SymNode). The intention is for SymInt +// to represent symbolic sizes that arise when doing shape computation in +// operator kernels. This allows for tracing through programs without baking in +// concrete sizes into kernel calls. +// +// SymInt has an API equivalent to int64_t. In particular, it is a value type. +// Internally, SymInt is represented in a clever packed way, so that it only +// occupies one word of space; but morally, it is a union between an int64_t +// and an intrusive pointer to SymNodeImpl. +// +// Invariant: the referenced SymNodeImpl is guaranteed to be a SymNode where +// is_int() returns true + +class C10_API SymInt { + public: + enum Unchecked { + UNCHECKED, + }; + + /*implicit*/ SymInt(int64_t d) : data_(d) { + if (is_heap_allocated()) { + // Large negative number, heap allocate it + promote_to_negative(); + } + }; + SymInt() : data_(0) {} + SymInt(SymNode n); + + // unchecked c-tor accepting raw `data_` + // One appropriate use for this is when you are constructing a symint + // in a situation where you know it is non-negative (or, if it is negative, + // the negative value is -1; i.e., not user controlled) + SymInt(Unchecked, int64_t d) : data_(d) {} + + // TODO: these implementations are not optimal because they allocate a + // temporary and then use the move constructor/assignment + SymInt(const SymInt& s) : data_(0) { + if (s.is_heap_allocated()) { + *this = SymInt(s.toSymNode()); + } else { + data_ = s.data_; + } + } + SymInt(SymInt&& s) noexcept : data_(s.data_) { + s.data_ = 0; + } + + SymInt& operator=(const SymInt& s) { + if (this != &s) { + if (s.is_heap_allocated()) { + *this = SymInt(s.toSymNode()); + } else { + data_ = s.data_; + } + } + return *this; + } + SymInt& operator=(SymInt&& s) noexcept { + if (this != &s) { + release_(); // release the current SymNode if any + data_ = s.data_; + if (s.is_heap_allocated()) + s.data_ = 0; + }; + return *this; + } + + SymNodeImpl* toSymNodeImplUnowned() const { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(is_heap_allocated()); + uint64_t unextended_bits = static_cast(data_) & ~MASK; + uint64_t sign_bit_mask = 1ULL << (62 - 1); + // https://stackoverflow.com/questions/42534749/signed-extension-from-24-bit-to-32-bit-in-c + uint64_t extended_bits = (unextended_bits ^ sign_bit_mask) - sign_bit_mask; + return static_cast( + // NOLINTNEXTLINE(performance-no-int-to-ptr) + reinterpret_cast(static_cast(extended_bits))); + } + + void release_() { + if (is_heap_allocated()) { + SymNode::reclaim(toSymNodeImplUnowned()); // steal + } + } + + SymNodeImpl* release() && { +#ifndef C10_MOBILE + TORCH_INTERNAL_ASSERT(is_heap_allocated()); + auto* r = toSymNodeImplUnowned(); + data_ = 0; // transfer ownership + return r; +#else + TORCH_INTERNAL_ASSERT(false); +#endif + } + + // Only valid if is_heap_allocated() + SymNode toSymNode() const; + + // Guaranteed to return a SymNode, wrapping using base if necessary + SymNode wrap_node(const SymNode& base) const; + + ~SymInt() { + release_(); + } + + // Require the int to be non-symbolic, and if it is symbolic raise an + // error. This is safe to use for C++ code that doesn't work for symbolic + // shapes, and you don't have time to fix it immediately, as if we + // try to trigger the path in C++ you'll appropriately get an error + int64_t expect_int() const { + if (auto r = maybe_as_int()) { + return *r; + } + TORCH_CHECK_ALWAYS_SHOW_CPP_STACKTRACE( + false, "when unpacking SymInt, expected int but got ", *this); + } + + // Test if we have a hint for this int (e.g., guard_int would work). + // Most of the time this is true; it is only false when you have + // an unbacked SymInt. + bool has_hint() const; + + // Insert a guard for the int to be its concrete value, and then return + // that value. This operation always works, even if the int is symbolic, + // so long as we know what the underlying value is (e.g., this won't work + // if you call it on the size of nonzero output). Don't blindly put this + // everywhere; you can cause overspecialization of PyTorch programs with + // this method. + // + // It should be called as guard_int(__FILE__, __LINE__). The file and line + // number can be used to diagnose overspecialization. + int64_t guard_int(const char* file, int64_t line) const; + + // Insert a guard that this SymInt must be size-like, returning true if + // the integer actually is >= 0. Unlike manually performing a >= 0 test, + // if the SymInt in question is an unbacked SymInt (or, potentially in the + // future, if it contains unbacked SymInts), we will also treat the + // unbacked SymInt as statically testing >= 2 (which will prevent us from + // choking on, e.g., contiguity checks.) + bool expect_size(const char* file, int64_t line) const; + + // Distinguish actual symbolic values from constants stored on the heap + bool is_symbolic() const { + return is_heap_allocated() && + !toSymNodeImplUnowned()->constant_int().has_value(); + } + + // N.B. It's important to keep this definition in the header + // as we expect if checks to be folded for mobile builds + // where `is_heap_allocated` is always false and optimize dead code paths + C10_ALWAYS_INLINE bool is_heap_allocated() const { +#ifdef C10_MOBILE + return false; +#else + return !check_range(data_); +#endif + } + + SymInt operator+(const SymInt& sci) const; + SymInt operator-(const SymInt& sci) const; + SymInt operator*(const SymInt& sci) const; + SymInt operator/(const SymInt& sci) const; + SymInt operator%(const SymInt& sci) const; + void operator*=(const SymInt& sci); + void operator+=(const SymInt& sci); + void operator/=(const SymInt& sci); + + SymInt clone() const; + + SymBool sym_eq(const SymInt&) const; + SymBool sym_ne(const SymInt&) const; + SymBool sym_lt(const SymInt&) const; + SymBool sym_le(const SymInt&) const; + SymBool sym_gt(const SymInt&) const; + SymBool sym_ge(const SymInt&) const; + + bool operator==(const SymInt& o) const { + return sym_eq(o).guard_bool(__FILE__, __LINE__); + } + bool operator!=(const SymInt& o) const { + return sym_ne(o).guard_bool(__FILE__, __LINE__); + } + bool operator<(const SymInt& o) const { + return sym_lt(o).guard_bool(__FILE__, __LINE__); + } + bool operator<=(const SymInt& o) const { + return sym_le(o).guard_bool(__FILE__, __LINE__); + } + bool operator>(const SymInt& o) const { + return sym_gt(o).guard_bool(__FILE__, __LINE__); + } + bool operator>=(const SymInt& o) const { + return sym_ge(o).guard_bool(__FILE__, __LINE__); + } + + SymInt min(const SymInt& sci) const; + SymInt max(const SymInt& sci) const; + + // If both are symbolic, this checks if + // they share the same node. + // If both are not symbolic this just checks normal equality. + bool is_same(const SymInt& other) const; + + operator SymFloat() const; + + // Don't use this. Prefer maybe_as_int instead + int64_t as_int_unchecked() const { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(!is_heap_allocated()); + return data_; + } + + c10::optional maybe_as_int() const { + if (!is_heap_allocated()) { + return c10::make_optional(data_); + } + auto* node = toSymNodeImplUnowned(); + if (auto c = node->constant_int()) { + return c; + } + return node->maybe_as_int(); + } + + // Return whether the integer is directly coercible to a SymInt + // without requiring heap allocation. You don't need to use this + // to check if you can pass an integer to SymInt; this is guaranteed + // to work (it just might heap allocate!) + static bool check_range(int64_t i) { + return i > MAX_UNREPRESENTABLE_INT; + } + + // Return the min representable integer as a SymInt without + // heap allocation. For quantities that count bytes (or larger), + // this is still much larger than you need, so you may consider + // using this as a more efficient version of MIN_INT + static constexpr int64_t min_representable_int() { + return MAX_UNREPRESENTABLE_INT + 1; + } + + private: + void promote_to_negative(); + + // Constraints on the internal representation: + // + // - Should represent positive and small negative ints + // - No conversion necessary for operations on ints + // - Must represent valid 64-bit pointers + // - Is symbolic test should be FAST (two arithmetic instructions is too + // much). + // This code being a hotpath is based on Strobelight profiles of + // is_heap_allocated(). FB only: https://fburl.com/strobelight/5l50ncxd + // (you will need to change the time window). + // + // So, the scheme is to reserve large negative numbers (assuming + // two's complement): + // + // - 0b0.... means we are a positive int + // - 0b11... means we are a small negative int + // - 0b10... means we are are a pointer. This means that + // [-2^63, -2^62-1] are not representable as ints. + // We don't actually need all of this space as on x86_64 + // as the top 16bits aren't used for anything + static constexpr uint64_t MASK = 1ULL << 63 | 1ULL << 62 | 1ULL << 61; + static constexpr uint64_t IS_SYM = 1ULL << 63 | 1ULL << 61; + // We must manually translate the bit pattern test into a greater + // than test because compiler doesn't figure it out: + // https://godbolt.org/z/356aferaW + static constexpr int64_t MAX_UNREPRESENTABLE_INT = + -1LL & static_cast(~(1ULL << 62)); + int64_t data_; +}; + +/// Sum of a list of SymInt; accumulates into the c10::SymInt expression +template < + typename C, + typename std::enable_if_t< + std::is_same_v, + int> = 0> +inline c10::SymInt multiply_integers(const C& container) { + return std::accumulate( + container.begin(), + container.end(), + c10::SymInt(1), + [](const c10::SymInt& a, const c10::SymInt& b) { return a * b; }); +} + +template < + typename Iter, + typename = std::enable_if_t::value_type, + c10::SymInt>>> +inline c10::SymInt multiply_integers(Iter begin, Iter end) { + return std::accumulate( + begin, + end, + c10::SymInt(1), + [](const c10::SymInt& a, const c10::SymInt& b) { return a * b; }); +} + +#define DECLARE_SYMINT_OP_INTONLY(scalar_t, RetTy) \ + C10_API RetTy operator%(const SymInt& a, scalar_t b); \ + C10_API RetTy operator%(scalar_t a, const SymInt& b); + +#define DECLARE_SYMINT_OP(scalar_t, RetTy) \ + C10_API RetTy operator+(const SymInt& a, scalar_t b); \ + C10_API RetTy operator-(const SymInt& a, scalar_t b); \ + C10_API RetTy operator*(const SymInt& a, scalar_t b); \ + C10_API RetTy operator/(const SymInt& a, scalar_t b); \ + C10_API RetTy operator+(scalar_t a, const SymInt& b); \ + C10_API RetTy operator-(scalar_t a, const SymInt& b); \ + C10_API RetTy operator*(scalar_t a, const SymInt& b); \ + C10_API RetTy operator/(scalar_t a, const SymInt& b); \ + C10_API bool operator==(const SymInt& a, scalar_t b); \ + C10_API bool operator!=(const SymInt& a, scalar_t b); \ + C10_API bool operator<(const SymInt& a, scalar_t b); \ + C10_API bool operator<=(const SymInt& a, scalar_t b); \ + C10_API bool operator>(const SymInt& a, scalar_t b); \ + C10_API bool operator>=(const SymInt& a, scalar_t b); \ + C10_API bool operator==(scalar_t a, const SymInt& b); \ + C10_API bool operator!=(scalar_t a, const SymInt& b); \ + C10_API bool operator<(scalar_t a, const SymInt& b); \ + C10_API bool operator<=(scalar_t a, const SymInt& b); \ + C10_API bool operator>(scalar_t a, const SymInt& b); \ + C10_API bool operator>=(scalar_t a, const SymInt& b); + +DECLARE_SYMINT_OP_INTONLY(int64_t, SymInt) +DECLARE_SYMINT_OP_INTONLY(int32_t, SymInt) +DECLARE_SYMINT_OP_INTONLY(uint64_t, SymInt) +DECLARE_SYMINT_OP_INTONLY(uint32_t, SymInt) +DECLARE_SYMINT_OP(int64_t, SymInt) +DECLARE_SYMINT_OP(int32_t, SymInt) // make sure constants work +DECLARE_SYMINT_OP(uint64_t, SymInt) +DECLARE_SYMINT_OP(uint32_t, SymInt) +DECLARE_SYMINT_OP(double, SymFloat) +DECLARE_SYMINT_OP(float, SymFloat) // just for completeness + +// On OSX size_t is different than uint64_t so we have to +// define it separately +#if defined(__APPLE__) +DECLARE_SYMINT_OP_INTONLY(size_t, SymInt) +DECLARE_SYMINT_OP(size_t, SymInt) +#endif + +#undef DECLARE_SYMINT_OP + +C10_API std::ostream& operator<<(std::ostream& os, const SymInt& s); +C10_API SymInt operator-(const SymInt& s); + +inline bool sym_eq(int64_t a, int64_t b) { + return a == b; +} + +inline SymBool sym_eq(const SymInt& a, const SymInt& b) { + return a.sym_eq(b); +} + +inline bool sym_ne(int64_t a, int64_t b) { + return a != b; +} + +inline SymBool sym_ne(const SymInt& a, const SymInt& b) { + return a.sym_ne(b); +} + +inline bool sym_lt(int64_t a, int64_t b) { + return a < b; +} + +inline SymBool sym_lt(const SymInt& a, const SymInt& b) { + return a.sym_lt(b); +} + +inline bool sym_le(int64_t a, int64_t b) { + return a <= b; +} + +inline SymBool sym_le(const SymInt& a, const SymInt& b) { + return a.sym_le(b); +} + +inline bool sym_gt(int64_t a, int64_t b) { + return a > b; +} + +inline SymBool sym_gt(const SymInt& a, const SymInt& b) { + return a.sym_gt(b); +} + +inline bool sym_ge(int64_t a, int64_t b) { + return a >= b; +} + +inline SymBool sym_ge(const SymInt& a, const SymInt& b) { + return a.sym_ge(b); +} + +inline bool definitely_true( + const c10::SymBool& b, + const char* file, + int64_t line) { + return b.has_hint() && b.guard_bool(file, line); +} + +} // namespace c10 diff --git a/shared/package-files/71/715d271062aadf2aed2ac3711e98a85f430e9b03bfe1d511bfd811ec28bc4ca3/_libsvm.pxi b/shared/package-files/71/715d271062aadf2aed2ac3711e98a85f430e9b03bfe1d511bfd811ec28bc4ca3/_libsvm.pxi new file mode 100644 index 0000000000000000000000000000000000000000..74ddfd66c538e712e95ba183bcf34695f5b85a14 --- /dev/null +++ b/shared/package-files/71/715d271062aadf2aed2ac3711e98a85f430e9b03bfe1d511bfd811ec28bc4ca3/_libsvm.pxi @@ -0,0 +1,75 @@ +################################################################################ +# Includes +from ..utils._typedefs cimport intp_t + +cdef extern from "_svm_cython_blas_helpers.h": + ctypedef double (*dot_func)(int, const double*, int, const double*, int) + cdef struct BlasFunctions: + dot_func dot + + +cdef extern from "svm.h": + cdef struct svm_node + cdef struct svm_model + cdef struct svm_parameter: + int svm_type + int kernel_type + int degree # for poly + double gamma # for poly/rbf/sigmoid + double coef0 # for poly/sigmoid + + # these are for training only + double cache_size # in MB + double eps # stopping criteria + double C # for C_SVC, EPSILON_SVR and NU_SVR + int nr_weight # for C_SVC + int *weight_label # for C_SVC + double* weight # for C_SVC + double nu # for NU_SVC, ONE_CLASS, and NU_SVR + double p # for EPSILON_SVR + int shrinking # use the shrinking heuristics + int probability # do probability estimates + int max_iter # ceiling on Solver runtime + int random_seed # seed for random generator in probability estimation + + cdef struct svm_problem: + int l + double *y + svm_node *x + double *W # instance weights + + char *svm_check_parameter(svm_problem *, svm_parameter *) + svm_model *svm_train(svm_problem *, svm_parameter *, int *, BlasFunctions *) nogil + void svm_free_and_destroy_model(svm_model** model_ptr_ptr) + void svm_cross_validation(svm_problem *, svm_parameter *, int nr_fold, double *target, BlasFunctions *) nogil + + +cdef extern from "libsvm_helper.c": + # this file contains methods for accessing libsvm 'hidden' fields + svm_node **dense_to_sparse (char *, intp_t *) + void set_parameter (svm_parameter *, int , int , int , double, double , + double , double , double , double, + double, int, int, int, char *, char *, int, + int) + void set_problem (svm_problem *, char *, char *, char *, intp_t *, int) + + svm_model *set_model (svm_parameter *, int, char *, intp_t *, + char *, intp_t *, intp_t *, char *, + char *, char *, char *, char *) + + void copy_sv_coef (char *, svm_model *) + void copy_n_iter (char *, svm_model *) + void copy_intercept (char *, svm_model *, intp_t *) + void copy_SV (char *, svm_model *, intp_t *) + int copy_support (char *data, svm_model *model) + int copy_predict (char *, svm_model *, intp_t *, char *, BlasFunctions *) nogil + int copy_predict_proba (char *, svm_model *, intp_t *, char *, BlasFunctions *) nogil + int copy_predict_values(char *, svm_model *, intp_t *, char *, int, BlasFunctions *) nogil + void copy_nSV (char *, svm_model *) + void copy_probA (char *, svm_model *, intp_t *) + void copy_probB (char *, svm_model *, intp_t *) + intp_t get_l (svm_model *) + intp_t get_nr (svm_model *) + int free_problem (svm_problem *) + int free_model (svm_model *) + void set_verbosity(int) diff --git a/shared/package-files/71/715de3ba5848074a299d3008da4fb093fa69d53903770f0e56eecace55d0397b/qu2cu.c b/shared/package-files/71/715de3ba5848074a299d3008da4fb093fa69d53903770f0e56eecace55d0397b/qu2cu.c new file mode 100644 index 0000000000000000000000000000000000000000..7a80bc2f1ffe47f2f96ff5b9a2111d30f83b54c3 --- /dev/null +++ b/shared/package-files/71/715de3ba5848074a299d3008da4fb093fa69d53903770f0e56eecace55d0397b/qu2cu.c @@ -0,0 +1,20325 @@ +/* Generated by Cython 3.3.0 */ + +/* BEGIN: Cython Metadata +{ + "distutils": { + "define_macros": [ + [ + "CYTHON_TRACE_NOGIL", + "1" + ] + ], + "libraries": [ + "m" + ], + "name": "fontTools.qu2cu.qu2cu", + "sources": [ + "Lib/fontTools/qu2cu/qu2cu.py" + ] + }, + "module_name": "fontTools.qu2cu.qu2cu" +} +END: Cython Metadata */ + +#ifndef PY_SSIZE_T_CLEAN +#define PY_SSIZE_T_CLEAN +#endif /* PY_SSIZE_T_CLEAN */ +/* InitLimitedAPI */ +#if defined(Py_LIMITED_API) + #if !defined(CYTHON_LIMITED_API) + #define CYTHON_LIMITED_API 1 + #endif +#elif defined(CYTHON_LIMITED_API) + #ifdef _MSC_VER + #pragma message ("Limited API usage is enabled with 'CYTHON_LIMITED_API' but 'Py_LIMITED_API' does not define a Python target version. Consider setting 'Py_LIMITED_API' instead.") + #else + #warning Limited API usage is enabled with 'CYTHON_LIMITED_API' but 'Py_LIMITED_API' does not define a Python target version. Consider setting 'Py_LIMITED_API' instead. + #endif +#endif + +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x03090000 + #error Cython requires Python 3.9+. +#elif defined(Py_LIMITED_API) && (Py_LIMITED_API & 0xFFFF0000) > (PY_VERSION_HEX & 0xFFFF0000) + #error 'Py_LIMITED_API' can only select past Python X.Y versions, not future ones. +#else +#define __PYX_ABI_VERSION "3_3_0" +#define CYTHON_HEX_VERSION 0x030300F0 +#define CYTHON_FUTURE_DIVISION 1 +/* CModulePreamble */ +#include +#ifndef offsetof + #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(_WIN32) && !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifdef __has_builtin + #define __Pyx_has_cbuiltin(name) __has_builtin(name) +#else + #define __Pyx_has_cbuiltin(name) (0) +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#define __PYX_COMMA , +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#define __PYX_LIMITED_VERSION_HEX PY_VERSION_HEX +#if defined(CYTHON_LIMITED_API) + #ifdef Py_LIMITED_API + #undef __PYX_LIMITED_VERSION_HEX + #define __PYX_LIMITED_VERSION_HEX Py_LIMITED_API + #if Py_LIMITED_API < 0x03090000 + #error "Cython 3.3 requires the Python Limited API version to be 3.9 or greater." + #endif + #endif + #if defined(GRAALVM_PYTHON) || defined(PYPY_VERSION) + #ifdef _MSC_VER + #pragma message ("Py_LIMITED_API is defined on PyPy or GraalPy. This takes precedence over Cython's specialized\ + code for PyPy and GraalPy and is unlikely to work.") + #else + #warning "Py_LIMITED_API is defined on PyPy or GraalPy. This takes precedence over Cython's specialized\ + code for PyPy and GraalPy and is unlikely to work." + #endif + #endif + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 1 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 1 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #endif + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_VECTORCALL + #define CYTHON_VECTORCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) + #ifndef CYTHON_VECTORCALL_TPNEW + #define CYTHON_VECTORCALL_TPNEW (CYTHON_VECTORCALL && __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE (__PYX_LIMITED_VERSION_HEX >= 0x030F0000 && PY_VERSION_HEX > 0x030F00A8) + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND (__PYX_LIMITED_VERSION_HEX >= 0x030A0000) + #endif + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #ifndef CYTHON_USE_OWN_PREP_RERAISE_STAR + #define CYTHON_USE_OWN_PREP_RERAISE_STAR 1 + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 1 + #endif + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 + #if __PYX_LIMITED_VERSION_HEX < 0x030E0000 + #undef CYTHON_OPAQUE_OBJECTS + #define CYTHON_OPAQUE_OBJECTS 0 + #elif !defined(CYTHON_OPAQUE_OBJECTS) + #define CYTHON_OPAQUE_OBJECTS (__PYX_LIMITED_VERSION_HEX >= 0x030F0000) + #endif +#elif defined(GRAALVM_PYTHON) + /* For very preliminary testing purposes. Most variables are set the same as PyPy. + The existence of this section does not imply that anything works or is even tested */ + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 1 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #ifndef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #endif + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #ifndef CYTHON_VECTORCALL + #define CYTHON_VECTORCALL 1 + #endif + #if CYTHON_USE_TYPE_SPECS && PY_VERSION_HEX < 0x030E0000 + #undef CYTHON_VECTORCALL_TPNEW + #define CYTHON_VECTORCALL_TPNEW 0 + #elif !defined(CYTHON_VECTORCALL_TPNEW) + #define CYTHON_VECTORCALL_TPNEW CYTHON_VECTORCALL + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #ifndef CYTHON_USE_OWN_PREP_RERAISE_STAR + #define CYTHON_USE_OWN_PREP_RERAISE_STAR 1 + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 + #undef CYTHON_OPAQUE_OBJECTS + #define CYTHON_OPAQUE_OBJECTS 0 +#elif defined(PYPY_VERSION) + #define CYTHON_COMPILING_IN_PYPY 1 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #ifndef CYTHON_VECTORCALL + #define CYTHON_VECTORCALL 1 + #endif + #if CYTHON_USE_TYPE_SPECS && PY_VERSION_HEX < 0x030E0000 + #undef CYTHON_VECTORCALL_TPNEW + #define CYTHON_VECTORCALL_TPNEW 0 + #elif !defined(CYTHON_VECTORCALL_TPNEW) + #define CYTHON_VECTORCALL_TPNEW (PYPY_VERSION_NUM >= 0x07030800 && CYTHON_VECTORCALL) + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE (PYPY_VERSION_NUM >= 0x07030C00) + #endif + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC (PYPY_VERSION_NUM >= 0x07031100) + #endif + #ifndef CYTHON_USE_OWN_PREP_RERAISE_STAR + #define CYTHON_USE_OWN_PREP_RERAISE_STAR 1 + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 + #undef CYTHON_OPAQUE_OBJECTS + #define CYTHON_OPAQUE_OBJECTS 0 +#else + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 1 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #ifdef Py_GIL_DISABLED + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 1 + #else + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #endif + #if PY_VERSION_HEX < 0x030A0000 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #elif !defined(CYTHON_USE_TYPE_SLOTS) + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #ifndef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 1 + #endif + #ifndef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #elif !defined(CYTHON_USE_PYLIST_INTERNALS) + #define CYTHON_USE_PYLIST_INTERNALS 1 + #endif + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING || PY_VERSION_HEX >= 0x030B00A2 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #elif !defined(CYTHON_USE_UNICODE_WRITER) + #define CYTHON_USE_UNICODE_WRITER 1 + #endif + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #elif !defined(CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS) + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #ifndef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #elif !defined(CYTHON_FAST_GIL) + #define CYTHON_FAST_GIL (PY_VERSION_HEX < 0x030C00A6) + #endif + #ifndef CYTHON_VECTORCALL + #define CYTHON_VECTORCALL 1 + #endif + #if CYTHON_USE_TYPE_SPECS && PY_VERSION_HEX < 0x030E0000 + #undef CYTHON_VECTORCALL_TPNEW + #define CYTHON_VECTORCALL_TPNEW 0 + #elif !defined(CYTHON_VECTORCALL_TPNEW) + #define CYTHON_VECTORCALL_TPNEW CYTHON_VECTORCALL + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #ifndef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING (PY_VERSION_HEX >= 0x030d00B1) + #endif + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 1 + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #elif !defined(CYTHON_USE_DICT_VERSIONS) + #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX < 0x030C00A5 && !CYTHON_USE_MODULE_STATE) + #endif + #ifndef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #endif + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 1 + #endif + #ifndef CYTHON_USE_OWN_PREP_RERAISE_STAR + #define CYTHON_USE_OWN_PREP_RERAISE_STAR (PY_VERSION_HEX < 0x030C00B2) + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS (!CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif + #if defined(CYTHON_IMMORTAL_CONSTANTS) && PY_VERSION_HEX < 0x030C0000 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 // definitely won't work + #elif !defined(CYTHON_IMMORTAL_CONSTANTS) + #define CYTHON_IMMORTAL_CONSTANTS (PY_VERSION_HEX >= 0x030C0000 && !CYTHON_USE_MODULE_STATE && CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif + #ifndef CYTHON_OPAQUE_OBJECTS + #define CYTHON_OPAQUE_OBJECTS 0 + #endif +#endif +#if CYTHON_USE_PYLONG_INTERNALS + #undef SHIFT + #undef BASE + #undef MASK + #ifdef SIZEOF_VOID_P + enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; + #endif +#endif +#ifndef __has_attribute + #define __has_attribute(x) 0 +#endif +#ifndef __has_cpp_attribute + #define __has_cpp_attribute(x) 0 +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifndef CYTHON_UNUSED + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(maybe_unused) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(maybe_unused) + #define CYTHON_UNUSED [[maybe_unused]] + #endif + #endif + #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L + #define CYTHON_UNUSED [[maybe_unused]] + #endif +#endif +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_UNUSED_VAR +# if defined(__cplusplus) + template void CYTHON_UNUSED_VAR( const T& ) { } +# else +# define CYTHON_UNUSED_VAR(x) (void)(x) +# endif +#endif +#ifndef CYTHON_MAYBE_UNUSED_VAR + #define CYTHON_MAYBE_UNUSED_VAR(x) CYTHON_UNUSED_VAR(x) +#endif +#ifndef CYTHON_NCP_UNUSED +# if CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +# define CYTHON_NCP_UNUSED +# else +# define CYTHON_NCP_UNUSED CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_USE_CPP_STD_MOVE + #if defined(__cplusplus) && (\ + __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600)) + #define CYTHON_USE_CPP_STD_MOVE 1 + #else + #define CYTHON_USE_CPP_STD_MOVE 0 + #endif +#endif +#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) +#include +typedef uintptr_t __pyx_uintptr_t; +#ifndef CYTHON_FALLTHROUGH + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(fallthrough) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(fallthrough) + #define CYTHON_FALLTHROUGH [[fallthrough]] + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_cpp_attribute(clang::fallthrough) + #define CYTHON_FALLTHROUGH [[clang::fallthrough]] + #elif __has_cpp_attribute(gnu::fallthrough) + #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] + #endif + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_attribute(fallthrough) + #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) + #else + #define CYTHON_FALLTHROUGH + #endif + #endif + #if defined(__clang__) && defined(__apple_build_version__) + #if __apple_build_version__ < 7000000 + #undef CYTHON_FALLTHROUGH + #define CYTHON_FALLTHROUGH + #endif + #endif +#endif +#ifdef Py_UNREACHABLE + #define __Pyx_UNREACHABLE() Py_UNREACHABLE() +#elif __Pyx_has_cbuiltin(__builtin_unreachable) + #define __Pyx_UNREACHABLE() __builtin_unreachable() +#elif defined(__clang__) || defined(__INTEL_COMPILER) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))) + #define __Pyx_UNREACHABLE() __builtin_unreachable() +#elif defined(_MSC_VER) + #define __Pyx_UNREACHABLE() __assume(0) +#else + #define __Pyx_UNREACHABLE() Py_FatalError("Unreachable C code path reached") +#endif +#ifndef Py_UNREACHABLE + #define Py_UNREACHABLE() __Pyx_UNREACHABLE() +#endif +#ifdef __cplusplus + template + struct __PYX_IS_UNSIGNED_IMPL {static const bool value = T(0) < T(-1);}; + #define __PYX_IS_UNSIGNED(type) (__PYX_IS_UNSIGNED_IMPL::value) +#else + #define __PYX_IS_UNSIGNED(type) (((type)-1) > 0) +#endif +#if CYTHON_COMPILING_IN_PYPY == 1 + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX < 0x030A0000) +#else + #define __PYX_NEED_TP_PRINT_SLOT 0 +#endif +#define __PYX_REINTERPRET_FUNCION(func_pointer, other_pointer) ((func_pointer)(void(*)(void))(other_pointer)) +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 +#define __Pyx_PyErr_FetchException(petype, peval, petb) PyErr_Fetch(petype, peval, petb) +#define __Pyx_PyErr_RestoreException(etype, eval, etb) PyErr_Restore(etype, eval, etb) +#else +#define __Pyx_PyErr_FetchException(petype, peval, petb) *(petype)=NULL; *(peval)=PyErr_GetRaisedException(); *(petb)=NULL +#define __Pyx_PyErr_RestoreException(etype, eval, etb) PyErr_SetRaisedException(eval) +#endif + +/* CInitCode */ +#ifndef CYTHON_INLINE + #if defined(__clang__) + #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) + #elif defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif + +/* PythonCompatibility */ +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" +#define __Pyx_BUILTIN_MODULE_NAME "builtins" +#define __Pyx_DefaultClassType PyType_Type +#if CYTHON_COMPILING_IN_LIMITED_API + #ifndef CO_OPTIMIZED + static int CO_OPTIMIZED; + #endif + #ifndef CO_NEWLOCALS + static int CO_NEWLOCALS; + #endif + #ifndef CO_VARARGS + static int CO_VARARGS; + #endif + #ifndef CO_VARKEYWORDS + static int CO_VARKEYWORDS; + #endif + #ifndef CO_ASYNC_GENERATOR + static int CO_ASYNC_GENERATOR; + #endif + #ifndef CO_GENERATOR + static int CO_GENERATOR; + #endif + #ifndef CO_COROUTINE + static int CO_COROUTINE; + #endif +#else + #ifndef CO_COROUTINE + #define CO_COROUTINE 0x80 + #endif + #ifndef CO_ASYNC_GENERATOR + #define CO_ASYNC_GENERATOR 0x200 + #endif +#endif +static int __Pyx_init_co_variables(void); +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_Is) + #define __Pyx_Py_Is(x, y) Py_Is(x, y) +#else + #define __Pyx_Py_Is(x, y) ((x) == (y)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsNone) + #define __Pyx_Py_IsNone(ob) Py_IsNone(ob) +#else + #define __Pyx_Py_IsNone(ob) __Pyx_Py_Is((ob), Py_None) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsTrue) + #define __Pyx_Py_IsTrue(ob) Py_IsTrue(ob) +#else + #define __Pyx_Py_IsTrue(ob) __Pyx_Py_Is((ob), Py_True) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsFalse) + #define __Pyx_Py_IsFalse(ob) Py_IsFalse(ob) +#else + #define __Pyx_Py_IsFalse(ob) __Pyx_Py_Is((ob), Py_False) +#endif +#define __Pyx_NoneAsNull(obj) (__Pyx_Py_IsNone(obj) ? NULL : (obj)) +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyObject_GC_IsFinalized(o) _PyGC_FINALIZED(o) +#else + #define __Pyx_PyObject_GC_IsFinalized(o) PyObject_GC_IsFinalized(o) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static unsigned long __Pyx_Runtime_TPFLAGS_SEQUENCE; +static unsigned long __Pyx_Runtime_TPFLAGS_MAPPING; +#else +#define __Pyx_Runtime_TPFLAGS_SEQUENCE Py_TPFLAGS_SEQUENCE +#define __Pyx_Runtime_TPFLAGS_MAPPING Py_TPFLAGS_MAPPING +#endif +static int __Pyx_init_tpflags_variables(void); +#ifndef Py_TPFLAGS_HAVE_FINALIZE + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#ifndef Py_TPFLAGS_SEQUENCE + #define Py_TPFLAGS_SEQUENCE (CYTHON_COMPILING_IN_LIMITED_API ? 0 : 1 << 5) +#endif +#ifndef Py_TPFLAGS_MAPPING + #define Py_TPFLAGS_MAPPING (CYTHON_COMPILING_IN_LIMITED_API ? 0 : 1 << 6) +#endif +#ifndef Py_TPFLAGS_IMMUTABLETYPE + #define Py_TPFLAGS_IMMUTABLETYPE (1UL << 8) +#endif +#ifndef Py_TPFLAGS_DISALLOW_INSTANTIATION + #define Py_TPFLAGS_DISALLOW_INSTANTIATION (1UL << 7) +#endif +#ifndef METH_STACKLESS + #define METH_STACKLESS 0 +#endif +#if !defined(METH_FASTCALL) || CYTHON_COMPILING_IN_PYPY + #ifndef METH_FASTCALL + #define METH_FASTCALL 0x80 + #endif + typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); + typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, + Py_ssize_t nargs, PyObject *kwnames); +#else + #if PY_VERSION_HEX >= 0x030d00A4 + # define __Pyx_PyCFunctionFast PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords PyCFunctionFastWithKeywords + #else + # define __Pyx_PyCFunctionFast _PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords + #endif +#endif +#if CYTHON_VECTORCALL + #define __Pyx_METH_FASTCALL METH_FASTCALL + #define __Pyx_PyCFunction_FastCall __Pyx_PyCFunctionFast + #define __Pyx_PyCFunction_FastCallWithKeywords __Pyx_PyCFunctionFastWithKeywords +#else + #define __Pyx_METH_FASTCALL METH_VARARGS + #define __Pyx_PyCFunction_FastCall PyCFunction + #define __Pyx_PyCFunction_FastCallWithKeywords PyCFunctionWithKeywords +#endif +#if CYTHON_VECTORCALL + #define __pyx_vectorcallfunc vectorcallfunc + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET PY_VECTORCALL_ARGUMENTS_OFFSET + #define __Pyx_PyVectorcall_NARGS(n) PyVectorcall_NARGS((size_t)(n)) +#else + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET 0 + #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(n)) +#endif +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_CheckExact(func) +#define __Pyx_CyOrPyCFunction_Check(func) PyCFunction_Check(func) +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) (((PyCFunctionObject*)(func))->m_ml->ml_meth) +#elif !CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) PyCFunction_GET_FUNCTION(func) +#endif +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FLAGS(func) (((PyCFunctionObject*)(func))->m_ml->ml_flags) +static CYTHON_INLINE PyObject* __Pyx_CyOrPyCFunction_GET_SELF(PyObject *func) { + return (__Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_STATIC) ? NULL : ((PyCFunctionObject*)func)->m_self; +} +#endif +static CYTHON_INLINE int __Pyx__IsSameCFunction(PyObject *func, void (*cfunc)(void)) { +#if CYTHON_COMPILING_IN_LIMITED_API + return PyCFunction_Check(func) && PyCFunction_GetFunction(func) == (PyCFunction) cfunc; +#else + return PyCFunction_Check(func) && PyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +#endif +} +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCFunction(func, cfunc) +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) ((void)m, PyType_FromSpecWithBases(s, b)) +#else + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) PyType_FromModuleAndSpec(m, s, b) +#endif +#if CYTHON_COMPILING_IN_PYPY + typedef PyObject *(*__Pyx_PyCMethod)(PyObject *, PyTypeObject *, PyObject *const *, size_t, PyObject *); +#else + #define __Pyx_PyCMethod PyCMethod +#endif +#ifndef METH_METHOD + #define METH_METHOD 0x200 +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) + #define PyObject_Malloc(s) PyMem_Malloc(s) + #define PyObject_Free(p) PyMem_Free(p) + #define PyObject_Realloc(p) PyMem_Realloc(p) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) +#elif CYTHON_COMPILING_IN_GRAAL && defined(GRAALPY_VERSION_NUM) && GRAALPY_VERSION_NUM > 0x19000000 + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) GraalPyFrame_SetLineNumber((frame), (lineno)) +#elif CYTHON_COMPILING_IN_GRAAL + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) _PyFrame_SetLineNumber((frame), (lineno)) +#else + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyThreadState_Current PyThreadState_Get() +#elif !CYTHON_FAST_THREAD_STATE + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#elif PY_VERSION_HEX >= 0x030d00A1 + #define __Pyx_PyThreadState_Current PyThreadState_GetUnchecked() +#else + #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() +#endif +#if CYTHON_OPAQUE_OBJECTS && CYTHON_COMPILING_IN_LIMITED_API + #define __PYX_SHARED_SIZEOF(T) -((int)sizeof(T)) + #define __PYX_SHARED_RELATIVE_OFFSET Py_RELATIVE_OFFSET + #define CYTHON_OPAQUE_SHARED_TYPES 1 +#else + #define __PYX_SHARED_SIZEOF(T) sizeof(T) + #define __PYX_SHARED_RELATIVE_OFFSET 0 + #define CYTHON_OPAQUE_SHARED_TYPES 0 +#endif +#if CYTHON_USE_MODULE_STATE +static CYTHON_INLINE void *__Pyx__PyModule_GetState(PyObject *op) +{ + void *result; + result = PyModule_GetState(op); + if (!result) + Py_FatalError("Couldn't find the module state"); + return result; +} +#define __Pyx_PyModule_GetState(o) (__pyx_mstatetype *)__Pyx__PyModule_GetState(o) +#else +#define __Pyx_PyModule_GetState(op) ((void)op,__pyx_mstate_global) +#endif +#define __Pyx_PyObject_GetSlot(obj, name, func_ctype) __Pyx_PyType_GetSlot(Py_TYPE((PyObject *) obj), name, func_ctype) +#define __Pyx_PyObject_TryGetSlot(obj, name, func_ctype) __Pyx_PyType_TryGetSlot(Py_TYPE(obj), name, func_ctype) +#define __Pyx_PyObject_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#define __Pyx_PyObject_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((type)->name) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype) __Pyx_PyType_GetSlot(type, name, func_ctype) + #define __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) (((type)->sub) ? ((type)->sub->name) : NULL) + #define __Pyx_PyType_TryGetSubSlot(type, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) +#else + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((func_ctype) PyType_GetSlot((type), Py_##name)) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype)\ + ((__PYX_LIMITED_VERSION_HEX >= 0x030A0000 ||\ + (PyType_GetFlags(type) & Py_TPFLAGS_HEAPTYPE) || __Pyx_get_runtime_version() >= 0x030A0000) ?\ + __Pyx_PyType_GetSlot(type, name, func_ctype) : NULL) + #define __Pyx_PyType_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSlot(obj, name, func_ctype) + #define __Pyx_PyType_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSlot(obj, name, func_ctype) +#endif +#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) +#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) +#else +#define __Pyx_PyDict_NewPresized(n) PyDict_New() +#endif +#define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) +#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_UNICODE_INTERNALS +#define __Pyx_PyDict_GetItemStrWithError(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStr(PyObject *dict, PyObject *name) { + PyObject *res = __Pyx_PyDict_GetItemStrWithError(dict, name); + if (res == NULL && PyErr_Occurred()) { + PyErr_WriteUnraisable(NULL); + } + return res; +} +#elif !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07020000 +#define __Pyx_PyDict_GetItemStrWithError PyDict_GetItemWithError +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#else +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStrWithError(PyObject *dict, PyObject *name) { +#if CYTHON_COMPILING_IN_PYPY + return PyDict_GetItem(dict, name); +#else + PyDictEntry *ep; + PyDictObject *mp = (PyDictObject*) dict; + long hash = ((PyStringObject *) name)->ob_shash; + assert(hash != -1); + ep = (mp->ma_lookup)(mp, name, hash); + if (ep == NULL) { + return NULL; + } + return ep->me_value; +#endif +} +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#endif +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetFlags(tp) (((PyTypeObject *)tp)->tp_flags) + #define __Pyx_PyType_HasFeature(type, feature) ((__Pyx_PyType_GetFlags(type) & (feature)) != 0) +#else + #define __Pyx_PyType_GetFlags(tp) (PyType_GetFlags((PyTypeObject *)tp)) + #define __Pyx_PyType_HasFeature(type, feature) PyType_HasFeature(type, feature) +#endif +#define __Pyx_PyObject_GetIterNextFunc(iterator) __Pyx_PyObject_GetSlot(iterator, tp_iternext, iternextfunc) +#if CYTHON_USE_TYPE_SPECS +#define __Pyx_PyHeapTypeObject_GC_Del(obj) {\ + PyTypeObject *type = Py_TYPE((PyObject*)obj);\ + assert(__Pyx_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE));\ + PyObject_GC_Del(obj);\ + Py_DECREF(type);\ +} +#else +#define __Pyx_PyHeapTypeObject_GC_Del(obj) PyObject_GC_Del(obj) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_ReadChar(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((void)u, 1114111U) + #define __Pyx_PyUnicode_KIND(u) ((void)u, (0)) + #define __Pyx_PyUnicode_KIND_04(u) __Pyx_PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) ((void*)u) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)k, PyUnicode_ReadChar((PyObject*)(d), i)) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GetLength(u)) +#else + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_READY(op) (0) + #else + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #endif + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) + #define __Pyx_PyUnicode_KIND(u) ((int)PyUnicode_KIND(u)) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, (Py_UCS4) ch) + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) + #else + #if CYTHON_COMPILING_IN_CPYTHON + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) + #else + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) + #endif + #endif + static CYTHON_INLINE int __Pyx_PyUnicode_KIND_04(PyObject *o) { + return __Pyx_PyUnicode_KIND(o) - (int) !!PyUnicode_IS_ASCII(o); + } +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#if CYTHON_COMPILING_IN_PYPY + #if !defined(PyUnicode_DecodeUnicodeEscape) + #define PyUnicode_DecodeUnicodeEscape(s, size, errors) PyUnicode_Decode(s, size, "unicode_escape", errors) + #endif + #if !defined(PyUnicode_Contains) + #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) + #endif + #if !defined(PyByteArray_Check) + #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) + #endif + #if !defined(PyObject_Format) + #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) + #endif +#endif +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && PyUnstable_Object_IsUniquelyReferenced(obj)) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#elif CYTHON_COMPILING_IN_CPYTHON + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && Py_REFCNT(obj) == 1) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#else + #define __Pyx_PySequence_ListKeepNew(obj) PySequence_List(obj) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) Py_IS_TYPE(obj, &PySet_Type) +#endif +enum __Pyx_ReferenceSharing { + __Pyx_ReferenceSharing_DefinitelyUnique, // We created it so we know it's unshared - no need to check + __Pyx_ReferenceSharing_OwnStrongReference, + __Pyx_ReferenceSharing_FunctionArgument, + __Pyx_ReferenceSharing_SharedReference, // Never trust it to be unshared because it's a global or similar +}; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && PY_VERSION_HEX >= 0x030E0000 +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing)\ + (sharing == __Pyx_ReferenceSharing_DefinitelyUnique ? 1 :\ + (sharing == __Pyx_ReferenceSharing_FunctionArgument ? PyUnstable_Object_IsUniqueReferencedTemporary(o) :\ + (sharing == __Pyx_ReferenceSharing_OwnStrongReference ? PyUnstable_Object_IsUniquelyReferenced(o) : 0))) +#elif (CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing) (((void)sharing), Py_REFCNT(o) == 1) +#else +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing) (((void)o), ((void)sharing), 0) +#endif +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #if CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GetItemRef(o, i) (likely((i) >= 0) ? PySequence_GetItem(o, i) : (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) + #else + #define __Pyx_PyList_GetItemRef(o, i) PySequence_ITEM(o, i) + #endif +#elif CYTHON_COMPILING_IN_LIMITED_API || !(CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE) + #define __Pyx_PyList_GetItemRef(o, i) __Pyx_XNewRef(PyList_GetItem(o, i)) +#else + #define __Pyx_PyList_GetItemRef(o, i) (likely(__Pyx_is_valid_index(i, PyList_GET_SIZE(o))) ?\ + __Pyx_NewRef(PyList_GET_ITEM(o, i)) : (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +#endif +#if CYTHON_AVOID_BORROWED_REFS || CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyList_GET_ITEM_REF(o, i, unsafe_shared) ((void)(unsafe_shared),\ + __Pyx_PyList_GetItemRef(o, i)) +#elif CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GET_ITEM_REF(o, i, unsafe_shared) (\ + __Pyx_IS_UNIQUELY_REFERENCED(o, unsafe_shared) ?\ + __Pyx_NewRef(PyList_GET_ITEM(o, i)) : __Pyx_PyList_GetItemRef(o, i)) + #else + #define __Pyx_PyList_GET_ITEM_REF(o, i, unsafe_shared) (\ + __Pyx_IS_UNIQUELY_REFERENCED(o, unsafe_shared) ?\ + __Pyx_XNewRef(PyList_GetItem(o, i)) : __Pyx_PyList_GetItemRef(o, i)) + #endif +#elif CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GET_ITEM_REF(o, i, unsafe_shared) ((void)(unsafe_shared),\ + __Pyx_NewRef(PyList_GET_ITEM(o, i))) +#else + #define __Pyx_PyList_GET_ITEM_REF(o, i, unsafe_shared) ((void)(unsafe_shared),\ + __Pyx_XNewRef(PyList_GetItem(o, i))) +#endif +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_PyDict_GetItemRef(dict, key, result) PyDict_GetItemRef(dict, key, result) +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyObject_GetItem(dict, key); + if (*result == NULL) { + if (PyErr_ExceptionMatches(PyExc_KeyError)) { + PyErr_Clear(); + return 0; + } + return -1; + } + return 1; +} +#else +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyDict_GetItemWithError(dict, key); + if (*result == NULL) { + return PyErr_Occurred() ? -1 : 0; + } + Py_INCREF(*result); + return 1; +} +#endif +#if defined(CYTHON_DEBUG_VISIT_CONST) && CYTHON_DEBUG_VISIT_CONST + #define __Pyx_VISIT_CONST(obj) Py_VISIT(obj) +#else + #define __Pyx_VISIT_CONST(obj) +#endif +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PySequence_ITEM(o, i) PySequence_ITEM(o, i) + #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) (PyTuple_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GET_ITEM(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) (PyList_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GET_ITEM(o, i) +#else + #define __Pyx_PySequence_ITEM(o, i) PySequence_GetItem(o, i) + #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) PyTuple_SetItem(o, i, v) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GetItem(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) PyList_SetItem(o, i, v) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GetItem(o, i) +#endif +#if CYTHON_ASSUME_SAFE_SIZE + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_GET_SIZE(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_GET_SIZE(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_GET_SIZE(o) + #define __Pyx_PyDict_GET_SIZE(o) PyDict_GET_SIZE(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_GET_SIZE(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_GET_SIZE(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GET_LENGTH(o) +#else + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_Size(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_Size(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_Size(o) + #define __Pyx_PyDict_GET_SIZE(o) PyDict_Size(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_Size(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_Size(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GetLength(o) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_InternFromString) + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) +#endif +#define __Pyx_PyLong_FromHash_t PyLong_FromSsize_t +#define __Pyx_PyLong_AsHash_t __Pyx_PyIndex_AsSsize_t +#if __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + #define __Pyx_PySendResult PySendResult +#else + typedef enum { + PYGEN_RETURN = 0, + PYGEN_ERROR = -1, + PYGEN_NEXT = 1, + } __Pyx_PySendResult; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030A00A3 + typedef __Pyx_PySendResult (*__Pyx_pyiter_sendfunc)(PyObject *iter, PyObject *value, PyObject **result); +#else + #define __Pyx_pyiter_sendfunc sendfunc +#endif +#if !CYTHON_USE_AM_SEND +#define __PYX_HAS_PY_AM_SEND 0 +#elif __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#define __PYX_HAS_PY_AM_SEND 1 +#else +#define __PYX_HAS_PY_AM_SEND 2 // our own backported implementation +#endif +#if __PYX_HAS_PY_AM_SEND < 2 + #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods +#else + typedef struct { + unaryfunc am_await; + unaryfunc am_aiter; + unaryfunc am_anext; + __Pyx_pyiter_sendfunc am_send; + } __Pyx_PyAsyncMethodsStruct; + #define __Pyx_SlotTpAsAsync(s) ((PyAsyncMethods*)(s)) +#endif +#if CYTHON_USE_AM_SEND && PY_VERSION_HEX < 0x030A00F0 + #define __Pyx_TPFLAGS_HAVE_AM_SEND (1UL << 21) +#else + #define __Pyx_TPFLAGS_HAVE_AM_SEND (0) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030A0000 +#ifdef __cplusplus +extern "C" +#endif +PyAPI_FUNC(void *) PyMem_Calloc(size_t nelem, size_t elsize); +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static int __Pyx_init_co_variable(PyObject *inspect, const char* name, int *write_to) { + int value; + PyObject *py_value = PyObject_GetAttrString(inspect, name); + if (!py_value) return 0; + value = (int) PyLong_AsLong(py_value); + Py_DECREF(py_value); + *write_to = value; + return value != -1 || !PyErr_Occurred(); +} +static int __Pyx_init_co_variables(void) { + PyObject *inspect; + int result; + inspect = PyImport_ImportModule("inspect"); + result = +#if !defined(CO_OPTIMIZED) + __Pyx_init_co_variable(inspect, "CO_OPTIMIZED", &CO_OPTIMIZED) && +#endif +#if !defined(CO_NEWLOCALS) + __Pyx_init_co_variable(inspect, "CO_NEWLOCALS", &CO_NEWLOCALS) && +#endif +#if !defined(CO_VARARGS) + __Pyx_init_co_variable(inspect, "CO_VARARGS", &CO_VARARGS) && +#endif +#if !defined(CO_VARKEYWORDS) + __Pyx_init_co_variable(inspect, "CO_VARKEYWORDS", &CO_VARKEYWORDS) && +#endif +#if !defined(CO_ASYNC_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_ASYNC_GENERATOR", &CO_ASYNC_GENERATOR) && +#endif +#if !defined(CO_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_GENERATOR", &CO_GENERATOR) && +#endif +#if !defined(CO_COROUTINE) + __Pyx_init_co_variable(inspect, "CO_COROUTINE", &CO_COROUTINE) && +#endif + 1; + Py_DECREF(inspect); + return result ? 0 : -1; +} +static int __Pyx_init_tpflags_bitcount(unsigned long flag) { + int count = 0; + while (flag) { + count += (int) (flag & 1); + flag >>= 1; + } + return count; +} +static int __Pyx_init_tpflags_variables(void) { + if (__Pyx_Runtime_TPFLAGS_SEQUENCE != 0 && __Pyx_Runtime_TPFLAGS_MAPPING != 0) { + return 0; + } + PyObject *collections_abc = PyImport_ImportModule("collections.abc"); + if (!collections_abc) return -1; + int result = 0; + PyObject *sequence = NULL, *mapping = NULL; +#if __PYX_LIMITED_VERSION_HEX >= 0x030D0000 + if (PyObject_GetOptionalAttrString(collections_abc, "Sequence", &sequence) != 1) goto fail; + if (PyObject_GetOptionalAttrString(collections_abc, "Mapping", &mapping) != 1) goto fail; +#else + sequence = PyObject_GetAttrString(collections_abc, "Sequence"); + if (!sequence) goto fail_attr_lookup; + mapping = PyObject_GetAttrString(collections_abc, "Mapping"); + if (!mapping) goto fail_attr_lookup; +#endif + if (!PyType_Check(sequence) || !PyType_Check(mapping)) goto fail; + { + unsigned long sequence_flags = PyType_GetFlags((PyTypeObject*)sequence); + unsigned long mapping_flags = PyType_GetFlags((PyTypeObject*)mapping); + unsigned long mutual_flags = sequence_flags & mapping_flags; + sequence_flags = sequence_flags ^ mutual_flags; + mapping_flags = mapping_flags ^ mutual_flags; + if (__Pyx_Runtime_TPFLAGS_SEQUENCE == 0 && __Pyx_init_tpflags_bitcount(sequence_flags) == 1) { + __Pyx_Runtime_TPFLAGS_SEQUENCE = sequence_flags; + } + if (__Pyx_Runtime_TPFLAGS_MAPPING == 0 && __Pyx_init_tpflags_bitcount(mapping_flags) == 1) { + __Pyx_Runtime_TPFLAGS_MAPPING = mapping_flags; + } + } + cleanup: + Py_XDECREF(mapping); + Py_XDECREF(sequence); + Py_DECREF(collections_abc); + return result; +#if __PYX_LIMITED_VERSION_HEX < 0x030D0000 + fail_attr_lookup: + if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + } +#endif + fail: + result = PyErr_Occurred() ? -1 : 0; + goto cleanup; +} +#else +static int __Pyx_init_co_variables(void) { + return 0; // It's a limited API-only feature +} +static int __Pyx_init_tpflags_variables(void) { + return 0; // It's a limited API-only feature +} +#endif + +/* MathInitCode */ +#if defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS) + #ifndef _USE_MATH_DEFINES + #define _USE_MATH_DEFINES + #endif +#endif +#include +#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) +#define __Pyx_truncl trunc +#else +#define __Pyx_truncl truncl +#endif + +#ifndef CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#define CYTHON_CLINE_IN_TRACEBACK_RUNTIME 0 +#endif +#ifndef CYTHON_CLINE_IN_TRACEBACK +#define CYTHON_CLINE_IN_TRACEBACK CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#endif +#if CYTHON_CLINE_IN_TRACEBACK +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; __pyx_clineno = __LINE__; (void) __pyx_clineno; } +#else +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; (void) __pyx_clineno; } +#endif +#define __PYX_ERR(f_index, lineno, Ln_error) \ + { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } + +#ifdef CYTHON_EXTERN_C + #undef __PYX_EXTERN_C + #define __PYX_EXTERN_C CYTHON_EXTERN_C +#elif defined(__PYX_EXTERN_C) + #ifdef _MSC_VER + #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.") + #else + #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead. + #endif +#else + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#define __PYX_HAVE__fontTools__qu2cu__qu2cu +#define __PYX_HAVE_API__fontTools__qu2cu__qu2cu +/* Early includes */ +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifdef CYTHON_FREETHREADING_COMPATIBLE +#if CYTHON_FREETHREADING_COMPATIBLE +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_NOT_USED +#else +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_USED +#endif +#else +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_USED +#endif +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_uchar_cast(c) ((unsigned char)c) +#define __Pyx_long_cast(x) ((long)x) +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ + (sizeof(type) < sizeof(Py_ssize_t)) ||\ + (sizeof(type) > sizeof(Py_ssize_t) &&\ + likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX) &&\ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ + v == (type)PY_SSIZE_T_MIN))) ||\ + (sizeof(type) == sizeof(Py_ssize_t) &&\ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { + return (size_t) i < (size_t) limit; +} +#if defined (__cplusplus) && __cplusplus >= 201103L + #include + #define __Pyx_sst_abs(value) std::abs(value) +#elif SIZEOF_INT >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) abs(value) +#elif SIZEOF_LONG >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) labs(value) +#elif defined (_MSC_VER) + #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define __Pyx_sst_abs(value) llabs(value) +#elif defined (__GNUC__) + #define __Pyx_sst_abs(value) __builtin_llabs(value) +#else + #define __Pyx_sst_abs(value) ((value<0) ? -value : value) +#endif +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s); +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char*); +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AS_STRING(s) +#else + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AsString(s) +#endif +#define __Pyx_PyObject_AsWritableString(s) ((char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableSString(s) ((signed char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +#define __Pyx_PyUnicode_FromOrdinal(o) PyUnicode_FromOrdinal((int)o) +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +static CYTHON_INLINE PyObject *__Pyx_NewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_NewRef) + return Py_NewRef(obj); +#else + Py_INCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_XNewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_XNewRef) + return Py_XNewRef(obj); +#else + Py_XINCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b); +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x); +#define __Pyx_PyObject_RichCompareBool(a,b,cmp) __Pyx_PyObject_IsTrueAndDecref(PyObject_RichCompare((a),(b),(cmp))) +#define __Pyx_PySequence_Tuple(obj)\ + (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t); +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); +#if CYTHON_ASSUME_SAFE_MACROS +#define __Pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AS_DOUBLE(x) +#define __Pyx_PyFloat_IsNonZero(x) (PyFloat_AS_DOUBLE(x) != 0.0) +#else +#define __Pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AsDouble(x) +#define __Pyx_PyFloat_IsNonZero(x) PyObject_IsTrue(x) +#endif +#define __Pyx_PyFloat_AsFloat(x) ((float) __Pyx_PyFloat_AsDouble(x)) +#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) +#if CYTHON_USE_PYLONG_INTERNALS + #if PY_VERSION_HEX >= 0x030C00A7 + #ifndef _PyLong_SIGN_MASK + #define _PyLong_SIGN_MASK 3 + #endif + #ifndef _PyLong_NON_SIZE_BITS + #define _PyLong_NON_SIZE_BITS 3 + #endif + #define __Pyx_PyLong_SignBits(x) ((int) (((PyLongObject*)x)->long_value.lv_tag & _PyLong_SIGN_MASK)) + #define __Pyx_PyLong_Sign(x) (1 - __Pyx_PyLong_SignBits(x)) + #define __Pyx_PyLong_IsNeg(x) ((__Pyx_PyLong_SignBits(x) & 2) != 0) + #define __Pyx_PyLong_IsNonNeg(x) (!__Pyx_PyLong_IsNeg(x)) + #define __Pyx_PyLong_IsZero(x) (__Pyx_PyLong_SignBits(x) & 1) + #define __Pyx_PyLong_IsPos(x) (__Pyx_PyLong_SignBits(x) == 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) (__Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) ((Py_ssize_t) (((PyLongObject*)x)->long_value.lv_tag >> _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_SignedDigitCount(x)\ + (((Py_ssize_t) __Pyx_PyLong_Sign(x)) * __Pyx_PyLong_DigitCount(x)) + #if defined(PyUnstable_Long_IsCompact) && defined(PyUnstable_Long_CompactValue) + #define __Pyx_PyLong_IsCompact(x) PyUnstable_Long_IsCompact((PyLongObject*) x) + #define __Pyx_PyLong_CompactValue(x) PyUnstable_Long_CompactValue((PyLongObject*) x) + #else + #define __Pyx_PyLong_IsCompact(x) (((PyLongObject*)x)->long_value.lv_tag < (2 << _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_CompactValue(x) (((Py_ssize_t) __Pyx_PyLong_Sign(x)) * (Py_ssize_t) __Pyx_PyLong_Digits(x)[0]) + #endif + static CYTHON_INLINE Py_ssize_t __Pyx_PyLong_CompareSignAndSize(PyObject *a, PyObject *b) { + uintptr_t tag_a = ((PyLongObject*)a)->long_value.lv_tag; + uintptr_t tag_b = ((PyLongObject*)b)->long_value.lv_tag; + if (tag_a == tag_b) return 0; + int sign_a = (int) (tag_a & _PyLong_SIGN_MASK); + int sign_b = (int) (tag_b & _PyLong_SIGN_MASK); + if (sign_a > sign_b) return -1; + if (sign_a < sign_b) return 1; + Py_ssize_t size_a = (Py_ssize_t) (tag_a >> _PyLong_NON_SIZE_BITS); + Py_ssize_t size_b = (Py_ssize_t) (tag_b >> _PyLong_NON_SIZE_BITS); + return (1 - sign_a) * (size_a - size_b); + } + typedef Py_ssize_t __Pyx_compact_pylong; + typedef size_t __Pyx_compact_upylong; + #else + #define __Pyx_PyLong_Sign(x) ((int) ((Py_SIZE(x) == 0) ? 0 : (Py_SIZE(x) < 0) ? -1 : 1)) + #define __Pyx_PyLong_IsNeg(x) (Py_SIZE(x) < 0) + #define __Pyx_PyLong_IsNonNeg(x) (Py_SIZE(x) >= 0) + #define __Pyx_PyLong_IsZero(x) (Py_SIZE(x) == 0) + #define __Pyx_PyLong_IsPos(x) (Py_SIZE(x) > 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) ((Py_SIZE(x) == 0) ? 0 : __Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) __Pyx_sst_abs(Py_SIZE(x)) + #define __Pyx_PyLong_SignedDigitCount(x) Py_SIZE(x) + #define __Pyx_PyLong_IsCompact(x) (Py_SIZE(x) == 0 || Py_SIZE(x) == 1 || Py_SIZE(x) == -1) + #define __Pyx_PyLong_CompactValue(x)\ + ((Py_SIZE(x) == 0) ? (sdigit) 0 : ((Py_SIZE(x) < 0) ? -(sdigit)__Pyx_PyLong_Digits(x)[0] : (sdigit)__Pyx_PyLong_Digits(x)[0])) + #define __Pyx_PyLong_CompareSignAndSize(a, b) (Py_SIZE(a) - Py_SIZE(b)) + typedef sdigit __Pyx_compact_pylong; + typedef digit __Pyx_compact_upylong; + #endif + #if PY_VERSION_HEX >= 0x030C00A5 + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->long_value.ob_digit) + #else + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->ob_digit) + #endif + #define __Pyx_PyLong_IsNonZero(x) (!__Pyx_PyLong_IsZero(x)) +#else + #define __Pyx_PyLong_IsNonZero(x) PyObject_IsTrue(x) +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#elif __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeASCII(c_str, size, NULL) +#else + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ +/* PretendToInitialize */ +#ifdef __cplusplus +#if __cplusplus > 201103L +#include +#endif +template +static void __Pyx_pretend_to_initialize(T* ptr) { +#if __cplusplus > 201103L + if ((std::is_trivially_default_constructible::value)) +#endif + *ptr = T(); + (void)ptr; +} +#else +static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } +#endif + + +#if !CYTHON_USE_MODULE_STATE +static PyObject *__pyx_m = NULL; +#endif +static const char * const __pyx_cfilenm = __FILE__; + +/* Header.proto */ +#if !defined(CYTHON_CCOMPLEX) + #if defined(__cplusplus) + #define CYTHON_CCOMPLEX 1 + #elif (defined(_Complex_I) && !defined(_MSC_VER)) || ((defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) && !defined(__STDC_NO_COMPLEX__) && !defined(_MSC_VER)) + #define CYTHON_CCOMPLEX 1 + #else + #define CYTHON_CCOMPLEX 0 + #endif +#endif +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #include + #else + #include + #endif +#endif +#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) + #undef _Complex_I + #define _Complex_I 1.0fj +#endif + +/* #### Code section: filename_table ### */ + +static const char* const __pyx_f[] = { + "Lib/fontTools/qu2cu/qu2cu.py", +}; +/* #### Code section: utility_code_proto_before_types ### */ +/* Atomics.proto (used by UnpackUnboundCMethod) */ +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __PYX_CYTHON_ATOMICS_ENABLED() CYTHON_ATOMICS +#define __PYX_GET_CYTHON_COMPILING_IN_CPYTHON_FREETHREADING() CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __pyx_atomic_int_type int +#define __pyx_nonatomic_int_type int +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__)) + #include +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ + (defined(_MSC_VER) && _MSC_VER >= 1700))) + #include +#endif +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type atomic_int + #define __pyx_atomic_ptr_type atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) atomic_fetch_add_explicit(value, 1, memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) atomic_fetch_add_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) atomic_fetch_sub_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) atomic_load(value) + #define __pyx_atomic_store(value, new_value) atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) atomic_load_explicit(value, memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) atomic_load_explicit(value, memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #define __pyx_atomic_pointer_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ +\ + (defined(_MSC_VER) && _MSC_VER >= 1700)) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type std::atomic_int + #define __pyx_atomic_ptr_type std::atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) std::atomic_fetch_sub_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) std::atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) std::atomic_load(value) + #define __pyx_atomic_store(value, new_value) std::atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) std::atomic_load_explicit(value, std::memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) std::atomic_load_explicit(value, std::memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) std::atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #define __pyx_atomic_pointer_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C++ atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C++ atomics" + #endif +#elif CYTHON_ATOMICS && (__GNUC__ >= 5 || (__GNUC__ == 4 &&\ + (__GNUC_MINOR__ > 1 ||\ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL__ >= 2)))) + #define __pyx_atomic_ptr_type void* + #define __pyx_nonatomic_ptr_type void* + #define __pyx_atomic_incr_relaxed(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_incr_acq_rel(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_acq_rel(value) __sync_fetch_and_sub(value, 1) + #define __pyx_atomic_sub(value, arg) __sync_fetch_and_sub(value, arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_store(value, new_value) __sync_lock_test_and_set(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_load_acquire(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) __sync_lock_test_and_set(value, (__pyx_atomic_ptr_type)new_value) + static CYTHON_INLINE int __pyx_atomic_pointer_cmp_exchange(__pyx_atomic_ptr_type* value, __pyx_nonatomic_ptr_type* expected, __pyx_nonatomic_ptr_type desired) { + __pyx_nonatomic_ptr_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && defined(_MSC_VER) + #include + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type long + #define __pyx_atomic_ptr_type void* + #undef __pyx_nonatomic_int_type + #define __pyx_nonatomic_int_type long + #define __pyx_nonatomic_ptr_type void* + #pragma intrinsic (_InterlockedExchangeAdd, _InterlockedExchange, _InterlockedCompareExchange, _InterlockedCompareExchangePointer, _InterlockedExchangePointer) + #define __pyx_atomic_incr_relaxed(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_incr_acq_rel(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_decr_acq_rel(value) _InterlockedExchangeAdd(value, -1) + #define __pyx_atomic_sub(value, arg) _InterlockedExchangeAdd(value, -arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = _InterlockedCompareExchange(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) _InterlockedExchangeAdd(value, 0) + #define __pyx_atomic_store(value, new_value) _InterlockedExchange(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) *(void * volatile *)value + #define __pyx_atomic_pointer_load_acquire(value) _InterlockedCompareExchangePointer(value, 0, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) _InterlockedExchangePointer(value, (__pyx_atomic_ptr_type)new_value) + static CYTHON_INLINE int __pyx_atomic_pointer_cmp_exchange(__pyx_atomic_ptr_type* value, __pyx_nonatomic_ptr_type* expected, __pyx_nonatomic_ptr_type desired) { + __pyx_atomic_ptr_type old = _InterlockedCompareExchangePointer(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #ifdef __PYX_DEBUG_ATOMICS + #pragma message ("Using MSVC atomics") + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif + +/* CriticalSectionsDefinition.proto (used by CriticalSections) */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection void* +#define __Pyx_PyCriticalSection2 void* +#define __Pyx_PyCriticalSection_End(cs) +#define __Pyx_PyCriticalSection2_End(cs) +#else +#define __Pyx_PyCriticalSection PyCriticalSection +#define __Pyx_PyCriticalSection2 PyCriticalSection2 +#define __Pyx_PyCriticalSection_End PyCriticalSection_End +#define __Pyx_PyCriticalSection2_End PyCriticalSection2_End +#endif + +/* CriticalSections.proto (used by ParseKeywordsImpl) */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection_Begin(cs, arg) (void)(cs) +#define __Pyx_PyCriticalSection2_Begin(cs, arg1, arg2) (void)(cs) +#else +#define __Pyx_PyCriticalSection_Begin PyCriticalSection_Begin +#define __Pyx_PyCriticalSection2_Begin PyCriticalSection2_Begin +#endif +#if PY_VERSION_HEX < 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_BEGIN_CRITICAL_SECTION(o) { +#define __Pyx_END_CRITICAL_SECTION() } +#else +#define __Pyx_BEGIN_CRITICAL_SECTION Py_BEGIN_CRITICAL_SECTION +#define __Pyx_END_CRITICAL_SECTION Py_END_CRITICAL_SECTION +#endif + +/* IncludeStructmemberH.proto (used by CythonFunctionShared) */ +#include + +/* #### Code section: numeric_typedefs ### */ +/* #### Code section: complex_type_declarations ### */ +/* Declarations.proto */ +#if CYTHON_CCOMPLEX && (1) && (!0 || __cplusplus) + #ifdef __cplusplus + typedef ::std::complex< double > __pyx_t_double_complex; + #else + typedef double _Complex __pyx_t_double_complex; + #endif +#else + typedef struct { double real, imag; } __pyx_t_double_complex; +#endif +static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); + +/* #### Code section: type_declarations ### */ + +/*--- Type declarations ---*/ +struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr; +struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr; + +/* "fontTools/qu2cu/qu2cu.py":263 + * + * if not is_complex: + * curves = [tuple((c.real, c.imag) for c in curve) for curve in curves] # <<<<<<<<<<<<<< + * return curves + * +*/ +struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr { + PyObject_HEAD + PyObject *__pyx_genexpr_arg_0; + PyObject *__pyx_v_c; + int __pyx_v_cost; + int __pyx_v_is_complex; + PyObject *__pyx_t_0; + Py_ssize_t __pyx_t_1; + PyObject *(*__pyx_t_2)(PyObject *); +}; + + +/* "fontTools/qu2cu/qu2cu.py":368 + * for k, reconst in enumerate(reconstructed): + * orig = elevated_quadratics[j + k] + * p0, p1, p2, p3 = tuple(v - u for v, u in zip(reconst, orig)) # <<<<<<<<<<<<<< + * + * if not cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance): +*/ +struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr { + PyObject_HEAD + PyObject *__pyx_genexpr_arg_0; + int __pyx_v_all_cubic; + int __pyx_v_count; + double __pyx_v_err; + double __pyx_v_error; + int __pyx_v_i; + int __pyx_v_i_sol_count; + double __pyx_v_i_sol_error; + int __pyx_v_is_cubic; + int __pyx_v_j; + int __pyx_v_j_sol_count; + double __pyx_v_j_sol_error; + int __pyx_v_k; + __pyx_t_double_complex __pyx_v_p0; + __pyx_t_double_complex __pyx_v_p1; + __pyx_t_double_complex __pyx_v_p2; + __pyx_t_double_complex __pyx_v_p3; + int __pyx_v_start; + int __pyx_v_this_sol_count; + double __pyx_v_tolerance; + __pyx_t_double_complex __pyx_v_u; + __pyx_t_double_complex __pyx_v_v; + PyObject *__pyx_t_0; + Py_ssize_t __pyx_t_1; + PyObject *(*__pyx_t_2)(PyObject *); +}; + +/* #### Code section: utility_code_proto ### */ + +/* --- Runtime support code (head) --- */ +/* Refnanny.proto */ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, Py_ssize_t); + void (*DECREF)(void*, PyObject*, Py_ssize_t); + void (*GOTREF)(void*, PyObject*, Py_ssize_t); + void (*GIVEREF)(void*, PyObject*, Py_ssize_t); + void* (*SetupContext)(const char*, Py_ssize_t, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + if (acquire_gil) {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + PyGILState_Release(__pyx_gilstate_save);\ + } else {\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContext()\ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_XINCREF(r) do { if((r) == NULL); else {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) == NULL); else {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) == NULL); else {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) == NULL); else {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContextNogil() + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif +#define __Pyx_Py_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; Py_XDECREF(tmp);\ + } while (0) +#define __Pyx_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_XDECREF(tmp);\ + } while (0) +#define __Pyx_DECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_DECREF(tmp);\ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +/* FastTypeChecks.proto (used by GivenExceptionMatches) */ +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) __Pyx_IsAnySubtype2(Py_TYPE(obj), (PyTypeObject *)type1, (PyTypeObject *)type2) +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b); +#define __Pyx_PyAnySet_Check(obj) __Pyx_TypeCheck2(obj, &PySet_Type, &PyFrozenSet_Type) +#else +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) (PyObject_TypeCheck(obj, (PyTypeObject *)type1) || PyObject_TypeCheck(obj, (PyTypeObject *)type2)) +#define __Pyx_PyAnySet_Check(obj) PyAnySet_Check(obj) +#endif + +/* PyThreadStateGet.proto (used by PyErrFetchRestore) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; +#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; +#if PY_VERSION_HEX >= 0x030C00A6 +#define __Pyx_PyErr_Occurred() (__pyx_tstate->current_exception != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->current_exception ? (PyObject*) Py_TYPE(__pyx_tstate->current_exception) : (PyObject*) NULL) +#else +#define __Pyx_PyErr_Occurred() (__pyx_tstate->curexc_type != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->curexc_type) +#endif +#else +#define __Pyx_PyThreadState_declare +#define __Pyx_PyThreadState_assign +#define __Pyx_PyErr_Occurred() (PyErr_Occurred() != NULL) +#define __Pyx_PyErr_CurrentExceptionType() PyErr_Occurred() +#endif + +/* PyErrFetchRestore.proto (used by GivenExceptionMatches) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) +#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A6 +#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) +#else +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#endif +#else +#define __Pyx_PyErr_Clear() PyErr_Clear() +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) +#endif + +/* GivenExceptionMatches.proto (used by PyErrExceptionMatches) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); +#else +#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2) { + return PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2); +} +#endif +#define __Pyx_PyErr_ExceptionMatches2(err1, err2) __Pyx_PyErr_GivenExceptionMatches2(__Pyx_PyErr_CurrentExceptionType(), err1, err2) + +/* PyErrExceptionMatches.proto (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) +static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); +#else +#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) +#endif + +/* PyObjectGetAttrStr.proto (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +/* PyObjectGetAttrStrNoError.proto (used by GetBuiltinName) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); + +/* GetBuiltinName.proto */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); + +/* CopyObjectArray.proto (used by TupleOrListFromArrayImpl) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_copy_object_array(PyObject *const *CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length); +#endif + +/* TupleOrListFromArrayImpl.proto (used by TupleFromArray) */ +#if PY_VERSION_HEX >= 0x030F0000 && !CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_PyTuple_FromArray(src, n) PyTuple_FromArray(src, ((n)<0) ? 0 : (n)) +#else +CYTHON_UNUSED static PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n); +#endif + +/* TupleFromArray.proto (used by fastcall) */ + + +/* IncludeStringH.proto (used by PyObjectCompare) */ +#include + +/* PyObjectCompare.proto (used by UnicodeEquals) */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolEq_str_str(PyObject *op1, PyObject *op2, int pyop); + +/* UnicodeEquals.proto (used by fastcall) */ +#define __Pyx_PyUnicode_Equals(s1, s2) __Pyx_PyObject_CompareBoolEq_str_str(s1, s2, Py_EQ) + +/* fastcall.proto */ +#if CYTHON_AVOID_BORROWED_REFS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_PySequence_ITEM(args, i) +#elif CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_NewRef(__Pyx_PyTuple_GET_ITEM(args, i)) +#else + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_XNewRef(PyTuple_GetItem(args, i)) +#endif +#define __Pyx_NumKwargs_VARARGS(kwds) PyDict_Size(kwds) +#define __Pyx_KwValues_VARARGS(args, nargs) NULL +#define __Pyx_GetKwValue_VARARGS(kw, kwvalues, s) __Pyx_PyDict_GetItemStrWithError(kw, s) +#define __Pyx_KwargsAsDict_VARARGS(kw, kwvalues) PyDict_Copy(kw) +#if CYTHON_VECTORCALL + #define __Pyx_ArgRef_FASTCALL(args, i) __Pyx_NewRef(args[i]) + #define __Pyx_NumKwargs_FASTCALL(kwds) __Pyx_PyTuple_GET_SIZE(kwds) + #define __Pyx_KwValues_FASTCALL(args, nargs) ((args) + (nargs)) + static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL + CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues); + #else + #define __Pyx_KwargsAsDict_FASTCALL(kw, kwvalues) _PyStack_AsDict(kwvalues, kw) + #endif +#else + #define __Pyx_ArgRef_FASTCALL __Pyx_ArgRef_VARARGS + #define __Pyx_NumKwargs_FASTCALL __Pyx_NumKwargs_VARARGS + #define __Pyx_KwValues_FASTCALL __Pyx_KwValues_VARARGS + #define __Pyx_GetKwValue_FASTCALL __Pyx_GetKwValue_VARARGS + #define __Pyx_KwargsAsDict_FASTCALL __Pyx_KwargsAsDict_VARARGS +#endif +#if CYTHON_VECTORCALL_TPNEW + #if !CYTHON_VECTORCALL + #error Enabling CYTHON_VECTORCALL_TPNEW without CYTHON_VECTORCALL is not supported + #endif + #define __Pyx_ArgRef_FASTCALL_TPNEW __Pyx_ArgRef_FASTCALL + #define __Pyx_NumKwargs_FASTCALL_TPNEW __Pyx_NumKwargs_FASTCALL + #define __Pyx_KwValues_FASTCALL_TPNEW __Pyx_KwValues_FASTCALL + #define __Pyx_GetKwValue_FASTCALL_TPNEW __Pyx_GetKwValue_FASTCALL + #define __Pyx_KwargsAsDict_FASTCALL_TPNEW __Pyx_KwargsAsDict_FASTCALL +#else + #define __Pyx_ArgRef_FASTCALL_TPNEW __Pyx_ArgRef_VARARGS + #define __Pyx_NumKwargs_FASTCALL_TPNEW __Pyx_NumKwargs_VARARGS + #define __Pyx_KwValues_FASTCALL_TPNEW __Pyx_KwValues_VARARGS + #define __Pyx_GetKwValue_FASTCALL_TPNEW __Pyx_GetKwValue_VARARGS + #define __Pyx_KwargsAsDict_FASTCALL_TPNEW __Pyx_KwargsAsDict_VARARGS +#endif +#define __Pyx_ArgsSlice_VARARGS(args, start, stop) PyTuple_GetSlice(args, start, stop) +#if CYTHON_VECTORCALL +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) __Pyx_PyTuple_FromArray(args + start, stop - start) +#else +#define __Pyx_ArgsSlice_FASTCALL __Pyx_ArgsSlice_VARARGS +#endif + +/* py_dict_items.proto (used by OwnedDictNext) */ +#define __Pyx_PyDict_items_TypePtr (&PyDictKeys_Type) +#define __Pyx_PyDict_items_Check(obj) PyObject_TypeCheck((obj), __Pyx_PyDictItems_TypePtr) +#define __Pyx_PyDict_items_CheckExact(obj) Py_IS_TYPE((obj), __Pyx_PyDictItems_TypePtr) +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d); + +/* CallCFunction.proto (used by CallUnboundCMethod0) */ +#define __Pyx_CallCFunction(cfunc, self, args)\ + ((PyCFunction)(void(*)(void))(cfunc)->func)(self, args) +#define __Pyx_CallCFunctionWithKeywords(cfunc, self, args, kwargs)\ + ((PyCFunctionWithKeywords)(void(*)(void))(cfunc)->func)(self, args, kwargs) +#define __Pyx_CallCFunctionFast(cfunc, self, args, nargs)\ + ((__Pyx_PyCFunctionFast)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs) +#define __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, nargs, kwnames)\ + ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs, kwnames) + +/* PyObjectCall.proto (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +/* PyObjectCallMethO.proto (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +/* PyObjectFastCall.proto (used by PyObjectCallOneArg) */ +#define __Pyx_PyObject_FastCall(func, args, nargs) __Pyx_PyObject_FastCallDict(func, args, (size_t)(nargs), NULL) +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject * const*args, size_t nargsf, PyObject *kwargs); + +/* PyObjectCallOneArg.proto (used by CallUnboundCMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +/* UnpackUnboundCMethod_decl.proto (used by UnpackUnboundCMethod) */ +typedef struct { + PyObject *type; + PyObject **method_name; + PyCFunction func; + PyObject *method; + int flag; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && CYTHON_ATOMICS + __pyx_atomic_int_type initialized; +#endif +} __Pyx_CachedCFunction; + +/* IgnoreException.proto (used by UnpackUnboundCMethod_impl) */ +static CYTHON_INLINE int __Pyx_IgnoreGivenException(PyObject *given_exception, PyObject *ignorable_exception); +#define __Pyx_IgnoreException(ignorable_exception) __Pyx_IgnoreGivenException(NULL, ignorable_exception) + +/* UnpackUnboundCMethod_impl.export */ +static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target); + +/* UnpackUnboundCMethod.proto (used by CallUnboundCMethod0) */ +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +static CYTHON_INLINE int __Pyx_CachedCFunction_GetAndSetInitializing(__Pyx_CachedCFunction *cfunc) { +#if !CYTHON_ATOMICS + return 1; +#else + __pyx_nonatomic_int_type expected = 0; + if (__pyx_atomic_int_cmp_exchange(&cfunc->initialized, &expected, 1)) { + return 0; + } + return expected; +#endif +} +static CYTHON_INLINE void __Pyx_CachedCFunction_SetFinishedInitializing(__Pyx_CachedCFunction *cfunc) { +#if CYTHON_ATOMICS + __pyx_atomic_store(&cfunc->initialized, 2); +#endif +} +#else +#define __Pyx_CachedCFunction_GetAndSetInitializing(cfunc) 2 +#define __Pyx_CachedCFunction_SetFinishedInitializing(cfunc) +#endif + +/* CallUnboundCMethod0.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#else +#define __Pyx_CallUnboundCMethod0(cfunc, self) __Pyx__CallUnboundCMethod0(cfunc, self) +#endif + +/* py_dict_values.proto (used by OwnedDictNext) */ +#define __Pyx_PyDict_values_TypePtr (&PyDictKeys_Type) +#define __Pyx_PyDict_values_Check(obj) PyObject_TypeCheck((obj), __Pyx_PyDictValues_TypePtr) +#define __Pyx_PyDict_values_CheckExact(obj) Py_IS_TYPE((obj), __Pyx_PyDictValues_TypePtr) +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d); + +/* OwnedDictNext.proto (used by ParseKeywordsImpl) */ +#if CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, PyObject **ppos, PyObject **pkey, PyObject **pvalue); +#else +CYTHON_INLINE +static int __Pyx_PyDict_NextRef(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue); +#endif + +/* RaiseDoubleKeywords.proto (used by ParseKeywordsImpl) */ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); + +/* ParseKeywordsImpl.export */ +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name +); +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* CallUnboundCMethod2.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2); +#else +#define __Pyx_CallUnboundCMethod2(cfunc, self, arg1, arg2) __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2) +#endif + +/* ParseKeywords.proto */ +static CYTHON_INLINE int __Pyx_ParseKeywords( + PyObject *kwds, PyObject *const *kwvalues, PyObject ** const argnames[], + PyObject *kwds2, PyObject *values[], + Py_ssize_t num_pos_args, Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* RaiseArgTupleInvalid.export */ +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); + +/* PyFrozenDict.proto (used by GetItemInt) */ +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_PyFrozenDict_TypePtr ((PyTypeObject*) __pyx_mstate_global->__Pyx_PyFrozenDictType) +#define __Pyx_PyFrozenDict_New(it) __Pyx__PyFrozenDict_New(__pyx_mstate_global->__Pyx_PyFrozenDictType, it) +static CYTHON_INLINE PyObject* __Pyx__PyFrozenDict_New(PyObject* frozendict_type, PyObject* it); +#define __Pyx_PyFrozenDict_NewEmpty() __Pyx_PyFrozenDict_New(NULL) +#define __Pyx_PyFrozenDict_Check(obj) PyObject_TypeCheck((obj), __Pyx_PyFrozenDict_TypePtr) +#define __Pyx_PyFrozenDict_CheckExact(obj) Py_IS_TYPE((obj), __Pyx_PyFrozenDict_TypePtr) +#define __Pyx_PyAnyDict_Check(obj) __Pyx__PyAnyDict_Check(obj, __Pyx_PyFrozenDict_TypePtr) +static CYTHON_INLINE int __Pyx__PyAnyDict_Check(PyObject *obj, PyTypeObject* frozendict_type) { + return PyObject_TypeCheck(obj, &PyDict_Type) || PyObject_TypeCheck(obj, frozendict_type); +} +#define __Pyx_PyAnyDict_CheckExact(obj) __Pyx__PyAnyDict_CheckExact(obj, __Pyx_PyFrozenDict_TypePtr) +static CYTHON_INLINE int __Pyx__PyAnyDict_CheckExact(PyObject *obj, PyTypeObject* frozendict_type) { + return Py_IS_TYPE(obj, &PyDict_Type) || Py_IS_TYPE(obj, frozendict_type); +} +#elif PY_VERSION_HEX >= 0x030f00a6 ||\ + (defined(PyFrozenDict_Check) && defined(PyAnyDict_Check) && defined(PyFrozenDict_New)) +#define __Pyx_PyFrozenDict_TypePtr (&PyFrozenDict_Type) +#define __Pyx_PyFrozenDict_New(it) PyFrozenDict_New(it) +#define __Pyx_PyFrozenDict_NewEmpty() PyFrozenDict_New(NULL) +#define __Pyx_PyFrozenDict_Check(obj) PyFrozenDict_Check(obj) +#define __Pyx_PyFrozenDict_CheckExact(obj) PyFrozenDict_CheckExact(obj) +#define __Pyx_PyAnyDict_Check(obj) PyAnyDict_Check(obj) +#define __Pyx_PyAnyDict_CheckExact(obj) PyAnyDict_CheckExact(obj) +#else +#define __Pyx_PyFrozenDict_TypePtr (&PyDict_Type) +static CYTHON_INLINE PyObject* __Pyx_PyFrozenDict_New(PyObject* it) { + if (!it) { + return PyDict_New(); + } else if (PyDict_Check(it)) { + return PyDict_Copy(it); + } else { + PyObject *dict = PyDict_New(); + if (!dict) return NULL; + PyObject *result = PyNumber_InPlaceOr(dict, it); + Py_DECREF(dict); + return result; + } +} +#define __Pyx_PyFrozenDict_NewEmpty() PyDict_New() +#define __Pyx_PyFrozenDict_Check(obj) PyDict_Check(obj) +#define __Pyx_PyFrozenDict_CheckExact(obj) PyDict_CheckExact(obj) +#define __Pyx_PyAnyDict_Check(obj) PyDict_Check(obj) +#define __Pyx_PyAnyDict_CheckExact(obj) PyDict_CheckExact(obj) +#endif + +/* GetItemInt.proto */ +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); + +/* AssertionsEnabled.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX >= 0x030C0000 + static int __pyx_assertions_enabled_flag; + #define __pyx_assertions_enabled() (__pyx_assertions_enabled_flag) + #if __clang__ || __GNUC__ + __attribute__((no_sanitize("thread"))) + #endif + static int __Pyx_init_assertions_enabled(void) { + PyObject *builtins, *debug, *debug_str; + int flag; + builtins = PyEval_GetBuiltins(); + if (!builtins) goto bad; + debug_str = PyUnicode_FromStringAndSize("__debug__", 9); + if (!debug_str) goto bad; + debug = PyObject_GetItem(builtins, debug_str); + Py_DECREF(debug_str); + if (!debug) goto bad; + flag = PyObject_IsTrue(debug); + Py_DECREF(debug); + if (flag == -1) goto bad; + __pyx_assertions_enabled_flag = flag; + return 0; + bad: + __pyx_assertions_enabled_flag = 1; + return -1; + } +#else + #define __Pyx_init_assertions_enabled() (0) + #define __pyx_assertions_enabled() (!Py_OptimizeFlag) +#endif + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolEq_object_object(PyObject *op1, PyObject *op2, int pyop); + +/* PyAssertionError_Check.proto */ +#define __Pyx_PyExc_AssertionError_Check(obj) __Pyx_TypeCheck(obj, PyExc_AssertionError) + +/* RaiseException.export */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); + +/* py_abs.proto */ +#if CYTHON_USE_PYLONG_INTERNALS +static PyObject *__Pyx_PyLong_AbsNeg(PyObject *num); +#define __Pyx_PyNumber_Absolute(x)\ + ((likely(PyLong_CheckExact(x))) ?\ + (likely(__Pyx_PyLong_IsNonNeg(x)) ? __Pyx_NewRef(x) : __Pyx_PyLong_AbsNeg(x)) :\ + PyNumber_Absolute(x)) +#else +#define __Pyx_PyNumber_Absolute(x) PyNumber_Absolute(x) +#endif + +/* FormatTypeName.proto (used by RaiseErrorWithObjectTypes) */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +typedef PyObject *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%N" +#define __Pyx_PyType_GetFullyQualifiedName(tp) Py_NewRef((PyObject*)tp) +#define __Pyx_DECREF_TypeName(obj) Py_DECREF(obj) +#elif CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%U" +#define __Pyx_DECREF_TypeName(obj) Py_XDECREF(obj) +static __Pyx_TypeName __Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp); +#else // !LIMITED_API +typedef const char *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%.200s" +#define __Pyx_PyType_GetFullyQualifiedName(tp) ((tp)->tp_name) +#define __Pyx_DECREF_TypeName(obj) +#endif + +/* RaiseErrorWithObjectTypes.proto (used by PyNumberBinop) */ +#define __Pyx_RaiseErrorWithObjectTypes1(exc_type, message, arg, obj1, obj2) __Pyx_RaiseErrorWithTypes1(exc_type, message, arg, Py_TYPE(obj1), Py_TYPE(obj2)) +#define __Pyx_RaiseTypeErrorWithObjectTypes(message, obj1, obj2) __Pyx_RaiseTypeErrorWithTypes(message, Py_TYPE(obj1), Py_TYPE(obj2)) +#define __Pyx_RaiseTypeErrorWithTypes(message, type_obj1, type_obj2) __Pyx_RaiseErrorWithTypes1(PyExc_TypeError, "%.1s" message, "", type_obj1, type_obj2) +CYTHON_UNUSED +static void __Pyx_RaiseErrorWithTypes1(PyObject* exc_type, const char *message, const char *arg, PyTypeObject *type_obj1, PyTypeObject *type_obj2); + +/* PyNumberBinop.proto */ +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_PyNumber_Subtract_object_object(op1, op2) PyNumber_Subtract(op1, op2) +#define __Pyx_PyNumber_InPlaceSubtract_object_object(op1, op2) PyNumber_InPlaceSubtract(op1, op2) +#else +#define __Pyx_PyNumber_Subtract_object_object(op1, op2) __Pyx__PyNumber_Subtract_object_object(op1, op2, 0) +#define __Pyx_PyNumber_InPlaceSubtract_object_object(op1, op2) __Pyx__PyNumber_Subtract_object_object(op1, op2, 1) +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Subtract_object_object(PyObject *op1, PyObject *op2, int inplace); +#endif + +/* ListAppend.proto */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x); +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif + +/* TupleOrListFromArrayImpl.proto (used by ListFromArray) */ +CYTHON_UNUSED static PyObject * +__Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n); + +/* ListFromArray.proto (used by SliceTupleAndList) */ + + +/* SliceTupleAndList.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyList_GetSlice(PyObject* src, Py_ssize_t start, Py_ssize_t stop); +static CYTHON_INLINE PyObject* __Pyx_PyTuple_GetSlice(PyObject* src, Py_ssize_t start, Py_ssize_t stop); +#else +#define __Pyx_PyList_GetSlice(seq, start, stop) PySequence_GetSlice(seq, start, stop) +#define __Pyx_PyTuple_GetSlice(seq, start, stop) PySequence_GetSlice(seq, start, stop) +#endif + +/* ListCompAppendAndDecref.proto */ +static CYTHON_INLINE int __Pyx_ListComp_AppendAndDecref(PyObject* list, PyObject* x); + +/* PyLongBinop.proto */ +#if !CYTHON_COMPILING_IN_PYPY +static CYTHON_INLINE PyObject* __Pyx_PyLong_SubtractCObj(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); +#else +#define __Pyx_PyLong_SubtractCObj(op1, op2, intval, inplace, zerodivision_check)\ + (inplace ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2)) +#endif + +/* PyValueError_Check.proto */ +#define __Pyx_PyExc_ValueError_Check(obj) __Pyx_TypeCheck(obj, PyExc_ValueError) + +/* PyObjectFormatAndDecref.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_FormatSimpleAndDecref(PyObject* s, PyObject* f); +static CYTHON_INLINE PyObject* __Pyx_PyObject_FormatAndDecref(PyObject* s, PyObject* f); + +/* JoinPyUnicode.proto */ +#define __Pyx_PyUnicode_Join_CAN_USE_KIND_AND_LENGTH\ + (!CYTHON_COMPILING_IN_GRAAL && !CYTHON_COMPILING_IN_PYPY && !CYTHON_COMPILING_IN_LIMITED_API) + +/* JoinPyUnicode.export */ +static PyObject* __Pyx_PyUnicode_Join(PyObject** values, Py_ssize_t value_count, Py_ssize_t result_ulength, int kind); + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolLe_object_int(PyObject *op1, PyObject *op2, int pyop); + +/* ArgTypeTestError.export */ +static void __Pyx_ArgTypeError(PyObject *obj, PyTypeObject *type, const char *name, int exact); + +/* ArgTypeTest.proto */ +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact); + +/* RaiseUnboundLocalError.proto */ +static void __Pyx_RaiseUnboundLocalError(const char *varname); + +/* GetException.proto (used by pep479) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* pep479.proto */ +static void __Pyx_Generator_Replace_StopIteration(int in_async_gen); + +/* PyDictVersioning.proto (used by GetModuleGlobalName) */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) +#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ + (version_var) = __PYX_GET_DICT_VERSION(dict);\ + (cache_var) = (value); +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ + (VAR) = __Pyx_XNewRef(__pyx_dict_cached_value);\ + } else {\ + (VAR) = __pyx_dict_cached_value = (LOOKUP);\ + __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ + }\ +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); +#else +#define __PYX_GET_DICT_VERSION(dict) (0) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); +#endif + +/* GetModuleGlobalName.proto */ +#if CYTHON_USE_DICT_VERSIONS +#define __Pyx_GetModuleGlobalName(var, name) do {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_mstate_global->__pyx_d))) ?\ + (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ + __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +#define __Pyx_GetModuleGlobalNameUncached(var, name) do {\ + PY_UINT64_T __pyx_dict_version;\ + PyObject *__pyx_dict_cached_value;\ + (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); +#else +#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) +#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); +#endif + +/* RaiseTooManyValuesToUnpack.proto */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +/* RaiseNeedMoreValuesToUnpack.proto */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +/* IterFinish.proto */ +static CYTHON_INLINE int __Pyx_IterFinish(void); + +/* UnpackItemEndCheck.proto */ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolNe_object_object(PyObject *op1, PyObject *op2, int pyop); + +/* RaiseErrorWithObjectType.proto (used by SliceObject) */ +#define __Pyx_RaiseTypeErrorWithObjectType(message, obj) __Pyx_RaiseErrorWithObjectType(PyExc_TypeError, message, obj) +#define __Pyx_RaiseErrorWithObjectType(exc_type, message, obj) __Pyx_RaiseErrorWithType(exc_type, message, Py_TYPE(obj)) +CYTHON_UNUSED +static void __Pyx_RaiseErrorWithType(PyObject* exc_type, const char* message, PyTypeObject *type_obj); + +/* SliceObject.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** py_start, PyObject** py_stop, PyObject** py_slice, + int has_cstart, int has_cstop, int wraparound); + +/* PyObjectCallMethod0.proto (used by pop) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); + +/* pop.proto */ +static CYTHON_INLINE PyObject* __Pyx__PyObject_Pop(PyObject* L); +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE +static CYTHON_INLINE PyObject* __Pyx_PyList_Pop(PyObject* L); +#define __Pyx_PyObject_Pop(L) (likely(PyList_CheckExact(L)) ?\ + __Pyx_PyList_Pop(L) : __Pyx__PyObject_Pop(L)) +#else +#define __Pyx_PyList_Pop(L) __Pyx__PyObject_Pop(L) +#define __Pyx_PyObject_Pop(L) __Pyx__PyObject_Pop(L) +#endif + +/* ListExtend.proto */ +#if (CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030d0000) && !defined(PyList_Extend) +static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v); +#else +#define __Pyx_PyList_Extend(L, v) PyList_Extend(L, v) +#endif + +/* RaiseErrorWithObjectType1.proto (used by RaiseUnexpectedTypeError) */ +#define __Pyx_RaiseTypeErrorWithObjectType1(message, arg, obj) __Pyx_RaiseErrorWithObjectType1(PyExc_TypeError, message, arg, obj) +#define __Pyx_RaiseErrorWithObjectType1(exc_type, message, arg, obj) __Pyx_RaiseErrorWithType1(exc_type, message, arg, Py_TYPE(obj)) +CYTHON_UNUSED +static void __Pyx_RaiseErrorWithType1(PyObject* exc_type, const char* message, const char *arg, PyTypeObject *type_obj); + +/* RaiseUnexpectedTypeError.proto */ +CYTHON_UNUSED +static int __Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj); + +/* PyLongBinop.proto */ +#if !CYTHON_COMPILING_IN_PYPY +static CYTHON_INLINE PyObject* __Pyx_PyLong_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); +#else +#define __Pyx_PyLong_AddObjC(op1, op2, intval, inplace, zerodivision_check)\ + (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) +#endif + +/* PyNumberBinop.proto */ +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_PyNumber_Add_int_object(op1, op2) PyNumber_Add(op1, op2) +#define __Pyx_PyNumber_InPlaceAdd_int_object(op1, op2) PyNumber_InPlaceAdd(op1, op2) +#else +#define __Pyx_PyNumber_Add_int_object(op1, op2) __Pyx__PyNumber_Add_int_object(op1, op2, 0) +#define __Pyx_PyNumber_InPlaceAdd_int_object(op1, op2) __Pyx__PyNumber_Add_int_object(op1, op2, 1) +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Add_int_object(PyObject *op1, PyObject *op2, int inplace); +#endif + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolLt_object_object(PyObject *op1, PyObject *op2, int pyop); + +/* GetTopmostException.proto (used by SaveResetException) */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); +#endif + +/* SaveResetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +#else +#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) +#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) +#endif + +/* PyZeroDivisionError_Check.proto */ +#define __Pyx_PyExc_ZeroDivisionError_Check(obj) __Pyx_TypeCheck(obj, PyExc_ZeroDivisionError) + +/* pyfrozenset_new.proto (used by PySetContains) */ +static PyObject* __Pyx_PyFrozenSet_New(PyObject* it); + +/* PySetContains.proto */ +static CYTHON_INLINE int __Pyx_PySet_ContainsTF(PyObject* key, PyObject* set, int eq); + +/* HasAttr.proto (used by ImportImpl) */ +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_HasAttr(o, n) PyObject_HasAttrWithError(o, n) +#else +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); +#endif + +/* ImportImpl.export */ +static PyObject *__Pyx__Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, PyObject *moddict, int level); + +/* Import.proto */ +static CYTHON_INLINE PyObject *__Pyx_Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, int level); + +/* ImportFrom.export */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); + +/* CheckTypeForFreelists.proto */ +#if CYTHON_USE_FREELISTS +#if CYTHON_USE_TYPE_SPECS +#define __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(t, expected_tp, expected_size) ((int) ((t) == (expected_tp))) +#define __PYX_CHECK_TYPE_FOR_FREELIST_FLAGS Py_TPFLAGS_IS_ABSTRACT +#else +#define __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(t, expected_tp, expected_size) ((int) ((t)->tp_basicsize == (expected_size))) +#define __PYX_CHECK_TYPE_FOR_FREELIST_FLAGS (Py_TPFLAGS_IS_ABSTRACT | Py_TPFLAGS_HEAPTYPE) +#endif +#define __PYX_CHECK_TYPE_FOR_FREELISTS(t, expected_tp, expected_size)\ + (__PYX_CHECK_FINAL_TYPE_FOR_FREELISTS((t), (expected_tp), (expected_size)) &\ + (int) (!__Pyx_PyType_HasFeature((t), __PYX_CHECK_TYPE_FOR_FREELIST_FLAGS))) +#endif + +/* AllocateExtensionType.proto */ +static PyObject *__Pyx_AllocateExtensionType(PyTypeObject *t, int is_final); + +/* CallSlotAsVectorcall.proto */ +#if CYTHON_VECTORCALL_TPNEW +typedef PyObject * (*__Pyx_tpnewvectorcallfunc)(PyTypeObject* o, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames); +static PyObject * __Pyx_CallTpnewAsVectorcall(__Pyx_tpnewvectorcallfunc f, PyTypeObject* o, PyObject *a, PyObject *k); +#endif + +/* CallNewInitFromVectorcall.proto */ +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__Pyx_CallNewInitFromVectorcall(PyTypeObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#endif + +/* CallTypeTraverse.proto */ +#if !CYTHON_USE_TYPE_SPECS +#define __Pyx_call_type_traverse(o, always_call, visit, arg) 0 +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg); +#endif + +/* GetTypeDictOffset.proto (used by ValidateBasesTuple) */ +#if !CYTHON_USE_TYPE_SLOTS +CYTHON_UNUSED static Py_ssize_t __Pyx_GetTypeDictOffset(PyObject *tp, int require_cython_valid_result); +#endif + +/* ValidateBasesTuple.proto (used by PyType_Ready) */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, int has_dictoffset, PyObject *bases); +#endif + +/* PyType_Ready.export */ +CYTHON_UNUSED static int __Pyx_PyType_Ready(PyTypeObject *t); + +/* dict_setdefault.proto (used by FetchCommonType) */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value); + +/* AddModuleRef.proto (used by FetchSharedCythonModule) */ +#if ((CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && PY_VERSION_HEX < 0x030F00a3) ||\ + __PYX_LIMITED_VERSION_HEX < 0x030d0000) + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name); +#else + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#endif + +/* FetchSharedCythonModule.proto (used by FetchCommonType) */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void); + +/* VerifyCachedType.proto (used by FetchCommonType) */ +static int __Pyx_VerifyCachedType(PyObject *cached_type, + const char *name, + Py_ssize_t expected_basicsize); + +/* FetchCommonType.proto (used by CommonTypesMetaclass) */ +static PyTypeObject* __Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases); + +/* CommonTypesMetaclass.proto (used by CythonFunctionShared) */ +static int __pyx_CommonTypesMetaclass_init(PyObject *module); +#define __Pyx_CommonTypesMetaclass_USED + +/* CythonFunctionPerModule.proto (used by CythonFunctionShared) */ +#define __Pyx_CyFunction_USED +#if CYTHON_OPAQUE_SHARED_TYPES +#define __Pyx_as_CyFunctionObject(o) ((__pyx_CyFunctionObject *)PyObject_GetTypeData((o), __pyx_mstate_global->__pyx_CyFunctionType)) +#else +#define __Pyx_as_CyFunctionObject(o) ((__pyx_CyFunctionObject *)o) +#endif +#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 +#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 +#define __Pyx_CYFUNCTION_CCLASS 0x04 +#define __Pyx_CYFUNCTION_COROUTINE 0x08 +#define __Pyx_CyFunction_GetClosure(f)\ + ((__Pyx_as_CyFunctionObject(f))->func_closure) +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx__CyFunction_GetClassObj(f)\ + ((f)->func_classobj) +#else + #define __Pyx__CyFunction_GetClassObj(f)\ + ((PyObject*) ((PyCMethodObject *) (f))->mm_class) +#endif +#define __Pyx_CyFunction_GetClassObj(f)\ + __Pyx__CyFunction_GetClassObj(__Pyx_as_CyFunctionObject(f)) +#define __Pyx_CyFunction_SetClassObj(f, classobj)\ + __Pyx__CyFunction_SetClassObj(__Pyx_as_CyFunctionObject(f), (classobj)) +#define __Pyx_CyFunction_Defaults(type, f)\ + ((type *)((__Pyx_as_CyFunctionObject(f))->defaults)) +#define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ + (__Pyx_as_CyFunctionObject(f))->defaults_getter = (g) +typedef struct { +#if CYTHON_COMPILING_IN_LIMITED_API +#if !CYTHON_OPAQUE_OBJECTS + PyObject_HEAD +#endif + PyMethodDef *func_methoddef; + PyObject *func_module; +#else + PyCMethodObject func; +#endif +#if (CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY) && CYTHON_VECTORCALL + __pyx_vectorcallfunc func_vectorcall; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_weakreflist; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_dict; +#endif + PyObject *func_name; + PyObject *func_qualname; + PyObject *func_doc; + PyObject *func_globals; + PyObject *func_code; + PyObject *func_closure; +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_classobj; +#endif + PyObject *defaults; + int flags; + PyObject *defaults_tuple; + PyObject *defaults_kwdict; + PyObject *(*defaults_getter)(PyObject *); + PyObject *func_annotations; +#if __PYX_LIMITED_VERSION_HEX < 0x030B0000 + PyObject *func_is_coroutine; +#endif +} __pyx_CyFunctionObject; +#undef __Pyx_CyOrPyCFunction_Check +#define __Pyx_CyFunction_Check(obj) __Pyx_TypeCheck(obj, __pyx_mstate_global->__pyx_CyFunctionType) +#define __Pyx_CyOrPyCFunction_Check(obj) __Pyx_TypeCheck2(obj, __pyx_mstate_global->__pyx_CyFunctionType, &PyCFunction_Type) +#define __Pyx_CyFunction_CheckExact(obj) Py_IS_TYPE(obj, __pyx_mstate_global->__pyx_CyFunctionType) +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)); +#undef __Pyx_IsSameCFunction +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCyOrCFunction(func, cfunc) +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj); +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, + PyTypeObject *defaults_type); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, + PyObject *tuple); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, + PyObject *dict); +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, + PyObject *dict); +static int __pyx_CyFunction_init(PyObject *module); +#if CYTHON_VECTORCALL +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY +#define __Pyx_CyFunction_func_vectorcall(f) ((f)->func_vectorcall) +#else +#define __Pyx_CyFunction_func_vectorcall(f) (((PyCFunctionObject*)f)->vectorcall) +#endif +#endif + +/* PyMethodNew.proto (used by CythonFunctionShared) */ +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ); + +/* PyVectorcallFastCallDict.proto (used by CythonFunctionShared) */ +#if CYTHON_VECTORCALL +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw); +#endif + +/* CythonFunctionShared.proto (used by CythonFunction) */ +static PyObject *__Pyx_CyFunction_Init(PyObject *op_in, PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); +#if CYTHON_VECTORCALL +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#endif + +/* CythonFunction.export */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); +static PyTypeObject *__Pyx_Get_CyFunction_Type(void); + +/* ObjectGetItem.proto */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject *key); +#else +#define __Pyx_PyObject_GetItem(obj, key) PyObject_GetItem(obj, key) +#endif + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolEq_object_str(PyObject *op1, PyObject *op2, int pyop); + +/* CLineInTraceback.proto (used by AddTraceback) */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); +#else +#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) +#endif + +/* CodeObjectCache.proto (used by AddTraceback) */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject __Pyx_CachedCodeObjectType; +#else +typedef PyCodeObject __Pyx_CachedCodeObjectType; +#endif +typedef struct { + __Pyx_CachedCodeObjectType* code_object; + int code_line; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_int_type accessor_count; + #endif +}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object); + +/* AddTraceback.proto */ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); + +/* RealImag.proto */ +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #define __Pyx_CREAL(z) ((z).real()) + #define __Pyx_CIMAG(z) ((z).imag()) + #else + #define __Pyx_CREAL(z) (__real__(z)) + #define __Pyx_CIMAG(z) (__imag__(z)) + #endif +#else + #define __Pyx_CREAL(z) ((z).real) + #define __Pyx_CIMAG(z) ((z).imag) +#endif +#if defined(__cplusplus) && CYTHON_CCOMPLEX\ + && (defined(_WIN32) || defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 5 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4 )) || __cplusplus >= 201103) + #define __Pyx_SET_CREAL(z,x) ((z).real(x)) + #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) +#else + #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) + #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) +#endif + +/* Arithmetic.proto */ +#if CYTHON_CCOMPLEX && (1) && (!0 || __cplusplus) + #define __Pyx_c_eq_double(a, b) ((a)==(b)) + #define __Pyx_c_sum_double(a, b) ((a)+(b)) + #define __Pyx_c_diff_double(a, b) ((a)-(b)) + #define __Pyx_c_prod_double(a, b) ((a)*(b)) + #define __Pyx_c_quot_double(a, b) ((a)/(b)) + #define __Pyx_c_neg_double(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zero_double(z) ((z)==(double)0) + #define __Pyx_c_conj_double(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_abs_double(z) (::std::abs(z)) + #define __Pyx_c_pow_double(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zero_double(z) ((z)==0) + #define __Pyx_c_conj_double(z) (conj(z)) + #if 1 + #define __Pyx_c_abs_double(z) (cabs(z)) + #define __Pyx_c_pow_double(a, b) (cpow(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex); + static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex); + #if 1 + static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex, __pyx_t_double_complex); + #endif +#endif + +/* FromPy.proto */ +static __pyx_t_double_complex __Pyx_PyComplex_As___pyx_t_double_complex(PyObject*); + +/* GCCDiagnostics.proto */ +#if !defined(__INTEL_COMPILER) && defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#define __Pyx_HAS_GCC_DIAGNOSTIC +#endif + +/* ToPy.proto */ +#define __pyx_PyComplex_FromComplex(z)\ + PyComplex_FromDoubles((double)__Pyx_CREAL(z),\ + (double)__Pyx_CIMAG(z)) + +/* CIntFromPy.proto */ +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *); + +/* PyObjectVectorcallKwds.proto (used by PyObjectVectorcallMethodKwds) */ +#if CYTHON_VECTORCALL +#define __Pyx_Object_VectorcallKwds PyObject_Vectorcall +CYTHON_UNUSED static int __Pyx_CheckVectorcallKwarg(PyObject *kwnames, Py_ssize_t i); +#else +#define __Pyx_Object_VectorcallKwds __Pyx_PyObject_FastCallDict +CYTHON_UNUSED static PyObject *__Pyx_MakeKwargDict(PyObject **keys, PyObject **values, Py_ssize_t n); +CYTHON_UNUSED static int __Pyx_CheckVectorcallKwarg(PyObject **kwnames, Py_ssize_t i); +#endif + +/* PyObjectVectorcallMethodKwds.proto (used by CIntToPy) */ +#if CYTHON_VECTORCALL +#define __Pyx_Object_VectorcallMethodKwds PyObject_VectorcallMethod +#else +static PyObject *__Pyx_Object_VectorcallMethodKwds(PyObject *name, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#endif + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value); + +/* CIntFromPy.proto */ +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *); + +/* GetRuntimeVersion.proto */ +#if __PYX_LIMITED_VERSION_HEX < 0x030b0000 +static unsigned long __Pyx_cached_runtime_version = 0; +static void __Pyx_init_runtime_version(void); +#else +#define __Pyx_init_runtime_version() +#endif +static unsigned long __Pyx_get_runtime_version(void); + +/* SwapException.proto (used by CoroutineBase) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* IterNextPlain.proto (used by CoroutineBase) */ +static CYTHON_INLINE PyObject *__Pyx_PyIter_Next_Plain(PyObject *iterator); +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject *__Pyx_GetBuiltinNext_LimitedAPI(void); +#endif + +/* PyObjectCallMethod1.proto (used by CoroutineBase) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); + +/* PyObjectCallNoArg.proto (used by CoroutineBase) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); + +/* ReturnWithStopIteration.proto (used by CoroutineBase) */ +static CYTHON_INLINE void __Pyx_ReturnWithStopIteration(PyObject* value, int async, int iternext); + +/* CoroutineBase.proto (used by Generator) */ +struct __pyx_CoroutineObject; +typedef PyObject *(*__pyx_coroutine_body_t)(struct __pyx_CoroutineObject *, PyThreadState *, PyObject *); +#if CYTHON_USE_EXC_INFO_STACK +#define __Pyx_ExcInfoStruct _PyErr_StackItem +#else +typedef struct { + PyObject *exc_type; + PyObject *exc_value; + PyObject *exc_traceback; +} __Pyx_ExcInfoStruct; +#endif +typedef struct __pyx_CoroutineObject { + PyObject_HEAD + __pyx_coroutine_body_t body; + PyObject *closure; + __Pyx_ExcInfoStruct gi_exc_state; +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *gi_weakreflist; +#endif + PyObject *classobj; + PyObject *yieldfrom; + __Pyx_pyiter_sendfunc yieldfrom_am_send; + PyObject *gi_name; + PyObject *gi_qualname; + PyObject *gi_modulename; + PyObject *gi_code; + PyObject *gi_frame; +#if CYTHON_USE_SYS_MONITORING && (CYTHON_PROFILE || CYTHON_TRACE) + PyMonitoringState __pyx_pymonitoring_state[__Pyx_MonitoringEventTypes_CyGen_count]; + uint64_t __pyx_pymonitoring_version; +#endif + int resume_label; + char is_running; +} __pyx_CoroutineObject; +static __pyx_CoroutineObject *__Pyx__Coroutine_New( + PyTypeObject *type, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, + PyObject *name, PyObject *qualname, PyObject *module_name); +static __pyx_CoroutineObject *__Pyx__Coroutine_NewInit( + __pyx_CoroutineObject *gen, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, + PyObject *name, PyObject *qualname, PyObject *module_name); +static CYTHON_INLINE void __Pyx_Coroutine_ExceptionClear(__Pyx_ExcInfoStruct *self); +static int __Pyx_Coroutine_clear(PyObject *self); +static __Pyx_PySendResult __Pyx_Coroutine_AmSend(PyObject *self, PyObject *value, PyObject **retval); +static PyObject *__Pyx_Coroutine_Send(PyObject *self, PyObject *value); +static __Pyx_PySendResult __Pyx_Coroutine_Close(PyObject *self, PyObject **retval); +static PyObject *__Pyx_Coroutine_Throw(PyObject *gen, +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + PyObject *args +#else + PyObject *const *args, Py_ssize_t nargs +#endif + ); +#if CYTHON_USE_EXC_INFO_STACK +#define __Pyx_Coroutine_SwapException(self) +#define __Pyx_Coroutine_ResetAndClearException(self) __Pyx_Coroutine_ExceptionClear(&(self)->gi_exc_state) +#else +#define __Pyx_Coroutine_SwapException(self) {\ + __Pyx_ExceptionSwap(&(self)->gi_exc_state.exc_type, &(self)->gi_exc_state.exc_value, &(self)->gi_exc_state.exc_traceback);\ + __Pyx_Coroutine_ResetFrameBackpointer(&(self)->gi_exc_state);\ + } +#define __Pyx_Coroutine_ResetAndClearException(self) {\ + __Pyx_ExceptionReset((self)->gi_exc_state.exc_type, (self)->gi_exc_state.exc_value, (self)->gi_exc_state.exc_traceback);\ + (self)->gi_exc_state.exc_type = (self)->gi_exc_state.exc_value = (self)->gi_exc_state.exc_traceback = NULL;\ + } +#endif +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyGen_FetchStopIterationValue(pvalue)\ + __Pyx_PyGen__FetchStopIterationValue(__pyx_tstate, pvalue) +#else +#define __Pyx_PyGen_FetchStopIterationValue(pvalue)\ + __Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, pvalue) +#endif +static int __Pyx_PyGen__FetchStopIterationValue(PyThreadState *tstate, PyObject **pvalue); +static CYTHON_INLINE void __Pyx_Coroutine_ResetFrameBackpointer(__Pyx_ExcInfoStruct *exc_state); +static char __Pyx_Coroutine_test_and_set_is_running(__pyx_CoroutineObject *gen); +static void __Pyx_Coroutine_unset_is_running(__pyx_CoroutineObject *gen); +static char __Pyx_Coroutine_get_is_running(__pyx_CoroutineObject *gen); +static PyObject *__Pyx_Coroutine_get_is_running_getter(PyObject *gen, void *closure); +#if __PYX_HAS_PY_AM_SEND == 2 +static void __Pyx_SetBackportTypeAmSend(PyTypeObject *type, __Pyx_PyAsyncMethodsStruct *static_amsend_methods, __Pyx_pyiter_sendfunc am_send); +#endif +static PyObject *__Pyx_Coroutine_fail_reduce_ex(PyObject *self, PyObject *arg); + +/* Generator.proto */ +#define __Pyx_Generator_USED +#define __Pyx_Generator_CheckExact(obj) Py_IS_TYPE(obj, __pyx_mstate_global->__pyx_GeneratorType) +#define __Pyx_Generator_New(body, code, closure, name, qualname, module_name)\ + __Pyx__Coroutine_New(__pyx_mstate_global->__pyx_GeneratorType, body, code, closure, name, qualname, module_name) +static PyObject *__Pyx_Generator_Next(PyObject *self); +static int __pyx_Generator_init(PyObject *module); +static CYTHON_INLINE PyObject *__Pyx_Generator_GetInlinedResult(PyObject *self); + +/* CheckBinaryVersion.proto */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer); + +/* DecompressString.proto */ +static PyObject *__Pyx_DecompressString(const char *s, Py_ssize_t length, int algo); + +/* DecompressString_LZSS.proto */ +static PyObject *__Pyx_DecompressString_LZSS(const char *s, size_t compressed_length, size_t uncompressed_length); + +/* MultiPhaseInitModuleState.proto */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +#include +static PyObject *__Pyx_State_FindModule(void*); +static int __Pyx_State_AddModule(PyObject* module, void*); +static int __Pyx_State_RemoveModule(void*); +#elif CYTHON_USE_MODULE_STATE +#define __Pyx_State_FindModule PyState_FindModule +#define __Pyx_State_AddModule PyState_AddModule +#define __Pyx_State_RemoveModule PyState_RemoveModule +#endif + +/* #### Code section: module_declarations ### */ +/* CythonABIVersion.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API + #if CYTHON_VECTORCALL + #define __PYX_VECTORCALL_ABI_SUFFIX "_vectorcall" + #else + #define __PYX_VECTORCALL_ABI_SUFFIX + #endif + #define __PYX_LIMITED_ABI_SUFFIX "limited" __PYX_VECTORCALL_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX +#else + #define __PYX_LIMITED_ABI_SUFFIX +#endif +#if __PYX_HAS_PY_AM_SEND == 1 + #define __PYX_AM_SEND_ABI_SUFFIX +#elif __PYX_HAS_PY_AM_SEND == 2 + #define __PYX_AM_SEND_ABI_SUFFIX "amsendbackport" +#else + #define __PYX_AM_SEND_ABI_SUFFIX "noamsend" +#endif +#ifndef __PYX_MONITORING_ABI_SUFFIX + #define __PYX_MONITORING_ABI_SUFFIX +#endif +#if CYTHON_USE_TP_FINALIZE + #define __PYX_TP_FINALIZE_ABI_SUFFIX +#else + #define __PYX_TP_FINALIZE_ABI_SUFFIX "nofinalize" +#endif +#if CYTHON_USE_FREELISTS || !defined(__Pyx_AsyncGen_USED) + #define __PYX_FREELISTS_ABI_SUFFIX +#else + #define __PYX_FREELISTS_ABI_SUFFIX "nofreelists" +#endif +#if CYTHON_OPAQUE_OBJECTS && CYTHON_COMPILING_IN_LIMITED_API + #define __PYX_OPAQUE_OBJECTS_ABI_SUFFIX "opaque" +#else + #define __PYX_OPAQUE_OBJECTS_ABI_SUFFIX +#endif +#define CYTHON_ABI __PYX_ABI_VERSION __PYX_LIMITED_ABI_SUFFIX __PYX_MONITORING_ABI_SUFFIX __PYX_TP_FINALIZE_ABI_SUFFIX __PYX_FREELISTS_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX __PYX_OPAQUE_OBJECTS_ABI_SUFFIX +#define __PYX_ABI_MODULE_NAME "_cython_" CYTHON_ABI +#define __PYX_TYPE_MODULE_PREFIX __PYX_ABI_MODULE_NAME "." + + +/* Module declarations from "cython" */ + +/* Module declarations from "fontTools.qu2cu.qu2cu" */ +static int __pyx_f_9fontTools_5qu2cu_5qu2cu_cubic_farthest_fit_inside(__pyx_t_double_complex, __pyx_t_double_complex, __pyx_t_double_complex, __pyx_t_double_complex, double); /*proto*/ +static PyObject *__pyx_f_9fontTools_5qu2cu_5qu2cu_merge_curves(PyObject *, int, int); /*proto*/ +/* #### Code section: typeinfo ### */ +/* #### Code section: before_global_var ### */ +#define __Pyx_MODULE_NAME "fontTools.qu2cu.qu2cu" +extern int __pyx_module_is_main_fontTools__qu2cu__qu2cu; +int __pyx_module_is_main_fontTools__qu2cu__qu2cu = 0; + +/* Implementation of "fontTools.qu2cu.qu2cu" */ +/* #### Code section: global_var ### */ +static PyObject *__pyx_builtin_enumerate; +static PyObject *__pyx_builtin_reversed; +static PyObject *__pyx_builtin_zip; +static PyObject *__pyx_builtin_print; +/* #### Code section: string_decls ### */ +/* #### Code section: decls ### */ +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_elevate_quadratic(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_p0, __pyx_t_double_complex __pyx_v_p1, __pyx_t_double_complex __pyx_v_p2); /* proto */ +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_2add_implicit_on_curves(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_p); /* proto */ +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_4_raise_incompatible_point(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_point, PyObject *__pyx_v_previous_point); /* proto */ +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_6_validate_spline_length(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_spline); /* proto */ +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_8_validate_positive_tolerance(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_max_err); /* proto */ +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_19quadratic_to_curves_8genexpr3_genexpr(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_genexpr_arg_0); /* proto */ +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_10quadratic_to_curves(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_quads, double __pyx_v_max_err, int __pyx_v_all_cubic); /* proto */ +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_16spline_to_curves_genexpr(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_genexpr_arg_0); /* proto */ +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_12spline_to_curves(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_q, PyObject *__pyx_v_costs, double __pyx_v_tolerance, int __pyx_v_all_cubic); /* proto */ +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_14main(CYTHON_UNUSED PyObject *__pyx_self); /* proto */ +static PyObject *__pyx_tp_new__initialisation_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr(PyObject *o, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +); /*proto*/ +static PyObject *__pyx_tp_new_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr(PyTypeObject *t, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +); /*proto*/ +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_new_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +#endif +#if !CYTHON_VECTORCALL_TPNEW +#define __pyx_tp_new_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr __pyx_tp_new_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr +#endif +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr(PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames); /*proto*/ +#endif +static PyObject *__pyx_tp_new__initialisation_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr(PyObject *o, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +); /*proto*/ +static PyObject *__pyx_tp_new_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr(PyTypeObject *t, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +); /*proto*/ +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_new_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +#endif +#if !CYTHON_VECTORCALL_TPNEW +#define __pyx_tp_new_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr __pyx_tp_new_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr +#endif +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr(PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames); /*proto*/ +#endif +/* #### Code section: late_includes ### */ +/* #### Code section: module_state ### */ +/* SmallCodeConfig */ +#ifndef CYTHON_SMALL_CODE +#if defined(__clang__) + #define CYTHON_SMALL_CODE +#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define CYTHON_SMALL_CODE __attribute__((cold)) +#else + #define CYTHON_SMALL_CODE +#endif +#endif + +#ifdef __cplusplus +namespace { + #endif + typedef struct { + PyObject *__pyx_d; + PyObject *__pyx_b; + PyObject *__pyx_cython_runtime; + PyObject *__pyx_empty_tuple; + PyObject *__pyx_empty_bytes; + PyObject *__pyx_empty_unicode; + PyObject *__pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr; + PyObject *__pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr; + PyTypeObject *__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr; + PyTypeObject *__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_items; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_pop; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_values; + __Pyx_CachedCFunction __pyx_umethod_PyList_Type_pop; + PyObject *__pyx_slice[1]; + PyObject *__pyx_tuple[1]; + PyObject *__pyx_codeobj_tab[10]; + PyObject *__pyx_string_tab[151]; + PyObject *__pyx_number_tab[3]; +/* #### Code section: module_state_contents ### */ +/* PyFrozenDict.module_state_decls */ +#if CYTHON_COMPILING_IN_LIMITED_API +PyObject *__Pyx_PyFrozenDictType; +#endif + + +#if CYTHON_USE_FREELISTS +struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr *__pyx_freelist_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr[8]; +int __pyx_freecount_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr; +#endif + +#if CYTHON_USE_FREELISTS +struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr *__pyx_freelist_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr[8]; +int __pyx_freecount_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr; +#endif +/* CommonTypesMetaclass.module_state_decls */ +PyTypeObject *__pyx_CommonTypesMetaclassType; + +/* CachedMethodType.module_state_decls */ +#if CYTHON_COMPILING_IN_LIMITED_API +PyObject *__Pyx_CachedMethodType; +#endif + +/* CythonFunctionPerModule.module_state_decls */ +PyTypeObject *__pyx_CyFunctionType; + +/* CodeObjectCache.module_state_decls */ +struct __Pyx_CodeObjectCache __pyx_code_cache; + +/* IterNextPlain.module_state_decls */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +PyObject *__Pyx_GetBuiltinNext_LimitedAPI_cache; +#endif + +/* Generator.module_state_decls */ +PyTypeObject *__pyx_GeneratorType; + +/* #### Code section: module_state_end ### */ +} __pyx_mstatetype; +#ifdef __cplusplus +} /* anonymous namespace */ +#endif + +#if CYTHON_USE_MODULE_STATE +#ifdef __cplusplus +namespace { +extern struct PyModuleDef __pyx_moduledef; +} /* anonymous namespace */ +#else +static struct PyModuleDef __pyx_moduledef; +#endif + +#define __pyx_mstate_global (__Pyx_PyModule_GetState(__Pyx_State_FindModule(&__pyx_moduledef))) + +#define __pyx_m (__Pyx_State_FindModule(&__pyx_moduledef)) +#else +static __pyx_mstatetype __pyx_mstate_global_static = +#ifdef __cplusplus + {}; +#else + {0}; +#endif +static __pyx_mstatetype * const __pyx_mstate_global = &__pyx_mstate_global_static; +#endif +/* #### Code section: constant_name_defines ### */ +#define __pyx_kp_u_then __pyx_string_tab[0] +#define __pyx_kp_u__2 __pyx_string_tab[1] +#define __pyx_kp_u_ __pyx_string_tab[2] +#define __pyx_kp_u_Lib_fontTools_qu2cu_qu2cu_py __pyx_string_tab[3] +#define __pyx_kp_u_List_Sequence_Point __pyx_string_tab[4] +#define __pyx_kp_u_List_Tuple_Point __pyx_string_tab[5] +#define __pyx_kp_u_Note_that_Cython_is_deliberately __pyx_string_tab[6] +#define __pyx_kp_u_One_random_cubic_turned_into_d_q __pyx_string_tab[7] +#define __pyx_kp_u_Original_curve __pyx_string_tab[8] +#define __pyx_kp_u_Quadratic_splines_must_connect_e __pyx_string_tab[9] +#define __pyx_kp_u_Quadratic_splines_must_contain_a __pyx_string_tab[10] +#define __pyx_kp_u_Reconstructed_curve_s __pyx_string_tab[11] +#define __pyx_kp_u_Those_quadratics_turned_back_int __pyx_string_tab[12] +#define __pyx_kp_u_add_note __pyx_string_tab[13] +#define __pyx_kp_u_cu2qu_tolerance_g_qu2cu_toleranc __pyx_string_tab[14] +#define __pyx_kp_u_disable __pyx_string_tab[15] +#define __pyx_kp_u_enable __pyx_string_tab[16] +#define __pyx_kp_u_gc __pyx_string_tab[17] +#define __pyx_kp_u_isenabled __pyx_string_tab[18] +#define __pyx_kp_u_max_err_must_be_greater_than_zer __pyx_string_tab[19] +#define __pyx_kp_u_quadratic_spline_requires_at_lea __pyx_string_tab[20] +#define __pyx_n_u_COMPILED __pyx_string_tab[21] +#define __pyx_n_u_List __pyx_string_tab[22] +#define __pyx_n_u_Point __pyx_string_tab[23] +#define __pyx_n_u_Sequence __pyx_string_tab[24] +#define __pyx_n_u_Solution __pyx_string_tab[25] +#define __pyx_n_u_Tuple __pyx_string_tab[26] +#define __pyx_n_u_Union __pyx_string_tab[27] +#define __pyx_n_u_Pyx_PyDict_NextRef __pyx_string_tab[28] +#define __pyx_n_u_all __pyx_string_tab[29] +#define __pyx_n_u_annotate __pyx_string_tab[30] +#define __pyx_n_u_class_getitem __pyx_string_tab[31] +#define __pyx_n_u_func __pyx_string_tab[32] +#define __pyx_n_u_main __pyx_string_tab[33] +#define __pyx_n_u_module __pyx_string_tab[34] +#define __pyx_n_u_name __pyx_string_tab[35] +#define __pyx_n_u_qualname __pyx_string_tab[36] +#define __pyx_n_u_test __pyx_string_tab[37] +#define __pyx_n_u_is_coroutine __pyx_string_tab[38] +#define __pyx_n_u_raise_incompatible_point __pyx_string_tab[39] +#define __pyx_n_u_validate_positive_tolerance __pyx_string_tab[40] +#define __pyx_n_u_validate_spline_length __pyx_string_tab[41] +#define __pyx_n_u_add_implicit_on_curves __pyx_string_tab[42] +#define __pyx_n_u_all_cubic __pyx_string_tab[43] +#define __pyx_n_u_asyncio_coroutines __pyx_string_tab[44] +#define __pyx_n_u_best_sol __pyx_string_tab[45] +#define __pyx_n_u_bool __pyx_string_tab[46] +#define __pyx_n_u_c __pyx_string_tab[47] +#define __pyx_n_u_cline_in_traceback __pyx_string_tab[48] +#define __pyx_n_u_close __pyx_string_tab[49] +#define __pyx_n_u_collections __pyx_string_tab[50] +#define __pyx_n_u_cost __pyx_string_tab[51] +#define __pyx_n_u_costs __pyx_string_tab[52] +#define __pyx_n_u_count __pyx_string_tab[53] +#define __pyx_n_u_cubic __pyx_string_tab[54] +#define __pyx_n_u_curve __pyx_string_tab[55] +#define __pyx_n_u_curve_to_quadratic __pyx_string_tab[56] +#define __pyx_n_u_curves __pyx_string_tab[57] +#define __pyx_n_u_elevate_quadratic __pyx_string_tab[58] +#define __pyx_n_u_elevated_quadratics __pyx_string_tab[59] +#define __pyx_n_u_enumerate __pyx_string_tab[60] +#define __pyx_n_u_err __pyx_string_tab[61] +#define __pyx_n_u_error __pyx_string_tab[62] +#define __pyx_n_u_float __pyx_string_tab[63] +#define __pyx_n_u_fontTools_cu2qu __pyx_string_tab[64] +#define __pyx_n_u_fontTools_cu2qu_benchmark __pyx_string_tab[65] +#define __pyx_n_u_fontTools_misc_bezierTools __pyx_string_tab[66] +#define __pyx_n_u_fontTools_qu2cu_qu2cu __pyx_string_tab[67] +#define __pyx_n_u_forced __pyx_string_tab[68] +#define __pyx_n_u_generate_curve __pyx_string_tab[69] +#define __pyx_n_u_genexpr __pyx_string_tab[70] +#define __pyx_n_u_i __pyx_string_tab[71] +#define __pyx_n_u_i_sol __pyx_string_tab[72] +#define __pyx_n_u_i_sol_count __pyx_string_tab[73] +#define __pyx_n_u_i_sol_error __pyx_string_tab[74] +#define __pyx_n_u_imag __pyx_string_tab[75] +#define __pyx_n_u_impossible __pyx_string_tab[76] +#define __pyx_n_u_is_complex __pyx_string_tab[77] +#define __pyx_n_u_is_cubic __pyx_string_tab[78] +#define __pyx_n_u_items __pyx_string_tab[79] +#define __pyx_n_u_j __pyx_string_tab[80] +#define __pyx_n_u_j_sol_count __pyx_string_tab[81] +#define __pyx_n_u_j_sol_error __pyx_string_tab[82] +#define __pyx_n_u_k __pyx_string_tab[83] +#define __pyx_n_u_main_2 __pyx_string_tab[84] +#define __pyx_n_u_math __pyx_string_tab[85] +#define __pyx_n_u_max_err __pyx_string_tab[86] +#define __pyx_n_u_namedtuple __pyx_string_tab[87] +#define __pyx_n_u_next __pyx_string_tab[88] +#define __pyx_n_u_num_offcurves __pyx_string_tab[89] +#define __pyx_n_u_num_points __pyx_string_tab[90] +#define __pyx_n_u_off1 __pyx_string_tab[91] +#define __pyx_n_u_off2 __pyx_string_tab[92] +#define __pyx_n_u_on __pyx_string_tab[93] +#define __pyx_n_u_orig __pyx_string_tab[94] +#define __pyx_n_u_p __pyx_string_tab[95] +#define __pyx_n_u_p0 __pyx_string_tab[96] +#define __pyx_n_u_p1 __pyx_string_tab[97] +#define __pyx_n_u_p1_2_3 __pyx_string_tab[98] +#define __pyx_n_u_p2 __pyx_string_tab[99] +#define __pyx_n_u_p3 __pyx_string_tab[100] +#define __pyx_n_u_point __pyx_string_tab[101] +#define __pyx_n_u_pop __pyx_string_tab[102] +#define __pyx_n_u_previous_point __pyx_string_tab[103] +#define __pyx_n_u_print __pyx_string_tab[104] +#define __pyx_n_u_q __pyx_string_tab[105] +#define __pyx_n_u_qq __pyx_string_tab[106] +#define __pyx_n_u_quadratic_to_curves __pyx_string_tab[107] +#define __pyx_n_u_quadratic_to_curves_locals_genex __pyx_string_tab[108] +#define __pyx_n_u_quadratics __pyx_string_tab[109] +#define __pyx_n_u_quads __pyx_string_tab[110] +#define __pyx_n_u_real __pyx_string_tab[111] +#define __pyx_n_u_reconst __pyx_string_tab[112] +#define __pyx_n_u_reconstruct_tolerance __pyx_string_tab[113] +#define __pyx_n_u_reconstructed __pyx_string_tab[114] +#define __pyx_n_u_reconstructed_iter __pyx_string_tab[115] +#define __pyx_n_u_return __pyx_string_tab[116] +#define __pyx_n_u_reversed __pyx_string_tab[117] +#define __pyx_n_u_send __pyx_string_tab[118] +#define __pyx_n_u_setdefault __pyx_string_tab[119] +#define __pyx_n_u_sols __pyx_string_tab[120] +#define __pyx_n_u_spline __pyx_string_tab[121] +#define __pyx_n_u_spline_to_curves __pyx_string_tab[122] +#define __pyx_n_u_spline_to_curves_locals_genexpr __pyx_string_tab[123] +#define __pyx_n_u_splitCubicAtTC __pyx_string_tab[124] +#define __pyx_n_u_splits __pyx_string_tab[125] +#define __pyx_n_u_start __pyx_string_tab[126] +#define __pyx_n_u_start_index __pyx_string_tab[127] +#define __pyx_n_u_this_count __pyx_string_tab[128] +#define __pyx_n_u_this_sol_count __pyx_string_tab[129] +#define __pyx_n_u_throw __pyx_string_tab[130] +#define __pyx_n_u_tolerance __pyx_string_tab[131] +#define __pyx_n_u_ts __pyx_string_tab[132] +#define __pyx_n_u_typing __pyx_string_tab[133] +#define __pyx_n_u_u __pyx_string_tab[134] +#define __pyx_n_u_v __pyx_string_tab[135] +#define __pyx_n_u_value __pyx_string_tab[136] +#define __pyx_n_u_values __pyx_string_tab[137] +#define __pyx_n_u_x __pyx_string_tab[138] +#define __pyx_n_u_y __pyx_string_tab[139] +#define __pyx_n_u_zip __pyx_string_tab[140] +#define __pyx_kp_b_iso88591_s_82Q_j __pyx_string_tab[141] +#define __pyx_kp_b_iso88591_xs_j __pyx_string_tab[142] +#define __pyx_kp_b_iso88591_Jb_N_1G1_2_8_Qa_q_Cq_Q_Q __pyx_string_tab[143] +#define __pyx_kp_b_iso88591_A_1_SSTTU __pyx_string_tab[144] +#define __pyx_kp_b_iso88591_Q_q_t1_q_q_Qe1Bat3a_t1_S_S_c_U __pyx_string_tab[145] +#define __pyx_kp_b_iso88591_AQ_A_Cq_2Q_U_3a_q_q_2Q_U_U_F_A __pyx_string_tab[146] +#define __pyx_kp_b_iso88591_S_2Rq_Cr_3b_Cr_3b __pyx_string_tab[147] +#define __pyx_kp_b_iso88591_a_3as_S_1AT_2T_U_q_3as_Cq_U_3c __pyx_string_tab[148] +#define __pyx_kp_b_iso88591__3 __pyx_string_tab[149] +#define __pyx_kp_b_iso88591__4 __pyx_string_tab[150] +#define __pyx_int_0 __pyx_number_tab[0] +#define __pyx_int_1 __pyx_number_tab[1] +#define __pyx_int_3 __pyx_number_tab[2] +/* #### Code section: module_state_clear ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_clear(PyObject *m) { + __pyx_mstatetype *clear_module_state = __Pyx_PyModule_GetState(m); + if (!clear_module_state) return 0; + Py_CLEAR(clear_module_state->__pyx_d); + Py_CLEAR(clear_module_state->__pyx_b); + Py_CLEAR(clear_module_state->__pyx_cython_runtime); + Py_CLEAR(clear_module_state->__pyx_empty_tuple); + Py_CLEAR(clear_module_state->__pyx_empty_bytes); + Py_CLEAR(clear_module_state->__pyx_empty_unicode); + #if CYTHON_PEP489_MULTI_PHASE_INIT + __Pyx_State_RemoveModule(NULL); + #endif + Py_CLEAR(clear_module_state->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr); + Py_CLEAR(clear_module_state->__pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr); + Py_CLEAR(clear_module_state->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr); + Py_CLEAR(clear_module_state->__pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr); + Py_CLEAR(clear_module_state->__pyx_umethod_PyDict_Type_items.method); + Py_CLEAR(clear_module_state->__pyx_umethod_PyDict_Type_pop.method); + Py_CLEAR(clear_module_state->__pyx_umethod_PyDict_Type_values.method); + Py_CLEAR(clear_module_state->__pyx_umethod_PyList_Type_pop.method); + for (int i=0; i<1; ++i) { Py_CLEAR(clear_module_state->__pyx_slice[i]); } + for (int i=0; i<1; ++i) { Py_CLEAR(clear_module_state->__pyx_tuple[i]); } + for (int i=0; i<10; ++i) { Py_CLEAR(clear_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<151; ++i) { Py_CLEAR(clear_module_state->__pyx_string_tab[i]); } + for (int i=0; i<3; ++i) { Py_CLEAR(clear_module_state->__pyx_number_tab[i]); } +/* #### Code section: module_state_clear_contents ### */ +/* CommonTypesMetaclass.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_CommonTypesMetaclassType); + +/* CythonFunctionPerModule.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_CyFunctionType); + +/* Generator.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_GeneratorType); + +/* #### Code section: module_state_clear_end ### */ +return 0; +} +#endif +/* #### Code section: module_state_traverse ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_traverse(PyObject *m, visitproc visit, void *arg) { + __pyx_mstatetype *traverse_module_state = __Pyx_PyModule_GetState(m); + if (!traverse_module_state) return 0; + Py_VISIT(traverse_module_state->__pyx_d); + Py_VISIT(traverse_module_state->__pyx_b); + Py_VISIT(traverse_module_state->__pyx_cython_runtime); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_tuple); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_bytes); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_unicode); + Py_VISIT(traverse_module_state->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr); + Py_VISIT(traverse_module_state->__pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr); + Py_VISIT(traverse_module_state->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr); + Py_VISIT(traverse_module_state->__pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr); + Py_VISIT(traverse_module_state->__pyx_umethod_PyDict_Type_items.method); + Py_VISIT(traverse_module_state->__pyx_umethod_PyDict_Type_pop.method); + Py_VISIT(traverse_module_state->__pyx_umethod_PyDict_Type_values.method); + Py_VISIT(traverse_module_state->__pyx_umethod_PyList_Type_pop.method); + for (int i=0; i<1; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_slice[i]); } + for (int i=0; i<1; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_tuple[i]); } + for (int i=0; i<10; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<151; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_string_tab[i]); } + for (int i=0; i<3; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_number_tab[i]); } +/* #### Code section: module_state_traverse_contents ### */ +/* CommonTypesMetaclass.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_CommonTypesMetaclassType); + +/* CythonFunctionPerModule.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_CyFunctionType); + +/* Generator.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_GeneratorType); + +/* #### Code section: module_state_traverse_end ### */ +return 0; +} +#endif +/* #### Code section: module_code ### */ + +/* "fontTools/qu2cu/qu2cu.py":40 + * + * # Copied from cu2qu + * @cython.cfunc # <<<<<<<<<<<<<< + * @cython.returns(cython.int) + * @cython.locals( +*/ + +static int __pyx_f_9fontTools_5qu2cu_5qu2cu_cubic_farthest_fit_inside(__pyx_t_double_complex __pyx_v_p0, __pyx_t_double_complex __pyx_v_p1, __pyx_t_double_complex __pyx_v_p2, __pyx_t_double_complex __pyx_v_p3, double __pyx_v_tolerance) { + __pyx_t_double_complex __pyx_v_mid; + __pyx_t_double_complex __pyx_v_deriv3; + int __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "fontTools/qu2cu/qu2cu.py":69 + * """ + * # First check p2 then p1, as p2 has higher error early on. + * if abs(p2) <= tolerance and abs(p1) <= tolerance: # <<<<<<<<<<<<<< + * return True + * +*/ + __pyx_t_2 = (__Pyx_c_abs_double(__pyx_v_p2) <= __pyx_v_tolerance); + + if (__pyx_t_2) { + + } else { + + __pyx_t_1 = __pyx_t_2; + + goto __pyx_L4_bool_binop_done; + } + __pyx_t_2 = (__Pyx_c_abs_double(__pyx_v_p1) <= __pyx_v_tolerance); + + + __pyx_t_1 = __pyx_t_2; + + __pyx_L4_bool_binop_done:; + if (__pyx_t_1) { + + + /* "fontTools/qu2cu/qu2cu.py":70 + * # First check p2 then p1, as p2 has higher error early on. + * if abs(p2) <= tolerance and abs(p1) <= tolerance: + * return True # <<<<<<<<<<<<<< + * + * # Split. +*/ + { + + __pyx_r = 1; + } + goto __pyx_L0; + + /* "fontTools/qu2cu/qu2cu.py":69 + * """ + * # First check p2 then p1, as p2 has higher error early on. + * if abs(p2) <= tolerance and abs(p1) <= tolerance: # <<<<<<<<<<<<<< + * return True + * +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":73 + * + * # Split. + * mid = (p0 + 3 * (p1 + p2) + p3) * 0.125 # <<<<<<<<<<<<<< + * if abs(mid) > tolerance: + * return False +*/ + __pyx_v_mid = __Pyx_c_prod_double(__Pyx_c_sum_double(__Pyx_c_sum_double(__pyx_v_p0, __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(3, 0), __Pyx_c_sum_double(__pyx_v_p1, __pyx_v_p2))), __pyx_v_p3), __pyx_t_double_complex_from_parts(0.125, 0)); + + /* "fontTools/qu2cu/qu2cu.py":74 + * # Split. + * mid = (p0 + 3 * (p1 + p2) + p3) * 0.125 + * if abs(mid) > tolerance: # <<<<<<<<<<<<<< + * return False + * deriv3 = (p3 + p2 - p1 - p0) * 0.125 +*/ + __pyx_t_1 = (__Pyx_c_abs_double(__pyx_v_mid) > __pyx_v_tolerance); + + if (__pyx_t_1) { + + + /* "fontTools/qu2cu/qu2cu.py":75 + * mid = (p0 + 3 * (p1 + p2) + p3) * 0.125 + * if abs(mid) > tolerance: + * return False # <<<<<<<<<<<<<< + * deriv3 = (p3 + p2 - p1 - p0) * 0.125 + * return cubic_farthest_fit_inside( +*/ + { + + __pyx_r = 0; + } + goto __pyx_L0; + + /* "fontTools/qu2cu/qu2cu.py":74 + * # Split. + * mid = (p0 + 3 * (p1 + p2) + p3) * 0.125 + * if abs(mid) > tolerance: # <<<<<<<<<<<<<< + * return False + * deriv3 = (p3 + p2 - p1 - p0) * 0.125 +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":76 + * if abs(mid) > tolerance: + * return False + * deriv3 = (p3 + p2 - p1 - p0) * 0.125 # <<<<<<<<<<<<<< + * return cubic_farthest_fit_inside( + * p0, (p0 + p1) * 0.5, mid - deriv3, mid, tolerance +*/ + __pyx_v_deriv3 = __Pyx_c_prod_double(__Pyx_c_diff_double(__Pyx_c_diff_double(__Pyx_c_sum_double(__pyx_v_p3, __pyx_v_p2), __pyx_v_p1), __pyx_v_p0), __pyx_t_double_complex_from_parts(0.125, 0)); + + /* "fontTools/qu2cu/qu2cu.py":77 + * return False + * deriv3 = (p3 + p2 - p1 - p0) * 0.125 + * return cubic_farthest_fit_inside( # <<<<<<<<<<<<<< + * p0, (p0 + p1) * 0.5, mid - deriv3, mid, tolerance + * ) and cubic_farthest_fit_inside(mid, mid + deriv3, (p2 + p3) * 0.5, p3, tolerance) +*/ + __pyx_t_4 = __pyx_f_9fontTools_5qu2cu_5qu2cu_cubic_farthest_fit_inside(__pyx_v_p0, __Pyx_c_prod_double(__Pyx_c_sum_double(__pyx_v_p0, __pyx_v_p1), __pyx_t_double_complex_from_parts(0.5, 0)), __Pyx_c_diff_double(__pyx_v_mid, __pyx_v_deriv3), __pyx_v_mid, __pyx_v_tolerance); if (unlikely(__pyx_t_4 == ((int)-1) && PyErr_Occurred())) __PYX_ERR(0, 77, __pyx_L1_error) + if (__pyx_t_4) { + + } else { + + __pyx_t_3 = __pyx_t_4; + + goto __pyx_L7_bool_binop_done; + } + + /* "fontTools/qu2cu/qu2cu.py":79 + * return cubic_farthest_fit_inside( + * p0, (p0 + p1) * 0.5, mid - deriv3, mid, tolerance + * ) and cubic_farthest_fit_inside(mid, mid + deriv3, (p2 + p3) * 0.5, p3, tolerance) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_4 = __pyx_f_9fontTools_5qu2cu_5qu2cu_cubic_farthest_fit_inside(__pyx_v_mid, __Pyx_c_sum_double(__pyx_v_mid, __pyx_v_deriv3), __Pyx_c_prod_double(__Pyx_c_sum_double(__pyx_v_p2, __pyx_v_p3), __pyx_t_double_complex_from_parts(0.5, 0)), __pyx_v_p3, __pyx_v_tolerance); if (unlikely(__pyx_t_4 == ((int)-1) && PyErr_Occurred())) __PYX_ERR(0, 79, __pyx_L1_error) + + __pyx_t_3 = __pyx_t_4; + + __pyx_L7_bool_binop_done:; + { + __pyx_r = __pyx_t_3; + } + goto __pyx_L0; + + /* "fontTools/qu2cu/qu2cu.py":40 + * + * # Copied from cu2qu + * @cython.cfunc # <<<<<<<<<<<<<< + * @cython.returns(cython.int) + * @cython.locals( +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu.cubic_farthest_fit_inside", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + + + + return __pyx_r; +} + +/* "fontTools/qu2cu/qu2cu.py":82 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * p0=cython.complex, + * p1=cython.complex, +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9fontTools_5qu2cu_5qu2cu_1elevate_quadratic(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9fontTools_5qu2cu_5qu2cu_elevate_quadratic, "elevate_quadratic(double complex p0, double complex p1, double complex p2)\n\nGiven a quadratic bezier curve, return its degree-elevated cubic."); +static PyMethodDef __pyx_mdef_9fontTools_5qu2cu_5qu2cu_1elevate_quadratic = {"elevate_quadratic", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9fontTools_5qu2cu_5qu2cu_1elevate_quadratic, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_9fontTools_5qu2cu_5qu2cu_elevate_quadratic}; +static PyObject *__pyx_pw_9fontTools_5qu2cu_5qu2cu_1elevate_quadratic(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + __pyx_t_double_complex __pyx_v_p0; + __pyx_t_double_complex __pyx_v_p1; + __pyx_t_double_complex __pyx_v_p2; + #if !CYTHON_VECTORCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("elevate_quadratic (wrapper)", 0); + #if !CYTHON_VECTORCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_p0,&__pyx_mstate_global->__pyx_n_u_p1,&__pyx_mstate_global->__pyx_n_u_p2,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) __PYX_ERR(0, 82, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 82, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 82, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 82, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "elevate_quadratic", 0) < (0)) __PYX_ERR(0, 82, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 3; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("elevate_quadratic", 1, 3, 3, i); __PYX_ERR(0, 82, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 3)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 82, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 82, __pyx_L3_error) + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 82, __pyx_L3_error) + } + __pyx_v_p0 = __Pyx_PyComplex_As___pyx_t_double_complex(values[0]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 88, __pyx_L3_error) + __pyx_v_p1 = __Pyx_PyComplex_As___pyx_t_double_complex(values[1]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 88, __pyx_L3_error) + __pyx_v_p2 = __Pyx_PyComplex_As___pyx_t_double_complex(values[2]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 88, __pyx_L3_error) + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("elevate_quadratic", 1, 3, 3, __pyx_nargs); __PYX_ERR(0, 82, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu.elevate_quadratic", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9fontTools_5qu2cu_5qu2cu_elevate_quadratic(__pyx_self, __pyx_v_p0, __pyx_v_p1, __pyx_v_p2); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + + + + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_elevate_quadratic(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_p0, __pyx_t_double_complex __pyx_v_p1, __pyx_t_double_complex __pyx_v_p2) { + __pyx_t_double_complex __pyx_v_p1_2_3; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + __pyx_t_double_complex __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("elevate_quadratic", 0); + + /* "fontTools/qu2cu/qu2cu.py":92 + * + * # https://pomax.github.io/bezierinfo/#reordering + * p1_2_3 = p1 * (2 / 3) # <<<<<<<<<<<<<< + * return ( + * p0, +*/ + __pyx_v_p1_2_3 = __Pyx_c_prod_double(__pyx_v_p1, __pyx_t_double_complex_from_parts((2.0 / 3.0), 0)); + + /* "fontTools/qu2cu/qu2cu.py":94 + * p1_2_3 = p1 * (2 / 3) + * return ( + * p0, # <<<<<<<<<<<<<< + * (p0 * (1 / 3) + p1_2_3), + * (p2 * (1 / 3) + p1_2_3), +*/ + __pyx_t_1 = __pyx_PyComplex_FromComplex(__pyx_v_p0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 94, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + + /* "fontTools/qu2cu/qu2cu.py":95 + * return ( + * p0, + * (p0 * (1 / 3) + p1_2_3), # <<<<<<<<<<<<<< + * (p2 * (1 / 3) + p1_2_3), + * p2, +*/ + __pyx_t_2 = __Pyx_c_sum_double(__Pyx_c_prod_double(__pyx_v_p0, __pyx_t_double_complex_from_parts((1.0 / 3.0), 0)), __pyx_v_p1_2_3); + + __pyx_t_3 = __pyx_PyComplex_FromComplex(__pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 95, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + + + /* "fontTools/qu2cu/qu2cu.py":96 + * p0, + * (p0 * (1 / 3) + p1_2_3), + * (p2 * (1 / 3) + p1_2_3), # <<<<<<<<<<<<<< + * p2, + * ) +*/ + __pyx_t_2 = __Pyx_c_sum_double(__Pyx_c_prod_double(__pyx_v_p2, __pyx_t_double_complex_from_parts((1.0 / 3.0), 0)), __pyx_v_p1_2_3); + + __pyx_t_4 = __pyx_PyComplex_FromComplex(__pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 96, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + + + /* "fontTools/qu2cu/qu2cu.py":97 + * (p0 * (1 / 3) + p1_2_3), + * (p2 * (1 / 3) + p1_2_3), + * p2, # <<<<<<<<<<<<<< + * ) + * +*/ + __pyx_t_5 = __pyx_PyComplex_FromComplex(__pyx_v_p2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 97, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + + /* "fontTools/qu2cu/qu2cu.py":94 + * p1_2_3 = p1 * (2 / 3) + * return ( + * p0, # <<<<<<<<<<<<<< + * (p0 * (1 / 3) + p1_2_3), + * (p2 * (1 / 3) + p1_2_3), +*/ + __pyx_t_6 = PyTuple_New(4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 94, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1) != (0)) __PYX_ERR(0, 94, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_3); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_3) != (0)) __PYX_ERR(0, 94, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_4); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_6, 2, __pyx_t_4) != (0)) __PYX_ERR(0, 94, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_5); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_6, 3, __pyx_t_5) != (0)) __PYX_ERR(0, 94, __pyx_L1_error); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_5 = 0; + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __pyx_r = __pyx_t_6; + } + __Pyx_XDECREF(__pyx_temp); + } + __pyx_t_6 = 0; + goto __pyx_L0; + + /* "fontTools/qu2cu/qu2cu.py":82 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * p0=cython.complex, + * p1=cython.complex, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu.elevate_quadratic", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/qu2cu/qu2cu.py":101 + * + * + * @cython.cfunc # <<<<<<<<<<<<<< + * @cython.locals( + * start=cython.int, +*/ + +static PyObject *__pyx_f_9fontTools_5qu2cu_5qu2cu_merge_curves(PyObject *__pyx_v_curves, int __pyx_v_start, int __pyx_v_n) { + int __pyx_v_k; + double __pyx_v_prod_ratio; + double __pyx_v_sum_ratio; + double __pyx_v_ratio; + __pyx_t_double_complex __pyx_v_p0; + __pyx_t_double_complex __pyx_v_p1; + __pyx_t_double_complex __pyx_v_p2; + __pyx_t_double_complex __pyx_v_p3; + PyObject *__pyx_v_ts = NULL; + PyObject *__pyx_v_ck = NULL; + PyObject *__pyx_v_c_before = NULL; + PyObject *__pyx_v_curve = NULL; + double __pyx_7genexpr__pyx_v_t; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + long __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + int __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + double __pyx_t_11; + int __pyx_t_12; + Py_ssize_t __pyx_t_13; + __pyx_t_double_complex __pyx_t_14; + PyObject *__pyx_t_15 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("merge_curves", 0); + + /* "fontTools/qu2cu/qu2cu.py":121 + * + * # Reconstruct the t values of the cut segments + * prod_ratio = 1.0 # <<<<<<<<<<<<<< + * sum_ratio = 1.0 + * ts = [1] +*/ + __pyx_v_prod_ratio = 1.0; + + /* "fontTools/qu2cu/qu2cu.py":122 + * # Reconstruct the t values of the cut segments + * prod_ratio = 1.0 + * sum_ratio = 1.0 # <<<<<<<<<<<<<< + * ts = [1] + * for k in range(1, n): +*/ + __pyx_v_sum_ratio = 1.0; + + /* "fontTools/qu2cu/qu2cu.py":123 + * prod_ratio = 1.0 + * sum_ratio = 1.0 + * ts = [1] # <<<<<<<<<<<<<< + * for k in range(1, n): + * ck = curves[start + k] +*/ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 123, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_1); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_1); + if (__Pyx_PyList_SET_ITEM(__pyx_t_1, 0, __pyx_mstate_global->__pyx_int_1) != (0)) __PYX_ERR(0, 123, __pyx_L1_error); + __pyx_v_ts = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "fontTools/qu2cu/qu2cu.py":124 + * sum_ratio = 1.0 + * ts = [1] + * for k in range(1, n): # <<<<<<<<<<<<<< + * ck = curves[start + k] + * c_before = curves[start + k - 1] +*/ + + __pyx_t_2 = __pyx_v_n; + __pyx_t_3 = __pyx_t_2; + + for (__pyx_t_4 = 1; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_k = __pyx_t_4; + + /* "fontTools/qu2cu/qu2cu.py":125 + * ts = [1] + * for k in range(1, n): + * ck = curves[start + k] # <<<<<<<<<<<<<< + * c_before = curves[start + k - 1] + * +*/ + __pyx_t_5 = (__pyx_v_start + __pyx_v_k); + + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_curves, __pyx_t_5, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 125, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + + __Pyx_XDECREF_SET(__pyx_v_ck, __pyx_t_1); + __pyx_t_1 = 0; + + /* "fontTools/qu2cu/qu2cu.py":126 + * for k in range(1, n): + * ck = curves[start + k] + * c_before = curves[start + k - 1] # <<<<<<<<<<<<<< + * + * # |t_(k+1) - t_k| / |t_k - t_(k - 1)| = ratio +*/ + __pyx_t_6 = ((__pyx_v_start + __pyx_v_k) - 1); + + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_curves, __pyx_t_6, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + + __Pyx_XDECREF_SET(__pyx_v_c_before, __pyx_t_1); + __pyx_t_1 = 0; + + /* "fontTools/qu2cu/qu2cu.py":129 + * + * # |t_(k+1) - t_k| / |t_k - t_(k - 1)| = ratio + * assert ck[0] == c_before[3] # <<<<<<<<<<<<<< + * ratio = abs(ck[1] - ck[0]) / abs(c_before[3] - c_before[2]) + * +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_ck, 0, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 129, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_GetItemInt(__pyx_v_c_before, 3, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 129, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = __Pyx_PyObject_CompareBoolEq_object_object(__pyx_t_1, __pyx_t_7, Py_EQ); if (unlikely((__pyx_t_8 < 0))) __PYX_ERR(0, 129, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_8)) { + __Pyx_Raise(((PyObject *)(((PyTypeObject*)PyExc_AssertionError))), 0, 0, 0); + __PYX_ERR(0, 129, __pyx_L1_error) + } + + } + #else + if ((1)); else __PYX_ERR(0, 129, __pyx_L1_error) + #endif + + /* "fontTools/qu2cu/qu2cu.py":130 + * # |t_(k+1) - t_k| / |t_k - t_(k - 1)| = ratio + * assert ck[0] == c_before[3] + * ratio = abs(ck[1] - ck[0]) / abs(c_before[3] - c_before[2]) # <<<<<<<<<<<<<< + * + * prod_ratio *= ratio +*/ + __pyx_t_7 = __Pyx_GetItemInt(__pyx_v_ck, 1, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_ck, 0, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_9 = __Pyx_PyNumber_Subtract_object_object(__pyx_t_7, __pyx_t_1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyNumber_Absolute(__pyx_t_9); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_GetItemInt(__pyx_v_c_before, 3, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_7 = __Pyx_GetItemInt(__pyx_v_c_before, 2, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_10 = __Pyx_PyNumber_Subtract_object_object(__pyx_t_9, __pyx_t_7); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyNumber_Absolute(__pyx_t_10); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_10 = __Pyx_PyNumber_Divide(__pyx_t_1, __pyx_t_7); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_11 = __Pyx_PyFloat_AsDouble(__pyx_t_10); if (unlikely((__pyx_t_11 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_v_ratio = __pyx_t_11; + + /* "fontTools/qu2cu/qu2cu.py":132 + * ratio = abs(ck[1] - ck[0]) / abs(c_before[3] - c_before[2]) + * + * prod_ratio *= ratio # <<<<<<<<<<<<<< + * sum_ratio += prod_ratio + * ts.append(sum_ratio) +*/ + __pyx_v_prod_ratio = (__pyx_v_prod_ratio * __pyx_v_ratio); + + /* "fontTools/qu2cu/qu2cu.py":133 + * + * prod_ratio *= ratio + * sum_ratio += prod_ratio # <<<<<<<<<<<<<< + * ts.append(sum_ratio) + * +*/ + __pyx_v_sum_ratio = (__pyx_v_sum_ratio + __pyx_v_prod_ratio); + + /* "fontTools/qu2cu/qu2cu.py":134 + * prod_ratio *= ratio + * sum_ratio += prod_ratio + * ts.append(sum_ratio) # <<<<<<<<<<<<<< + * + * # (t(n) - t(n - 1)) / (t_(1) - t(0)) = prod_ratio +*/ + __pyx_t_10 = PyFloat_FromDouble(__pyx_v_sum_ratio); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 134, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_12 = __Pyx_PyList_Append(__pyx_v_ts, __pyx_t_10); if (unlikely(__pyx_t_12 == ((int)-1))) __PYX_ERR(0, 134, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + + } + + + /* "fontTools/qu2cu/qu2cu.py":138 + * # (t(n) - t(n - 1)) / (t_(1) - t(0)) = prod_ratio + * + * ts = [t / sum_ratio for t in ts[:-1]] # <<<<<<<<<<<<<< + * + * p0 = curves[start][0] +*/ + { /* enter inner scope */ + __pyx_t_10 = PyList_New(0); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_7 = __Pyx_PyList_GetSlice(__pyx_v_ts, 0, -1L); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_1 = __pyx_t_7; __Pyx_INCREF(__pyx_t_1); + __pyx_t_13 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + for (;;) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 138, __pyx_L1_error) + #endif + if (__pyx_t_13 >= __pyx_temp) break; + } + __pyx_t_7 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_1, __pyx_t_13, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_13; + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_11 = __Pyx_PyFloat_AsDouble(__pyx_t_7); if (unlikely((__pyx_t_11 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_7genexpr__pyx_v_t = __pyx_t_11; + if (unlikely(__pyx_v_sum_ratio == 0)) { + PyErr_SetString(PyExc_ZeroDivisionError, "float division"); + __PYX_ERR(0, 138, __pyx_L1_error) + } + __pyx_t_7 = PyFloat_FromDouble((__pyx_7genexpr__pyx_v_t / __pyx_v_sum_ratio)); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + if (unlikely(__Pyx_ListComp_AppendAndDecref(__pyx_t_10, __pyx_t_7))) __PYX_ERR(0, 138, __pyx_L1_error) + __pyx_t_7 = 0; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } /* exit inner scope */ + __Pyx_DECREF_SET(__pyx_v_ts, ((PyObject*)__pyx_t_10)); + __pyx_t_10 = 0; + + /* "fontTools/qu2cu/qu2cu.py":140 + * ts = [t / sum_ratio for t in ts[:-1]] + * + * p0 = curves[start][0] # <<<<<<<<<<<<<< + * p1 = curves[start][1] + * p2 = curves[start + n - 1][2] +*/ + __pyx_t_10 = __Pyx_GetItemInt(__pyx_v_curves, __pyx_v_start, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 140, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_10, 0, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 140, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_14 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_1); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 140, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_p0 = __pyx_t_14; + + /* "fontTools/qu2cu/qu2cu.py":141 + * + * p0 = curves[start][0] + * p1 = curves[start][1] # <<<<<<<<<<<<<< + * p2 = curves[start + n - 1][2] + * p3 = curves[start + n - 1][3] +*/ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_curves, __pyx_v_start, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 141, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_10 = __Pyx_GetItemInt(__pyx_t_1, 1, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 141, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_14 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_10); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 141, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_v_p1 = __pyx_t_14; + + /* "fontTools/qu2cu/qu2cu.py":142 + * p0 = curves[start][0] + * p1 = curves[start][1] + * p2 = curves[start + n - 1][2] # <<<<<<<<<<<<<< + * p3 = curves[start + n - 1][3] + * +*/ + __pyx_t_6 = ((__pyx_v_start + __pyx_v_n) - 1); + + __pyx_t_10 = __Pyx_GetItemInt(__pyx_v_curves, __pyx_t_6, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + + __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_10, 2, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_14 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_1); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_p2 = __pyx_t_14; + + /* "fontTools/qu2cu/qu2cu.py":143 + * p1 = curves[start][1] + * p2 = curves[start + n - 1][2] + * p3 = curves[start + n - 1][3] # <<<<<<<<<<<<<< + * + * # Build the curve by scaling the control-points. +*/ + __pyx_t_6 = ((__pyx_v_start + __pyx_v_n) - 1); + + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_curves, __pyx_t_6, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 143, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + + __pyx_t_10 = __Pyx_GetItemInt(__pyx_t_1, 3, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 143, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_14 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_10); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 143, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_v_p3 = __pyx_t_14; + + /* "fontTools/qu2cu/qu2cu.py":146 + * + * # Build the curve by scaling the control-points. + * p1 = p0 + (p1 - p0) / (ts[0] if ts else 1) # <<<<<<<<<<<<<< + * p2 = p3 + (p2 - p3) / ((1 - ts[-1]) if ts else 1) + * +*/ + __pyx_t_10 = __pyx_PyComplex_FromComplex(__pyx_v_p0); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 146, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_14 = __Pyx_c_diff_double(__pyx_v_p1, __pyx_v_p0); + + __pyx_t_1 = __pyx_PyComplex_FromComplex(__pyx_t_14); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 146, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_v_ts); + if (unlikely(((!CYTHON_ASSUME_SAFE_SIZE) && __pyx_temp < 0))) __PYX_ERR(0, 146, __pyx_L1_error) + __pyx_t_8 = (__pyx_temp != 0); + } + + if (__pyx_t_8) { + __pyx_t_9 = __Pyx_GetItemInt_List(__pyx_v_ts, 0, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 146, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_7 = __pyx_t_9; + __pyx_t_9 = 0; + } else { + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_1); + __pyx_t_7 = __pyx_mstate_global->__pyx_int_1; + } + + __pyx_t_9 = __Pyx_PyNumber_Divide(__pyx_t_1, __pyx_t_7); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 146, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyNumber_Add(__pyx_t_10, __pyx_t_9); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 146, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_14 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_7); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 146, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_v_p1 = __pyx_t_14; + + /* "fontTools/qu2cu/qu2cu.py":147 + * # Build the curve by scaling the control-points. + * p1 = p0 + (p1 - p0) / (ts[0] if ts else 1) + * p2 = p3 + (p2 - p3) / ((1 - ts[-1]) if ts else 1) # <<<<<<<<<<<<<< + * + * curve = (p0, p1, p2, p3) +*/ + __pyx_t_7 = __pyx_PyComplex_FromComplex(__pyx_v_p3); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_14 = __Pyx_c_diff_double(__pyx_v_p2, __pyx_v_p3); + + __pyx_t_9 = __pyx_PyComplex_FromComplex(__pyx_t_14); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_v_ts); + if (unlikely(((!CYTHON_ASSUME_SAFE_SIZE) && __pyx_temp < 0))) __PYX_ERR(0, 147, __pyx_L1_error) + __pyx_t_8 = (__pyx_temp != 0); + } + + if (__pyx_t_8) { + __pyx_t_1 = __Pyx_GetItemInt_List(__pyx_v_ts, -1L, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_15 = __Pyx_PyLong_SubtractCObj(__pyx_mstate_global->__pyx_int_1, __pyx_t_1, 1, 0, 0); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_10 = __pyx_t_15; + __pyx_t_15 = 0; + } else { + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_1); + __pyx_t_10 = __pyx_mstate_global->__pyx_int_1; + } + + __pyx_t_15 = __Pyx_PyNumber_Divide(__pyx_t_9, __pyx_t_10); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_10 = PyNumber_Add(__pyx_t_7, __pyx_t_15); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_t_14 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_10); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_v_p2 = __pyx_t_14; + + /* "fontTools/qu2cu/qu2cu.py":149 + * p2 = p3 + (p2 - p3) / ((1 - ts[-1]) if ts else 1) + * + * curve = (p0, p1, p2, p3) # <<<<<<<<<<<<<< + * + * return curve, ts +*/ + __pyx_t_10 = __pyx_PyComplex_FromComplex(__pyx_v_p0); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 149, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_15 = __pyx_PyComplex_FromComplex(__pyx_v_p1); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 149, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __pyx_t_7 = __pyx_PyComplex_FromComplex(__pyx_v_p2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 149, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_9 = __pyx_PyComplex_FromComplex(__pyx_v_p3); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 149, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = PyTuple_New(4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 149, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_10); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_10) != (0)) __PYX_ERR(0, 149, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_15); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_15) != (0)) __PYX_ERR(0, 149, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_7); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_t_7) != (0)) __PYX_ERR(0, 149, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_9); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 3, __pyx_t_9) != (0)) __PYX_ERR(0, 149, __pyx_L1_error); + __pyx_t_10 = 0; + __pyx_t_15 = 0; + __pyx_t_7 = 0; + __pyx_t_9 = 0; + __pyx_v_curve = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "fontTools/qu2cu/qu2cu.py":151 + * curve = (p0, p1, p2, p3) + * + * return curve, ts # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 151, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_curve); + __Pyx_GIVEREF(__pyx_v_curve); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_curve) != (0)) __PYX_ERR(0, 151, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_ts); + __Pyx_GIVEREF(__pyx_v_ts); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_ts) != (0)) __PYX_ERR(0, 151, __pyx_L1_error); + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __pyx_r = __pyx_t_1; + } + __Pyx_XDECREF(__pyx_temp); + } + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "fontTools/qu2cu/qu2cu.py":101 + * + * + * @cython.cfunc # <<<<<<<<<<<<<< + * @cython.locals( + * start=cython.int, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_15); + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu.merge_curves", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + + + + + + + + + __Pyx_XDECREF(__pyx_v_ts); + __Pyx_XDECREF(__pyx_v_ck); + __Pyx_XDECREF(__pyx_v_c_before); + __Pyx_XDECREF(__pyx_v_curve); + + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/qu2cu/qu2cu.py":154 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * count=cython.int, + * num_offcurves=cython.int, +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9fontTools_5qu2cu_5qu2cu_3add_implicit_on_curves(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9fontTools_5qu2cu_5qu2cu_2add_implicit_on_curves, "add_implicit_on_curves(p)"); +static PyMethodDef __pyx_mdef_9fontTools_5qu2cu_5qu2cu_3add_implicit_on_curves = {"add_implicit_on_curves", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9fontTools_5qu2cu_5qu2cu_3add_implicit_on_curves, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_9fontTools_5qu2cu_5qu2cu_2add_implicit_on_curves}; +static PyObject *__pyx_pw_9fontTools_5qu2cu_5qu2cu_3add_implicit_on_curves(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_p = 0; + #if !CYTHON_VECTORCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("add_implicit_on_curves (wrapper)", 0); + #if !CYTHON_VECTORCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_p,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) __PYX_ERR(0, 154, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 154, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "add_implicit_on_curves", 0) < (0)) __PYX_ERR(0, 154, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("add_implicit_on_curves", 1, 1, 1, i); __PYX_ERR(0, 154, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 154, __pyx_L3_error) + } + __pyx_v_p = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("add_implicit_on_curves", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 154, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu.add_implicit_on_curves", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9fontTools_5qu2cu_5qu2cu_2add_implicit_on_curves(__pyx_self, __pyx_v_p); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_2add_implicit_on_curves(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_p) { + int __pyx_v_count; + int __pyx_v_num_offcurves; + int __pyx_v_i; + __pyx_t_double_complex __pyx_v_off1; + __pyx_t_double_complex __pyx_v_off2; + __pyx_t_double_complex __pyx_v_on; + PyObject *__pyx_v_q = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + __pyx_t_double_complex __pyx_t_6; + long __pyx_t_7; + int __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("add_implicit_on_curves", 0); + + /* "fontTools/qu2cu/qu2cu.py":163 + * ) + * def add_implicit_on_curves(p): + * q = list(p) # <<<<<<<<<<<<<< + * count = 0 + * num_offcurves = len(p) - 2 +*/ + __pyx_t_1 = PySequence_List(__pyx_v_p); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_q = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "fontTools/qu2cu/qu2cu.py":164 + * def add_implicit_on_curves(p): + * q = list(p) + * count = 0 # <<<<<<<<<<<<<< + * num_offcurves = len(p) - 2 + * for i in range(1, num_offcurves): +*/ + __pyx_v_count = 0; + + /* "fontTools/qu2cu/qu2cu.py":165 + * q = list(p) + * count = 0 + * num_offcurves = len(p) - 2 # <<<<<<<<<<<<<< + * for i in range(1, num_offcurves): + * off1 = p[i] +*/ + __pyx_t_2 = PyObject_Length(__pyx_v_p); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 165, __pyx_L1_error) + __pyx_v_num_offcurves = (__pyx_t_2 - 2); + + + /* "fontTools/qu2cu/qu2cu.py":166 + * count = 0 + * num_offcurves = len(p) - 2 + * for i in range(1, num_offcurves): # <<<<<<<<<<<<<< + * off1 = p[i] + * off2 = p[i + 1] +*/ + + __pyx_t_3 = __pyx_v_num_offcurves; + __pyx_t_4 = __pyx_t_3; + + for (__pyx_t_5 = 1; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "fontTools/qu2cu/qu2cu.py":167 + * num_offcurves = len(p) - 2 + * for i in range(1, num_offcurves): + * off1 = p[i] # <<<<<<<<<<<<<< + * off2 = p[i + 1] + * on = off1 + (off2 - off1) * 0.5 +*/ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_p, __pyx_v_i, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 167, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_1); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 167, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_off1 = __pyx_t_6; + + /* "fontTools/qu2cu/qu2cu.py":168 + * for i in range(1, num_offcurves): + * off1 = p[i] + * off2 = p[i + 1] # <<<<<<<<<<<<<< + * on = off1 + (off2 - off1) * 0.5 + * q.insert(i + 1 + count, on) +*/ + __pyx_t_7 = (__pyx_v_i + 1); + + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_p, __pyx_t_7, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 168, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + + __pyx_t_6 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_1); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 168, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_off2 = __pyx_t_6; + + /* "fontTools/qu2cu/qu2cu.py":169 + * off1 = p[i] + * off2 = p[i + 1] + * on = off1 + (off2 - off1) * 0.5 # <<<<<<<<<<<<<< + * q.insert(i + 1 + count, on) + * count += 1 +*/ + __pyx_v_on = __Pyx_c_sum_double(__pyx_v_off1, __Pyx_c_prod_double(__Pyx_c_diff_double(__pyx_v_off2, __pyx_v_off1), __pyx_t_double_complex_from_parts(0.5, 0))); + + /* "fontTools/qu2cu/qu2cu.py":170 + * off2 = p[i + 1] + * on = off1 + (off2 - off1) * 0.5 + * q.insert(i + 1 + count, on) # <<<<<<<<<<<<<< + * count += 1 + * return q +*/ + __pyx_t_1 = __pyx_PyComplex_FromComplex(__pyx_v_on); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 170, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_8 = PyList_Insert(__pyx_v_q, ((__pyx_v_i + 1) + __pyx_v_count), __pyx_t_1); if (unlikely(__pyx_t_8 == ((int)-1))) __PYX_ERR(0, 170, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + + /* "fontTools/qu2cu/qu2cu.py":171 + * on = off1 + (off2 - off1) * 0.5 + * q.insert(i + 1 + count, on) + * count += 1 # <<<<<<<<<<<<<< + * return q + * +*/ + __pyx_v_count = (__pyx_v_count + 1); + } + + + /* "fontTools/qu2cu/qu2cu.py":172 + * q.insert(i + 1 + count, on) + * count += 1 + * return q # <<<<<<<<<<<<<< + * + * +*/ + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(__pyx_v_q); + __pyx_r = __pyx_v_q; + } + __Pyx_XDECREF(__pyx_temp); + } + goto __pyx_L0; + + /* "fontTools/qu2cu/qu2cu.py":154 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * count=cython.int, + * num_offcurves=cython.int, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu.add_implicit_on_curves", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + + + + + + + __Pyx_XDECREF(__pyx_v_q); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/qu2cu/qu2cu.py":178 + * + * + * def _raise_incompatible_point(point, previous_point): # <<<<<<<<<<<<<< + * raise ValueError( + * f"Quadratic splines must connect end-to-start; got {previous_point!r} then {point!r}" +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9fontTools_5qu2cu_5qu2cu_5_raise_incompatible_point(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9fontTools_5qu2cu_5qu2cu_4_raise_incompatible_point, "_raise_incompatible_point(point, previous_point)"); +static PyMethodDef __pyx_mdef_9fontTools_5qu2cu_5qu2cu_5_raise_incompatible_point = {"_raise_incompatible_point", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9fontTools_5qu2cu_5qu2cu_5_raise_incompatible_point, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_9fontTools_5qu2cu_5qu2cu_4_raise_incompatible_point}; +static PyObject *__pyx_pw_9fontTools_5qu2cu_5qu2cu_5_raise_incompatible_point(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_point = 0; + PyObject *__pyx_v_previous_point = 0; + #if !CYTHON_VECTORCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_raise_incompatible_point (wrapper)", 0); + #if !CYTHON_VECTORCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_point,&__pyx_mstate_global->__pyx_n_u_previous_point,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) __PYX_ERR(0, 178, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 178, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 178, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "_raise_incompatible_point", 0) < (0)) __PYX_ERR(0, 178, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("_raise_incompatible_point", 1, 2, 2, i); __PYX_ERR(0, 178, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 2)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 178, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 178, __pyx_L3_error) + } + __pyx_v_point = values[0]; + __pyx_v_previous_point = values[1]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_raise_incompatible_point", 1, 2, 2, __pyx_nargs); __PYX_ERR(0, 178, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu._raise_incompatible_point", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9fontTools_5qu2cu_5qu2cu_4_raise_incompatible_point(__pyx_self, __pyx_v_point, __pyx_v_previous_point); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_4_raise_incompatible_point(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_point, PyObject *__pyx_v_previous_point) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5[4]; + Py_ssize_t __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + size_t __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_raise_incompatible_point", 0); + + /* "fontTools/qu2cu/qu2cu.py":179 + * + * def _raise_incompatible_point(point, previous_point): + * raise ValueError( # <<<<<<<<<<<<<< + * f"Quadratic splines must connect end-to-start; got {previous_point!r} then {point!r}" + * ) +*/ + __pyx_t_2 = NULL; + + /* "fontTools/qu2cu/qu2cu.py":180 + * def _raise_incompatible_point(point, previous_point): + * raise ValueError( + * f"Quadratic splines must connect end-to-start; got {previous_point!r} then {point!r}" # <<<<<<<<<<<<<< + * ) + * +*/ + __pyx_t_3 = __Pyx_PyObject_FormatSimpleAndDecref(PyObject_Repr(__pyx_v_previous_point), __pyx_mstate_global->__pyx_empty_unicode); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 180, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_FormatSimpleAndDecref(PyObject_Repr(__pyx_v_point), __pyx_mstate_global->__pyx_empty_unicode); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 180, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5[0] = __pyx_mstate_global->__pyx_kp_u_Quadratic_splines_must_connect_e; + __pyx_t_5[1] = __pyx_t_3; + __pyx_t_5[2] = __pyx_mstate_global->__pyx_kp_u_then; + __pyx_t_5[3] = __pyx_t_4; + __pyx_t_6 = 55; + #if __Pyx_PyUnicode_Join_CAN_USE_KIND_AND_LENGTH + __pyx_t_6 += __Pyx_PyUnicode_GET_LENGTH(__pyx_t_5[1]) + __Pyx_PyUnicode_GET_LENGTH(__pyx_t_5[3]); + #endif + __pyx_t_7 = 0; + #if __Pyx_PyUnicode_Join_CAN_USE_KIND_AND_LENGTH + __pyx_t_7 |= __Pyx_PyUnicode_KIND_04(__pyx_t_5[1]) | __Pyx_PyUnicode_KIND_04(__pyx_t_5[3]); + #endif + __pyx_t_8 = __Pyx_PyUnicode_Join(__pyx_t_5, 4, __pyx_t_6, __pyx_t_7); + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 180, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_9 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_t_8}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)(((PyTypeObject*)PyExc_ValueError)), __pyx_callargs+__pyx_t_9, (2-__pyx_t_9) | (__pyx_t_9*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 179, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 179, __pyx_L1_error) + + /* "fontTools/qu2cu/qu2cu.py":178 + * + * + * def _raise_incompatible_point(point, previous_point): # <<<<<<<<<<<<<< + * raise ValueError( + * f"Quadratic splines must connect end-to-start; got {previous_point!r} then {point!r}" +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu._raise_incompatible_point", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/qu2cu/qu2cu.py":184 + * + * + * def _validate_spline_length(spline): # <<<<<<<<<<<<<< + * if len(spline) < 3: + * raise ValueError("Quadratic splines must contain at least 3 points") +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9fontTools_5qu2cu_5qu2cu_7_validate_spline_length(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9fontTools_5qu2cu_5qu2cu_6_validate_spline_length, "_validate_spline_length(spline)"); +static PyMethodDef __pyx_mdef_9fontTools_5qu2cu_5qu2cu_7_validate_spline_length = {"_validate_spline_length", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9fontTools_5qu2cu_5qu2cu_7_validate_spline_length, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_9fontTools_5qu2cu_5qu2cu_6_validate_spline_length}; +static PyObject *__pyx_pw_9fontTools_5qu2cu_5qu2cu_7_validate_spline_length(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_spline = 0; + #if !CYTHON_VECTORCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_validate_spline_length (wrapper)", 0); + #if !CYTHON_VECTORCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_spline,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) __PYX_ERR(0, 184, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 184, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "_validate_spline_length", 0) < (0)) __PYX_ERR(0, 184, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("_validate_spline_length", 1, 1, 1, i); __PYX_ERR(0, 184, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 184, __pyx_L3_error) + } + __pyx_v_spline = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_validate_spline_length", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 184, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu._validate_spline_length", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9fontTools_5qu2cu_5qu2cu_6_validate_spline_length(__pyx_self, __pyx_v_spline); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_6_validate_spline_length(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_spline) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_validate_spline_length", 0); + + /* "fontTools/qu2cu/qu2cu.py":185 + * + * def _validate_spline_length(spline): + * if len(spline) < 3: # <<<<<<<<<<<<<< + * raise ValueError("Quadratic splines must contain at least 3 points") + * +*/ + __pyx_t_1 = PyObject_Length(__pyx_v_spline); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 185, __pyx_L1_error) + __pyx_t_2 = (__pyx_t_1 < 3); + + + if (unlikely(__pyx_t_2)) { + + + /* "fontTools/qu2cu/qu2cu.py":186 + * def _validate_spline_length(spline): + * if len(spline) < 3: + * raise ValueError("Quadratic splines must contain at least 3 points") # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_4 = NULL; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_Quadratic_splines_must_contain_a}; + __pyx_t_3 = __Pyx_PyObject_FastCall((PyObject*)(((PyTypeObject*)PyExc_ValueError)), __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 186, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 186, __pyx_L1_error) + + /* "fontTools/qu2cu/qu2cu.py":185 + * + * def _validate_spline_length(spline): + * if len(spline) < 3: # <<<<<<<<<<<<<< + * raise ValueError("Quadratic splines must contain at least 3 points") + * +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":184 + * + * + * def _validate_spline_length(spline): # <<<<<<<<<<<<<< + * if len(spline) < 3: + * raise ValueError("Quadratic splines must contain at least 3 points") +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu._validate_spline_length", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/qu2cu/qu2cu.py":189 + * + * + * def _validate_positive_tolerance(max_err): # <<<<<<<<<<<<<< + * if max_err <= 0: + * raise ValueError("max_err must be greater than zero") +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9fontTools_5qu2cu_5qu2cu_9_validate_positive_tolerance(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9fontTools_5qu2cu_5qu2cu_8_validate_positive_tolerance, "_validate_positive_tolerance(max_err)"); +static PyMethodDef __pyx_mdef_9fontTools_5qu2cu_5qu2cu_9_validate_positive_tolerance = {"_validate_positive_tolerance", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9fontTools_5qu2cu_5qu2cu_9_validate_positive_tolerance, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_9fontTools_5qu2cu_5qu2cu_8_validate_positive_tolerance}; +static PyObject *__pyx_pw_9fontTools_5qu2cu_5qu2cu_9_validate_positive_tolerance(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_max_err = 0; + #if !CYTHON_VECTORCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_validate_positive_tolerance (wrapper)", 0); + #if !CYTHON_VECTORCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_max_err,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) __PYX_ERR(0, 189, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 189, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "_validate_positive_tolerance", 0) < (0)) __PYX_ERR(0, 189, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("_validate_positive_tolerance", 1, 1, 1, i); __PYX_ERR(0, 189, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 189, __pyx_L3_error) + } + __pyx_v_max_err = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_validate_positive_tolerance", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 189, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu._validate_positive_tolerance", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9fontTools_5qu2cu_5qu2cu_8_validate_positive_tolerance(__pyx_self, __pyx_v_max_err); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_8_validate_positive_tolerance(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_max_err) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_validate_positive_tolerance", 0); + + /* "fontTools/qu2cu/qu2cu.py":190 + * + * def _validate_positive_tolerance(max_err): + * if max_err <= 0: # <<<<<<<<<<<<<< + * raise ValueError("max_err must be greater than zero") + * +*/ + __pyx_t_1 = __Pyx_PyObject_CompareBoolLe_object_int(__pyx_v_max_err, __pyx_mstate_global->__pyx_int_0, Py_LE); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 190, __pyx_L1_error) + if (unlikely(__pyx_t_1)) { + + + /* "fontTools/qu2cu/qu2cu.py":191 + * def _validate_positive_tolerance(max_err): + * if max_err <= 0: + * raise ValueError("max_err must be greater than zero") # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_3 = NULL; + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_max_err_must_be_greater_than_zer}; + __pyx_t_2 = __Pyx_PyObject_FastCall((PyObject*)(((PyTypeObject*)PyExc_ValueError)), __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 191, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 191, __pyx_L1_error) + + /* "fontTools/qu2cu/qu2cu.py":190 + * + * def _validate_positive_tolerance(max_err): + * if max_err <= 0: # <<<<<<<<<<<<<< + * raise ValueError("max_err must be greater than zero") + * +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":189 + * + * + * def _validate_positive_tolerance(max_err): # <<<<<<<<<<<<<< + * if max_err <= 0: + * raise ValueError("max_err must be greater than zero") +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu._validate_positive_tolerance", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/qu2cu/qu2cu.py":194 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * cost=cython.int, + * is_complex=cython.int, +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9fontTools_5qu2cu_5qu2cu_11quadratic_to_curves(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9fontTools_5qu2cu_5qu2cu_10quadratic_to_curves, "quadratic_to_curves(list quads: List[Sequence[Point]], double max_err: float = 0.5, bool all_cubic: bool = False) -> List[Tuple[Point, ...]]\n\nConverts a connecting list of quadratic splines to a list of quadratic\nand cubic curves.\n\nA quadratic spline is specified as a sequence of points. Either each point is\na 2-tuple of X,Y coordinates, or each point is a complex number with\nreal/imaginary components representing X,Y coordinates.\n\nThe first and last points are on-curve points and the rest are off-curve\npoints, with an implied on-curve point in the middle between every two\nconsequtive off-curve points.\n\nReturns:\n The output is a list of tuples of points. Points are represented\n in the same format as the input, either as 2-tuples or complex numbers.\n If ``quads`` is empty, returns an empty list.\n\n Each tuple is either of length three, for a quadratic curve, or four,\n for a cubic curve. Each curve\047s last point is the same as the next\n curve\047s first point.\n\nArgs:\n quads: quadratic splines\n\n max_err: absolute error tolerance; defaults to 0.5\n\n all_cubic: if True, only cubic curves are generated; defaults to False\n\nRaises:\n ValueError: if an input spline has fewer than 3 points, or if adjacent\n splines do not connect end-to-start."); +static PyMethodDef __pyx_mdef_9fontTools_5qu2cu_5qu2cu_11quadratic_to_curves = {"quadratic_to_curves", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9fontTools_5qu2cu_5qu2cu_11quadratic_to_curves, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_9fontTools_5qu2cu_5qu2cu_10quadratic_to_curves}; +static PyObject *__pyx_pw_9fontTools_5qu2cu_5qu2cu_11quadratic_to_curves(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_quads = 0; + double __pyx_v_max_err; + int __pyx_v_all_cubic; + #if !CYTHON_VECTORCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("quadratic_to_curves (wrapper)", 0); + #if !CYTHON_VECTORCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_quads,&__pyx_mstate_global->__pyx_n_u_max_err,&__pyx_mstate_global->__pyx_n_u_all_cubic,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) __PYX_ERR(0, 194, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 194, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 194, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 194, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "quadratic_to_curves", 0) < (0)) __PYX_ERR(0, 194, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("quadratic_to_curves", 0, 1, 3, i); __PYX_ERR(0, 194, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 194, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 194, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 194, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_quads = ((PyObject*)values[0]); + if (values[1]) { + __pyx_v_max_err = __Pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_max_err == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 200, __pyx_L3_error) + } else { + __pyx_v_max_err = ((double)((double)0.5)); + } + if (values[2]) { + __pyx_v_all_cubic = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_all_cubic == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 201, __pyx_L3_error) + } else { + + /* "fontTools/qu2cu/qu2cu.py":201 + * quads: List[Sequence[Point]], + * max_err: float = 0.5, + * all_cubic: bool = False, # <<<<<<<<<<<<<< + * ) -> List[Tuple[Point, ...]]: + * """Converts a connecting list of quadratic splines to a list of quadratic +*/ + __pyx_v_all_cubic = ((int)((int)0)); + } + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("quadratic_to_curves", 0, 1, 3, __pyx_nargs); __PYX_ERR(0, 194, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu.quadratic_to_curves", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_quads), (&PyList_Type), 0, "quads", 2))) __PYX_ERR(0, 199, __pyx_L1_error) + __pyx_r = __pyx_pf_9fontTools_5qu2cu_5qu2cu_10quadratic_to_curves(__pyx_self, __pyx_v_quads, __pyx_v_max_err, __pyx_v_all_cubic); + + /* "fontTools/qu2cu/qu2cu.py":194 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * cost=cython.int, + * is_complex=cython.int, +*/ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + + + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +static PyObject *__pyx_gb_9fontTools_5qu2cu_5qu2cu_19quadratic_to_curves_8genexpr3_2generator(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value); /* proto */ + +/* "fontTools/qu2cu/qu2cu.py":263 + * + * if not is_complex: + * curves = [tuple((c.real, c.imag) for c in curve) for curve in curves] # <<<<<<<<<<<<<< + * return curves + * +*/ + +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_19quadratic_to_curves_8genexpr3_genexpr(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_genexpr_arg_0) { + struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr *__pyx_cur_scope; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("genexpr", 0); + __pyx_cur_scope = (struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr *)__pyx_tp_new_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr(__pyx_mstate_global->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr, __pyx_mstate_global->__pyx_empty_tuple, NULL); + if (unlikely(!__pyx_cur_scope)) { + __pyx_cur_scope = ((struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr *)Py_None); + __Pyx_INCREF(Py_None); + __PYX_ERR(0, 263, __pyx_L1_error) + } else { + __Pyx_GOTREF((PyObject *)__pyx_cur_scope); + } + __pyx_cur_scope->__pyx_genexpr_arg_0 = __pyx_genexpr_arg_0; + __Pyx_INCREF(__pyx_cur_scope->__pyx_genexpr_arg_0); + __Pyx_GIVEREF(__pyx_cur_scope->__pyx_genexpr_arg_0); + { + __pyx_CoroutineObject *gen = __Pyx_Generator_New((__pyx_coroutine_body_t) __pyx_gb_9fontTools_5qu2cu_5qu2cu_19quadratic_to_curves_8genexpr3_2generator, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[0]), (PyObject *) __pyx_cur_scope, __pyx_mstate_global->__pyx_n_u_genexpr, __pyx_mstate_global->__pyx_n_u_quadratic_to_curves_locals_genex, __pyx_mstate_global->__pyx_n_u_fontTools_qu2cu_qu2cu); if (unlikely(!gen)) __PYX_ERR(0, 263, __pyx_L1_error) + __Pyx_DECREF(__pyx_cur_scope); + __Pyx_RefNannyFinishContext(); + return (PyObject *) gen; + } + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu.quadratic_to_curves.genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_DECREF((PyObject *)__pyx_cur_scope); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_gb_9fontTools_5qu2cu_5qu2cu_19quadratic_to_curves_8genexpr3_2generator(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value) /* generator body */ +{ + struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr *__pyx_cur_scope = ((struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr *)__pyx_generator->closure); + PyObject *__pyx_r = NULL; + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *(*__pyx_t_3)(PyObject *); + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("genexpr", 0); + switch (__pyx_generator->resume_label) { + case 0: goto __pyx_L3_first_run; + case 1: goto __pyx_L6_resume_from_yield; + default: /* CPython raises the right error here */ + __Pyx_RefNannyFinishContext(); + return NULL; + } + __pyx_L3_first_run:; + if (unlikely(__pyx_sent_value != Py_None)) { + if (unlikely(__pyx_sent_value)) PyErr_SetString(PyExc_TypeError, "can't send non-None value to a just-started generator"); + __PYX_ERR(0, 263, __pyx_L1_error) + } + if (unlikely(!__pyx_cur_scope->__pyx_genexpr_arg_0)) { __Pyx_RaiseUnboundLocalError(".0"); __PYX_ERR(0, 263, __pyx_L1_error) } + if (likely(PyList_CheckExact(__pyx_cur_scope->__pyx_genexpr_arg_0)) || PyTuple_CheckExact(__pyx_cur_scope->__pyx_genexpr_arg_0)) { + __pyx_t_1 = __pyx_cur_scope->__pyx_genexpr_arg_0; __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = 0; + __pyx_t_3 = NULL; + } else { + __pyx_t_2 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_cur_scope->__pyx_genexpr_arg_0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 263, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 263, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_3)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 263, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + __pyx_t_4 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_1, __pyx_t_2, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_2; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 263, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2)); + #else + __pyx_t_4 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_2); + #endif + ++__pyx_t_2; + } + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 263, __pyx_L1_error) + } else { + __pyx_t_4 = __pyx_t_3(__pyx_t_1); + if (unlikely(!__pyx_t_4)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 263, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_c); + __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_c, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_cur_scope->__pyx_v_c, __pyx_mstate_global->__pyx_n_u_real); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 263, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_cur_scope->__pyx_v_c, __pyx_mstate_global->__pyx_n_u_imag); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 263, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 263, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GIVEREF(__pyx_t_4); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_4) != (0)) __PYX_ERR(0, 263, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_5); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_5) != (0)) __PYX_ERR(0, 263, __pyx_L1_error); + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_r = __pyx_t_6; + __pyx_t_6 = 0; + __Pyx_XGIVEREF(__pyx_t_1); + __pyx_cur_scope->__pyx_t_0 = __pyx_t_1; + + __pyx_cur_scope->__pyx_t_1 = __pyx_t_2; + + __pyx_cur_scope->__pyx_t_2 = __pyx_t_3; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + __Pyx_Coroutine_ResetAndClearException(__pyx_generator); + /* return from generator, yielding value */ + __pyx_generator->resume_label = 1; + return __pyx_r; + __pyx_L6_resume_from_yield:; + __pyx_t_1 = __pyx_cur_scope->__pyx_t_0; + __pyx_cur_scope->__pyx_t_0 = 0; + __Pyx_XGOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_cur_scope->__pyx_t_1; + __pyx_t_3 = __pyx_cur_scope->__pyx_t_2; + if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 263, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + if (__Pyx_PyErr_Occurred()) { + __Pyx_Generator_Replace_StopIteration(0); + __Pyx_AddTraceback("genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + #if !CYTHON_USE_EXC_INFO_STACK + __Pyx_Coroutine_ResetAndClearException(__pyx_generator); + #endif + __pyx_generator->resume_label = -1; + __Pyx_Coroutine_clear((PyObject*)__pyx_generator); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/qu2cu/qu2cu.py":194 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * cost=cython.int, + * is_complex=cython.int, +*/ + +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_10quadratic_to_curves(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_quads, double __pyx_v_max_err, int __pyx_v_all_cubic) { + int __pyx_v_cost; + int __pyx_v_is_complex; + PyObject *__pyx_v_spline = NULL; + PyObject *__pyx_v_q = NULL; + PyObject *__pyx_v_costs = NULL; + PyObject *__pyx_v_p = NULL; + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + PyObject *__pyx_v_qq = NULL; + PyObject *__pyx_v_curves = NULL; + PyObject *__pyx_8genexpr1__pyx_v_p = NULL; + PyObject *__pyx_8genexpr2__pyx_v_x = NULL; + PyObject *__pyx_8genexpr2__pyx_v_y = NULL; + PyObject *__pyx_8genexpr3__pyx_v_curve = NULL; + PyObject *__pyx_8genexpr3__pyx_v_0 = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + size_t __pyx_t_7; + Py_ssize_t __pyx_t_8; + Py_ssize_t __pyx_t_9; + PyObject *(*__pyx_t_10)(PyObject *); + PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; + PyObject *__pyx_t_13 = NULL; + PyObject *__pyx_t_14 = NULL; + PyObject *(*__pyx_t_15)(PyObject *); + Py_ssize_t __pyx_t_16; + Py_ssize_t __pyx_t_17; + int __pyx_t_18; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("quadratic_to_curves", 0); + __Pyx_INCREF(__pyx_v_quads); + + /* "fontTools/qu2cu/qu2cu.py":234 + * splines do not connect end-to-start. + * """ + * if not quads: # <<<<<<<<<<<<<< + * return [] + * _validate_positive_tolerance(max_err) +*/ + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_v_quads); + if (unlikely(((!CYTHON_ASSUME_SAFE_SIZE) && __pyx_temp < 0))) __PYX_ERR(0, 234, __pyx_L1_error) + __pyx_t_1 = (__pyx_temp != 0); + } + + __pyx_t_2 = (!__pyx_t_1); + + + if (__pyx_t_2) { + + + /* "fontTools/qu2cu/qu2cu.py":235 + * """ + * if not quads: + * return [] # <<<<<<<<<<<<<< + * _validate_positive_tolerance(max_err) + * for spline in quads: +*/ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 235, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __pyx_r = ((PyObject*)__pyx_t_3); + } + __Pyx_XDECREF(__pyx_temp); + } + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "fontTools/qu2cu/qu2cu.py":234 + * splines do not connect end-to-start. + * """ + * if not quads: # <<<<<<<<<<<<<< + * return [] + * _validate_positive_tolerance(max_err) +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":236 + * if not quads: + * return [] + * _validate_positive_tolerance(max_err) # <<<<<<<<<<<<<< + * for spline in quads: + * _validate_spline_length(spline) +*/ + __pyx_t_4 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_validate_positive_tolerance); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 236, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyFloat_FromDouble(__pyx_v_max_err); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 236, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_5))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_5); + assert(__pyx_t_4); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_5); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_5, __pyx__function); + __pyx_t_7 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_t_6}; + __pyx_t_3 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_5, __pyx_callargs+__pyx_t_7, (2-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 236, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "fontTools/qu2cu/qu2cu.py":237 + * return [] + * _validate_positive_tolerance(max_err) + * for spline in quads: # <<<<<<<<<<<<<< + * _validate_spline_length(spline) + * +*/ + __pyx_t_3 = __pyx_v_quads; __Pyx_INCREF(__pyx_t_3); + __pyx_t_8 = 0; + for (;;) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_3); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 237, __pyx_L1_error) + #endif + if (__pyx_t_8 >= __pyx_temp) break; + } + __pyx_t_5 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_3, __pyx_t_8, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_8; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 237, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_XDECREF_SET(__pyx_v_spline, __pyx_t_5); + __pyx_t_5 = 0; + + /* "fontTools/qu2cu/qu2cu.py":238 + * _validate_positive_tolerance(max_err) + * for spline in quads: + * _validate_spline_length(spline) # <<<<<<<<<<<<<< + * + * is_complex = type(quads[0][0]) is complex +*/ + __pyx_t_6 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_validate_spline_length); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 238, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_7 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_4); + assert(__pyx_t_6); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_6); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_4, __pyx__function); + __pyx_t_7 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_6, __pyx_v_spline}; + __pyx_t_5 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_4, __pyx_callargs+__pyx_t_7, (2-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 238, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "fontTools/qu2cu/qu2cu.py":237 + * return [] + * _validate_positive_tolerance(max_err) + * for spline in quads: # <<<<<<<<<<<<<< + * _validate_spline_length(spline) + * +*/ + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "fontTools/qu2cu/qu2cu.py":240 + * _validate_spline_length(spline) + * + * is_complex = type(quads[0][0]) is complex # <<<<<<<<<<<<<< + * if not is_complex: + * quads = [[complex(x, y) for (x, y) in p] for p in quads] +*/ + __pyx_t_3 = __Pyx_GetItemInt_List(__pyx_v_quads, 0, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 240, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_GetItemInt(__pyx_t_3, 0, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 240, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_2 = (((PyObject *)Py_TYPE(__pyx_t_5)) == ((PyObject *)(&PyComplex_Type))); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_is_complex = __pyx_t_2; + + /* "fontTools/qu2cu/qu2cu.py":241 + * + * is_complex = type(quads[0][0]) is complex + * if not is_complex: # <<<<<<<<<<<<<< + * quads = [[complex(x, y) for (x, y) in p] for p in quads] + * +*/ + __pyx_t_2 = (!(__pyx_v_is_complex != 0)); + + if (__pyx_t_2) { + + + /* "fontTools/qu2cu/qu2cu.py":242 + * is_complex = type(quads[0][0]) is complex + * if not is_complex: + * quads = [[complex(x, y) for (x, y) in p] for p in quads] # <<<<<<<<<<<<<< + * + * q = [quads[0][0]] +*/ + { /* enter inner scope */ + __pyx_t_5 = PyList_New(0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 242, __pyx_L10_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __pyx_v_quads; __Pyx_INCREF(__pyx_t_3); + __pyx_t_8 = 0; + for (;;) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_3); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 242, __pyx_L10_error) + #endif + if (__pyx_t_8 >= __pyx_temp) break; + } + __pyx_t_4 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_3, __pyx_t_8, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_8; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 242, __pyx_L10_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_8genexpr1__pyx_v_p, __pyx_t_4); + __pyx_t_4 = 0; + { /* enter inner scope */ + __pyx_t_4 = PyList_New(0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 242, __pyx_L15_error) + __Pyx_GOTREF(__pyx_t_4); + if (likely(PyList_CheckExact(__pyx_8genexpr1__pyx_v_p)) || PyTuple_CheckExact(__pyx_8genexpr1__pyx_v_p)) { + __pyx_t_6 = __pyx_8genexpr1__pyx_v_p; __Pyx_INCREF(__pyx_t_6); + __pyx_t_9 = 0; + __pyx_t_10 = NULL; + } else { + __pyx_t_9 = -1; __pyx_t_6 = PyObject_GetIter(__pyx_8genexpr1__pyx_v_p); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 242, __pyx_L15_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_10 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_6); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 242, __pyx_L15_error) + } + for (;;) { + if (likely(!__pyx_t_10)) { + if (likely(PyList_CheckExact(__pyx_t_6))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 242, __pyx_L15_error) + #endif + if (__pyx_t_9 >= __pyx_temp) break; + } + __pyx_t_11 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_6, __pyx_t_9, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_9; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 242, __pyx_L15_error) + #endif + if (__pyx_t_9 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_11 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_6, __pyx_t_9)); + #else + __pyx_t_11 = __Pyx_PySequence_ITEM(__pyx_t_6, __pyx_t_9); + #endif + ++__pyx_t_9; + } + if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 242, __pyx_L15_error) + } else { + __pyx_t_11 = __pyx_t_10(__pyx_t_6); + if (unlikely(!__pyx_t_11)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 242, __pyx_L15_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_11); + if ((likely(PyTuple_CheckExact(__pyx_t_11))) || (PyList_CheckExact(__pyx_t_11))) { + PyObject* sequence = __pyx_t_11; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 242, __pyx_L15_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_12 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_12); + __pyx_t_13 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_13); + } else { + __pyx_t_12 = __Pyx_PyList_GET_ITEM_REF(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 242, __pyx_L15_error) + __Pyx_XGOTREF(__pyx_t_12); + __pyx_t_13 = __Pyx_PyList_GET_ITEM_REF(sequence, 1, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 242, __pyx_L15_error) + __Pyx_XGOTREF(__pyx_t_13); + } + #else + __pyx_t_12 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 242, __pyx_L15_error) + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_13 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 242, __pyx_L15_error) + __Pyx_GOTREF(__pyx_t_13); + #endif + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_14 = PyObject_GetIter(__pyx_t_11); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 242, __pyx_L15_error) + __Pyx_GOTREF(__pyx_t_14); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_15 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_14); + index = 0; __pyx_t_12 = __pyx_t_15(__pyx_t_14); if (unlikely(!__pyx_t_12)) goto __pyx_L18_unpacking_failed; + __Pyx_GOTREF(__pyx_t_12); + index = 1; __pyx_t_13 = __pyx_t_15(__pyx_t_14); if (unlikely(!__pyx_t_13)) goto __pyx_L18_unpacking_failed; + __Pyx_GOTREF(__pyx_t_13); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_15(__pyx_t_14), 2) < (0)) __PYX_ERR(0, 242, __pyx_L15_error) + __pyx_t_15 = NULL; + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + goto __pyx_L19_unpacking_done; + __pyx_L18_unpacking_failed:; + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + __pyx_t_15 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 242, __pyx_L15_error) + __pyx_L19_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_8genexpr2__pyx_v_x, __pyx_t_12); + __pyx_t_12 = 0; + __Pyx_XDECREF_SET(__pyx_8genexpr2__pyx_v_y, __pyx_t_13); + __pyx_t_13 = 0; + __pyx_t_13 = NULL; + __pyx_t_7 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_13, __pyx_8genexpr2__pyx_v_x, __pyx_8genexpr2__pyx_v_y}; + __pyx_t_11 = __Pyx_PyObject_FastCall((PyObject*)(&PyComplex_Type), __pyx_callargs+__pyx_t_7, (3-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; + if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 242, __pyx_L15_error) + __Pyx_GOTREF(__pyx_t_11); + } + __Pyx_GIVEREF(__pyx_t_11); + if (unlikely(__Pyx_ListComp_AppendAndDecref(__pyx_t_4, __pyx_t_11))) __PYX_ERR(0, 242, __pyx_L15_error) + __pyx_t_11 = 0; + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_x); __pyx_8genexpr2__pyx_v_x = 0; + __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_y); __pyx_8genexpr2__pyx_v_y = 0; + goto __pyx_L21_exit_scope; + __pyx_L15_error:; + __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_x); __pyx_8genexpr2__pyx_v_x = 0; + __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_y); __pyx_8genexpr2__pyx_v_y = 0; + goto __pyx_L10_error; + __pyx_L21_exit_scope:; + } /* exit inner scope */ + __Pyx_GIVEREF(__pyx_t_4); + if (unlikely(__Pyx_ListComp_AppendAndDecref(__pyx_t_5, __pyx_t_4))) __PYX_ERR(0, 242, __pyx_L10_error) + __pyx_t_4 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_p); __pyx_8genexpr1__pyx_v_p = 0; + goto __pyx_L23_exit_scope; + __pyx_L10_error:; + __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_p); __pyx_8genexpr1__pyx_v_p = 0; + goto __pyx_L1_error; + __pyx_L23_exit_scope:; + } /* exit inner scope */ + __Pyx_DECREF_SET(__pyx_v_quads, ((PyObject*)__pyx_t_5)); + __pyx_t_5 = 0; + + /* "fontTools/qu2cu/qu2cu.py":241 + * + * is_complex = type(quads[0][0]) is complex + * if not is_complex: # <<<<<<<<<<<<<< + * quads = [[complex(x, y) for (x, y) in p] for p in quads] + * +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":244 + * quads = [[complex(x, y) for (x, y) in p] for p in quads] + * + * q = [quads[0][0]] # <<<<<<<<<<<<<< + * costs = [1] + * cost = 1 +*/ + __pyx_t_5 = __Pyx_GetItemInt_List(__pyx_v_quads, 0, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 244, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_5, 0, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 244, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyList_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 244, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_3); + if (__Pyx_PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_3) != (0)) __PYX_ERR(0, 244, __pyx_L1_error); + __pyx_t_3 = 0; + __pyx_v_q = ((PyObject*)__pyx_t_5); + __pyx_t_5 = 0; + + /* "fontTools/qu2cu/qu2cu.py":245 + * + * q = [quads[0][0]] + * costs = [1] # <<<<<<<<<<<<<< + * cost = 1 + * for p in quads: +*/ + __pyx_t_5 = PyList_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 245, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_1); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_1); + if (__Pyx_PyList_SET_ITEM(__pyx_t_5, 0, __pyx_mstate_global->__pyx_int_1) != (0)) __PYX_ERR(0, 245, __pyx_L1_error); + __pyx_v_costs = ((PyObject*)__pyx_t_5); + __pyx_t_5 = 0; + + /* "fontTools/qu2cu/qu2cu.py":246 + * q = [quads[0][0]] + * costs = [1] + * cost = 1 # <<<<<<<<<<<<<< + * for p in quads: + * if q[-1] != p[0]: +*/ + __pyx_v_cost = 1; + + /* "fontTools/qu2cu/qu2cu.py":247 + * costs = [1] + * cost = 1 + * for p in quads: # <<<<<<<<<<<<<< + * if q[-1] != p[0]: + * _raise_incompatible_point(p[0], q[-1]) +*/ + __pyx_t_5 = __pyx_v_quads; __Pyx_INCREF(__pyx_t_5); + __pyx_t_8 = 0; + for (;;) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_5); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 247, __pyx_L1_error) + #endif + if (__pyx_t_8 >= __pyx_temp) break; + } + __pyx_t_3 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_5, __pyx_t_8, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_8; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 247, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_XDECREF_SET(__pyx_v_p, __pyx_t_3); + __pyx_t_3 = 0; + + /* "fontTools/qu2cu/qu2cu.py":248 + * cost = 1 + * for p in quads: + * if q[-1] != p[0]: # <<<<<<<<<<<<<< + * _raise_incompatible_point(p[0], q[-1]) + * for i in range(len(p) - 2): +*/ + __pyx_t_3 = __Pyx_GetItemInt_List(__pyx_v_q, -1L, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 248, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_p, 0, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 248, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_CompareBoolNe_object_object(__pyx_t_3, __pyx_t_4, Py_NE); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 248, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_2) { + + + /* "fontTools/qu2cu/qu2cu.py":249 + * for p in quads: + * if q[-1] != p[0]: + * _raise_incompatible_point(p[0], q[-1]) # <<<<<<<<<<<<<< + * for i in range(len(p) - 2): + * cost += 1 +*/ + __pyx_t_3 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_raise_incompatible_point); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 249, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_11 = __Pyx_GetItemInt(__pyx_v_p, 0, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 249, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_13 = __Pyx_GetItemInt_List(__pyx_v_q, -1L, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 249, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_13); + __pyx_t_7 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_6); + assert(__pyx_t_3); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_6, __pyx__function); + __pyx_t_7 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_3, __pyx_t_11, __pyx_t_13}; + __pyx_t_4 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_6, __pyx_callargs+__pyx_t_7, (3-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 249, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/qu2cu/qu2cu.py":248 + * cost = 1 + * for p in quads: + * if q[-1] != p[0]: # <<<<<<<<<<<<<< + * _raise_incompatible_point(p[0], q[-1]) + * for i in range(len(p) - 2): +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":250 + * if q[-1] != p[0]: + * _raise_incompatible_point(p[0], q[-1]) + * for i in range(len(p) - 2): # <<<<<<<<<<<<<< + * cost += 1 + * costs.append(cost) +*/ + __pyx_t_9 = PyObject_Length(__pyx_v_p); if (unlikely(__pyx_t_9 == ((Py_ssize_t)-1))) __PYX_ERR(0, 250, __pyx_L1_error) + + __pyx_t_16 = (__pyx_t_9 - 2); + + __pyx_t_9 = __pyx_t_16; + + for (__pyx_t_17 = 0; __pyx_t_17 < __pyx_t_9; __pyx_t_17+=1) { + __pyx_v_i = __pyx_t_17; + + /* "fontTools/qu2cu/qu2cu.py":251 + * _raise_incompatible_point(p[0], q[-1]) + * for i in range(len(p) - 2): + * cost += 1 # <<<<<<<<<<<<<< + * costs.append(cost) + * costs.append(cost) +*/ + __pyx_v_cost = (__pyx_v_cost + 1); + + /* "fontTools/qu2cu/qu2cu.py":252 + * for i in range(len(p) - 2): + * cost += 1 + * costs.append(cost) # <<<<<<<<<<<<<< + * costs.append(cost) + * qq = add_implicit_on_curves(p)[1:] +*/ + __pyx_t_4 = __Pyx_PyLong_From_int(__pyx_v_cost); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 252, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_18 = __Pyx_PyList_Append(__pyx_v_costs, __pyx_t_4); if (unlikely(__pyx_t_18 == ((int)-1))) __PYX_ERR(0, 252, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + + /* "fontTools/qu2cu/qu2cu.py":253 + * cost += 1 + * costs.append(cost) + * costs.append(cost) # <<<<<<<<<<<<<< + * qq = add_implicit_on_curves(p)[1:] + * costs.pop() +*/ + __pyx_t_4 = __Pyx_PyLong_From_int(__pyx_v_cost); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 253, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_18 = __Pyx_PyList_Append(__pyx_v_costs, __pyx_t_4); if (unlikely(__pyx_t_18 == ((int)-1))) __PYX_ERR(0, 253, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + } + + + /* "fontTools/qu2cu/qu2cu.py":254 + * costs.append(cost) + * costs.append(cost) + * qq = add_implicit_on_curves(p)[1:] # <<<<<<<<<<<<<< + * costs.pop() + * q.extend(qq) +*/ + __pyx_t_6 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_13, __pyx_mstate_global->__pyx_n_u_add_implicit_on_curves); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 254, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_13); + __pyx_t_7 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_13))) { + __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_13); + assert(__pyx_t_6); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_13); + __Pyx_INCREF(__pyx_t_6); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_13, __pyx__function); + __pyx_t_7 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_6, __pyx_v_p}; + __pyx_t_4 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_13, __pyx_callargs+__pyx_t_7, (2-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 254, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __pyx_t_13 = __Pyx_PyObject_GetSlice(__pyx_t_4, 1, 0, NULL, NULL, &__pyx_mstate_global->__pyx_slice[0], 1, 0, 1); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 254, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_13); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF_SET(__pyx_v_qq, __pyx_t_13); + __pyx_t_13 = 0; + + /* "fontTools/qu2cu/qu2cu.py":255 + * costs.append(cost) + * qq = add_implicit_on_curves(p)[1:] + * costs.pop() # <<<<<<<<<<<<<< + * q.extend(qq) + * cost += 1 +*/ + __pyx_t_13 = __Pyx_PyList_Pop(__pyx_v_costs); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 255, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_13); + __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; + + /* "fontTools/qu2cu/qu2cu.py":256 + * qq = add_implicit_on_curves(p)[1:] + * costs.pop() + * q.extend(qq) # <<<<<<<<<<<<<< + * cost += 1 + * costs.append(cost) +*/ + __pyx_t_18 = __Pyx_PyList_Extend(__pyx_v_q, __pyx_v_qq); if (unlikely(__pyx_t_18 == ((int)-1))) __PYX_ERR(0, 256, __pyx_L1_error) + + + /* "fontTools/qu2cu/qu2cu.py":257 + * costs.pop() + * q.extend(qq) + * cost += 1 # <<<<<<<<<<<<<< + * costs.append(cost) + * +*/ + __pyx_v_cost = (__pyx_v_cost + 1); + + /* "fontTools/qu2cu/qu2cu.py":258 + * q.extend(qq) + * cost += 1 + * costs.append(cost) # <<<<<<<<<<<<<< + * + * curves = spline_to_curves(q, costs, max_err, all_cubic) +*/ + __pyx_t_13 = __Pyx_PyLong_From_int(__pyx_v_cost); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 258, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_13); + __pyx_t_18 = __Pyx_PyList_Append(__pyx_v_costs, __pyx_t_13); if (unlikely(__pyx_t_18 == ((int)-1))) __PYX_ERR(0, 258, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; + + + /* "fontTools/qu2cu/qu2cu.py":247 + * costs = [1] + * cost = 1 + * for p in quads: # <<<<<<<<<<<<<< + * if q[-1] != p[0]: + * _raise_incompatible_point(p[0], q[-1]) +*/ + } + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "fontTools/qu2cu/qu2cu.py":260 + * costs.append(cost) + * + * curves = spline_to_curves(q, costs, max_err, all_cubic) # <<<<<<<<<<<<<< + * + * if not is_complex: +*/ + __pyx_t_13 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_spline_to_curves); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 260, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = PyFloat_FromDouble(__pyx_v_max_err); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 260, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_11 = __Pyx_PyBool_FromLong(__pyx_v_all_cubic); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 260, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_7 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_13 = PyMethod_GET_SELF(__pyx_t_4); + assert(__pyx_t_13); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_13); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_4, __pyx__function); + __pyx_t_7 = 0; + } + #endif + { + PyObject *__pyx_callargs[5] = {__pyx_t_13, __pyx_v_q, __pyx_v_costs, __pyx_t_6, __pyx_t_11}; + __pyx_t_5 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_4, __pyx_callargs+__pyx_t_7, (5-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 260, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + } + __pyx_v_curves = __pyx_t_5; + __pyx_t_5 = 0; + + /* "fontTools/qu2cu/qu2cu.py":262 + * curves = spline_to_curves(q, costs, max_err, all_cubic) + * + * if not is_complex: # <<<<<<<<<<<<<< + * curves = [tuple((c.real, c.imag) for c in curve) for curve in curves] + * return curves +*/ + __pyx_t_2 = (!(__pyx_v_is_complex != 0)); + + if (__pyx_t_2) { + + + /* "fontTools/qu2cu/qu2cu.py":263 + * + * if not is_complex: + * curves = [tuple((c.real, c.imag) for c in curve) for curve in curves] # <<<<<<<<<<<<<< + * return curves + * +*/ + { /* enter inner scope */ + __pyx_t_5 = PyList_New(0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 263, __pyx_L33_error) + __Pyx_GOTREF(__pyx_t_5); + if (likely(PyList_CheckExact(__pyx_v_curves)) || PyTuple_CheckExact(__pyx_v_curves)) { + __pyx_t_4 = __pyx_v_curves; __Pyx_INCREF(__pyx_t_4); + __pyx_t_8 = 0; + __pyx_t_10 = NULL; + } else { + __pyx_t_8 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_curves); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 263, __pyx_L33_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_10 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_4); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 263, __pyx_L33_error) + } + for (;;) { + if (likely(!__pyx_t_10)) { + if (likely(PyList_CheckExact(__pyx_t_4))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_4); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 263, __pyx_L33_error) + #endif + if (__pyx_t_8 >= __pyx_temp) break; + } + __pyx_t_11 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_4, __pyx_t_8, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_8; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_4); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 263, __pyx_L33_error) + #endif + if (__pyx_t_8 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_11 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_8)); + #else + __pyx_t_11 = __Pyx_PySequence_ITEM(__pyx_t_4, __pyx_t_8); + #endif + ++__pyx_t_8; + } + if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 263, __pyx_L33_error) + } else { + __pyx_t_11 = __pyx_t_10(__pyx_t_4); + if (unlikely(!__pyx_t_11)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 263, __pyx_L33_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_11); + __Pyx_XDECREF_SET(__pyx_8genexpr3__pyx_v_curve, __pyx_t_11); + __pyx_t_11 = 0; + __pyx_t_11 = __pyx_pf_9fontTools_5qu2cu_5qu2cu_19quadratic_to_curves_8genexpr3_genexpr(NULL, __pyx_8genexpr3__pyx_v_curve); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 263, __pyx_L33_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_6 = __Pyx_PySequence_Tuple(__pyx_t_11); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 263, __pyx_L33_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_GIVEREF(__pyx_t_6); + if (unlikely(__Pyx_ListComp_AppendAndDecref(__pyx_t_5, __pyx_t_6))) __PYX_ERR(0, 263, __pyx_L33_error) + __pyx_t_6 = 0; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_8genexpr3__pyx_v_curve); __pyx_8genexpr3__pyx_v_curve = 0; + goto __pyx_L37_exit_scope; + __pyx_L33_error:; + __Pyx_XDECREF(__pyx_8genexpr3__pyx_v_curve); __pyx_8genexpr3__pyx_v_curve = 0; + goto __pyx_L1_error; + __pyx_L37_exit_scope:; + } /* exit inner scope */ + __Pyx_DECREF_SET(__pyx_v_curves, __pyx_t_5); + __pyx_t_5 = 0; + + /* "fontTools/qu2cu/qu2cu.py":262 + * curves = spline_to_curves(q, costs, max_err, all_cubic) + * + * if not is_complex: # <<<<<<<<<<<<<< + * curves = [tuple((c.real, c.imag) for c in curve) for curve in curves] + * return curves +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":264 + * if not is_complex: + * curves = [tuple((c.real, c.imag) for c in curve) for curve in curves] + * return curves # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_5 = __pyx_v_curves; + __Pyx_INCREF(__pyx_t_5); + if (!(likely(PyList_CheckExact(__pyx_t_5))||((__pyx_t_5) == Py_None) || __Pyx_RaiseUnexpectedTypeError("list", __pyx_t_5))) __PYX_ERR(0, 264, __pyx_L1_error) + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __pyx_r = ((PyObject*)__pyx_t_5); + } + __Pyx_XDECREF(__pyx_temp); + } + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "fontTools/qu2cu/qu2cu.py":194 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * cost=cython.int, + * is_complex=cython.int, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_XDECREF(__pyx_t_13); + __Pyx_XDECREF(__pyx_t_14); + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu.quadratic_to_curves", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + + + __Pyx_XDECREF(__pyx_v_spline); + __Pyx_XDECREF(__pyx_v_q); + __Pyx_XDECREF(__pyx_v_costs); + __Pyx_XDECREF(__pyx_v_p); + + __Pyx_XDECREF(__pyx_v_qq); + __Pyx_XDECREF(__pyx_v_curves); + __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_p); + __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_x); + __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_y); + __Pyx_XDECREF(__pyx_8genexpr3__pyx_v_curve); + __Pyx_XDECREF(__pyx_8genexpr3__pyx_v_0); + __Pyx_XDECREF(__pyx_v_quads); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/qu2cu/qu2cu.py":270 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * i=cython.int, + * j=cython.int, +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9fontTools_5qu2cu_5qu2cu_13spline_to_curves(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9fontTools_5qu2cu_5qu2cu_12spline_to_curves, "spline_to_curves(q, costs, double tolerance=0.5, int all_cubic=False)\n\nq: quadratic spline with alternating on-curve / off-curve points.\n\ncosts: cumulative list of encoding cost of q in terms of number of\n points that need to be encoded. Implied on-curve points do not\n contribute to the cost. If all points need to be encoded, then\n costs will be range(1, len(q)+1)."); +static PyMethodDef __pyx_mdef_9fontTools_5qu2cu_5qu2cu_13spline_to_curves = {"spline_to_curves", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9fontTools_5qu2cu_5qu2cu_13spline_to_curves, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_9fontTools_5qu2cu_5qu2cu_12spline_to_curves}; +static PyObject *__pyx_pw_9fontTools_5qu2cu_5qu2cu_13spline_to_curves(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_q = 0; + PyObject *__pyx_v_costs = 0; + double __pyx_v_tolerance; + int __pyx_v_all_cubic; + #if !CYTHON_VECTORCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[4] = {0,0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("spline_to_curves (wrapper)", 0); + #if !CYTHON_VECTORCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_q,&__pyx_mstate_global->__pyx_n_u_costs,&__pyx_mstate_global->__pyx_n_u_tolerance,&__pyx_mstate_global->__pyx_n_u_all_cubic,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) __PYX_ERR(0, 270, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 270, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 270, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 270, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 270, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "spline_to_curves", 0) < (0)) __PYX_ERR(0, 270, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("spline_to_curves", 0, 2, 4, i); __PYX_ERR(0, 270, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 270, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 270, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 270, __pyx_L3_error) + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 270, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_q = values[0]; + __pyx_v_costs = values[1]; + if (values[2]) { + __pyx_v_tolerance = __Pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_tolerance == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 293, __pyx_L3_error) + } else { + __pyx_v_tolerance = ((double)((double)0.5)); + } + if (values[3]) { + __pyx_v_all_cubic = __Pyx_PyLong_As_int(values[3]); if (unlikely((__pyx_v_all_cubic == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 293, __pyx_L3_error) + } else { + + /* "fontTools/qu2cu/qu2cu.py":293 + * u=cython.complex, + * ) + * def spline_to_curves(q, costs, tolerance=0.5, all_cubic=False): # <<<<<<<<<<<<<< + * """ + * q: quadratic spline with alternating on-curve / off-curve points. +*/ + __pyx_v_all_cubic = ((int)((int)0)); + } + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("spline_to_curves", 0, 2, 4, __pyx_nargs); __PYX_ERR(0, 270, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu.spline_to_curves", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9fontTools_5qu2cu_5qu2cu_12spline_to_curves(__pyx_self, __pyx_v_q, __pyx_v_costs, __pyx_v_tolerance, __pyx_v_all_cubic); + + /* "fontTools/qu2cu/qu2cu.py":270 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * i=cython.int, + * j=cython.int, +*/ + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + + + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +static PyObject *__pyx_gb_9fontTools_5qu2cu_5qu2cu_16spline_to_curves_2generator1(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value); /* proto */ + +/* "fontTools/qu2cu/qu2cu.py":368 + * for k, reconst in enumerate(reconstructed): + * orig = elevated_quadratics[j + k] + * p0, p1, p2, p3 = tuple(v - u for v, u in zip(reconst, orig)) # <<<<<<<<<<<<<< + * + * if not cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance): +*/ + +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_16spline_to_curves_genexpr(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_genexpr_arg_0) { + struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr *__pyx_cur_scope; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("genexpr", 0); + __pyx_cur_scope = (struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr *)__pyx_tp_new_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr(__pyx_mstate_global->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr, __pyx_mstate_global->__pyx_empty_tuple, NULL); + if (unlikely(!__pyx_cur_scope)) { + __pyx_cur_scope = ((struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr *)Py_None); + __Pyx_INCREF(Py_None); + __PYX_ERR(0, 368, __pyx_L1_error) + } else { + __Pyx_GOTREF((PyObject *)__pyx_cur_scope); + } + __pyx_cur_scope->__pyx_genexpr_arg_0 = __pyx_genexpr_arg_0; + __Pyx_INCREF(__pyx_cur_scope->__pyx_genexpr_arg_0); + __Pyx_GIVEREF(__pyx_cur_scope->__pyx_genexpr_arg_0); + { + __pyx_CoroutineObject *gen = __Pyx_Generator_New((__pyx_coroutine_body_t) __pyx_gb_9fontTools_5qu2cu_5qu2cu_16spline_to_curves_2generator1, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[1]), (PyObject *) __pyx_cur_scope, __pyx_mstate_global->__pyx_n_u_genexpr, __pyx_mstate_global->__pyx_n_u_spline_to_curves_locals_genexpr, __pyx_mstate_global->__pyx_n_u_fontTools_qu2cu_qu2cu); if (unlikely(!gen)) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_DECREF(__pyx_cur_scope); + __Pyx_RefNannyFinishContext(); + return (PyObject *) gen; + } + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu.spline_to_curves.genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_DECREF((PyObject *)__pyx_cur_scope); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_gb_9fontTools_5qu2cu_5qu2cu_16spline_to_curves_2generator1(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value) /* generator body */ +{ + struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr *__pyx_cur_scope = ((struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr *)__pyx_generator->closure); + PyObject *__pyx_r = NULL; + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *(*__pyx_t_3)(PyObject *); + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *(*__pyx_t_8)(PyObject *); + __pyx_t_double_complex __pyx_t_9; + __pyx_t_double_complex __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("genexpr", 0); + switch (__pyx_generator->resume_label) { + case 0: goto __pyx_L3_first_run; + case 1: goto __pyx_L8_resume_from_yield; + default: /* CPython raises the right error here */ + __Pyx_RefNannyFinishContext(); + return NULL; + } + __pyx_L3_first_run:; + if (unlikely(__pyx_sent_value != Py_None)) { + if (unlikely(__pyx_sent_value)) PyErr_SetString(PyExc_TypeError, "can't send non-None value to a just-started generator"); + __PYX_ERR(0, 368, __pyx_L1_error) + } + if (unlikely(!__pyx_cur_scope->__pyx_genexpr_arg_0)) { __Pyx_RaiseUnboundLocalError(".0"); __PYX_ERR(0, 368, __pyx_L1_error) } + if (likely(PyList_CheckExact(__pyx_cur_scope->__pyx_genexpr_arg_0)) || PyTuple_CheckExact(__pyx_cur_scope->__pyx_genexpr_arg_0)) { + __pyx_t_1 = __pyx_cur_scope->__pyx_genexpr_arg_0; __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = 0; + __pyx_t_3 = NULL; + } else { + __pyx_t_2 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_cur_scope->__pyx_genexpr_arg_0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 368, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_3)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 368, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + __pyx_t_4 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_1, __pyx_t_2, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_2; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 368, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2)); + #else + __pyx_t_4 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_2); + #endif + ++__pyx_t_2; + } + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 368, __pyx_L1_error) + } else { + __pyx_t_4 = __pyx_t_3(__pyx_t_1); + if (unlikely(!__pyx_t_4)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 368, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_4); + if ((likely(PyTuple_CheckExact(__pyx_t_4))) || (PyList_CheckExact(__pyx_t_4))) { + PyObject* sequence = __pyx_t_4; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 368, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_5); + __pyx_t_6 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_6); + } else { + __pyx_t_5 = __Pyx_PyList_GET_ITEM_REF(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyList_GET_ITEM_REF(sequence, 1, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_6); + } + #else + __pyx_t_5 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + #endif + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_7 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_8 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_7); + index = 0; __pyx_t_5 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_5)) goto __pyx_L6_unpacking_failed; + __Pyx_GOTREF(__pyx_t_5); + index = 1; __pyx_t_6 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_6)) goto __pyx_L6_unpacking_failed; + __Pyx_GOTREF(__pyx_t_6); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_7), 2) < (0)) __PYX_ERR(0, 368, __pyx_L1_error) + __pyx_t_8 = NULL; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L7_unpacking_done; + __pyx_L6_unpacking_failed:; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 368, __pyx_L1_error) + __pyx_L7_unpacking_done:; + } + __pyx_t_9 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_5); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_10 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_6); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_cur_scope->__pyx_v_v = __pyx_t_9; + __pyx_cur_scope->__pyx_v_u = __pyx_t_10; + __pyx_t_10 = __Pyx_c_diff_double(__pyx_cur_scope->__pyx_v_v, __pyx_cur_scope->__pyx_v_u); + + __pyx_t_4 = __pyx_PyComplex_FromComplex(__pyx_t_10); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + __Pyx_XGIVEREF(__pyx_t_1); + __pyx_cur_scope->__pyx_t_0 = __pyx_t_1; + + __pyx_cur_scope->__pyx_t_1 = __pyx_t_2; + + __pyx_cur_scope->__pyx_t_2 = __pyx_t_3; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + __Pyx_Coroutine_ResetAndClearException(__pyx_generator); + /* return from generator, yielding value */ + __pyx_generator->resume_label = 1; + return __pyx_r; + __pyx_L8_resume_from_yield:; + __pyx_t_1 = __pyx_cur_scope->__pyx_t_0; + __pyx_cur_scope->__pyx_t_0 = 0; + __Pyx_XGOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_cur_scope->__pyx_t_1; + __pyx_t_3 = __pyx_cur_scope->__pyx_t_2; + if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 368, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + if (__Pyx_PyErr_Occurred()) { + __Pyx_Generator_Replace_StopIteration(0); + __Pyx_AddTraceback("genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + #if !CYTHON_USE_EXC_INFO_STACK + __Pyx_Coroutine_ResetAndClearException(__pyx_generator); + #endif + __pyx_generator->resume_label = -1; + __Pyx_Coroutine_clear((PyObject*)__pyx_generator); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/qu2cu/qu2cu.py":270 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * i=cython.int, + * j=cython.int, +*/ + +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_12spline_to_curves(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_q, PyObject *__pyx_v_costs, double __pyx_v_tolerance, int __pyx_v_all_cubic) { + int __pyx_v_i; + int __pyx_v_j; + int __pyx_v_k; + int __pyx_v_start; + int __pyx_v_i_sol_count; + int __pyx_v_j_sol_count; + double __pyx_v_err; + double __pyx_v_error; + double __pyx_v_i_sol_error; + double __pyx_v_j_sol_error; + int __pyx_v_is_cubic; + int __pyx_v_count; + __pyx_t_double_complex __pyx_v_p0; + __pyx_t_double_complex __pyx_v_p1; + __pyx_t_double_complex __pyx_v_p2; + __pyx_t_double_complex __pyx_v_p3; + PyObject *__pyx_v_elevated_quadratics = NULL; + PyObject *__pyx_v_forced = NULL; + PyObject *__pyx_v_sols = NULL; + PyObject *__pyx_v_impossible = NULL; + PyObject *__pyx_v_best_sol = NULL; + PyObject *__pyx_v_this_count = NULL; + PyObject *__pyx_v_i_sol = NULL; + PyObject *__pyx_v_curve = NULL; + PyObject *__pyx_v_ts = NULL; + PyObject *__pyx_v_reconstructed_iter = NULL; + PyObject *__pyx_v_reconstructed = NULL; + PyObject *__pyx_v_reconst = NULL; + PyObject *__pyx_v_orig = NULL; + PyObject *__pyx_v_splits = NULL; + PyObject *__pyx_v_cubic = NULL; + PyObject *__pyx_v_curves = NULL; + int __pyx_8genexpr5__pyx_v_i; + PyObject *__pyx_gb_9fontTools_5qu2cu_5qu2cu_16spline_to_curves_2generator1 = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + Py_ssize_t __pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + long __pyx_t_9; + __pyx_t_double_complex __pyx_t_10; + int __pyx_t_11; + size_t __pyx_t_12; + int __pyx_t_13; + int __pyx_t_14; + int __pyx_t_15; + int __pyx_t_16; + double __pyx_t_17; + PyObject *__pyx_t_18 = NULL; + PyObject *__pyx_t_19 = NULL; + PyObject *__pyx_t_20 = NULL; + PyObject *__pyx_t_21 = NULL; + PyObject *__pyx_t_22 = NULL; + PyObject *(*__pyx_t_23)(PyObject *); + Py_ssize_t __pyx_t_24; + PyObject *(*__pyx_t_25)(PyObject *); + int __pyx_t_26; + double __pyx_t_27; + double __pyx_t_28; + __pyx_t_double_complex __pyx_t_29; + __pyx_t_double_complex __pyx_t_30; + __pyx_t_double_complex __pyx_t_31; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("spline_to_curves", 0); + + /* "fontTools/qu2cu/qu2cu.py":303 + * """ + * + * assert len(q) >= 3, "quadratic spline requires at least 3 points" # <<<<<<<<<<<<<< + * + * # Elevate quadratic segments to cubic +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __pyx_t_1 = PyObject_Length(__pyx_v_q); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 303, __pyx_L1_error) + __pyx_t_2 = (__pyx_t_1 >= 3); + + + if (unlikely(!__pyx_t_2)) { + __Pyx_Raise(((PyObject *)(((PyTypeObject*)PyExc_AssertionError))), __pyx_mstate_global->__pyx_kp_u_quadratic_spline_requires_at_lea, 0, 0); + __PYX_ERR(0, 303, __pyx_L1_error) + } + + } + #else + if ((1)); else __PYX_ERR(0, 303, __pyx_L1_error) + #endif + + /* "fontTools/qu2cu/qu2cu.py":306 + * + * # Elevate quadratic segments to cubic + * elevated_quadratics = [ # <<<<<<<<<<<<<< + * elevate_quadratic(*q[i : i + 3]) for i in range(0, len(q) - 2, 2) + * ] +*/ + { /* enter inner scope */ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 306, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + + /* "fontTools/qu2cu/qu2cu.py":307 + * # Elevate quadratic segments to cubic + * elevated_quadratics = [ + * elevate_quadratic(*q[i : i + 3]) for i in range(0, len(q) - 2, 2) # <<<<<<<<<<<<<< + * ] + * +*/ + __pyx_t_1 = PyObject_Length(__pyx_v_q); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 307, __pyx_L1_error) + + __pyx_t_4 = (__pyx_t_1 - 2); + + __pyx_t_1 = __pyx_t_4; + + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_1; __pyx_t_5+=2) { + __pyx_8genexpr5__pyx_v_i = __pyx_t_5; + __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_elevate_quadratic); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 307, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyObject_GetSlice(__pyx_v_q, __pyx_8genexpr5__pyx_v_i, (__pyx_8genexpr5__pyx_v_i + 3), NULL, NULL, NULL, 1, 1, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 307, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = __Pyx_PySequence_Tuple(__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 307, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 307, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_GIVEREF(__pyx_t_7); + if (unlikely(__Pyx_ListComp_AppendAndDecref(__pyx_t_3, __pyx_t_7))) __PYX_ERR(0, 306, __pyx_L1_error) + __pyx_t_7 = 0; + } + + } /* exit inner scope */ + __pyx_v_elevated_quadratics = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "fontTools/qu2cu/qu2cu.py":311 + * + * # Find sharp corners; they have to be oncurves for sure. + * forced = set() # <<<<<<<<<<<<<< + * for i in range(1, len(elevated_quadratics)): + * p0 = elevated_quadratics[i - 1][2] +*/ + __pyx_t_3 = PySet_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 311, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_forced = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "fontTools/qu2cu/qu2cu.py":312 + * # Find sharp corners; they have to be oncurves for sure. + * forced = set() + * for i in range(1, len(elevated_quadratics)): # <<<<<<<<<<<<<< + * p0 = elevated_quadratics[i - 1][2] + * p1 = elevated_quadratics[i][0] +*/ + __pyx_t_4 = __Pyx_PyList_GET_SIZE(__pyx_v_elevated_quadratics); if (unlikely(__pyx_t_4 == ((Py_ssize_t)-1))) __PYX_ERR(0, 312, __pyx_L1_error) + __pyx_t_1 = __pyx_t_4; + + for (__pyx_t_5 = 1; __pyx_t_5 < __pyx_t_1; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "fontTools/qu2cu/qu2cu.py":313 + * forced = set() + * for i in range(1, len(elevated_quadratics)): + * p0 = elevated_quadratics[i - 1][2] # <<<<<<<<<<<<<< + * p1 = elevated_quadratics[i][0] + * p2 = elevated_quadratics[i][1] +*/ + __pyx_t_9 = (__pyx_v_i - 1); + + __pyx_t_3 = __Pyx_GetItemInt_List(__pyx_v_elevated_quadratics, __pyx_t_9, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 313, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + + __pyx_t_7 = __Pyx_GetItemInt(__pyx_t_3, 2, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 313, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_10 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_7); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 313, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_v_p0 = __pyx_t_10; + + /* "fontTools/qu2cu/qu2cu.py":314 + * for i in range(1, len(elevated_quadratics)): + * p0 = elevated_quadratics[i - 1][2] + * p1 = elevated_quadratics[i][0] # <<<<<<<<<<<<<< + * p2 = elevated_quadratics[i][1] + * if abs(p1 - p0) + abs(p2 - p1) > tolerance + abs(p2 - p0): +*/ + __pyx_t_7 = __Pyx_GetItemInt_List(__pyx_v_elevated_quadratics, __pyx_v_i, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 314, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_7, 0, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 314, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_10 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_3); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 314, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_p1 = __pyx_t_10; + + /* "fontTools/qu2cu/qu2cu.py":315 + * p0 = elevated_quadratics[i - 1][2] + * p1 = elevated_quadratics[i][0] + * p2 = elevated_quadratics[i][1] # <<<<<<<<<<<<<< + * if abs(p1 - p0) + abs(p2 - p1) > tolerance + abs(p2 - p0): + * forced.add(i) +*/ + __pyx_t_3 = __Pyx_GetItemInt_List(__pyx_v_elevated_quadratics, __pyx_v_i, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 315, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_7 = __Pyx_GetItemInt(__pyx_t_3, 1, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 315, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_10 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_7); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 315, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_v_p2 = __pyx_t_10; + + /* "fontTools/qu2cu/qu2cu.py":316 + * p1 = elevated_quadratics[i][0] + * p2 = elevated_quadratics[i][1] + * if abs(p1 - p0) + abs(p2 - p1) > tolerance + abs(p2 - p0): # <<<<<<<<<<<<<< + * forced.add(i) + * +*/ + __pyx_t_2 = ((__Pyx_c_abs_double(__Pyx_c_diff_double(__pyx_v_p1, __pyx_v_p0)) + __Pyx_c_abs_double(__Pyx_c_diff_double(__pyx_v_p2, __pyx_v_p1))) > (__pyx_v_tolerance + __Pyx_c_abs_double(__Pyx_c_diff_double(__pyx_v_p2, __pyx_v_p0)))); + + if (__pyx_t_2) { + + + /* "fontTools/qu2cu/qu2cu.py":317 + * p2 = elevated_quadratics[i][1] + * if abs(p1 - p0) + abs(p2 - p1) > tolerance + abs(p2 - p0): + * forced.add(i) # <<<<<<<<<<<<<< + * + * # Dynamic-Programming to find the solution with fewest number of +*/ + __pyx_t_7 = __Pyx_PyLong_From_int(__pyx_v_i); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 317, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_11 = PySet_Add(__pyx_v_forced, __pyx_t_7); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(0, 317, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + + /* "fontTools/qu2cu/qu2cu.py":316 + * p1 = elevated_quadratics[i][0] + * p2 = elevated_quadratics[i][1] + * if abs(p1 - p0) + abs(p2 - p1) > tolerance + abs(p2 - p0): # <<<<<<<<<<<<<< + * forced.add(i) + * +*/ + } + } + + + + /* "fontTools/qu2cu/qu2cu.py":321 + * # Dynamic-Programming to find the solution with fewest number of + * # cubic curves, and within those the one with smallest error. + * sols = [Solution(0, 0, 0, False)] # <<<<<<<<<<<<<< + * impossible = Solution(len(elevated_quadratics) * 3 + 1, 0, 1, False) + * start = 0 +*/ + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_Solution); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 321, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_mstate_global->__pyx_tuple[0], NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 321, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyList_New(1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 321, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GIVEREF(__pyx_t_3); + if (__Pyx_PyList_SET_ITEM(__pyx_t_7, 0, __pyx_t_3) != (0)) __PYX_ERR(0, 321, __pyx_L1_error); + __pyx_t_3 = 0; + __pyx_v_sols = ((PyObject*)__pyx_t_7); + __pyx_t_7 = 0; + + /* "fontTools/qu2cu/qu2cu.py":322 + * # cubic curves, and within those the one with smallest error. + * sols = [Solution(0, 0, 0, False)] + * impossible = Solution(len(elevated_quadratics) * 3 + 1, 0, 1, False) # <<<<<<<<<<<<<< + * start = 0 + * for i in range(1, len(elevated_quadratics) + 1): +*/ + __pyx_t_3 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_mstate_global->__pyx_n_u_Solution); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 322, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_4 = __Pyx_PyList_GET_SIZE(__pyx_v_elevated_quadratics); if (unlikely(__pyx_t_4 == ((Py_ssize_t)-1))) __PYX_ERR(0, 322, __pyx_L1_error) + __pyx_t_6 = PyLong_FromSsize_t(((__pyx_t_4 * 3) + 1)); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 322, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + + __pyx_t_12 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_8))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_8); + assert(__pyx_t_3); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_8); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_8, __pyx__function); + __pyx_t_12 = 0; + } + #endif + { + PyObject *__pyx_callargs[5] = {__pyx_t_3, __pyx_t_6, __pyx_mstate_global->__pyx_int_0, __pyx_mstate_global->__pyx_int_1, Py_False}; + __pyx_t_7 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_8, __pyx_callargs+__pyx_t_12, (5-__pyx_t_12) | (__pyx_t_12*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 322, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + } + __pyx_v_impossible = __pyx_t_7; + __pyx_t_7 = 0; + + /* "fontTools/qu2cu/qu2cu.py":323 + * sols = [Solution(0, 0, 0, False)] + * impossible = Solution(len(elevated_quadratics) * 3 + 1, 0, 1, False) + * start = 0 # <<<<<<<<<<<<<< + * for i in range(1, len(elevated_quadratics) + 1): + * best_sol = impossible +*/ + __pyx_v_start = 0; + + /* "fontTools/qu2cu/qu2cu.py":324 + * impossible = Solution(len(elevated_quadratics) * 3 + 1, 0, 1, False) + * start = 0 + * for i in range(1, len(elevated_quadratics) + 1): # <<<<<<<<<<<<<< + * best_sol = impossible + * for j in range(start, i): +*/ + __pyx_t_4 = __Pyx_PyList_GET_SIZE(__pyx_v_elevated_quadratics); if (unlikely(__pyx_t_4 == ((Py_ssize_t)-1))) __PYX_ERR(0, 324, __pyx_L1_error) + + __pyx_t_1 = (__pyx_t_4 + 1); + + __pyx_t_4 = __pyx_t_1; + + for (__pyx_t_5 = 1; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "fontTools/qu2cu/qu2cu.py":325 + * start = 0 + * for i in range(1, len(elevated_quadratics) + 1): + * best_sol = impossible # <<<<<<<<<<<<<< + * for j in range(start, i): + * j_sol_count, j_sol_error = sols[j].num_points, sols[j].error +*/ + __Pyx_INCREF(__pyx_v_impossible); + __Pyx_XDECREF_SET(__pyx_v_best_sol, __pyx_v_impossible); + + /* "fontTools/qu2cu/qu2cu.py":326 + * for i in range(1, len(elevated_quadratics) + 1): + * best_sol = impossible + * for j in range(start, i): # <<<<<<<<<<<<<< + * j_sol_count, j_sol_error = sols[j].num_points, sols[j].error + * +*/ + + __pyx_t_13 = __pyx_v_i; + __pyx_t_14 = __pyx_t_13; + + for (__pyx_t_15 = __pyx_v_start; __pyx_t_15 < __pyx_t_14; __pyx_t_15+=1) { + __pyx_v_j = __pyx_t_15; + + /* "fontTools/qu2cu/qu2cu.py":327 + * best_sol = impossible + * for j in range(start, i): + * j_sol_count, j_sol_error = sols[j].num_points, sols[j].error # <<<<<<<<<<<<<< + * + * if not all_cubic: +*/ + __pyx_t_7 = __Pyx_GetItemInt_List(__pyx_v_sols, __pyx_v_j, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 327, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_num_points); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 327, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_16 = __Pyx_PyLong_As_int(__pyx_t_8); if (unlikely((__pyx_t_16 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 327, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_GetItemInt_List(__pyx_v_sols, __pyx_v_j, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 327, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_mstate_global->__pyx_n_u_error); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 327, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_17 = __Pyx_PyFloat_AsDouble(__pyx_t_7); if (unlikely((__pyx_t_17 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 327, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_v_j_sol_count = __pyx_t_16; + __pyx_v_j_sol_error = __pyx_t_17; + + /* "fontTools/qu2cu/qu2cu.py":329 + * j_sol_count, j_sol_error = sols[j].num_points, sols[j].error + * + * if not all_cubic: # <<<<<<<<<<<<<< + * # Solution with quadratics between j:i + * this_count = costs[2 * i - 1] - costs[2 * j] + 1 +*/ + __pyx_t_2 = (!(__pyx_v_all_cubic != 0)); + + if (__pyx_t_2) { + + + /* "fontTools/qu2cu/qu2cu.py":331 + * if not all_cubic: + * # Solution with quadratics between j:i + * this_count = costs[2 * i - 1] - costs[2 * j] + 1 # <<<<<<<<<<<<<< + * i_sol_count = j_sol_count + this_count + * i_sol_error = j_sol_error +*/ + __pyx_t_9 = ((2 * __pyx_v_i) - 1); + + __pyx_t_7 = __Pyx_GetItemInt(__pyx_v_costs, __pyx_t_9, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 331, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + + __pyx_t_9 = (2 * __pyx_v_j); + + __pyx_t_8 = __Pyx_GetItemInt(__pyx_v_costs, __pyx_t_9, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 331, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + + __pyx_t_6 = __Pyx_PyNumber_Subtract_object_object(__pyx_t_7, __pyx_t_8); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 331, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyLong_AddObjC(__pyx_t_6, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 331, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF_SET(__pyx_v_this_count, __pyx_t_8); + __pyx_t_8 = 0; + + /* "fontTools/qu2cu/qu2cu.py":332 + * # Solution with quadratics between j:i + * this_count = costs[2 * i - 1] - costs[2 * j] + 1 + * i_sol_count = j_sol_count + this_count # <<<<<<<<<<<<<< + * i_sol_error = j_sol_error + * i_sol = Solution(i_sol_count, i_sol_error, i - j, False) +*/ + __pyx_t_8 = __Pyx_PyLong_From_int(__pyx_v_j_sol_count); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 332, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_6 = __Pyx_PyNumber_Add_int_object(__pyx_t_8, __pyx_v_this_count); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 332, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_16 = __Pyx_PyLong_As_int(__pyx_t_6); if (unlikely((__pyx_t_16 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 332, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_i_sol_count = __pyx_t_16; + + /* "fontTools/qu2cu/qu2cu.py":333 + * this_count = costs[2 * i - 1] - costs[2 * j] + 1 + * i_sol_count = j_sol_count + this_count + * i_sol_error = j_sol_error # <<<<<<<<<<<<<< + * i_sol = Solution(i_sol_count, i_sol_error, i - j, False) + * if i_sol < best_sol: +*/ + __pyx_v_i_sol_error = __pyx_v_j_sol_error; + + /* "fontTools/qu2cu/qu2cu.py":334 + * i_sol_count = j_sol_count + this_count + * i_sol_error = j_sol_error + * i_sol = Solution(i_sol_count, i_sol_error, i - j, False) # <<<<<<<<<<<<<< + * if i_sol < best_sol: + * best_sol = i_sol +*/ + __pyx_t_8 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_Solution); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 334, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_i_sol_count); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 334, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_18 = PyFloat_FromDouble(__pyx_v_i_sol_error); if (unlikely(!__pyx_t_18)) __PYX_ERR(0, 334, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_18); + __pyx_t_19 = __Pyx_PyLong_From_int((__pyx_v_i - __pyx_v_j)); if (unlikely(!__pyx_t_19)) __PYX_ERR(0, 334, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_19); + __pyx_t_12 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_7))) { + __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_7); + assert(__pyx_t_8); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_7); + __Pyx_INCREF(__pyx_t_8); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_7, __pyx__function); + __pyx_t_12 = 0; + } + #endif + { + PyObject *__pyx_callargs[5] = {__pyx_t_8, __pyx_t_3, __pyx_t_18, __pyx_t_19, Py_False}; + __pyx_t_6 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_7, __pyx_callargs+__pyx_t_12, (5-__pyx_t_12) | (__pyx_t_12*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; + __Pyx_DECREF(__pyx_t_19); __pyx_t_19 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 334, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __Pyx_XDECREF_SET(__pyx_v_i_sol, __pyx_t_6); + __pyx_t_6 = 0; + + /* "fontTools/qu2cu/qu2cu.py":335 + * i_sol_error = j_sol_error + * i_sol = Solution(i_sol_count, i_sol_error, i - j, False) + * if i_sol < best_sol: # <<<<<<<<<<<<<< + * best_sol = i_sol + * +*/ + __pyx_t_2 = __Pyx_PyObject_CompareBoolLt_object_object(__pyx_v_i_sol, __pyx_v_best_sol, Py_LT); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 335, __pyx_L1_error) + if (__pyx_t_2) { + + + /* "fontTools/qu2cu/qu2cu.py":336 + * i_sol = Solution(i_sol_count, i_sol_error, i - j, False) + * if i_sol < best_sol: + * best_sol = i_sol # <<<<<<<<<<<<<< + * + * if this_count <= 3: +*/ + __Pyx_INCREF(__pyx_v_i_sol); + __Pyx_DECREF_SET(__pyx_v_best_sol, __pyx_v_i_sol); + + /* "fontTools/qu2cu/qu2cu.py":335 + * i_sol_error = j_sol_error + * i_sol = Solution(i_sol_count, i_sol_error, i - j, False) + * if i_sol < best_sol: # <<<<<<<<<<<<<< + * best_sol = i_sol + * +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":338 + * best_sol = i_sol + * + * if this_count <= 3: # <<<<<<<<<<<<<< + * # Can't get any better than this in the path below + * continue +*/ + __pyx_t_2 = __Pyx_PyObject_CompareBoolLe_object_int(__pyx_v_this_count, __pyx_mstate_global->__pyx_int_3, Py_LE); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 338, __pyx_L1_error) + if (__pyx_t_2) { + + + /* "fontTools/qu2cu/qu2cu.py":340 + * if this_count <= 3: + * # Can't get any better than this in the path below + * continue # <<<<<<<<<<<<<< + * + * # Fit elevated_quadratics[j:i] into one cubic +*/ + goto __pyx_L10_continue; + + /* "fontTools/qu2cu/qu2cu.py":338 + * best_sol = i_sol + * + * if this_count <= 3: # <<<<<<<<<<<<<< + * # Can't get any better than this in the path below + * continue +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":329 + * j_sol_count, j_sol_error = sols[j].num_points, sols[j].error + * + * if not all_cubic: # <<<<<<<<<<<<<< + * # Solution with quadratics between j:i + * this_count = costs[2 * i - 1] - costs[2 * j] + 1 +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":343 + * + * # Fit elevated_quadratics[j:i] into one cubic + * try: # <<<<<<<<<<<<<< + * curve, ts = merge_curves(elevated_quadratics, j, i - j) + * except ZeroDivisionError: +*/ + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_20, &__pyx_t_21, &__pyx_t_22); + __Pyx_XGOTREF(__pyx_t_20); + __Pyx_XGOTREF(__pyx_t_21); + __Pyx_XGOTREF(__pyx_t_22); + /*try:*/ { + + /* "fontTools/qu2cu/qu2cu.py":344 + * # Fit elevated_quadratics[j:i] into one cubic + * try: + * curve, ts = merge_curves(elevated_quadratics, j, i - j) # <<<<<<<<<<<<<< + * except ZeroDivisionError: + * continue +*/ + __pyx_t_6 = __pyx_f_9fontTools_5qu2cu_5qu2cu_merge_curves(__pyx_v_elevated_quadratics, __pyx_v_j, (__pyx_v_i - __pyx_v_j)); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 344, __pyx_L15_error) + __Pyx_GOTREF(__pyx_t_6); + if ((likely(PyTuple_CheckExact(__pyx_t_6))) || (PyList_CheckExact(__pyx_t_6))) { + PyObject* sequence = __pyx_t_6; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 344, __pyx_L15_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_7 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_7); + __pyx_t_19 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_19); + } else { + __pyx_t_7 = __Pyx_PyList_GET_ITEM_REF(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 344, __pyx_L15_error) + __Pyx_XGOTREF(__pyx_t_7); + __pyx_t_19 = __Pyx_PyList_GET_ITEM_REF(sequence, 1, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_19)) __PYX_ERR(0, 344, __pyx_L15_error) + __Pyx_XGOTREF(__pyx_t_19); + } + #else + __pyx_t_7 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 344, __pyx_L15_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_19 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_19)) __PYX_ERR(0, 344, __pyx_L15_error) + __Pyx_GOTREF(__pyx_t_19); + #endif + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_18 = PyObject_GetIter(__pyx_t_6); if (unlikely(!__pyx_t_18)) __PYX_ERR(0, 344, __pyx_L15_error) + __Pyx_GOTREF(__pyx_t_18); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_23 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_18); + index = 0; __pyx_t_7 = __pyx_t_23(__pyx_t_18); if (unlikely(!__pyx_t_7)) goto __pyx_L23_unpacking_failed; + __Pyx_GOTREF(__pyx_t_7); + index = 1; __pyx_t_19 = __pyx_t_23(__pyx_t_18); if (unlikely(!__pyx_t_19)) goto __pyx_L23_unpacking_failed; + __Pyx_GOTREF(__pyx_t_19); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_23(__pyx_t_18), 2) < (0)) __PYX_ERR(0, 344, __pyx_L15_error) + __pyx_t_23 = NULL; + __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; + goto __pyx_L24_unpacking_done; + __pyx_L23_unpacking_failed:; + __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; + __pyx_t_23 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 344, __pyx_L15_error) + __pyx_L24_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_v_curve, __pyx_t_7); + __pyx_t_7 = 0; + __Pyx_XDECREF_SET(__pyx_v_ts, __pyx_t_19); + __pyx_t_19 = 0; + + /* "fontTools/qu2cu/qu2cu.py":343 + * + * # Fit elevated_quadratics[j:i] into one cubic + * try: # <<<<<<<<<<<<<< + * curve, ts = merge_curves(elevated_quadratics, j, i - j) + * except ZeroDivisionError: +*/ + } + __Pyx_XDECREF(__pyx_t_20); __pyx_t_20 = 0; + __Pyx_XDECREF(__pyx_t_21); __pyx_t_21 = 0; + __Pyx_XDECREF(__pyx_t_22); __pyx_t_22 = 0; + goto __pyx_L22_try_end; + __pyx_L15_error:; + __Pyx_XDECREF(__pyx_t_18); __pyx_t_18 = 0; + __Pyx_XDECREF(__pyx_t_19); __pyx_t_19 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "fontTools/qu2cu/qu2cu.py":345 + * try: + * curve, ts = merge_curves(elevated_quadratics, j, i - j) + * except ZeroDivisionError: # <<<<<<<<<<<<<< + * continue + * +*/ + __pyx_t_16 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(((PyTypeObject*)PyExc_ZeroDivisionError)))); + if (__pyx_t_16) { + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu.spline_to_curves", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_6, &__pyx_t_19, &__pyx_t_7) < 0) __PYX_ERR(0, 345, __pyx_L17_except_error) + __Pyx_XGOTREF(__pyx_t_6); + __Pyx_XGOTREF(__pyx_t_19); + __Pyx_XGOTREF(__pyx_t_7); + + /* "fontTools/qu2cu/qu2cu.py":346 + * curve, ts = merge_curves(elevated_quadratics, j, i - j) + * except ZeroDivisionError: + * continue # <<<<<<<<<<<<<< + * + * # Now reconstruct the segments from the fitted curve +*/ + goto __pyx_L25_except_continue; + __pyx_L25_except_continue:; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_19); __pyx_t_19 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L21_try_continue; + } + goto __pyx_L17_except_error; + + /* "fontTools/qu2cu/qu2cu.py":343 + * + * # Fit elevated_quadratics[j:i] into one cubic + * try: # <<<<<<<<<<<<<< + * curve, ts = merge_curves(elevated_quadratics, j, i - j) + * except ZeroDivisionError: +*/ + __pyx_L17_except_error:; + __Pyx_XGIVEREF(__pyx_t_20); + __Pyx_XGIVEREF(__pyx_t_21); + __Pyx_XGIVEREF(__pyx_t_22); + __Pyx_ExceptionReset(__pyx_t_20, __pyx_t_21, __pyx_t_22); + goto __pyx_L1_error; + __pyx_L21_try_continue:; + __Pyx_XGIVEREF(__pyx_t_20); + __Pyx_XGIVEREF(__pyx_t_21); + __Pyx_XGIVEREF(__pyx_t_22); + __Pyx_ExceptionReset(__pyx_t_20, __pyx_t_21, __pyx_t_22); + goto __pyx_L10_continue; + __pyx_L22_try_end:; + } + + /* "fontTools/qu2cu/qu2cu.py":349 + * + * # Now reconstruct the segments from the fitted curve + * reconstructed_iter = splitCubicAtTC(*curve, *ts) # <<<<<<<<<<<<<< + * reconstructed = [] + * +*/ + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_splitCubicAtTC); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 349, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_19 = __Pyx_PySequence_Tuple(__pyx_v_curve); if (unlikely(!__pyx_t_19)) __PYX_ERR(0, 349, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_19); + __pyx_t_6 = __Pyx_PySequence_Tuple(__pyx_v_ts); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 349, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_18 = PyNumber_Add(__pyx_t_19, __pyx_t_6); if (unlikely(!__pyx_t_18)) __PYX_ERR(0, 349, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_18); + __Pyx_DECREF(__pyx_t_19); __pyx_t_19 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_18, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 349, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; + __Pyx_XDECREF_SET(__pyx_v_reconstructed_iter, __pyx_t_6); + __pyx_t_6 = 0; + + /* "fontTools/qu2cu/qu2cu.py":350 + * # Now reconstruct the segments from the fitted curve + * reconstructed_iter = splitCubicAtTC(*curve, *ts) + * reconstructed = [] # <<<<<<<<<<<<<< + * + * # Knot errors +*/ + __pyx_t_6 = PyList_New(0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 350, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_XDECREF_SET(__pyx_v_reconstructed, ((PyObject*)__pyx_t_6)); + __pyx_t_6 = 0; + + /* "fontTools/qu2cu/qu2cu.py":353 + * + * # Knot errors + * error = 0 # <<<<<<<<<<<<<< + * for k, reconst in enumerate(reconstructed_iter): + * orig = elevated_quadratics[j + k] +*/ + __pyx_v_error = 0.0; + + /* "fontTools/qu2cu/qu2cu.py":354 + * # Knot errors + * error = 0 + * for k, reconst in enumerate(reconstructed_iter): # <<<<<<<<<<<<<< + * orig = elevated_quadratics[j + k] + * err = abs(reconst[3] - orig[3]) +*/ + + __pyx_t_16 = 0; + if (likely(PyList_CheckExact(__pyx_v_reconstructed_iter)) || PyTuple_CheckExact(__pyx_v_reconstructed_iter)) { + __pyx_t_6 = __pyx_v_reconstructed_iter; __Pyx_INCREF(__pyx_t_6); + __pyx_t_24 = 0; + __pyx_t_25 = NULL; + } else { + __pyx_t_24 = -1; __pyx_t_6 = PyObject_GetIter(__pyx_v_reconstructed_iter); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 354, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_25 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_6); if (unlikely(!__pyx_t_25)) __PYX_ERR(0, 354, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_25)) { + if (likely(PyList_CheckExact(__pyx_t_6))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 354, __pyx_L1_error) + #endif + if (__pyx_t_24 >= __pyx_temp) break; + } + __pyx_t_18 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_6, __pyx_t_24, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_24; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 354, __pyx_L1_error) + #endif + if (__pyx_t_24 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_18 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_6, __pyx_t_24)); + #else + __pyx_t_18 = __Pyx_PySequence_ITEM(__pyx_t_6, __pyx_t_24); + #endif + ++__pyx_t_24; + } + if (unlikely(!__pyx_t_18)) __PYX_ERR(0, 354, __pyx_L1_error) + } else { + __pyx_t_18 = __pyx_t_25(__pyx_t_6); + if (unlikely(!__pyx_t_18)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 354, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_18); + __Pyx_XDECREF_SET(__pyx_v_reconst, __pyx_t_18); + __pyx_t_18 = 0; + __pyx_v_k = __pyx_t_16; + __pyx_t_16 = (__pyx_t_16 + 1); + + /* "fontTools/qu2cu/qu2cu.py":355 + * error = 0 + * for k, reconst in enumerate(reconstructed_iter): + * orig = elevated_quadratics[j + k] # <<<<<<<<<<<<<< + * err = abs(reconst[3] - orig[3]) + * error = max(error, err) +*/ + __pyx_t_26 = (__pyx_v_j + __pyx_v_k); + + __pyx_t_18 = __Pyx_GetItemInt_List(__pyx_v_elevated_quadratics, __pyx_t_26, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_18)) __PYX_ERR(0, 355, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_18); + + __Pyx_XDECREF_SET(__pyx_v_orig, __pyx_t_18); + __pyx_t_18 = 0; + + /* "fontTools/qu2cu/qu2cu.py":356 + * for k, reconst in enumerate(reconstructed_iter): + * orig = elevated_quadratics[j + k] + * err = abs(reconst[3] - orig[3]) # <<<<<<<<<<<<<< + * error = max(error, err) + * if error > tolerance: +*/ + __pyx_t_18 = __Pyx_GetItemInt(__pyx_v_reconst, 3, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_18)) __PYX_ERR(0, 356, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_18); + __pyx_t_7 = __Pyx_GetItemInt(__pyx_v_orig, 3, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 356, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_19 = __Pyx_PyNumber_Subtract_object_object(__pyx_t_18, __pyx_t_7); if (unlikely(!__pyx_t_19)) __PYX_ERR(0, 356, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_19); + __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyNumber_Absolute(__pyx_t_19); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 356, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_19); __pyx_t_19 = 0; + __pyx_t_17 = __Pyx_PyFloat_AsDouble(__pyx_t_7); if (unlikely((__pyx_t_17 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 356, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_v_err = __pyx_t_17; + + /* "fontTools/qu2cu/qu2cu.py":357 + * orig = elevated_quadratics[j + k] + * err = abs(reconst[3] - orig[3]) + * error = max(error, err) # <<<<<<<<<<<<<< + * if error > tolerance: + * break +*/ + + __pyx_t_17 = __pyx_v_err; + + __pyx_t_27 = __pyx_v_error; + __pyx_t_2 = (__pyx_t_17 > __pyx_t_27); + + if (__pyx_t_2) { + + __pyx_t_28 = __pyx_t_17; + } else { + + __pyx_t_28 = __pyx_t_27; + } + + __pyx_v_error = __pyx_t_28; + + + /* "fontTools/qu2cu/qu2cu.py":358 + * err = abs(reconst[3] - orig[3]) + * error = max(error, err) + * if error > tolerance: # <<<<<<<<<<<<<< + * break + * reconstructed.append(reconst) +*/ + __pyx_t_2 = (__pyx_v_error > __pyx_v_tolerance); + + if (__pyx_t_2) { + + + /* "fontTools/qu2cu/qu2cu.py":359 + * error = max(error, err) + * if error > tolerance: + * break # <<<<<<<<<<<<<< + * reconstructed.append(reconst) + * if error > tolerance: +*/ + goto __pyx_L28_break; + + /* "fontTools/qu2cu/qu2cu.py":358 + * err = abs(reconst[3] - orig[3]) + * error = max(error, err) + * if error > tolerance: # <<<<<<<<<<<<<< + * break + * reconstructed.append(reconst) +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":360 + * if error > tolerance: + * break + * reconstructed.append(reconst) # <<<<<<<<<<<<<< + * if error > tolerance: + * # Not feasible +*/ + __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_reconstructed, __pyx_v_reconst); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(0, 360, __pyx_L1_error) + + + /* "fontTools/qu2cu/qu2cu.py":354 + * # Knot errors + * error = 0 + * for k, reconst in enumerate(reconstructed_iter): # <<<<<<<<<<<<<< + * orig = elevated_quadratics[j + k] + * err = abs(reconst[3] - orig[3]) +*/ + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L30_for_end; + __pyx_L28_break:; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L30_for_end; + __pyx_L30_for_end:; + + /* "fontTools/qu2cu/qu2cu.py":361 + * break + * reconstructed.append(reconst) + * if error > tolerance: # <<<<<<<<<<<<<< + * # Not feasible + * continue +*/ + __pyx_t_2 = (__pyx_v_error > __pyx_v_tolerance); + + if (__pyx_t_2) { + + + /* "fontTools/qu2cu/qu2cu.py":363 + * if error > tolerance: + * # Not feasible + * continue # <<<<<<<<<<<<<< + * + * # Interior errors +*/ + goto __pyx_L10_continue; + + /* "fontTools/qu2cu/qu2cu.py":361 + * break + * reconstructed.append(reconst) + * if error > tolerance: # <<<<<<<<<<<<<< + * # Not feasible + * continue +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":366 + * + * # Interior errors + * for k, reconst in enumerate(reconstructed): # <<<<<<<<<<<<<< + * orig = elevated_quadratics[j + k] + * p0, p1, p2, p3 = tuple(v - u for v, u in zip(reconst, orig)) +*/ + + __pyx_t_16 = 0; + __pyx_t_6 = __pyx_v_reconstructed; __Pyx_INCREF(__pyx_t_6); + __pyx_t_24 = 0; + for (;;) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 366, __pyx_L1_error) + #endif + if (__pyx_t_24 >= __pyx_temp) break; + } + __pyx_t_7 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_6, __pyx_t_24, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_24; + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 366, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_XDECREF_SET(__pyx_v_reconst, __pyx_t_7); + __pyx_t_7 = 0; + __pyx_v_k = __pyx_t_16; + __pyx_t_16 = (__pyx_t_16 + 1); + + /* "fontTools/qu2cu/qu2cu.py":367 + * # Interior errors + * for k, reconst in enumerate(reconstructed): + * orig = elevated_quadratics[j + k] # <<<<<<<<<<<<<< + * p0, p1, p2, p3 = tuple(v - u for v, u in zip(reconst, orig)) + * +*/ + __pyx_t_26 = (__pyx_v_j + __pyx_v_k); + + __pyx_t_7 = __Pyx_GetItemInt_List(__pyx_v_elevated_quadratics, __pyx_t_26, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 367, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + + __Pyx_XDECREF_SET(__pyx_v_orig, __pyx_t_7); + __pyx_t_7 = 0; + + /* "fontTools/qu2cu/qu2cu.py":368 + * for k, reconst in enumerate(reconstructed): + * orig = elevated_quadratics[j + k] + * p0, p1, p2, p3 = tuple(v - u for v, u in zip(reconst, orig)) # <<<<<<<<<<<<<< + * + * if not cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance): +*/ + __pyx_t_19 = NULL; + __pyx_t_12 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_19, __pyx_v_reconst, __pyx_v_orig}; + __pyx_t_7 = __Pyx_PyObject_FastCall((PyObject*)__pyx_builtin_zip, __pyx_callargs+__pyx_t_12, (3-__pyx_t_12) | (__pyx_t_12*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_19); __pyx_t_19 = 0; + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + } + __pyx_t_19 = __pyx_pf_9fontTools_5qu2cu_5qu2cu_16spline_to_curves_genexpr(NULL, __pyx_t_7); if (unlikely(!__pyx_t_19)) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_19); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PySequence_Tuple(__pyx_t_19); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_19); __pyx_t_19 = 0; + if (1) { + PyObject* sequence = __pyx_t_7; + Py_ssize_t size = __Pyx_PyTuple_GET_SIZE(sequence); + if (unlikely(size != 4)) { + if (size > 4) __Pyx_RaiseTooManyValuesError(4); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 368, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_19 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_19); + __pyx_t_18 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_18); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 2); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_8 = PyTuple_GET_ITEM(sequence, 3); + __Pyx_INCREF(__pyx_t_8); + #else + { + Py_ssize_t i; + PyObject** temps[4] = {&__pyx_t_19,&__pyx_t_18,&__pyx_t_3,&__pyx_t_8}; + for (i=0; i < 4; i++) { + PyObject* item = __Pyx_PySequence_ITEM(sequence, i); if (unlikely(!item)) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_GOTREF(item); + *(temps[i]) = item; + } + } + #endif + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + } + __pyx_t_10 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_19); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_19); __pyx_t_19 = 0; + __pyx_t_29 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_18); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; + __pyx_t_30 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_3); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_31 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_8); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 368, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_v_p0 = __pyx_t_10; + __pyx_v_p1 = __pyx_t_29; + __pyx_v_p2 = __pyx_t_30; + __pyx_v_p3 = __pyx_t_31; + + /* "fontTools/qu2cu/qu2cu.py":370 + * p0, p1, p2, p3 = tuple(v - u for v, u in zip(reconst, orig)) + * + * if not cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance): # <<<<<<<<<<<<<< + * error = tolerance + 1 + * break +*/ + __pyx_t_26 = __pyx_f_9fontTools_5qu2cu_5qu2cu_cubic_farthest_fit_inside(__pyx_v_p0, __pyx_v_p1, __pyx_v_p2, __pyx_v_p3, __pyx_v_tolerance); if (unlikely(__pyx_t_26 == ((int)-1) && PyErr_Occurred())) __PYX_ERR(0, 370, __pyx_L1_error) + __pyx_t_2 = (!(__pyx_t_26 != 0)); + + + if (__pyx_t_2) { + + + /* "fontTools/qu2cu/qu2cu.py":371 + * + * if not cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance): + * error = tolerance + 1 # <<<<<<<<<<<<<< + * break + * if error > tolerance: +*/ + __pyx_v_error = (__pyx_v_tolerance + 1.0); + + /* "fontTools/qu2cu/qu2cu.py":372 + * if not cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance): + * error = tolerance + 1 + * break # <<<<<<<<<<<<<< + * if error > tolerance: + * # Not feasible +*/ + goto __pyx_L33_break; + + /* "fontTools/qu2cu/qu2cu.py":370 + * p0, p1, p2, p3 = tuple(v - u for v, u in zip(reconst, orig)) + * + * if not cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance): # <<<<<<<<<<<<<< + * error = tolerance + 1 + * break +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":366 + * + * # Interior errors + * for k, reconst in enumerate(reconstructed): # <<<<<<<<<<<<<< + * orig = elevated_quadratics[j + k] + * p0, p1, p2, p3 = tuple(v - u for v, u in zip(reconst, orig)) +*/ + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L35_for_end; + __pyx_L33_break:; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L35_for_end; + __pyx_L35_for_end:; + + /* "fontTools/qu2cu/qu2cu.py":373 + * error = tolerance + 1 + * break + * if error > tolerance: # <<<<<<<<<<<<<< + * # Not feasible + * continue +*/ + __pyx_t_2 = (__pyx_v_error > __pyx_v_tolerance); + + if (__pyx_t_2) { + + + /* "fontTools/qu2cu/qu2cu.py":375 + * if error > tolerance: + * # Not feasible + * continue # <<<<<<<<<<<<<< + * + * # Save best solution +*/ + goto __pyx_L10_continue; + + /* "fontTools/qu2cu/qu2cu.py":373 + * error = tolerance + 1 + * break + * if error > tolerance: # <<<<<<<<<<<<<< + * # Not feasible + * continue +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":378 + * + * # Save best solution + * i_sol_count = j_sol_count + 3 # <<<<<<<<<<<<<< + * i_sol_error = max(j_sol_error, error) + * i_sol = Solution(i_sol_count, i_sol_error, i - j, True) +*/ + __pyx_v_i_sol_count = (__pyx_v_j_sol_count + 3); + + /* "fontTools/qu2cu/qu2cu.py":379 + * # Save best solution + * i_sol_count = j_sol_count + 3 + * i_sol_error = max(j_sol_error, error) # <<<<<<<<<<<<<< + * i_sol = Solution(i_sol_count, i_sol_error, i - j, True) + * if i_sol < best_sol: +*/ + + __pyx_t_28 = __pyx_v_error; + + __pyx_t_17 = __pyx_v_j_sol_error; + __pyx_t_2 = (__pyx_t_28 > __pyx_t_17); + + if (__pyx_t_2) { + + __pyx_t_27 = __pyx_t_28; + } else { + + __pyx_t_27 = __pyx_t_17; + } + + __pyx_v_i_sol_error = __pyx_t_27; + + + /* "fontTools/qu2cu/qu2cu.py":380 + * i_sol_count = j_sol_count + 3 + * i_sol_error = max(j_sol_error, error) + * i_sol = Solution(i_sol_count, i_sol_error, i - j, True) # <<<<<<<<<<<<<< + * if i_sol < best_sol: + * best_sol = i_sol +*/ + __pyx_t_7 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_mstate_global->__pyx_n_u_Solution); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 380, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_i_sol_count); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 380, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_18 = PyFloat_FromDouble(__pyx_v_i_sol_error); if (unlikely(!__pyx_t_18)) __PYX_ERR(0, 380, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_18); + __pyx_t_19 = __Pyx_PyLong_From_int((__pyx_v_i - __pyx_v_j)); if (unlikely(!__pyx_t_19)) __PYX_ERR(0, 380, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_19); + __pyx_t_12 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_8))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_8); + assert(__pyx_t_7); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_8); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_8, __pyx__function); + __pyx_t_12 = 0; + } + #endif + { + PyObject *__pyx_callargs[5] = {__pyx_t_7, __pyx_t_3, __pyx_t_18, __pyx_t_19, Py_True}; + __pyx_t_6 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_8, __pyx_callargs+__pyx_t_12, (5-__pyx_t_12) | (__pyx_t_12*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; + __Pyx_DECREF(__pyx_t_19); __pyx_t_19 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 380, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __Pyx_XDECREF_SET(__pyx_v_i_sol, __pyx_t_6); + __pyx_t_6 = 0; + + /* "fontTools/qu2cu/qu2cu.py":381 + * i_sol_error = max(j_sol_error, error) + * i_sol = Solution(i_sol_count, i_sol_error, i - j, True) + * if i_sol < best_sol: # <<<<<<<<<<<<<< + * best_sol = i_sol + * +*/ + __pyx_t_2 = __Pyx_PyObject_CompareBoolLt_object_object(__pyx_v_i_sol, __pyx_v_best_sol, Py_LT); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 381, __pyx_L1_error) + if (__pyx_t_2) { + + + /* "fontTools/qu2cu/qu2cu.py":382 + * i_sol = Solution(i_sol_count, i_sol_error, i - j, True) + * if i_sol < best_sol: + * best_sol = i_sol # <<<<<<<<<<<<<< + * + * if i_sol_count == 3: +*/ + __Pyx_INCREF(__pyx_v_i_sol); + __Pyx_DECREF_SET(__pyx_v_best_sol, __pyx_v_i_sol); + + /* "fontTools/qu2cu/qu2cu.py":381 + * i_sol_error = max(j_sol_error, error) + * i_sol = Solution(i_sol_count, i_sol_error, i - j, True) + * if i_sol < best_sol: # <<<<<<<<<<<<<< + * best_sol = i_sol + * +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":384 + * best_sol = i_sol + * + * if i_sol_count == 3: # <<<<<<<<<<<<<< + * # Can't get any better than this + * break +*/ + __pyx_t_2 = (__pyx_v_i_sol_count == 3); + + if (__pyx_t_2) { + + + /* "fontTools/qu2cu/qu2cu.py":386 + * if i_sol_count == 3: + * # Can't get any better than this + * break # <<<<<<<<<<<<<< + * + * sols.append(best_sol) +*/ + goto __pyx_L11_break; + + /* "fontTools/qu2cu/qu2cu.py":384 + * best_sol = i_sol + * + * if i_sol_count == 3: # <<<<<<<<<<<<<< + * # Can't get any better than this + * break +*/ + } + __pyx_L10_continue:; + } + __pyx_L11_break:; + + + /* "fontTools/qu2cu/qu2cu.py":388 + * break + * + * sols.append(best_sol) # <<<<<<<<<<<<<< + * if i in forced: + * start = i +*/ + __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_sols, __pyx_v_best_sol); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(0, 388, __pyx_L1_error) + + + /* "fontTools/qu2cu/qu2cu.py":389 + * + * sols.append(best_sol) + * if i in forced: # <<<<<<<<<<<<<< + * start = i + * +*/ + __pyx_t_6 = __Pyx_PyLong_From_int(__pyx_v_i); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 389, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_2 = (__Pyx_PySet_ContainsTF(__pyx_t_6, __pyx_v_forced, Py_EQ)); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 389, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (__pyx_t_2) { + + + /* "fontTools/qu2cu/qu2cu.py":390 + * sols.append(best_sol) + * if i in forced: + * start = i # <<<<<<<<<<<<<< + * + * # Reconstruct solution +*/ + __pyx_v_start = __pyx_v_i; + + /* "fontTools/qu2cu/qu2cu.py":389 + * + * sols.append(best_sol) + * if i in forced: # <<<<<<<<<<<<<< + * start = i + * +*/ + } + } + + + /* "fontTools/qu2cu/qu2cu.py":393 + * + * # Reconstruct solution + * splits = [] # <<<<<<<<<<<<<< + * cubic = [] + * i = len(sols) - 1 +*/ + __pyx_t_6 = PyList_New(0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 393, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_v_splits = ((PyObject*)__pyx_t_6); + __pyx_t_6 = 0; + + /* "fontTools/qu2cu/qu2cu.py":394 + * # Reconstruct solution + * splits = [] + * cubic = [] # <<<<<<<<<<<<<< + * i = len(sols) - 1 + * while i: +*/ + __pyx_t_6 = PyList_New(0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 394, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_v_cubic = ((PyObject*)__pyx_t_6); + __pyx_t_6 = 0; + + /* "fontTools/qu2cu/qu2cu.py":395 + * splits = [] + * cubic = [] + * i = len(sols) - 1 # <<<<<<<<<<<<<< + * while i: + * count, is_cubic = sols[i].start_index, sols[i].is_cubic +*/ + __pyx_t_1 = __Pyx_PyList_GET_SIZE(__pyx_v_sols); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 395, __pyx_L1_error) + __pyx_v_i = (__pyx_t_1 - 1); + + + /* "fontTools/qu2cu/qu2cu.py":396 + * cubic = [] + * i = len(sols) - 1 + * while i: # <<<<<<<<<<<<<< + * count, is_cubic = sols[i].start_index, sols[i].is_cubic + * splits.append(i) +*/ + while (1) { + __pyx_t_2 = (__pyx_v_i != 0); + + + if (!__pyx_t_2) break; + + /* "fontTools/qu2cu/qu2cu.py":397 + * i = len(sols) - 1 + * while i: + * count, is_cubic = sols[i].start_index, sols[i].is_cubic # <<<<<<<<<<<<<< + * splits.append(i) + * cubic.append(is_cubic) +*/ + __pyx_t_6 = __Pyx_GetItemInt_List(__pyx_v_sols, __pyx_v_i, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 397, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_start_index); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 397, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_5 = __Pyx_PyLong_As_int(__pyx_t_8); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 397, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_GetItemInt_List(__pyx_v_sols, __pyx_v_i, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 397, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_mstate_global->__pyx_n_u_is_cubic); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 397, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_13 = __Pyx_PyLong_As_int(__pyx_t_6); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 397, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_count = __pyx_t_5; + __pyx_v_is_cubic = __pyx_t_13; + + /* "fontTools/qu2cu/qu2cu.py":398 + * while i: + * count, is_cubic = sols[i].start_index, sols[i].is_cubic + * splits.append(i) # <<<<<<<<<<<<<< + * cubic.append(is_cubic) + * i -= count +*/ + __pyx_t_6 = __Pyx_PyLong_From_int(__pyx_v_i); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 398, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_splits, __pyx_t_6); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(0, 398, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + + /* "fontTools/qu2cu/qu2cu.py":399 + * count, is_cubic = sols[i].start_index, sols[i].is_cubic + * splits.append(i) + * cubic.append(is_cubic) # <<<<<<<<<<<<<< + * i -= count + * curves = [] +*/ + __pyx_t_6 = __Pyx_PyLong_From_int(__pyx_v_is_cubic); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 399, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_cubic, __pyx_t_6); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(0, 399, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + + /* "fontTools/qu2cu/qu2cu.py":400 + * splits.append(i) + * cubic.append(is_cubic) + * i -= count # <<<<<<<<<<<<<< + * curves = [] + * j = 0 +*/ + __pyx_v_i = (__pyx_v_i - __pyx_v_count); + } + + /* "fontTools/qu2cu/qu2cu.py":401 + * cubic.append(is_cubic) + * i -= count + * curves = [] # <<<<<<<<<<<<<< + * j = 0 + * for i, is_cubic in reversed(list(zip(splits, cubic))): +*/ + __pyx_t_6 = PyList_New(0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 401, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_v_curves = ((PyObject*)__pyx_t_6); + __pyx_t_6 = 0; + + /* "fontTools/qu2cu/qu2cu.py":402 + * i -= count + * curves = [] + * j = 0 # <<<<<<<<<<<<<< + * for i, is_cubic in reversed(list(zip(splits, cubic))): + * if is_cubic: +*/ + __pyx_v_j = 0; + + /* "fontTools/qu2cu/qu2cu.py":403 + * curves = [] + * j = 0 + * for i, is_cubic in reversed(list(zip(splits, cubic))): # <<<<<<<<<<<<<< + * if is_cubic: + * curves.append(merge_curves(elevated_quadratics, j, i - j)[0]) +*/ + __pyx_t_8 = NULL; + __pyx_t_12 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_8, __pyx_v_splits, __pyx_v_cubic}; + __pyx_t_6 = __Pyx_PyObject_FastCall((PyObject*)__pyx_builtin_zip, __pyx_callargs+__pyx_t_12, (3-__pyx_t_12) | (__pyx_t_12*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 403, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __pyx_t_8 = __Pyx_PySequence_ListKeepNew(__pyx_t_6); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 403, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __pyx_t_8; __Pyx_INCREF(__pyx_t_6); + __pyx_t_1 = __Pyx_PyList_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 403, __pyx_L1_error) + #endif + --__pyx_t_1; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + for (;;) { + if (__pyx_t_1 < 0) break; + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 403, __pyx_L1_error) + #endif + if (__pyx_t_1 >= __pyx_temp) break; + } + __pyx_t_8 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_6, __pyx_t_1, __Pyx_ReferenceSharing_OwnStrongReference); + --__pyx_t_1; + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 403, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + if ((likely(PyTuple_CheckExact(__pyx_t_8))) || (PyList_CheckExact(__pyx_t_8))) { + PyObject* sequence = __pyx_t_8; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 403, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_19 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_19); + __pyx_t_18 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_18); + } else { + __pyx_t_19 = __Pyx_PyList_GET_ITEM_REF(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_19)) __PYX_ERR(0, 403, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_19); + __pyx_t_18 = __Pyx_PyList_GET_ITEM_REF(sequence, 1, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_18)) __PYX_ERR(0, 403, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_18); + } + #else + __pyx_t_19 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_19)) __PYX_ERR(0, 403, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_19); + __pyx_t_18 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_18)) __PYX_ERR(0, 403, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_18); + #endif + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_3 = PyObject_GetIter(__pyx_t_8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 403, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_23 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_3); + index = 0; __pyx_t_19 = __pyx_t_23(__pyx_t_3); if (unlikely(!__pyx_t_19)) goto __pyx_L44_unpacking_failed; + __Pyx_GOTREF(__pyx_t_19); + index = 1; __pyx_t_18 = __pyx_t_23(__pyx_t_3); if (unlikely(!__pyx_t_18)) goto __pyx_L44_unpacking_failed; + __Pyx_GOTREF(__pyx_t_18); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_23(__pyx_t_3), 2) < (0)) __PYX_ERR(0, 403, __pyx_L1_error) + __pyx_t_23 = NULL; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L45_unpacking_done; + __pyx_L44_unpacking_failed:; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_23 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 403, __pyx_L1_error) + __pyx_L45_unpacking_done:; + } + __pyx_t_13 = __Pyx_PyLong_As_int(__pyx_t_19); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 403, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_19); __pyx_t_19 = 0; + __pyx_t_5 = __Pyx_PyLong_As_int(__pyx_t_18); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 403, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; + __pyx_v_i = __pyx_t_13; + __pyx_v_is_cubic = __pyx_t_5; + + /* "fontTools/qu2cu/qu2cu.py":404 + * j = 0 + * for i, is_cubic in reversed(list(zip(splits, cubic))): + * if is_cubic: # <<<<<<<<<<<<<< + * curves.append(merge_curves(elevated_quadratics, j, i - j)[0]) + * else: +*/ + __pyx_t_2 = (__pyx_v_is_cubic != 0); + + if (__pyx_t_2) { + + + /* "fontTools/qu2cu/qu2cu.py":405 + * for i, is_cubic in reversed(list(zip(splits, cubic))): + * if is_cubic: + * curves.append(merge_curves(elevated_quadratics, j, i - j)[0]) # <<<<<<<<<<<<<< + * else: + * for k in range(j, i): +*/ + __pyx_t_8 = __pyx_f_9fontTools_5qu2cu_5qu2cu_merge_curves(__pyx_v_elevated_quadratics, __pyx_v_j, (__pyx_v_i - __pyx_v_j)); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 405, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_18 = __Pyx_GetItemInt(__pyx_t_8, 0, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_18)) __PYX_ERR(0, 405, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_18); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_curves, __pyx_t_18); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(0, 405, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; + + + /* "fontTools/qu2cu/qu2cu.py":404 + * j = 0 + * for i, is_cubic in reversed(list(zip(splits, cubic))): + * if is_cubic: # <<<<<<<<<<<<<< + * curves.append(merge_curves(elevated_quadratics, j, i - j)[0]) + * else: +*/ + goto __pyx_L46; + } + + /* "fontTools/qu2cu/qu2cu.py":407 + * curves.append(merge_curves(elevated_quadratics, j, i - j)[0]) + * else: + * for k in range(j, i): # <<<<<<<<<<<<<< + * curves.append(q[k * 2 : k * 2 + 3]) + * j = i +*/ + /*else*/ { + + __pyx_t_5 = __pyx_v_i; + __pyx_t_13 = __pyx_t_5; + + for (__pyx_t_14 = __pyx_v_j; __pyx_t_14 < __pyx_t_13; __pyx_t_14+=1) { + __pyx_v_k = __pyx_t_14; + + /* "fontTools/qu2cu/qu2cu.py":408 + * else: + * for k in range(j, i): + * curves.append(q[k * 2 : k * 2 + 3]) # <<<<<<<<<<<<<< + * j = i + * +*/ + __pyx_t_18 = __Pyx_PyObject_GetSlice(__pyx_v_q, (__pyx_v_k * 2), ((__pyx_v_k * 2) + 3), NULL, NULL, NULL, 1, 1, 1); if (unlikely(!__pyx_t_18)) __PYX_ERR(0, 408, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_18); + __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_curves, __pyx_t_18); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(0, 408, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; + + } + + } + __pyx_L46:; + + /* "fontTools/qu2cu/qu2cu.py":409 + * for k in range(j, i): + * curves.append(q[k * 2 : k * 2 + 3]) + * j = i # <<<<<<<<<<<<<< + * + * return curves +*/ + __pyx_v_j = __pyx_v_i; + + /* "fontTools/qu2cu/qu2cu.py":403 + * curves = [] + * j = 0 + * for i, is_cubic in reversed(list(zip(splits, cubic))): # <<<<<<<<<<<<<< + * if is_cubic: + * curves.append(merge_curves(elevated_quadratics, j, i - j)[0]) +*/ + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "fontTools/qu2cu/qu2cu.py":411 + * j = i + * + * return curves # <<<<<<<<<<<<<< + * + * +*/ + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(__pyx_v_curves); + __pyx_r = __pyx_v_curves; + } + __Pyx_XDECREF(__pyx_temp); + } + goto __pyx_L0; + + /* "fontTools/qu2cu/qu2cu.py":270 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * i=cython.int, + * j=cython.int, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_18); + __Pyx_XDECREF(__pyx_t_19); + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu.spline_to_curves", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + + + + + + + + + + + + + + + + + __Pyx_XDECREF(__pyx_v_elevated_quadratics); + __Pyx_XDECREF(__pyx_v_forced); + __Pyx_XDECREF(__pyx_v_sols); + __Pyx_XDECREF(__pyx_v_impossible); + __Pyx_XDECREF(__pyx_v_best_sol); + __Pyx_XDECREF(__pyx_v_this_count); + __Pyx_XDECREF(__pyx_v_i_sol); + __Pyx_XDECREF(__pyx_v_curve); + __Pyx_XDECREF(__pyx_v_ts); + __Pyx_XDECREF(__pyx_v_reconstructed_iter); + __Pyx_XDECREF(__pyx_v_reconstructed); + __Pyx_XDECREF(__pyx_v_reconst); + __Pyx_XDECREF(__pyx_v_orig); + __Pyx_XDECREF(__pyx_v_splits); + __Pyx_XDECREF(__pyx_v_cubic); + __Pyx_XDECREF(__pyx_v_curves); + + __Pyx_XDECREF(__pyx_gb_9fontTools_5qu2cu_5qu2cu_16spline_to_curves_2generator1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/qu2cu/qu2cu.py":414 + * + * + * def main(): # <<<<<<<<<<<<<< + * from fontTools.cu2qu.benchmark import generate_curve + * from fontTools.cu2qu import curve_to_quadratic +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9fontTools_5qu2cu_5qu2cu_15main(PyObject *__pyx_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9fontTools_5qu2cu_5qu2cu_14main, "main()"); +static PyMethodDef __pyx_mdef_9fontTools_5qu2cu_5qu2cu_15main = {"main", (PyCFunction)__pyx_pw_9fontTools_5qu2cu_5qu2cu_15main, METH_NOARGS, __pyx_doc_9fontTools_5qu2cu_5qu2cu_14main}; +static PyObject *__pyx_pw_9fontTools_5qu2cu_5qu2cu_15main(PyObject *__pyx_self, CYTHON_UNUSED PyObject *unused) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("main (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9fontTools_5qu2cu_5qu2cu_14main(__pyx_self); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9fontTools_5qu2cu_5qu2cu_14main(CYTHON_UNUSED PyObject *__pyx_self) { + PyObject *__pyx_v_generate_curve = NULL; + PyObject *__pyx_v_curve_to_quadratic = NULL; + double __pyx_v_tolerance; + double __pyx_v_reconstruct_tolerance; + PyObject *__pyx_v_curve = NULL; + PyObject *__pyx_v_quadratics = NULL; + PyObject *__pyx_v_curves = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("main", 0); + + /* "fontTools/qu2cu/qu2cu.py":415 + * + * def main(): + * from fontTools.cu2qu.benchmark import generate_curve # <<<<<<<<<<<<<< + * from fontTools.cu2qu import curve_to_quadratic + * +*/ + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_generate_curve}; + __pyx_t_2 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_fontTools_cu2qu_benchmark, __pyx_imported_names, 1, NULL, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 415, __pyx_L1_error) + } + __pyx_t_1 = __pyx_t_2; + __Pyx_GOTREF(__pyx_t_1); + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_generate_curve}; + __pyx_t_3 = 0; { + __pyx_t_4 = __Pyx_ImportFrom(__pyx_t_1, __pyx_imported_names[__pyx_t_3]); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 415, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + switch (__pyx_t_3) { + case 0: + __Pyx_INCREF(__pyx_t_4); + __pyx_v_generate_curve = __pyx_t_4; + break; + default:; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "fontTools/qu2cu/qu2cu.py":416 + * def main(): + * from fontTools.cu2qu.benchmark import generate_curve + * from fontTools.cu2qu import curve_to_quadratic # <<<<<<<<<<<<<< + * + * tolerance = 0.05 +*/ + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_curve_to_quadratic}; + __pyx_t_2 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_fontTools_cu2qu, __pyx_imported_names, 1, NULL, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 416, __pyx_L1_error) + } + __pyx_t_1 = __pyx_t_2; + __Pyx_GOTREF(__pyx_t_1); + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_curve_to_quadratic}; + __pyx_t_3 = 0; { + __pyx_t_4 = __Pyx_ImportFrom(__pyx_t_1, __pyx_imported_names[__pyx_t_3]); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 416, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + switch (__pyx_t_3) { + case 0: + __Pyx_INCREF(__pyx_t_4); + __pyx_v_curve_to_quadratic = __pyx_t_4; + break; + default:; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "fontTools/qu2cu/qu2cu.py":418 + * from fontTools.cu2qu import curve_to_quadratic + * + * tolerance = 0.05 # <<<<<<<<<<<<<< + * reconstruct_tolerance = tolerance * 1 + * curve = generate_curve() +*/ + __pyx_v_tolerance = 0.05; + + /* "fontTools/qu2cu/qu2cu.py":419 + * + * tolerance = 0.05 + * reconstruct_tolerance = tolerance * 1 # <<<<<<<<<<<<<< + * curve = generate_curve() + * quadratics = curve_to_quadratic(curve, tolerance) +*/ + __pyx_v_reconstruct_tolerance = (__pyx_v_tolerance * 1.0); + + /* "fontTools/qu2cu/qu2cu.py":420 + * tolerance = 0.05 + * reconstruct_tolerance = tolerance * 1 + * curve = generate_curve() # <<<<<<<<<<<<<< + * quadratics = curve_to_quadratic(curve, tolerance) + * print( +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_v_generate_curve); + __pyx_t_5 = __pyx_v_generate_curve; + __pyx_t_6 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_5))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_5); + assert(__pyx_t_4); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_5); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_5, __pyx__function); + __pyx_t_6 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_5, __pyx_callargs+__pyx_t_6, (1-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 420, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_v_curve = __pyx_t_1; + __pyx_t_1 = 0; + + /* "fontTools/qu2cu/qu2cu.py":421 + * reconstruct_tolerance = tolerance * 1 + * curve = generate_curve() + * quadratics = curve_to_quadratic(curve, tolerance) # <<<<<<<<<<<<<< + * print( + * "cu2qu tolerance %g. qu2cu tolerance %g." % (tolerance, reconstruct_tolerance) +*/ + __pyx_t_5 = NULL; + __Pyx_INCREF(__pyx_v_curve_to_quadratic); + __pyx_t_4 = __pyx_v_curve_to_quadratic; + __pyx_t_7 = PyFloat_FromDouble(__pyx_v_tolerance); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 421, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); + assert(__pyx_t_5); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_4, __pyx__function); + __pyx_t_6 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_5, __pyx_v_curve, __pyx_t_7}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_4, __pyx_callargs+__pyx_t_6, (3-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 421, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_v_quadratics = __pyx_t_1; + __pyx_t_1 = 0; + + /* "fontTools/qu2cu/qu2cu.py":422 + * curve = generate_curve() + * quadratics = curve_to_quadratic(curve, tolerance) + * print( # <<<<<<<<<<<<<< + * "cu2qu tolerance %g. qu2cu tolerance %g." % (tolerance, reconstruct_tolerance) + * ) +*/ + __pyx_t_4 = NULL; + + /* "fontTools/qu2cu/qu2cu.py":423 + * quadratics = curve_to_quadratic(curve, tolerance) + * print( + * "cu2qu tolerance %g. qu2cu tolerance %g." % (tolerance, reconstruct_tolerance) # <<<<<<<<<<<<<< + * ) + * print("One random cubic turned into %d quadratics." % len(quadratics)) +*/ + __pyx_t_7 = PyFloat_FromDouble(__pyx_v_tolerance); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 423, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_5 = PyFloat_FromDouble(__pyx_v_reconstruct_tolerance); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 423, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_8 = PyTuple_New(2); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 423, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GIVEREF(__pyx_t_7); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_7) != (0)) __PYX_ERR(0, 423, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_5); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_5) != (0)) __PYX_ERR(0, 423, __pyx_L1_error); + __pyx_t_7 = 0; + __pyx_t_5 = 0; + __pyx_t_5 = PyUnicode_Format(__pyx_mstate_global->__pyx_kp_u_cu2qu_tolerance_g_qu2cu_toleranc, __pyx_t_8); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 423, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_t_5}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_builtin_print, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 422, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "fontTools/qu2cu/qu2cu.py":425 + * "cu2qu tolerance %g. qu2cu tolerance %g." % (tolerance, reconstruct_tolerance) + * ) + * print("One random cubic turned into %d quadratics." % len(quadratics)) # <<<<<<<<<<<<<< + * curves = quadratic_to_curves([quadratics], reconstruct_tolerance) + * print("Those quadratics turned back into %d cubics. " % len(curves)) +*/ + __pyx_t_5 = NULL; + __pyx_t_3 = PyObject_Length(__pyx_v_quadratics); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1))) __PYX_ERR(0, 425, __pyx_L1_error) + __pyx_t_4 = PyLong_FromSsize_t(__pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 425, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + + __pyx_t_8 = PyUnicode_Format(__pyx_mstate_global->__pyx_kp_u_One_random_cubic_turned_into_d_q, __pyx_t_4); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 425, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_t_8}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_builtin_print, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 425, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "fontTools/qu2cu/qu2cu.py":426 + * ) + * print("One random cubic turned into %d quadratics." % len(quadratics)) + * curves = quadratic_to_curves([quadratics], reconstruct_tolerance) # <<<<<<<<<<<<<< + * print("Those quadratics turned back into %d cubics. " % len(curves)) + * print("Original curve:", curve) +*/ + __pyx_t_8 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_quadratic_to_curves); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 426, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyList_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 426, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v_quadratics); + __Pyx_GIVEREF(__pyx_v_quadratics); + if (__Pyx_PyList_SET_ITEM(__pyx_t_4, 0, __pyx_v_quadratics) != (0)) __PYX_ERR(0, 426, __pyx_L1_error); + __pyx_t_7 = PyFloat_FromDouble(__pyx_v_reconstruct_tolerance); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 426, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_5))) { + __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_5); + assert(__pyx_t_8); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_5); + __Pyx_INCREF(__pyx_t_8); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_5, __pyx__function); + __pyx_t_6 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_8, __pyx_t_4, __pyx_t_7}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_5, __pyx_callargs+__pyx_t_6, (3-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 426, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_v_curves = __pyx_t_1; + __pyx_t_1 = 0; + + /* "fontTools/qu2cu/qu2cu.py":427 + * print("One random cubic turned into %d quadratics." % len(quadratics)) + * curves = quadratic_to_curves([quadratics], reconstruct_tolerance) + * print("Those quadratics turned back into %d cubics. " % len(curves)) # <<<<<<<<<<<<<< + * print("Original curve:", curve) + * print("Reconstructed curve(s):", curves) +*/ + __pyx_t_5 = NULL; + __pyx_t_3 = PyObject_Length(__pyx_v_curves); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1))) __PYX_ERR(0, 427, __pyx_L1_error) + __pyx_t_7 = PyLong_FromSsize_t(__pyx_t_3); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 427, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + + __pyx_t_4 = PyUnicode_Format(__pyx_mstate_global->__pyx_kp_u_Those_quadratics_turned_back_int, __pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 427, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_t_4}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_builtin_print, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 427, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "fontTools/qu2cu/qu2cu.py":428 + * curves = quadratic_to_curves([quadratics], reconstruct_tolerance) + * print("Those quadratics turned back into %d cubics. " % len(curves)) + * print("Original curve:", curve) # <<<<<<<<<<<<<< + * print("Reconstructed curve(s):", curves) + * +*/ + __pyx_t_4 = NULL; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_Original_curve, __pyx_v_curve}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_builtin_print, __pyx_callargs+__pyx_t_6, (3-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 428, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "fontTools/qu2cu/qu2cu.py":429 + * print("Those quadratics turned back into %d cubics. " % len(curves)) + * print("Original curve:", curve) + * print("Reconstructed curve(s):", curves) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_4 = NULL; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_Reconstructed_curve_s, __pyx_v_curves}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_builtin_print, __pyx_callargs+__pyx_t_6, (3-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 429, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "fontTools/qu2cu/qu2cu.py":414 + * + * + * def main(): # <<<<<<<<<<<<<< + * from fontTools.cu2qu.benchmark import generate_curve + * from fontTools.cu2qu import curve_to_quadratic +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("fontTools.qu2cu.qu2cu.main", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_generate_curve); + __Pyx_XDECREF(__pyx_v_curve_to_quadratic); + + + __Pyx_XDECREF(__pyx_v_curve); + __Pyx_XDECREF(__pyx_v_quadratics); + __Pyx_XDECREF(__pyx_v_curves); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +/* #### Code section: module_exttypes ### */ + +static PyObject *__pyx_tp_new__initialisation_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr(PyObject *o, +#if CYTHON_VECTORCALL_TPNEW + CYTHON_UNUSED PyObject *const *args, CYTHON_UNUSED Py_ssize_t nargs, CYTHON_UNUSED PyObject *kwnames +#else + CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k +#endif +) { + return o; +} + +static PyObject *__pyx_tp_new_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr(PyTypeObject *t, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +) { + PyObject *o; + #if CYTHON_USE_FREELISTS + if (likely((int)(__pyx_mstate_global->__pyx_freecount_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr > 0) & __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(t, __pyx_mstate_global->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr, sizeof(struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr)))) + { + o = (PyObject*)__pyx_mstate_global->__pyx_freelist_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr[--__pyx_mstate_global->__pyx_freecount_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr]; + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(Py_TYPE(o)); + #endif + memset(o, 0, sizeof(struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr)); + #if CYTHON_COMPILING_IN_LIMITED_API + (void) PyObject_Init(o, t); + #else + (void) PyObject_INIT(o, t); + #endif + PyObject_GC_Track(o); + } else + #endif + { + o = __Pyx_AllocateExtensionType(t, 1); + } + if (unlikely(!o)) return 0; + return __pyx_tp_new__initialisation_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr(o, +#if CYTHON_VECTORCALL_TPNEW + args, nargs, kwnames +#else + a, k +#endif +); +} + +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_new_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr(PyTypeObject *t, PyObject *a, PyObject *k) { + return __Pyx_CallTpnewAsVectorcall(__pyx_tp_new_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr, t, a, k); +} +#endif + +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr(PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames) { + if (unlikely((PyTypeObject*)t != __pyx_mstate_global->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr || __Pyx_PyType_HasFeature((PyTypeObject*)t, Py_TPFLAGS_IS_ABSTRACT))) { + return __Pyx_CallNewInitFromVectorcall((PyTypeObject*)t, args, nargsf, kwnames); + } + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *o = __pyx_tp_new_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr((PyTypeObject*)t, args, nargs, kwnames); + return o; +} +#endif + +static void __pyx_tp_dealloc_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr(PyObject *o) { + struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr *p = (struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(__Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->__pyx_genexpr_arg_0); + Py_CLEAR(p->__pyx_v_c); + Py_CLEAR(p->__pyx_t_0); + #if CYTHON_USE_FREELISTS + if (likely((int)(__pyx_mstate_global->__pyx_freecount_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr < 8) & __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(Py_TYPE(o), __pyx_mstate_global->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr, sizeof(struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr)))) + { + __pyx_mstate_global->__pyx_freelist_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr[__pyx_mstate_global->__pyx_freecount_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr++] = ((struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr *)o); + } else + #endif + { + PyTypeObject *tp = Py_TYPE(o); + #if CYTHON_USE_TYPE_SLOTS + (*tp->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(tp, Py_tp_free); + if (tp_free) tp_free(o); + } + #endif + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(tp); + #endif + } +} + +static int __pyx_tp_traverse_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr *p = (struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr *)o; + { + e = __Pyx_call_type_traverse(o, 1, v, a); + if (e) return e; + } + if (p->__pyx_genexpr_arg_0) { + e = (*v)(p->__pyx_genexpr_arg_0, a); if (e) return e; + } + if (p->__pyx_v_c) { + e = (*v)(p->__pyx_v_c, a); if (e) return e; + } + if (p->__pyx_t_0) { + e = (*v)(p->__pyx_t_0, a); if (e) return e; + } + return 0; +} +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr}, + {Py_tp_new, (void *)__pyx_tp_new_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr}, + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) && (!CYTHON_COMPILING_IN_LIMITED_API || __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #if CYTHON_VECTORCALL_TPNEW + {Py_tp_vectorcall, (void *)__pyx_tp_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr}, + #endif + #endif + {0, 0}, +}; +static PyType_Spec __pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr_spec = { + "fontTools.qu2cu.qu2cu.__pyx_scope_struct__genexpr", + sizeof(struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_HAVE_GC, + __pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr_slots, +}; +#else + +static PyTypeObject __pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr = { + PyVarObject_HEAD_INIT(0, 0) + "fontTools.qu2cu.qu2cu.""__pyx_scope_struct__genexpr", /*tp_name*/ + sizeof(struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr, /*tp_dealloc*/ + 0, /*tp_vectorcall_offset*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) && (!CYTHON_COMPILING_IN_LIMITED_API || __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #if CYTHON_VECTORCALL_TPNEW + __pyx_tp_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr, /*tp_vectorcall*/ + #else + NULL, /*tp_vectorcall*/ + #endif + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyObject *__pyx_tp_new__initialisation_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr(PyObject *o, +#if CYTHON_VECTORCALL_TPNEW + CYTHON_UNUSED PyObject *const *args, CYTHON_UNUSED Py_ssize_t nargs, CYTHON_UNUSED PyObject *kwnames +#else + CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k +#endif +) { + return o; +} + +static PyObject *__pyx_tp_new_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr(PyTypeObject *t, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +) { + PyObject *o; + #if CYTHON_USE_FREELISTS + if (likely((int)(__pyx_mstate_global->__pyx_freecount_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr > 0) & __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(t, __pyx_mstate_global->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr, sizeof(struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr)))) + { + o = (PyObject*)__pyx_mstate_global->__pyx_freelist_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr[--__pyx_mstate_global->__pyx_freecount_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr]; + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(Py_TYPE(o)); + #endif + memset(o, 0, sizeof(struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr)); + #if CYTHON_COMPILING_IN_LIMITED_API + (void) PyObject_Init(o, t); + #else + (void) PyObject_INIT(o, t); + #endif + PyObject_GC_Track(o); + } else + #endif + { + o = __Pyx_AllocateExtensionType(t, 1); + } + if (unlikely(!o)) return 0; + return __pyx_tp_new__initialisation_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr(o, +#if CYTHON_VECTORCALL_TPNEW + args, nargs, kwnames +#else + a, k +#endif +); +} + +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_new_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr(PyTypeObject *t, PyObject *a, PyObject *k) { + return __Pyx_CallTpnewAsVectorcall(__pyx_tp_new_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr, t, a, k); +} +#endif + +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr(PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames) { + if (unlikely((PyTypeObject*)t != __pyx_mstate_global->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr || __Pyx_PyType_HasFeature((PyTypeObject*)t, Py_TPFLAGS_IS_ABSTRACT))) { + return __Pyx_CallNewInitFromVectorcall((PyTypeObject*)t, args, nargsf, kwnames); + } + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *o = __pyx_tp_new_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr((PyTypeObject*)t, args, nargs, kwnames); + return o; +} +#endif + +static void __pyx_tp_dealloc_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr(PyObject *o) { + struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr *p = (struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(__Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->__pyx_genexpr_arg_0); + Py_CLEAR(p->__pyx_t_0); + #if CYTHON_USE_FREELISTS + if (likely((int)(__pyx_mstate_global->__pyx_freecount_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr < 8) & __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(Py_TYPE(o), __pyx_mstate_global->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr, sizeof(struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr)))) + { + __pyx_mstate_global->__pyx_freelist_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr[__pyx_mstate_global->__pyx_freecount_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr++] = ((struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr *)o); + } else + #endif + { + PyTypeObject *tp = Py_TYPE(o); + #if CYTHON_USE_TYPE_SLOTS + (*tp->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(tp, Py_tp_free); + if (tp_free) tp_free(o); + } + #endif + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(tp); + #endif + } +} + +static int __pyx_tp_traverse_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr *p = (struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr *)o; + { + e = __Pyx_call_type_traverse(o, 1, v, a); + if (e) return e; + } + if (p->__pyx_genexpr_arg_0) { + e = (*v)(p->__pyx_genexpr_arg_0, a); if (e) return e; + } + if (p->__pyx_t_0) { + e = (*v)(p->__pyx_t_0, a); if (e) return e; + } + return 0; +} +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr}, + {Py_tp_new, (void *)__pyx_tp_new_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr}, + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) && (!CYTHON_COMPILING_IN_LIMITED_API || __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #if CYTHON_VECTORCALL_TPNEW + {Py_tp_vectorcall, (void *)__pyx_tp_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr}, + #endif + #endif + {0, 0}, +}; +static PyType_Spec __pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr_spec = { + "fontTools.qu2cu.qu2cu.__pyx_scope_struct_1_genexpr", + sizeof(struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_HAVE_GC, + __pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr_slots, +}; +#else + +static PyTypeObject __pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr = { + PyVarObject_HEAD_INIT(0, 0) + "fontTools.qu2cu.qu2cu.""__pyx_scope_struct_1_genexpr", /*tp_name*/ + sizeof(struct __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr, /*tp_dealloc*/ + 0, /*tp_vectorcall_offset*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) && (!CYTHON_COMPILING_IN_LIMITED_API || __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #if CYTHON_VECTORCALL_TPNEW + __pyx_tp_vectorcall_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr, /*tp_vectorcall*/ + #else + NULL, /*tp_vectorcall*/ + #endif + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; +/* #### Code section: initfunc_declarations ### */ +static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitAfterSharedUtility(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Global_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Variable_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Function_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Exttype___pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Exttype___pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Type_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Variable_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Function_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate); /*proto*/ +/* #### Code section: init_module ### */ + +static int __Pyx_modinit_Global_init_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Global_init_code", 0); + /*--- Global init code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_Variable_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Variable_export_code", 0); + /*--- Variable export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_Function_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Function_export_code", 0); + /*--- Function export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_Exttype___pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Exttype___pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr", 0); + /*--- Exttype __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr ---*/ + #if CYTHON_USE_TYPE_SPECS + __pyx_mstate->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr)) __PYX_ERR(0, 263, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr = &__pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr) < (0)) __PYX_ERR(0, 263, __pyx_L1_error) + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount((PyObject*)__pyx_mstate->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr); + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr->tp_dictoffset && __pyx_mstate->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr->tp_getattro = PyObject_GenericGetAttr; + } + #endif + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_Exttype___pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Exttype___pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr", 0); + /*--- Exttype __pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr ---*/ + #if CYTHON_USE_TYPE_SPECS + __pyx_mstate->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr)) __PYX_ERR(0, 368, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr = &__pyx_type_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr) < (0)) __PYX_ERR(0, 368, __pyx_L1_error) + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount((PyObject*)__pyx_mstate->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr); + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr->tp_dictoffset && __pyx_mstate->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr->tp_getattro = PyObject_GenericGetAttr; + } + #endif + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_Type_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Type_import_code", 0); + /*--- Type import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_Variable_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Variable_import_code", 0); + /*--- Variable import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_Function_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Function_import_code", 0); + /*--- Function import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +#if CYTHON_PEP489_MULTI_PHASE_INIT +static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ +static int __pyx_pymod_exec_qu2cu(PyObject* module); /*proto*/ +static PyModuleDef_Slot __pyx_moduledef_slots[] = { + {Py_mod_create, (void*)__pyx_pymod_create}, + {Py_mod_exec, (void*)__pyx_pymod_exec_qu2cu}, + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + {Py_mod_gil, __Pyx_FREETHREADING_COMPATIBLE}, + #endif + #if PY_VERSION_HEX >= 0x030C0000 && CYTHON_USE_MODULE_STATE + {Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED}, + #endif + {0, NULL} +}; +#endif + +#ifdef __cplusplus +namespace { + struct PyModuleDef __pyx_moduledef = + #else + static struct PyModuleDef __pyx_moduledef = + #endif + { + PyModuleDef_HEAD_INIT, + "qu2cu", + 0, /* m_doc */ + #if CYTHON_USE_MODULE_STATE + sizeof(__pyx_mstatetype), /* m_size */ + #else + (CYTHON_PEP489_MULTI_PHASE_INIT) ? 0 : -1, /* m_size */ + #endif + __pyx_methods /* m_methods */, + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_moduledef_slots, /* m_slots */ + #else + NULL, /* m_reload */ + #endif + #if CYTHON_USE_MODULE_STATE + __pyx_m_traverse, /* m_traverse */ + __pyx_m_clear, /* m_clear */ + NULL /* m_free */ + #else + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ + #endif + }; + #ifdef __cplusplus +} /* anonymous namespace */ +#endif + +/* PyModInitFuncType */ +#ifndef CYTHON_NO_PYINIT_EXPORT + #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#else + #ifdef __cplusplus + #define __Pyx_PyMODINIT_FUNC extern "C" PyObject * + #else + #define __Pyx_PyMODINIT_FUNC PyObject * + #endif +#endif + +__Pyx_PyMODINIT_FUNC PyInit_qu2cu(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC PyInit_qu2cu(void) +#if CYTHON_PEP489_MULTI_PHASE_INIT +{ + return PyModuleDef_Init(&__pyx_moduledef); +} +/* ModuleCreationPEP489 */ +#if CYTHON_COMPILING_IN_LIMITED_API && (__PYX_LIMITED_VERSION_HEX < 0x030A0000 &&\ + (defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS))) +static PY_INT64_T __Pyx_GetCurrentInterpreterId(void) { + { + PyObject *module = PyImport_ImportModule("_interpreters"); // 3.13+ I think + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_Exception)) { + goto bad; // BaseException + } + PyErr_Clear(); // just try the 3.8-3.12 version + module = PyImport_ImportModule("_xxsubinterpreters"); + if (!module) goto bad; + } + PyObject *current = PyObject_CallMethod(module, "get_current", NULL); + Py_DECREF(module); + if (!current) goto bad; + if (PyTuple_Check(current)) { + PyObject *new_current = PySequence_GetItem(current, 0); + Py_DECREF(current); + current = new_current; + if (!new_current) goto bad; + } + long long as_c_int = PyLong_AsLongLong(current); + Py_DECREF(current); + return as_c_int; + } + bad: + PySys_WriteStderr("__Pyx_GetCurrentInterpreterId failed. Try setting the C define CYTHON_PEP489_MULTI_PHASE_INIT=0\n"); + return -1; +} +#endif +#if !CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { + static PY_INT64_T main_interpreter_id = -1; +#if CYTHON_COMPILING_IN_GRAAL && defined(GRAALPY_VERSION_NUM) && GRAALPY_VERSION_NUM > 0x19000000 + PY_INT64_T current_id = GraalPyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_GRAAL + PY_INT64_T current_id = PyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_LIMITED_API && (__PYX_LIMITED_VERSION_HEX < 0x030A0000 &&\ + (defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS))) + PY_INT64_T current_id = __Pyx_GetCurrentInterpreterId(); +#elif CYTHON_COMPILING_IN_LIMITED_API + PY_INT64_T current_id = PyInterpreterState_GetID(PyInterpreterState_Get()); +#else + PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); +#endif + if (unlikely(current_id == -1)) { + return -1; + } + if (main_interpreter_id == -1) { + main_interpreter_id = current_id; + return 0; + } else if (unlikely(main_interpreter_id != current_id)) { + PyErr_SetString( + PyExc_ImportError, + "Interpreter change detected - this module can only be loaded into one interpreter per process."); + return -1; + } + return 0; +} +#endif +static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) +{ + PyObject *value = PyObject_GetAttrString(spec, from_name); + int result = 0; + if (likely(value)) { + if (allow_none || value != Py_None) { + result = PyDict_SetItemString(moddict, to_name, value); + } + Py_DECREF(value); + } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + } else { + result = -1; + } + return result; +} +static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def) { + PyObject *module = NULL, *moddict, *modname; + CYTHON_UNUSED_VAR(def); + #if !CYTHON_USE_MODULE_STATE + if (__Pyx_check_single_interpreter()) + return NULL; + #endif + if (__pyx_m) + return __Pyx_NewRef(__pyx_m); + modname = PyObject_GetAttrString(spec, "name"); + if (unlikely(!modname)) goto bad; + module = PyModule_NewObject(modname); + Py_DECREF(modname); + if (unlikely(!module)) goto bad; + moddict = PyModule_GetDict(module); + if (unlikely(!moddict)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; + return module; +bad: + Py_XDECREF(module); + return NULL; +} + + +static CYTHON_SMALL_CODE int __pyx_pymod_exec_qu2cu(PyObject *__pyx_pyinit_module) +#endif +{ + int stringtab_initialized = 0; + #if CYTHON_USE_MODULE_STATE + int pystate_addmodule_run = 0; + #endif + __pyx_mstatetype *__pyx_mstate = NULL; + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + size_t __pyx_t_9; + int __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_PEP489_MULTI_PHASE_INIT + if (__pyx_m) { + if (__pyx_m == __pyx_pyinit_module) return 0; + PyErr_SetString(PyExc_RuntimeError, "Module 'qu2cu' has already been imported. Re-initialisation is not supported."); + return -1; + } + #else + if (__pyx_m) return __Pyx_NewRef(__pyx_m); + #endif + /*--- Module creation code ---*/ + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_t_1 = __pyx_pyinit_module; + Py_INCREF(__pyx_t_1); + #else + __pyx_t_1 = PyModule_Create(&__pyx_moduledef); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #if CYTHON_USE_MODULE_STATE + { + int add_module_result = __Pyx_State_AddModule(__pyx_t_1, &__pyx_moduledef); + __pyx_t_1 = 0; /* transfer ownership from __pyx_t_1 to "qu2cu" pseudovariable */ + if (unlikely((add_module_result < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + pystate_addmodule_run = 1; + } + #else + __pyx_m = __pyx_t_1; + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + PyUnstable_Module_SetGIL(__pyx_m, Py_MOD_GIL_USED); + #endif + __pyx_mstate = __pyx_mstate_global; + CYTHON_UNUSED_VAR(__pyx_t_1); + __pyx_mstate->__pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_mstate->__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) + Py_INCREF(__pyx_mstate->__pyx_d); + __pyx_mstate->__pyx_b = __Pyx_PyImport_AddModuleRef(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_mstate->__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_cython_runtime = __Pyx_PyImport_AddModuleRef("cython_runtime"); if (unlikely(!__pyx_mstate->__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_mstate->__pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /* ImportRefnannyAPI */ + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + if (PyErr_ExceptionMatches(PyExc_Exception)) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + } + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + +__Pyx_RefNannySetupContext("PyInit_qu2cu", 0); + __Pyx_init_runtime_version(); + if (__Pyx_check_binary_version(__PYX_LIMITED_VERSION_HEX, __Pyx_get_runtime_version(), CYTHON_COMPILING_IN_LIMITED_API) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_mstate->__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Library function declarations ---*/ + /*--- Initialize various global constants etc. ---*/ + if (__Pyx_InitConstants(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + stringtab_initialized = 1; + if (__Pyx_InitGlobals() < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (__pyx_module_is_main_fontTools__qu2cu__qu2cu) { + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_name, __pyx_mstate_global->__pyx_n_u_main) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + } + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) + if (!PyDict_GetItemString(modules, "fontTools.qu2cu.qu2cu")) { + if (unlikely((PyDict_SetItemString(modules, "fontTools.qu2cu.qu2cu", __pyx_m) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + /*--- Builtin init code ---*/ + if (__Pyx_InitCachedBuiltins(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Constants init code ---*/ + if (__Pyx_InitCachedConstants(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_CreateCodeObjects(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Global type/function init code ---*/ + (void)__Pyx_modinit_Global_init_code(__pyx_mstate); + (void)__Pyx_modinit_Variable_export_code(__pyx_mstate); + (void)__Pyx_modinit_Function_export_code(__pyx_mstate); + /*--- Type init code ---*/ + if (unlikely((__Pyx_modinit_Exttype___pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct__genexpr(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + if (unlikely((__Pyx_modinit_Exttype___pyx_obj_9fontTools_5qu2cu_5qu2cu___pyx_scope_struct_1_genexpr(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + (void)__Pyx_modinit_Type_import_code(__pyx_mstate); + (void)__Pyx_modinit_Variable_import_code(__pyx_mstate); + (void)__Pyx_modinit_Function_import_code(__pyx_mstate); + if (__Pyx_InitAfterSharedUtility() < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Execution code ---*/ + + /* "fontTools/qu2cu/qu2cu.py":19 + * # limitations under the License. + * + * try: # <<<<<<<<<<<<<< + * import cython + * except (AttributeError, ImportError): +*/ + { + (void)__pyx_t_1; (void)__pyx_t_2; (void)__pyx_t_3; /* mark used */ + /*try:*/ { + + /* "fontTools/qu2cu/qu2cu.py":20 + * + * try: + * import cython # <<<<<<<<<<<<<< + * except (AttributeError, ImportError): + * # if cython not installed, use mock module with no-op decorators and types +*/ + } + } + + /* "fontTools/qu2cu/qu2cu.py":24 + * # if cython not installed, use mock module with no-op decorators and types + * from fontTools.misc import cython + * COMPILED = cython.compiled # <<<<<<<<<<<<<< + * + * from fontTools.misc.bezierTools import splitCubicAtTC +*/ + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_COMPILED, Py_True) < (0)) __PYX_ERR(0, 24, __pyx_L1_error) + + /* "fontTools/qu2cu/qu2cu.py":26 + * COMPILED = cython.compiled + * + * from fontTools.misc.bezierTools import splitCubicAtTC # <<<<<<<<<<<<<< + * from collections import namedtuple + * import math +*/ + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_splitCubicAtTC}; + __pyx_t_3 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_fontTools_misc_bezierTools, __pyx_imported_names, 1, NULL, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 26, __pyx_L1_error) + } + __pyx_t_4 = __pyx_t_3; + __Pyx_GOTREF(__pyx_t_4); + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_splitCubicAtTC}; + __pyx_t_5 = 0; { + __pyx_t_6 = __Pyx_ImportFrom(__pyx_t_4, __pyx_imported_names[__pyx_t_5]); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 26, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_imported_names[__pyx_t_5], __pyx_t_6) < (0)) __PYX_ERR(0, 26, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/qu2cu/qu2cu.py":27 + * + * from fontTools.misc.bezierTools import splitCubicAtTC + * from collections import namedtuple # <<<<<<<<<<<<<< + * import math + * from typing import ( +*/ + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_namedtuple}; + __pyx_t_3 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_collections, __pyx_imported_names, 1, NULL, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 27, __pyx_L1_error) + } + __pyx_t_4 = __pyx_t_3; + __Pyx_GOTREF(__pyx_t_4); + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_namedtuple}; + __pyx_t_5 = 0; { + __pyx_t_6 = __Pyx_ImportFrom(__pyx_t_4, __pyx_imported_names[__pyx_t_5]); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 27, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_imported_names[__pyx_t_5], __pyx_t_6) < (0)) __PYX_ERR(0, 27, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/qu2cu/qu2cu.py":28 + * from fontTools.misc.bezierTools import splitCubicAtTC + * from collections import namedtuple + * import math # <<<<<<<<<<<<<< + * from typing import ( + * List, +*/ + __pyx_t_3 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_math, 0, 0, NULL, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 28, __pyx_L1_error) + __pyx_t_4 = __pyx_t_3; + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_math, __pyx_t_4) < (0)) __PYX_ERR(0, 28, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/qu2cu/qu2cu.py":29 + * from collections import namedtuple + * import math + * from typing import ( # <<<<<<<<<<<<<< + * List, + * Sequence, +*/ + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_List,__pyx_mstate_global->__pyx_n_u_Sequence,__pyx_mstate_global->__pyx_n_u_Tuple,__pyx_mstate_global->__pyx_n_u_Union}; + __pyx_t_3 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_typing, __pyx_imported_names, 4, NULL, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 29, __pyx_L1_error) + } + __pyx_t_4 = __pyx_t_3; + __Pyx_GOTREF(__pyx_t_4); + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_List,__pyx_mstate_global->__pyx_n_u_Sequence,__pyx_mstate_global->__pyx_n_u_Tuple,__pyx_mstate_global->__pyx_n_u_Union}; + for (__pyx_t_5=0; __pyx_t_5 < 4; __pyx_t_5++) { + __pyx_t_6 = __Pyx_ImportFrom(__pyx_t_4, __pyx_imported_names[__pyx_t_5]); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 29, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_imported_names[__pyx_t_5], __pyx_t_6) < (0)) __PYX_ERR(0, 29, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/qu2cu/qu2cu.py":36 + * ) + * + * __all__ = ["quadratic_to_curves"] # <<<<<<<<<<<<<< + * + * +*/ + { + PyObject* __pyx_temp[1] = {__pyx_mstate_global->__pyx_n_u_quadratic_to_curves}; + __pyx_t_4 = __Pyx_PyList_FromArray(__pyx_temp, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 36, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_all, __pyx_t_4) < (0)) __PYX_ERR(0, 36, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/qu2cu/qu2cu.py":82 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * p0=cython.complex, + * p1=cython.complex, +*/ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_5qu2cu_5qu2cu_1elevate_quadratic, 0, __pyx_mstate_global->__pyx_n_u_elevate_quadratic, NULL, __pyx_mstate_global->__pyx_n_u_fontTools_qu2cu_qu2cu, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[2])); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 82, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_elevate_quadratic, __pyx_t_4) < (0)) __PYX_ERR(0, 82, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/qu2cu/qu2cu.py":154 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * count=cython.int, + * num_offcurves=cython.int, +*/ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_5qu2cu_5qu2cu_3add_implicit_on_curves, 0, __pyx_mstate_global->__pyx_n_u_add_implicit_on_curves, NULL, __pyx_mstate_global->__pyx_n_u_fontTools_qu2cu_qu2cu, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[3])); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 154, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_add_implicit_on_curves, __pyx_t_4) < (0)) __PYX_ERR(0, 154, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/qu2cu/qu2cu.py":175 + * + * + * Point = Union[Tuple[float, float], complex] # <<<<<<<<<<<<<< + * + * +*/ + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_Union); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 175, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_Tuple); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 175, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + { + PyObject* __pyx_temp[2] = {((PyObject *)(&PyFloat_Type)), ((PyObject *)(&PyFloat_Type))}; + __pyx_t_7 = __Pyx_PyTuple_FromArray(__pyx_temp, 2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 175, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + } + __pyx_t_8 = __Pyx_PyObject_GetItem(__pyx_t_6, __pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 175, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + { + PyObject* __pyx_temp[2] = {__pyx_t_8, ((PyObject *)(&PyComplex_Type))}; + __pyx_t_7 = __Pyx_PyTuple_FromArray(__pyx_temp, 2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 175, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + } + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_GetItem(__pyx_t_4, __pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 175, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_Point, __pyx_t_8) < (0)) __PYX_ERR(0, 175, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "fontTools/qu2cu/qu2cu.py":178 + * + * + * def _raise_incompatible_point(point, previous_point): # <<<<<<<<<<<<<< + * raise ValueError( + * f"Quadratic splines must connect end-to-start; got {previous_point!r} then {point!r}" +*/ + __pyx_t_8 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_5qu2cu_5qu2cu_5_raise_incompatible_point, 0, __pyx_mstate_global->__pyx_n_u_raise_incompatible_point, NULL, __pyx_mstate_global->__pyx_n_u_fontTools_qu2cu_qu2cu, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[4])); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 178, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_8); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_raise_incompatible_point, __pyx_t_8) < (0)) __PYX_ERR(0, 178, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "fontTools/qu2cu/qu2cu.py":184 + * + * + * def _validate_spline_length(spline): # <<<<<<<<<<<<<< + * if len(spline) < 3: + * raise ValueError("Quadratic splines must contain at least 3 points") +*/ + __pyx_t_8 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_5qu2cu_5qu2cu_7_validate_spline_length, 0, __pyx_mstate_global->__pyx_n_u_validate_spline_length, NULL, __pyx_mstate_global->__pyx_n_u_fontTools_qu2cu_qu2cu, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[5])); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 184, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_8); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_validate_spline_length, __pyx_t_8) < (0)) __PYX_ERR(0, 184, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "fontTools/qu2cu/qu2cu.py":189 + * + * + * def _validate_positive_tolerance(max_err): # <<<<<<<<<<<<<< + * if max_err <= 0: + * raise ValueError("max_err must be greater than zero") +*/ + __pyx_t_8 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_5qu2cu_5qu2cu_9_validate_positive_tolerance, 0, __pyx_mstate_global->__pyx_n_u_validate_positive_tolerance, NULL, __pyx_mstate_global->__pyx_n_u_fontTools_qu2cu_qu2cu, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[6])); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 189, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_8); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_validate_positive_tolerance, __pyx_t_8) < (0)) __PYX_ERR(0, 189, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "fontTools/qu2cu/qu2cu.py":200 + * def quadratic_to_curves( + * quads: List[Sequence[Point]], + * max_err: float = 0.5, # <<<<<<<<<<<<<< + * all_cubic: bool = False, + * ) -> List[Tuple[Point, ...]]: +*/ + __pyx_t_8 = PyFloat_FromDouble(((double)0.5)); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 200, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + + /* "fontTools/qu2cu/qu2cu.py":201 + * quads: List[Sequence[Point]], + * max_err: float = 0.5, + * all_cubic: bool = False, # <<<<<<<<<<<<<< + * ) -> List[Tuple[Point, ...]]: + * """Converts a connecting list of quadratic splines to a list of quadratic +*/ + __pyx_t_7 = __Pyx_PyBool_FromLong(((int)0)); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 201, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + + /* "fontTools/qu2cu/qu2cu.py":194 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * cost=cython.int, + * is_complex=cython.int, +*/ + { + PyObject* __pyx_temp[2] = {__pyx_t_8, __pyx_t_7}; + __pyx_t_4 = __Pyx_PyTuple_FromArray(__pyx_temp, 2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 194, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyDict_NewPresized(4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 194, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_quads, __pyx_mstate_global->__pyx_kp_u_List_Sequence_Point) < (0)) __PYX_ERR(0, 194, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_max_err, __pyx_mstate_global->__pyx_n_u_float) < (0)) __PYX_ERR(0, 194, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_all_cubic, __pyx_mstate_global->__pyx_n_u_bool) < (0)) __PYX_ERR(0, 194, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_return, __pyx_mstate_global->__pyx_kp_u_List_Tuple_Point) < (0)) __PYX_ERR(0, 194, __pyx_L1_error) + __pyx_t_8 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_5qu2cu_5qu2cu_11quadratic_to_curves, 0, __pyx_mstate_global->__pyx_n_u_quadratic_to_curves, NULL, __pyx_mstate_global->__pyx_n_u_fontTools_qu2cu_qu2cu, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[7])); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 194, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_8); + #endif + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_8, __pyx_t_4); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_8, __pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_quadratic_to_curves, __pyx_t_8) < (0)) __PYX_ERR(0, 194, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "fontTools/qu2cu/qu2cu.py":267 + * + * + * Solution = namedtuple("Solution", ["num_points", "error", "start_index", "is_cubic"]) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_7 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_namedtuple); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 267, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + { + PyObject* __pyx_temp[4] = {__pyx_mstate_global->__pyx_n_u_num_points, __pyx_mstate_global->__pyx_n_u_error, __pyx_mstate_global->__pyx_n_u_start_index, __pyx_mstate_global->__pyx_n_u_is_cubic}; + __pyx_t_6 = __Pyx_PyList_FromArray(__pyx_temp, 4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 267, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __pyx_t_9 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_7, __pyx_mstate_global->__pyx_n_u_Solution, __pyx_t_6}; + __pyx_t_8 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_4, __pyx_callargs+__pyx_t_9, (3-__pyx_t_9) | (__pyx_t_9*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 267, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + } + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_Solution, __pyx_t_8) < (0)) __PYX_ERR(0, 267, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "fontTools/qu2cu/qu2cu.py":293 + * u=cython.complex, + * ) + * def spline_to_curves(q, costs, tolerance=0.5, all_cubic=False): # <<<<<<<<<<<<<< + * """ + * q: quadratic spline with alternating on-curve / off-curve points. +*/ + __pyx_t_8 = PyFloat_FromDouble(((double)0.5)); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 293, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_4 = __Pyx_PyBool_FromLong(((int)0)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 293, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + + /* "fontTools/qu2cu/qu2cu.py":270 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * i=cython.int, + * j=cython.int, +*/ + { + PyObject* __pyx_temp[2] = {__pyx_t_8, __pyx_t_4}; + __pyx_t_6 = __Pyx_PyTuple_FromArray(__pyx_temp, 2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 270, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_5qu2cu_5qu2cu_13spline_to_curves, 0, __pyx_mstate_global->__pyx_n_u_spline_to_curves, NULL, __pyx_mstate_global->__pyx_n_u_fontTools_qu2cu_qu2cu, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[8])); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 270, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_t_6); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_spline_to_curves, __pyx_t_4) < (0)) __PYX_ERR(0, 270, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/qu2cu/qu2cu.py":414 + * + * + * def main(): # <<<<<<<<<<<<<< + * from fontTools.cu2qu.benchmark import generate_curve + * from fontTools.cu2qu import curve_to_quadratic +*/ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_5qu2cu_5qu2cu_15main, 0, __pyx_mstate_global->__pyx_n_u_main_2, NULL, __pyx_mstate_global->__pyx_n_u_fontTools_qu2cu_qu2cu, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[9])); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 414, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_main_2, __pyx_t_4) < (0)) __PYX_ERR(0, 414, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/qu2cu/qu2cu.py":432 + * + * + * if __name__ == "__main__": # <<<<<<<<<<<<<< + * main() +*/ + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_name); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 432, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_10 = __Pyx_PyObject_CompareBoolEq_object_str(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_main, Py_EQ); if (unlikely((__pyx_t_10 < 0))) __PYX_ERR(0, 432, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_10) { + + + /* "fontTools/qu2cu/qu2cu.py":433 + * + * if __name__ == "__main__": + * main() # <<<<<<<<<<<<<< +*/ + __pyx_t_6 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_mstate_global->__pyx_n_u_main_2); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 433, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_6, NULL}; + __pyx_t_4 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_8, __pyx_callargs+__pyx_t_9, (1-__pyx_t_9) | (__pyx_t_9*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 433, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/qu2cu/qu2cu.py":432 + * + * + * if __name__ == "__main__": # <<<<<<<<<<<<<< + * main() +*/ + } + + /* "fontTools/qu2cu/qu2cu.py":1 + * # cython: language_level=3 # <<<<<<<<<<<<<< + * # distutils: define_macros=CYTHON_TRACE_NOGIL=1 + * +*/ + __pyx_t_4 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_test, __pyx_t_4) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + if (__pyx_m) { + if (__pyx_mstate->__pyx_d && stringtab_initialized) { + __Pyx_AddTraceback("init fontTools.qu2cu.qu2cu", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + #if !CYTHON_USE_MODULE_STATE + Py_CLEAR(__pyx_m); + #else + Py_DECREF(__pyx_m); + if (pystate_addmodule_run) { + PyObject *tp, *value, *tb; + __Pyx_PyErr_FetchException(&tp, &value, &tb); + __Pyx_State_RemoveModule(&__pyx_moduledef); + __Pyx_PyErr_RestoreException(tp, value, tb); + } + #endif + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init fontTools.qu2cu.qu2cu"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if CYTHON_PEP489_MULTI_PHASE_INIT + return (__pyx_m != NULL) ? 0 : -1; + #else + return __pyx_m; + #endif +} +/* #### Code section: pystring_table ### */ +/* #### Code section: cached_builtins ### */ + +static int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate) { + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + CYTHON_UNUSED_VAR(__pyx_mstate); + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(0, 354, __pyx_L1_error) + __pyx_builtin_reversed = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_reversed); if (!__pyx_builtin_reversed) __PYX_ERR(0, 403, __pyx_L1_error) + __pyx_builtin_zip = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_zip); if (!__pyx_builtin_zip) __PYX_ERR(0, 403, __pyx_L1_error) + __pyx_builtin_print = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_print); if (!__pyx_builtin_print) __PYX_ERR(0, 422, __pyx_L1_error) + + /* Cached unbound methods */ + __pyx_mstate->__pyx_umethod_PyDict_Type_items.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_items.method_name = &__pyx_mstate->__pyx_n_u_items; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.method_name = &__pyx_mstate->__pyx_n_u_pop; + __pyx_mstate->__pyx_umethod_PyDict_Type_values.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_values.method_name = &__pyx_mstate->__pyx_n_u_values; + __pyx_mstate->__pyx_umethod_PyList_Type_pop.type = (PyObject*)&PyList_Type; + __pyx_mstate->__pyx_umethod_PyList_Type_pop.method_name = &__pyx_mstate->__pyx_n_u_pop; + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cached_constants ### */ + +static int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "fontTools/qu2cu/qu2cu.py":254 + * costs.append(cost) + * costs.append(cost) + * qq = add_implicit_on_curves(p)[1:] # <<<<<<<<<<<<<< + * costs.pop() + * q.extend(qq) +*/ + __pyx_mstate_global->__pyx_slice[0] = PySlice_New(__pyx_mstate_global->__pyx_int_1, Py_None, Py_None); if (unlikely(!__pyx_mstate_global->__pyx_slice[0])) __PYX_ERR(0, 254, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_slice[0]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_slice[0]); + + /* "fontTools/qu2cu/qu2cu.py":321 + * # Dynamic-Programming to find the solution with fewest number of + * # cubic curves, and within those the one with smallest error. + * sols = [Solution(0, 0, 0, False)] # <<<<<<<<<<<<<< + * impossible = Solution(len(elevated_quadratics) * 3 + 1, 0, 1, False) + * start = 0 +*/ + { + PyObject* __pyx_temp[4] = {__pyx_mstate_global->__pyx_int_0, __pyx_mstate_global->__pyx_int_0, __pyx_mstate_global->__pyx_int_0, Py_False}; + __pyx_mstate_global->__pyx_tuple[0] = __Pyx_PyTuple_FromArray(__pyx_temp, 4); if (unlikely(!__pyx_mstate_global->__pyx_tuple[0])) __PYX_ERR(0, 321, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[0]); + } + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[0]); + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = __pyx_mstate->__pyx_tuple; + for (Py_ssize_t i=0; i<1; ++i) { + #if PY_VERSION_HEX >= 0x030F0000 + PyUnstable_SetImmortal(table[i]); + #elif CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + if ((PY_SSIZE_T_MAX <= _Py_IMMORTAL_REFCNT_LOCAL)) break; + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], ((Py_ssize_t)_Py_IMMORTAL_REFCNT_LOCAL + 1)); + } + #else + if ((PY_SSIZE_T_MAX < _Py_IMMORTAL_INITIAL_REFCNT)) break; + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = __pyx_mstate->__pyx_slice; + for (Py_ssize_t i=0; i<1; ++i) { + #if PY_VERSION_HEX >= 0x030F0000 + PyUnstable_SetImmortal(table[i]); + #elif CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + if ((PY_SSIZE_T_MAX <= _Py_IMMORTAL_REFCNT_LOCAL)) break; + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], ((Py_ssize_t)_Py_IMMORTAL_REFCNT_LOCAL + 1)); + } + #else + if ((PY_SSIZE_T_MAX < _Py_IMMORTAL_INITIAL_REFCNT)) break; + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} +/* #### Code section: init_constants ### */ + +static int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate) { + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + CYTHON_UNUSED_VAR(__pyx_mstate); + { + const struct { const unsigned int length: 8; } str_length_index[] = {{6},{1},{1},{28},{21},{23},{179},{43},{15},{49},{48},{23},{45},{8},{39},{7},{6},{2},{9},{33},{43},{8},{4},{5},{8},{8},{5},{5},{20},{7},{12},{17},{8},{8},{10},{8},{12},{8},{13},{25},{28},{23},{22},{9},{18},{8},{4},{1},{18},{5},{11},{4},{5},{5},{5},{5},{18},{6},{17},{19},{9},{3},{5},{5},{15},{25},{26},{21},{6},{14},{7},{1},{5},{11},{11},{4},{10},{10},{8},{5},{1},{11},{11},{1},{4},{4},{7},{10},{4},{13},{10},{4},{4},{2},{4},{1},{2},{2},{6},{2},{2},{5},{3},{14},{5},{1},{2},{19},{36},{10},{5},{4},{7},{21},{13},{18},{6},{8},{4},{10},{4},{6},{16},{33},{14},{6},{5},{11},{10},{14},{5},{9},{2},{6},{1},{1},{5},{6},{1},{1},{3}}; + const struct { const unsigned int length: 10; } bytes_length_index[] = {{24},{20},{131},{23},{313},{112},{56},{914},{2},{2}}; + #ifndef CYTHON_COMPRESS_STRINGS + #define CYTHON_COMPRESS_STRINGS 90 + #endif + #if (CYTHON_COMPRESS_STRINGS) == 1 /* compression: zlib (1951 bytes) */ +static const char cstring[] = "x\332uTOs\323H\026\217!f\034\3060qp60\014\214\234\014\305\316\024\230\261Cm\261@\315\256\023\376\314l1\200c\247\246\266(J\325\226;\216@\226lu+\223\260{\340\250\243\216:\352\250\243\217:\372#\370\250\243?\002\037a\177\257\345\330\300\354\244b\251\373\265\272\337\373\375\351\247\311Cnk\325\177<3;w\016\034[\266\035\307\022w\206^\335\360\262gup\362\314\024\362U\213\017=n\033\374\325K\307\264\345\353\327*\330\366\006\326,rK\253V\253\257_?w$\327\344!\223\332\356\211~y\373\356\275\273\032\263\273\232\313\337pC\nMx\035\303bBp\2419\007Z\3073-i\332\232<\031pQ\325~9\320N\034O\2639\357j\322\321\006\370\356\343\r\n\215\340\222\006\332Mf\333\216d\322tl\035\333M\273wS\353\232.\222\230G\234v?a\226\340\325\0276\327\\\024\340\3645\303\353\230\206&=\327\306\361\000\345h7\272\332\320c]\024o\032\242\372\3025{\246\315,|\350\036\361\373\315\323\025M\014,\323F\376\276\047\244f8\266\215$\032\267\273\267\245s[H\346\312\007Z\317\221\332\237o\220\014\030\301\232\305\031\002\333\332\2008\025{\034K`\314\003c\335,\351_\305\367\367\333\207\216\340\037\325uZq\207\031o\347e+,`\214u\273:h\340\206W\037z@mA\t\350\250\335\350U5\245\360\247\261\256)X\307\342\334\246g\3170E6\352\366\331\261\316]7+\270\303\265\236\313\331\\\306w\334u\206\237a\203\236C\017l\213?\302\332}\361\353\313_\236=~D\036R\34695W\313\261<\222K\371j\337&\341\364\227\047\307\370=\202i\364\347\374X\356\361\003]g\226\245\343o\246/\247\261r\200\336\343\322\224\274O\201\003\3176\350\335\007\263\352\355t=K}j\263\276z\243b\353t,\271\220x\231B7\034\327A\0216\327]\006\364\272i\033N\177\000``AW\365\353G\3142\273\224w\340\010\223\314\244\317)\\\254e,\350\026\267{\340\010\"\230}D\014S\352@\245\244\024\004C\311\304\304\211m\230Nu\236[t\250\036\341X\035\334G\303P\047\001\206t\231\301Ie\303\202\003\014\307\262\310\314\260\210\341\010I?\014<[\2523U\n\365@u\372\\\235,3\267\370\021\0259\017\317\002\335E\004\302{}uk!;\376\035\367\300r\230\2347\211\2522\324g\323j\0072\036\366\231\373v\261\3207""\205\201\370;\223\273*\260X\311\032\214z\0368\256\301\273=n\253\214\031?4;\036\270\246ID\250\207\256\340eCU\222\331g=\360\352\010A\362(\365\3002?\246\021\221@f\020o\336,\366\276Y\354}K\316\3503y8\2636Y\241+\311yH+\001^w\016\0162\272h\222Y\027\241\032~u\307F\362\336`\360\343\2406\250\351u}{P\037l\253O\006\316`\340\362#\323\361D\266\007\010l9\304\337)\263\244Gv\356\377\tU\037Z\216\201\276\364Su\006\177!\010\215\004\256\235\345\316\332\302\242;,\014\350~\3342>\231\350 \003JR\257@}\334\025\274\013\215\361\223]~\300<\013\340,1\353K\231w\347E}>\377C\221\364\201\334%\306\033\262\275\253fB\365=\365\200u\273\240\364P\351\003\021\324h.\211\307lr\376^r&\331J\232\tK\227/L.\340\230\250\024\335\216\207i\266z?\331Lv\223\34187\233_\013\233\263\321\215\250I%\234\367\177\010\032i\341AR\233,\3451.`\354\357\370Fp)h \005K\213\250?b\3210^\216\033\361\036\360\026\212\376\343`=`\201\010+\341v\330\211ri\261\014h\305R\260A|/\006\005\360D\214\356\320~\314\374v\200\340\212\277A\025\252B)\370\033%\232\022\247\340,4\242\215xeT\232\236\242)\241\320\033\201;\271\362\367\244\234\374{\314T\261 nm)\277\342/g\345\003E\272\\\016v\203ax6\254\023\361\204e?\250\004\333\000@4f\t\263\301Z\346\230\013\370`+\330\0177\303\047\321f\3248\255\213V\367\0027\334\000,J~\232\257\274\224\277\350\267\202\263j\031\262\344\261!])\372\273\240r\ry:a\356\363ia\005\373\252K\332\235\230\321\366\242\277\r\342\005\222\266\302\334\207sK\371""\2530]\341J\270\006\025\033a;Z\213\352Q;.\307\373\243\033\243ar6\331NX\"\306\233\343\335\361\360Ca)_\"\313.p\031\320\267\242\030&\203\320\336=h\224\373(R#P\237\316\276\234\225\260\031<\n\317\300\036D\367Zt7r\343\257G\365Q+\311%\227\222\035\030\274\270\026|\007\201U\336\"\374\3603$j\201\333\355\020\374\227\202\313\312[\315\311\365m\354\332\033\271\330\265\213R+3%>)r\362\365\235\330\035\201\374KAma\235\337qP\361Jx=\222q-\336\211\373\311]\\\2353\343\312\264\370\225/\203\332t\365Z\270\037U\024(7^\213\267\343\316(?j\216:\352\n\356%\303t\365zh\305\233q\203\006,]\275\034\026\200\362\032\016\252c\231JY\275\024\374\215\250M\313\2702S\314\036\000kiZ^\007\363\027.\246\253\033\201\027>\213s\223\357\177J\214\361\332\270>n\246\227\312\351j\211\2267\243\353\250\371r\002+\177\0236(\262N\376^\205\372\017BS\321\274\2721\331@G\211\353\352J\254\376E\351q\023\035a\013%\023(Tv\025\302>\215j\037\225\262\236\002\330oQ#j\246\000zDN\232f)K\177~v\031b-\207\217\243\365\310\210K\204\344\356d\343\307Q\0167\272\215+\321\036\227\322\362i\047C\202\317\316\275\032\336R+E\272[}t6\\\325\237a\267\327\361m\350\266F&\233oQ\025\223\002\377%\241q\300\024z=\rj\201rN\035\356\317n:y\367\342\374\336\025\374\263p\310\023x\252AM\256B\327\354?\341whK.h\224\243\332hg\304\250\031\367T;9\275\3604h\316:\037\232Rv\316\303\340\030\375m\031\004\265\342\\|\231lC\255\tv\244vv+b\223\233\017a57\023l\314\246\320$\217;\\Q\316\204\n=\240d8\342\014\256\364\243\370\014\034\262\003\353\344\310x\215)\335\344\260\024\227\376\007\303%\375\203"; + PyObject *data = __Pyx_DecompressString(cstring, 1951, 1); + #define __Pyx_DecompressString_LZSS_UNUSED + if (unlikely(!data)) __PYX_ERR(0, 1, __pyx_L1_error) + const char* const bytes = __Pyx_PyBytes_AsString(data); + #if !CYTHON_ASSUME_SAFE_MACROS + if (likely(bytes)); else { Py_DECREF(data); __PYX_ERR(0, 1, __pyx_L1_error) } + #endif + #elif (CYTHON_COMPRESS_STRINGS) > 0 && (CYTHON_COMPRESS_STRINGS) <= 90 /* compression: lzss (2554 bytes) */ +static const char cstring[] = "\377 then .?\377Lib/font\377Tools/qu\3672cu\000\003.pyL\377ist[Sequ\377ence[Poi\357nt]]\020\002Tup\375l\013\004, ...]\337]NoteQ\000at\377 Cython \377is delib\377erately \377stricter\376!\001n PEP-4\37784 and r\377ejects s\377ubclasse\377s of bui\377ltin typ\377es. If y\377ou need \217to p%\000%\t\311\002s\373et\323\001 \047ann\377otation_\376<\000ing\047 di\355rb\000iv\242\000o F\377alse.One\373 r~\000om cu\377bic turn\374\\\000\344\000o %d q\367uad\272\000ics.\377Original\276&\000rve:Q\022\005 \337splin\256\000mu\177st conn\307\000\377 end-to-\377start; g7ot \027\027ta\341\000\263 wlea?\0003 p\342!\247sReI\000\257 u\257 d\376o\003(s):Tho\363se\215\010\252\005back\361 \257\005\307\002\257 add_~\204 ecu2qu\261 \371l\207@\305@ %g. \374\343B\006\013disabl\367een\002\001gcis\376\004\003dmax_er\373r \335\002be gr\373ea\276Fzeroql\376\014\315@qu\353 s \306\016\377COMPILEDx\325a\312b\325eSolu\253A\366\323bUn\265A_Pyx\372\001\000D\262`_Next\377Ref__all\223__\004\000\332Ce\010\001\256b_\177getitem\031\001/func!\001m\327 \003\002\357odul&\002nam\364.\002\326@l\004\005test\376P\000is_coro\276\202\000ne_ra\373\000_?incomp\303`\223 \375_\222B_validwate\014\000sit\312`\307_to\320$\022\007\215c_l\337ength\201Aim\376\242`cit_on_\313cu\275`s\303\001\356bas\277yncio.s\006s\375b\214\001solboo\347lcc\331a\206\000_tr\267ace\342Acl\377@c\367oll\311\204\001onsc\347ost\000\001\006\000unt\220\302\204\002^\002c\002\233\000_\274\204\006t\003eGlev\275\001\323\204\006\n\004d\037\007\306\366@um\261\206\002\364@\367@or_float\234\207\006.\314b\376\000\014.benchm\367ark\036\007misc\036\025\000zier\331\207\0028\007\342\207\002\375.\350\207\002forced\307gen\243\207\002\232#\n\001xp\017rii_\206 \000\002\232@\334\000\274\005\003\216\002imag\325 o?ssible\271B\343 \343ex\304A\310\206\001\211asjj\320=\0016\003\005\003\312\002k\226ama\263th\324\204\004\223adt\316\210\001n\376\345`num_off\320\243C\t\001\214\206\003\020\0001\024\0002o\377norigpp0\377p1p1_2_3\357p2p3\260\206\002pop\377previous|\251c\277\000nt""qqq\277\207\006\370\214A\373C\000\020..\370\004\365\207\007\205\210\001?srealr\220\207\004\224\207\007r\367gr\247\207\t\000\n_it\306A\374\332\210\001\235\000erseds\373en\001\000tdefa\027ult\354`s\302\210\004\312\210\002\236\007\261s\001\014\224\016\374\210\001tC\272\211\001A\227tTC\t\002s\363\210\002\370\210\002_\177indexth\331\205\002wunt\005\002sol\311C\337throw\270\205\006ts\376\245\212\003uvvalue\376\000\002sxyzip\200\377\001\330\004\007\200s\210!\377\2108\2202\220Q\330\010\177\016\210j\230\001\230\021\022\003\337x\210s\220!\007\n\t\320\277\t*\250!\330\004\005\000 \277\240\001\340\004\020\220>\000\034\337\230J\240b\250G\000\014\210\373N\230\032\000\021\320\021#\240\3371\240G\2501&\000\210\021\377\330\0102\260#\260[\300\376,\000\t\210\021\320\n8\270\377\002\270#\270Q\270a\330\357\004\r\320\rD\000\240\021\240\367-\250q\047\002\320\n:\270\177\"\270C\270q\300\001\t\004w\035\230Q\023\004%\240Q\253\001\377\n\210*\220A\330\010;\377\2701\320\323 \t\210\027\220\001\005\001\201A\312\022\000We\001\340\320!\261 \230c\377\240\027\250\t\260\021\340\004\372\307\004\021\311\000%\220r\320\031?9\270\024\270Y\300\372 \252\000~\266 \022\000\005\t\210\004\271\003\376\303\000\330\004\024\220C\220q\357\230\003\2302\365!\010\210\005\377\210U\220!\2203\220aP\302""\"k\003\337 w\000\022\254c\r\036\000\377#\220U\230\"\230F\240\343\"\240\227@\222\003\032\001R\220rk\230\027\324\000\010z\000\330\004j\003\377\024\000\005\016\210S\220\003\366\354`R\220\362@\005\330\010\t_\330\t\014\210C\310 \022e\000\307b\230\001\000\014\036\000\336@.\000\337 /\250a\360<\000\014\210\3753\366 s\220#\220S\230\277\001\360\006\000\005\033\362`\010\367\031\230\022\303@A\230T\240\377\022\2402\240T\250\024\250\377U\260%\260q\270\003\270\3773\270a\270s\300\"\300\377C\300q\360\010\000\005\021\024\257\204\001\316\007c\335@!\321 \204\204\0038\001\225R\241@\001\007\0101\321\001\243\204\004\022\365\240\t\002\013|\004\"\220D\230\365\002\234`Q\354 \022\2404\240\377r\250\032\2602\260S\270\277\001\270\023\270B\270\361@\022\363\220$\336@s\002\014\2101\210\365H\211`S\331 3\230a\330\357\004\021\220\030\327bQ\320\036]33\000R\260r3\000C\250\000\360\312c\247\204\001\365%\242\000\320\032/\250\377r\260\021\330\010\023\2201\365\330\262fwF\000\014\031\230\036\377\240t\2501\250B\250m\377\2704\270q\300\002\300!\377\340\014\017\210t\2201\340\277\020\035\230U\240!\216 R\376\231\000\022\2503\250b\260\005\357\260Q\260b\376\205\002R\270q\377\330\020\036\230l\250\"\250\375A\005\001a\330\020\030\230\010\357\240\001\240\035F\0002\270R\336\206\002\020\023\2206\327!\330\024\257\037\230q\340\013\000;\330`\021\367\340\024\025\367 \r\016\330\020\377\027\220u\230L\250\001\320\377)>\270c\300\022\3002\377\300Q\330\023\024\330\020\021\356\033\001\"\240\036\261\000\030\270\021_\330\014\034\230A-\001\025\334\204\001\335\020\373@;\230i\342\"\020\027\177\320\027*\250!\2502\216\205\002\367\020\026\220\214A\047\240\021\240\347#\240R\320\002\227\000\033\2301\337\230G\2401\330\201\007\025\330~\326\000W\240A\240Q\330\346\000\253v\220\307`\340m\003\021B\027\024\376\252@\004\230E\240\025\240c\373\250\021\306\0014\320\0270\260\377\001\260\024\260T\270\024\270\337T\300\021\330\024\302\210\005\024\025\256H\r\033\230,\337\210\002\014\330\205\001m\373\2501\247\206\001H\230A\230]\313\250-\265@\022\341a\202\006""\330\020\314\257\000\376!|\230\346@\226\000\340\010\337\014\210G\2201\263\210\001\013\210O2\210S\220\344\206\003\270\204\001\016\256\210\001\356\363\205\002\010\210\003\237`F\220\"\177\220A\330\004\n\210!\263\210\001\177{\230$\230a\230r\304 \177t\2601\260B\260a\235\212\001\321g\312\207\002\351\206\005\213\207\001Q\363\210\004\010\210\375\001\335\210\001\003\210<\220x\230\367q\240\004\236 S\250\001\250\331\030\263a\227\210\001\014\022\312\210\002,\240\377a\320\047<\270C\270r\376\253C\300a\340\014\020\220\005\363\220U\203\210\002\203`\026\220g\230\377Q\230a\230q\240\002\240_\"\240D\250\002\237`B\270`\355\001\365aA\340\306\206\001\230\021\250\001\021"; + PyObject *data = __Pyx_DecompressString_LZSS(cstring, 2554, 3304); + #define __Pyx_DecompressString_UNUSED + if (unlikely(!data)) __PYX_ERR(0, 1, __pyx_L1_error) + const char* const bytes = __Pyx_PyBytes_AsString(data); + #if !CYTHON_ASSUME_SAFE_MACROS + if (likely(bytes)); else { Py_DECREF(data); __PYX_ERR(0, 1, __pyx_L1_error) } + #endif + #else /* compression: none (3304 bytes) */ +static const char bytes[] = " then .?Lib/fontTools/qu2cu/qu2cu.pyList[Sequence[Point]]List[Tuple[Point, ...]]Note that Cython is deliberately stricter than PEP-484 and rejects subclasses of builtin types. If you need to pass subclasses then set the \047annotation_typing\047 directive to False.One random cubic turned into %d quadratics.Original curve:Quadratic splines must connect end-to-start; got Quadratic splines must contain at least 3 pointsReconstructed curve(s):Those quadratics turned back into %d cubics. add_notecu2qu tolerance %g. qu2cu tolerance %g.disableenablegcisenabledmax_err must be greater than zeroquadratic spline requires at least 3 pointsCOMPILEDListPointSequenceSolutionTupleUnion__Pyx_PyDict_NextRef__all____annotate____class_getitem____func____main____module____name____qualname____test___is_coroutine_raise_incompatible_point_validate_positive_tolerance_validate_spline_lengthadd_implicit_on_curvesall_cubicasyncio.coroutinesbest_solboolccline_in_tracebackclosecollectionscostcostscountcubiccurvecurve_to_quadraticcurveselevate_quadraticelevated_quadraticsenumerateerrerrorfloatfontTools.cu2qufontTools.cu2qu.benchmarkfontTools.misc.bezierToolsfontTools.qu2cu.qu2cuforcedgenerate_curvegenexprii_soli_sol_counti_sol_errorimagimpossibleis_complexis_cubicitemsjj_sol_countj_sol_errorkmainmathmax_errnamedtuplenextnum_offcurvesnum_pointsoff1off2onorigpp0p1p1_2_3p2p3pointpopprevious_pointprintqqqquadratic_to_curvesquadratic_to_curves..genexprquadraticsquadsrealreconstreconstruct_tolerancereconstructedreconstructed_iterreturnreversedsendsetdefaultsolssplinespline_to_curvesspline_to_curves..genexprsplitCubicAtTCsplitsstartstart_indexthis_countthis_sol_countthrowtolerancetstypinguvvaluevaluesxyzip\200\001\330\004\007\200s\210!\2108\2202\220Q\330\010\016\210j\230\001\230\021\200\001\330\004\007\200x\210s\220!\330\010\016\210j\230\001\230\021\200\001\330\004\t\320\t*\250!\330\004\t\320\t \240\001\340\004\020\220\001\330\004\034\230J\240b\250\001\330\004\014\210N\230!\330\004\021""\320\021#\2401\240G\2501\330\004\t\210\021\330\0102\260#\260[\300\001\340\004\t\210\021\320\n8\270\002\270#\270Q\270a\330\004\r\320\r \240\001\240\021\240-\250q\330\004\t\210\021\320\n:\270\"\270C\270q\300\001\330\004\t\210\021\320\n\035\230Q\330\004\t\210\021\320\n%\240Q\200\001\330\004\n\210*\220A\330\010;\2701\320\270c\300\022\3002\300Q\330\023\024\330\020\021\360\006\000\r\"\240\036\250r\260\030\270\021\330\014\034\230A\360\006\000\r\025\220A\330\014\020\220\003\220;\230i\240q\250\001\330\020\027\320\027*\250!\2502\250R\250q\330\020\026\220c\230\021\230\047\240\021\240#\240R\240t\2501\250A\330\020\033\2301\230G\2401\330\020\023\2206\230\022\2301\330\024\025\330\020\035\230W\240A\240Q\330\014\017\210v\220R\220q\340\020\021\360\006\000\r\021\220\003\220;\230i\240q\250\001\330\020\027\320\027*\250!\2502\250R\250q\330\020\024\220D\230\004\230E\240\025\240c\250\021\340\020\023\2204\320\0270\260\001\260\024\260T\270\024\270T\300\021\330\024\034\230J\240b\250\001\330\024\025\330\014\017\210v\220R\220q\340\020\021\360\006\000\r\033\230,\240b\250\001\330\014\035\230Q\230m\2501\330\014\024\220H\230A\230]""\250-\260r\270\022\2703\270a\330\014\017\210v\220R\220q\330\020\033\2301\340\014\017\210|\2303\230a\340\020\021\340\010\014\210G\2201\220A\330\010\013\2102\210S\220\001\330\014\024\220A\360\006\000\005\016\210Q\330\004\014\210A\330\004\010\210\003\2101\210F\220\"\220A\330\004\n\210!\330\010\017\210{\230$\230a\230r\240\036\250t\2601\260B\260a\330\010\016\210g\220Q\220a\330\010\r\210W\220A\220Q\330\010\r\210Q\330\004\r\210Q\330\004\010\210\001\330\004\010\210\003\210<\220x\230q\240\004\240A\240S\250\001\250\030\260\021\330\010\013\2101\330\014\022\220\047\230\021\230,\240a\320\047<\270C\270r\300\022\3002\300Q\300a\340\014\020\220\005\220U\230!\2303\230a\330\020\026\220g\230Q\230a\230q\240\002\240\"\240D\250\002\250\"\250B\250b\260\001\330\010\014\210A\340\004\013\2101\230\021\250\021"; + PyObject *data = NULL; + #define __Pyx_DecompressString_UNUSED + #define __Pyx_DecompressString_LZSS_UNUSED + #endif + PyObject **stringtab = __pyx_mstate->__pyx_string_tab; + Py_ssize_t pos = 0; + for (int i = 0; i < 141; i++) { + Py_ssize_t bytes_length = str_length_index[i].length; + PyObject *string = PyUnicode_DecodeUTF8(bytes + pos, bytes_length, NULL); + if (likely(string) && i >= 21) PyUnicode_InternInPlace(&string); + if (unlikely(!string)) { + Py_XDECREF(data); + __PYX_ERR(0, 1, __pyx_L1_error) + } + stringtab[i] = string; + pos += bytes_length; + } + for (int i = 141; i < 151; i++) { + Py_ssize_t bytes_length = bytes_length_index[i-141].length; + PyObject *string = PyBytes_FromStringAndSize(bytes + pos, bytes_length); + stringtab[i] = string; + pos += bytes_length; + if (unlikely(!string)) { + Py_XDECREF(data); + __PYX_ERR(0, 1, __pyx_L1_error) + } + } + Py_XDECREF(data); + for (Py_ssize_t i = 0; i < 151; i++) { + if (unlikely(PyObject_Hash(stringtab[i]) == -1)) { + __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = stringtab + 141; + for (Py_ssize_t i=0; i<10; ++i) { + #if PY_VERSION_HEX >= 0x030F0000 + PyUnstable_SetImmortal(table[i]); + #elif CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + if ((PY_SSIZE_T_MAX <= _Py_IMMORTAL_REFCNT_LOCAL)) break; + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], ((Py_ssize_t)_Py_IMMORTAL_REFCNT_LOCAL + 1)); + } + #else + if ((PY_SSIZE_T_MAX < _Py_IMMORTAL_INITIAL_REFCNT)) break; + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + } + { + PyObject **numbertab = __pyx_mstate->__pyx_number_tab + 0; + int8_t const cint_constants_1[] = {0,1,3}; + for (int i = 0; i < 3; i++) { + numbertab[i] = PyLong_FromLong(cint_constants_1[i - 0]); + if (unlikely(!numbertab[i])) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = __pyx_mstate->__pyx_number_tab; + for (Py_ssize_t i=0; i<3; ++i) { + #if PY_VERSION_HEX >= 0x030F0000 + PyUnstable_SetImmortal(table[i]); + #elif CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + if ((PY_SSIZE_T_MAX <= _Py_IMMORTAL_REFCNT_LOCAL)) break; + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], ((Py_ssize_t)_Py_IMMORTAL_REFCNT_LOCAL + 1)); + } + #else + if ((PY_SSIZE_T_MAX < _Py_IMMORTAL_INITIAL_REFCNT)) break; + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: init_codeobjects ### */ +#ifdef __cplusplus +namespace { +#endif +typedef struct { + unsigned int argcount : 3; + unsigned int num_posonly_args : 1; + unsigned int num_kwonly_args : 1; + unsigned int nlocals : 6; + unsigned int flags : 10; + unsigned int first_line : 9; +} __Pyx_PyCode_New_function_description; +#ifdef __cplusplus +} /* anonymous namespace */ +#endif +/* NewCodeObj.proto */ +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + PyObject *line_table, + PyObject *tuple_dedup_map +); + + +static int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate) { + PyObject* tuple_dedup_map = PyDict_New(); + if (unlikely(!tuple_dedup_map)) return -1; + { + const __Pyx_PyCode_New_function_description descr = {0, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS|CO_GENERATOR), 263}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_cost, __pyx_mstate->__pyx_n_u_is_complex, __pyx_mstate->__pyx_n_u_c}; + __pyx_mstate_global->__pyx_codeobj_tab[0] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_qu2cu_qu2cu_py, __pyx_mstate->__pyx_n_u_genexpr, __pyx_mstate->__pyx_kp_b_iso88591__3, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[0])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {0, 0, 0, 21, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS|CO_GENERATOR), 368}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_i, __pyx_mstate->__pyx_n_u_j, __pyx_mstate->__pyx_n_u_k, __pyx_mstate->__pyx_n_u_start, __pyx_mstate->__pyx_n_u_i_sol_count, __pyx_mstate->__pyx_n_u_j_sol_count, __pyx_mstate->__pyx_n_u_this_sol_count, __pyx_mstate->__pyx_n_u_tolerance, __pyx_mstate->__pyx_n_u_err, __pyx_mstate->__pyx_n_u_error, __pyx_mstate->__pyx_n_u_i_sol_error, __pyx_mstate->__pyx_n_u_j_sol_error, __pyx_mstate->__pyx_n_u_all_cubic, __pyx_mstate->__pyx_n_u_is_cubic, __pyx_mstate->__pyx_n_u_count, __pyx_mstate->__pyx_n_u_p0, __pyx_mstate->__pyx_n_u_p1, __pyx_mstate->__pyx_n_u_p2, __pyx_mstate->__pyx_n_u_p3, __pyx_mstate->__pyx_n_u_v, __pyx_mstate->__pyx_n_u_u}; + __pyx_mstate_global->__pyx_codeobj_tab[1] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_qu2cu_qu2cu_py, __pyx_mstate->__pyx_n_u_genexpr, __pyx_mstate->__pyx_kp_b_iso88591__4, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[1])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 82}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_p0, __pyx_mstate->__pyx_n_u_p1, __pyx_mstate->__pyx_n_u_p2, __pyx_mstate->__pyx_n_u_p1_2_3}; + __pyx_mstate_global->__pyx_codeobj_tab[2] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_qu2cu_qu2cu_py, __pyx_mstate->__pyx_n_u_elevate_quadratic, __pyx_mstate->__pyx_kp_b_iso88591_S_2Rq_Cr_3b_Cr_3b, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[2])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 8, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 154}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_p, __pyx_mstate->__pyx_n_u_count, __pyx_mstate->__pyx_n_u_num_offcurves, __pyx_mstate->__pyx_n_u_i, __pyx_mstate->__pyx_n_u_off1, __pyx_mstate->__pyx_n_u_off2, __pyx_mstate->__pyx_n_u_on, __pyx_mstate->__pyx_n_u_q}; + __pyx_mstate_global->__pyx_codeobj_tab[3] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_qu2cu_qu2cu_py, __pyx_mstate->__pyx_n_u_add_implicit_on_curves, __pyx_mstate->__pyx_kp_b_iso88591_AQ_A_Cq_2Q_U_3a_q_q_2Q_U_U_F_A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[3])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 178}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_point, __pyx_mstate->__pyx_n_u_previous_point}; + __pyx_mstate_global->__pyx_codeobj_tab[4] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_qu2cu_qu2cu_py, __pyx_mstate->__pyx_n_u_raise_incompatible_point, __pyx_mstate->__pyx_kp_b_iso88591_A_1_SSTTU, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[4])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 184}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_spline}; + __pyx_mstate_global->__pyx_codeobj_tab[5] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_qu2cu_qu2cu_py, __pyx_mstate->__pyx_n_u_validate_spline_length, __pyx_mstate->__pyx_kp_b_iso88591_s_82Q_j, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[5])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 189}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_max_err}; + __pyx_mstate_global->__pyx_codeobj_tab[6] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_qu2cu_qu2cu_py, __pyx_mstate->__pyx_n_u_validate_positive_tolerance, __pyx_mstate->__pyx_kp_b_iso88591_xs_j, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[6])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 18, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 194}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_quads, __pyx_mstate->__pyx_n_u_max_err, __pyx_mstate->__pyx_n_u_all_cubic, __pyx_mstate->__pyx_n_u_cost, __pyx_mstate->__pyx_n_u_is_complex, __pyx_mstate->__pyx_n_u_spline, __pyx_mstate->__pyx_n_u_q, __pyx_mstate->__pyx_n_u_costs, __pyx_mstate->__pyx_n_u_p, __pyx_mstate->__pyx_n_u_i, __pyx_mstate->__pyx_n_u_qq, __pyx_mstate->__pyx_n_u_curves, __pyx_mstate->__pyx_n_u_p, __pyx_mstate->__pyx_n_u_x, __pyx_mstate->__pyx_n_u_y, __pyx_mstate->__pyx_n_u_curve, __pyx_mstate->__pyx_n_u_genexpr, __pyx_mstate->__pyx_n_u_genexpr}; + __pyx_mstate_global->__pyx_codeobj_tab[7] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_qu2cu_qu2cu_py, __pyx_mstate->__pyx_n_u_quadratic_to_curves, __pyx_mstate->__pyx_kp_b_iso88591_Q_q_t1_q_q_Qe1Bat3a_t1_S_S_c_U, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[7])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {4, 0, 0, 42, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 270}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_q, __pyx_mstate->__pyx_n_u_costs, __pyx_mstate->__pyx_n_u_tolerance, __pyx_mstate->__pyx_n_u_all_cubic, __pyx_mstate->__pyx_n_u_i, __pyx_mstate->__pyx_n_u_j, __pyx_mstate->__pyx_n_u_k, __pyx_mstate->__pyx_n_u_start, __pyx_mstate->__pyx_n_u_i_sol_count, __pyx_mstate->__pyx_n_u_j_sol_count, __pyx_mstate->__pyx_n_u_this_sol_count, __pyx_mstate->__pyx_n_u_err, __pyx_mstate->__pyx_n_u_error, __pyx_mstate->__pyx_n_u_i_sol_error, __pyx_mstate->__pyx_n_u_j_sol_error, __pyx_mstate->__pyx_n_u_is_cubic, __pyx_mstate->__pyx_n_u_count, __pyx_mstate->__pyx_n_u_p0, __pyx_mstate->__pyx_n_u_p1, __pyx_mstate->__pyx_n_u_p2, __pyx_mstate->__pyx_n_u_p3, __pyx_mstate->__pyx_n_u_v, __pyx_mstate->__pyx_n_u_u, __pyx_mstate->__pyx_n_u_elevated_quadratics, __pyx_mstate->__pyx_n_u_forced, __pyx_mstate->__pyx_n_u_sols, __pyx_mstate->__pyx_n_u_impossible, __pyx_mstate->__pyx_n_u_best_sol, __pyx_mstate->__pyx_n_u_this_count, __pyx_mstate->__pyx_n_u_i_sol, __pyx_mstate->__pyx_n_u_curve, __pyx_mstate->__pyx_n_u_ts, __pyx_mstate->__pyx_n_u_reconstructed_iter, __pyx_mstate->__pyx_n_u_reconstructed, __pyx_mstate->__pyx_n_u_reconst, __pyx_mstate->__pyx_n_u_orig, __pyx_mstate->__pyx_n_u_splits, __pyx_mstate->__pyx_n_u_cubic, __pyx_mstate->__pyx_n_u_curves, __pyx_mstate->__pyx_n_u_i, __pyx_mstate->__pyx_n_u_genexpr, __pyx_mstate->__pyx_n_u_genexpr}; + __pyx_mstate_global->__pyx_codeobj_tab[8] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_qu2cu_qu2cu_py, __pyx_mstate->__pyx_n_u_spline_to_curves, __pyx_mstate->__pyx_kp_b_iso88591_a_3as_S_1AT_2T_U_q_3as_Cq_U_3c, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[8])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {0, 0, 0, 7, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 414}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_generate_curve, __pyx_mstate->__pyx_n_u_curve_to_quadratic, __pyx_mstate->__pyx_n_u_tolerance, __pyx_mstate->__pyx_n_u_reconstruct_tolerance, __pyx_mstate->__pyx_n_u_curve, __pyx_mstate->__pyx_n_u_quadratics, __pyx_mstate->__pyx_n_u_curves}; + __pyx_mstate_global->__pyx_codeobj_tab[9] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_qu2cu_qu2cu_py, __pyx_mstate->__pyx_n_u_main_2, __pyx_mstate->__pyx_kp_b_iso88591_Jb_N_1G1_2_8_Qa_q_Cq_Q_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[9])) goto bad; + } + Py_DECREF(tuple_dedup_map); + return 0; + bad: + Py_DECREF(tuple_dedup_map); + return -1; +} +/* #### Code section: init_globals ### */ + +static int __Pyx_InitGlobals(void) { + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + /* PythonCompatibility.init */ + if (likely(__Pyx_init_co_variables() == 0 && __Pyx_init_tpflags_variables() == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* PyFrozenDict.init */ + #if CYTHON_COMPILING_IN_LIMITED_API + { + PyObject *builtins = PyEval_GetBuiltins(); // borrowed + if (likely(builtins)) { + PyObject *type_name = PyUnicode_FromStringAndSize("frozendict", sizeof("frozendict")-1); + if (likely(type_name)) { + PyObject *frozendict_type = PyObject_GetItem(builtins, type_name); + Py_DECREF(type_name); + if (!frozendict_type && PyErr_ExceptionMatches(PyExc_KeyError)) { + PyErr_Clear(); + frozendict_type = (PyObject*) &PyDict_Type; + Py_INCREF(frozendict_type); + } + __pyx_mstate_global->__Pyx_PyFrozenDictType = frozendict_type; + } + } + } // error handling follows + #endif + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* AssertionsEnabled.init */ + if (likely(__Pyx_init_assertions_enabled() == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CommonTypesMetaclass.init */ + if (likely(__pyx_CommonTypesMetaclass_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CachedMethodType.init */ + #if CYTHON_COMPILING_IN_LIMITED_API + { + PyObject *typesModule=NULL; + typesModule = PyImport_ImportModule("types"); + if (typesModule) { + __pyx_mstate_global->__Pyx_CachedMethodType = PyObject_GetAttrString(typesModule, "MethodType"); + Py_DECREF(typesModule); + } + } // error handling follows + #endif + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* Generator.init */ + if (likely(__pyx_Generator_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: init_after_shared_utility ### */ + +static int __Pyx_InitAfterSharedUtility(void) { + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + /* CythonFunctionPerModule.init */ + if (likely(__pyx_CyFunction_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cleanup_globals ### */ +/* #### Code section: cleanup_module ### */ +/* #### Code section: main_method ### */ +/* #### Code section: utility_code_pragmas ### */ +#ifdef _MSC_VER +#pragma warning( push ) +/* Warning 4127: conditional expression is constant + * Cython uses constant conditional expressions to allow in inline functions to be optimized at + * compile-time, so this warning is not useful + */ +#pragma warning( disable : 4127 ) +#endif + + + +/* #### Code section: utility_code_def ### */ + +/* --- Runtime support code --- */ +/* Refnanny */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule(modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, "RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +/* FastTypeChecks (used by GivenExceptionMatches) */ +#if CYTHON_COMPILING_IN_CPYTHON +static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { + while (a) { + a = __Pyx_PyType_GetSlot(a, tp_base, PyTypeObject*); + if (a == b) + return 1; + } + return b == &PyBaseObject_Type; +} +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (a == b) return 1; + mro = a->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(a, b); +} +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (cls == a || cls == b) return 1; + mro = cls->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + PyObject *base = PyTuple_GET_ITEM(mro, i); + if (base == (PyObject *)a || base == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(cls, a) || __Pyx_InBases(cls, b); +} +#endif + +/* PyErrFetchRestore (used by GivenExceptionMatches) */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject *tmp_value; + assert(type == NULL || (value != NULL && type == (PyObject*) Py_TYPE(value))); + if (value) { + #if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(((PyBaseExceptionObject*) value)->traceback != tb)) + #endif + PyException_SetTraceback(value, tb); + } + tmp_value = tstate->current_exception; + tstate->current_exception = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject* exc_value; + exc_value = tstate->current_exception; + tstate->current_exception = 0; + *value = exc_value; + *type = NULL; + *tb = NULL; + if (exc_value) { + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + #if CYTHON_COMPILING_IN_CPYTHON + *tb = ((PyBaseExceptionObject*) exc_value)->traceback; + Py_XINCREF(*tb); + #else + *tb = PyException_GetTraceback(exc_value); + #endif + } +#else + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#endif +} +#endif + +/* GivenExceptionMatches (used by PyErrExceptionMatches) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { + if (exc_type1) { + return __Pyx_IsAnySubtype2((PyTypeObject*)err, (PyTypeObject*)exc_type1, (PyTypeObject*)exc_type2); + } else { + return __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); + } +} +static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + assert(PyExceptionClass_Check(exc_type)); + n = PyTuple_GET_SIZE(tuple); + for (i=0; i= 0x030C00A6 + PyObject *current_exception = tstate->current_exception; + if (unlikely(!current_exception)) return 0; + exc_type = (PyObject*) Py_TYPE(current_exception); + if (exc_type == err) return 1; +#else + exc_type = tstate->curexc_type; + if (exc_type == err) return 1; + if (unlikely(!exc_type)) return 0; +#endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(exc_type); + #endif + if (unlikely(PyTuple_Check(err))) { + result = __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); + } else { + result = __Pyx_PyErr_GivenExceptionMatches(exc_type, err); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(exc_type); + #endif + return result; +} +#endif + +/* PyObjectGetAttrStr (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); + return PyObject_GetAttr(obj, attr_name); +} +#endif + +/* PyObjectGetAttrStrNoError (used by GetBuiltinName) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + __Pyx_PyErr_Clear(); +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { + PyObject *result; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + (void) PyObject_GetOptionalAttr(obj, attr_name, &result); + return result; +#else +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { + return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); + } +#endif + result = __Pyx_PyObject_GetAttrStr(obj, attr_name); + if (unlikely(!result)) { + __Pyx_PyObject_GetAttrStr_ClearAttributeError(); + } + return result; +#endif +} + +/* GetBuiltinName */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStrNoError(__pyx_mstate_global->__pyx_b, name); + if (unlikely(!result) && !PyErr_Occurred()) { + PyErr_Format(PyExc_NameError, + "name '%U' is not defined", name); + } + return result; +} + +/* CopyObjectArray (used by TupleOrListFromArrayImpl) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_copy_object_array(PyObject *const *CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length) { + PyObject *v; + Py_ssize_t i; + for (i = 0; i < length; i++) { + v = dest[i] = src[i]; + Py_INCREF(v); + } +} +#endif + +/* TupleOrListFromArrayImpl (used by TupleFromArray) */ +#if !(PY_VERSION_HEX >= 0x030F0000 && !CYTHON_COMPILING_IN_LIMITED_API) +CYTHON_UNUSED static PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) { + if (n <= 0) { + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + PyObject *res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + #if CYTHON_COMPILING_IN_CPYTHON + __Pyx_copy_object_array(src, ((PyTupleObject*)res)->ob_item, n); + #else + Py_ssize_t i; + for (i = 0; i < n; i++) { + Py_INCREF(src[i]); + if (unlikely(__Pyx_PyTuple_SET_ITEM(res, i, src[i]) < (0))) { + Py_DECREF(res); + return NULL; + } + } + #endif + return res; +} +#endif + +/* PyObjectCompare (used by UnicodeEquals) */ +#ifndef __Pyx_DEFINED_PyObject_CompareStrStrBoolEq +#define __Pyx_DEFINED_PyObject_CompareStrStrBoolEq +static CYTHON_INLINE int __Pyx_PyObject_CompareStrStrBoolEq(PyObject* s1, PyObject* s2) { + #if __PYX_LIMITED_VERSION_HEX >= 0x030e0000 + int result = PyUnicode_Equal(s1, s2); + #if !CYTHON_COMPILING_IN_CPYTHON + if (unlikely(result == -1)) return -1; + #endif + if (result == 0) goto __pyx_return_false; else goto __pyx_return_true; + #else + int result = PyUnicode_Compare(s1, s2); + if (unlikely((result == -1) && PyErr_Occurred())) return -1; + if (result == 0) goto __pyx_return_true; else goto __pyx_return_false; + #endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolEq_str_str(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (unlikely(op1 == Py_None)) { + if (op2 == Py_None) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(op2 == Py_None)) { + if (op1 == Py_None) goto __pyx_return_true; else goto __pyx_return_false; + } + + if (likely(op1 != Py_None)) { + if (op1 == op2) goto __pyx_return_true; + if (likely(op2 != Py_None)) { + return __Pyx_PyObject_CompareStrStrBoolEq(op1, op2); + } + goto __pyx_richcmp; + } + + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* fastcall */ +#if CYTHON_VECTORCALL +static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s) +{ + Py_ssize_t i, n = __Pyx_PyTuple_GET_SIZE(kwnames); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(n == -1)) return NULL; + #endif + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + if (s == namei) return kwvalues[i]; + } + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + int eq = __Pyx_PyUnicode_Equals(s, namei); + if (unlikely(eq != 0)) { + if (unlikely(eq < 0)) return NULL; + return kwvalues[i]; + } + } + return NULL; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL +CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues) { + Py_ssize_t i, nkwargs; + PyObject *dict; +#if !CYTHON_ASSUME_SAFE_SIZE + nkwargs = PyTuple_Size(kwnames); + if (unlikely(nkwargs < 0)) return NULL; +#else + nkwargs = PyTuple_GET_SIZE(kwnames); +#endif + dict = PyDict_New(); + if (unlikely(!dict)) + return NULL; + for (i=0; itp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectCallMethO (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = __Pyx_CyOrPyCFunction_GET_FUNCTION(func); + self = __Pyx_CyOrPyCFunction_GET_SELF(func); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectFastCall (used by PyObjectCallOneArg) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject* __Pyx_PyObject_FastCall_fallback(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs) { + PyObject *argstuple; + PyObject *result = 0; + size_t i; + argstuple = PyTuple_New((Py_ssize_t)nargs); + if (unlikely(!argstuple)) return NULL; + for (i = 0; i < nargs; i++) { + Py_INCREF(args[i]); + if (__Pyx_PyTuple_SET_ITEM(argstuple, (Py_ssize_t)i, args[i]) != (0)) goto bad; + } + result = __Pyx_PyObject_Call(func, argstuple, kwargs); + bad: + Py_DECREF(argstuple); + return result; +} +#endif +#if CYTHON_VECTORCALL && !(CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY) + #if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE vectorcallfunc __Pyx_PyVectorcall_Function(PyObject *callable) { + PyTypeObject *tp = Py_TYPE(callable); + #if defined(__Pyx_CyFunction_USED) + if (__Pyx_CyFunction_CheckExact(callable)) { + return __Pyx_CyFunction_func_vectorcall(callable); + } + #endif + if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_VECTORCALL)) { + return NULL; + } + assert(PyCallable_Check(callable)); + Py_ssize_t offset = tp->tp_vectorcall_offset; + assert(offset > 0); + vectorcallfunc ptr; + memcpy(&ptr, (char *) callable + offset, sizeof(ptr)); + return ptr; +} + #else + #define __Pyx_PyVectorcall_Function(callable) PyVectorcall_Function(callable) + #endif +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwargs) { + Py_ssize_t nargs = __Pyx_PyVectorcall_NARGS(nargsf); +#if CYTHON_COMPILING_IN_CPYTHON + if (nargs == 0 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_NOARGS)) + return __Pyx_PyObject_CallMethO(func, NULL); + } + else if (nargs == 1 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_O)) + return __Pyx_PyObject_CallMethO(func, args[0]); + } +#endif + if (kwargs == NULL) { + #if CYTHON_VECTORCALL + #if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + return PyObject_Vectorcall(func, args, nargsf, NULL); + #else + vectorcallfunc f = __Pyx_PyVectorcall_Function(func); + if (f) { + return f(func, args, nargsf, NULL); + } + #endif + #endif + } + if (nargs == 0) { + return __Pyx_PyObject_Call(func, __pyx_mstate_global->__pyx_empty_tuple, kwargs); + } + #if CYTHON_COMPILING_IN_LIMITED_API + return __Pyx_PyObject_FastCall_fallback(func, args, (size_t)nargs, kwargs); + #elif CYTHON_COMPILING_IN_PYPY + return PyObject_VectorcallDict(func, args, (size_t) nargs, kwargs); + #else + return PyObject_VectorcallDict(func, args, nargsf, kwargs); + #endif +} + +/* PyObjectCallOneArg (used by CallUnboundCMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *args[2] = {NULL, arg}; + return __Pyx_PyObject_FastCall(func, args+1, 1 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* IgnoreException (used by UnpackUnboundCMethod_impl) */ +static CYTHON_INLINE int __Pyx_IgnoreGivenException(PyObject *given_exception, PyObject *ignorable_exception) { + if (PyErr_GivenExceptionMatches(given_exception ? given_exception : PyErr_Occurred(), ignorable_exception)) { + PyErr_Clear(); + return 1; + } + return 0; +} + +/* UnpackUnboundCMethod_impl (used by UnpackUnboundCMethod) */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *args, PyObject *kwargs) { + PyObject *result; + PyObject *selfless_args = PyTuple_GetSlice(args, 1, PyTuple_Size(args)); + if (unlikely(!selfless_args)) return NULL; + result = PyObject_Call(method, selfless_args, kwargs); + Py_DECREF(selfless_args); + return result; +} +#else +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { + return PyObject_Vectorcall(method, args ? args+1 : NULL, nargs ? (size_t) nargs-1 : 0, kwnames); +} +#endif +static PyMethodDef __Pyx_UnboundCMethod_Def = { + "CythonUnboundCMethod", + __PYX_REINTERPRET_FUNCION(PyCFunction, __Pyx_SelflessCall), +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 + METH_VARARGS | METH_KEYWORDS, +#else + METH_FASTCALL | METH_KEYWORDS, +#endif + NULL +}; +static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { + PyObject *method, *result=NULL; + method = __Pyx_PyObject_GetAttrStr(target->type, *target->method_name); + if (unlikely(!method)) + return -1; + result = method; +#if CYTHON_COMPILING_IN_CPYTHON + if (likely(__Pyx_TypeCheck(method, &PyMethodDescr_Type))) + { + PyMethodDescrObject *descr = (PyMethodDescrObject*) method; + target->func = descr->d_method->ml_meth; + target->flag = descr->d_method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST); + } else +#endif +#if CYTHON_COMPILING_IN_PYPY +#else + if (PyCFunction_Check(method)) +#endif + { + PyObject *self; + int self_found; +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + self = PyObject_GetAttrString(method, "__self__"); + if (!self && !__Pyx_IgnoreException(PyExc_AttributeError)) { + return -1; + } +#else + self = PyCFunction_GET_SELF(method); +#endif + self_found = (self && self != Py_None); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + Py_XDECREF(self); +#endif + if (self_found) { + PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method); + if (unlikely(!unbound_method)) return -1; + Py_DECREF(method); + result = unbound_method; + } + } +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + if (unlikely(target->method)) { + Py_DECREF(result); + } else +#endif + target->method = result; + return 0; +} + +/* CallUnboundCMethod0 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + if (likely(cfunc->flag == METH_NOARGS)) + return __Pyx_CallCFunction(cfunc, self, NULL); + if (likely(cfunc->flag == METH_FASTCALL)) + return __Pyx_CallCFunctionFast(cfunc, self, NULL, 0); + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, NULL, 0, NULL); + if (likely(cfunc->flag == (METH_VARARGS | METH_KEYWORDS))) + return __Pyx_CallCFunctionWithKeywords(cfunc, self, __pyx_mstate_global->__pyx_empty_tuple, NULL); + if (cfunc->flag == METH_VARARGS) + return __Pyx_CallCFunction(cfunc, self, __pyx_mstate_global->__pyx_empty_tuple); + return __Pyx__CallUnboundCMethod0(cfunc, self); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod0(&tmp_cfunc, self); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod0(cfunc, self); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + PyObject *result; + if (unlikely(!cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; + result = __Pyx_PyObject_CallOneArg(cfunc->method, self); + return result; +} + +/* py_dict_items (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d) { + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_items, d); +} + +/* py_dict_values (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d) { + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_values, d); +} + +/* OwnedDictNext (used by ParseKeywordsImpl) */ +#if CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, PyObject **ppos, PyObject **pkey, PyObject **pvalue) { + PyObject *next = NULL; + if (!*ppos) { + if (pvalue) { + PyObject *dictview = pkey ? __Pyx_PyDict_Items(p) : __Pyx_PyDict_Values(p); + if (unlikely(!dictview)) goto bad; + *ppos = PyObject_GetIter(dictview); + Py_DECREF(dictview); + } else { + *ppos = PyObject_GetIter(p); + } + if (unlikely(!*ppos)) goto bad; + } + next = PyIter_Next(*ppos); + if (!next) { + if (PyErr_Occurred()) goto bad; + return 0; + } + if (pkey && pvalue) { + *pkey = __Pyx_PySequence_ITEM(next, 0); + if (unlikely(*pkey)) goto bad; + *pvalue = __Pyx_PySequence_ITEM(next, 1); + if (unlikely(*pvalue)) goto bad; + Py_DECREF(next); + } else if (pkey) { + *pkey = next; + } else { + assert(pvalue); + *pvalue = next; + } + return 1; + bad: + Py_XDECREF(next); +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 + PyErr_FormatUnraisable("Exception ignored in __Pyx_PyDict_NextRef"); +#else + PyErr_WriteUnraisable(__pyx_mstate_global->__pyx_n_u_Pyx_PyDict_NextRef); +#endif + if (pkey) *pkey = NULL; + if (pvalue) *pvalue = NULL; + return 0; +} +#else // !CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) { + int result = PyDict_Next(p, ppos, pkey, pvalue); + if (likely(result == 1)) { + if (pkey) Py_INCREF(*pkey); + if (pvalue) Py_INCREF(*pvalue); + } + return result; +} +#endif + +/* RaiseDoubleKeywords (used by ParseKeywordsImpl) */ +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); +} + +/* CallUnboundCMethod2 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + PyObject *args[2] = {arg1, arg2}; + if (cfunc->flag == METH_FASTCALL) { + return __Pyx_CallCFunctionFast(cfunc, self, args, 2); + } + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, 2, NULL); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod2(&tmp_cfunc, self, arg1, arg2); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2){ + if (unlikely(!cfunc->func && !cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; +#if CYTHON_COMPILING_IN_CPYTHON + if (cfunc->func && (cfunc->flag & METH_VARARGS)) { + PyObject *result = NULL; + PyObject *args = PyTuple_New(2); + if (unlikely(!args)) return NULL; + Py_INCREF(arg1); + PyTuple_SET_ITEM(args, 0, arg1); + Py_INCREF(arg2); + PyTuple_SET_ITEM(args, 1, arg2); + if (cfunc->flag & METH_KEYWORDS) + result = __Pyx_CallCFunctionWithKeywords(cfunc, self, args, NULL); + else + result = __Pyx_CallCFunction(cfunc, self, args); + Py_DECREF(args); + return result; + } +#endif + { + PyObject *args[4] = {NULL, self, arg1, arg2}; + return __Pyx_PyObject_FastCall(cfunc->method, args+1, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); + } +} + +/* ParseKeywordsImpl (used by ParseKeywords) */ +static int __Pyx_ValidateDuplicatePosArgs( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char* function_name) +{ + PyObject ** const *name = argnames; + while (name != first_kw_arg) { + PyObject *key = **name; + int found = PyDict_Contains(kwds, key); + if (unlikely(found)) { + if (found == 1) __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; + } + name++; + } + return 0; +bad: + return -1; +} +#if CYTHON_USE_UNICODE_INTERNALS +static CYTHON_INLINE int __Pyx_UnicodeKeywordsEqual(PyObject *s1, PyObject *s2) { + int kind; + Py_ssize_t len = PyUnicode_GET_LENGTH(s1); + if (len != PyUnicode_GET_LENGTH(s2)) return 0; + kind = PyUnicode_KIND(s1); + if (kind != PyUnicode_KIND(s2)) return 0; + const void *data1 = PyUnicode_DATA(s1); + const void *data2 = PyUnicode_DATA(s2); + return (memcmp(data1, data2, (size_t) len * (size_t) kind) == 0); +} +#endif +static int __Pyx_MatchKeywordArg_str( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + #if CYTHON_USE_UNICODE_INTERNALS + Py_hash_t key_hash = ((PyASCIIObject*)key)->hash; + if (unlikely(key_hash == -1)) { + key_hash = PyObject_Hash(key); + if (unlikely(key_hash == -1)) + goto bad; + } + #endif + name = first_kw_arg; + while (*name) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (key_hash == ((PyASCIIObject*)name_str)->hash && __Pyx_UnicodeKeywordsEqual(name_str, key)) { + *index_found = (size_t) (name - argnames); + return 1; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + *index_found = (size_t) (name - argnames); + return 1; + } + } + #endif + name++; + } + name = argnames; + while (name != first_kw_arg) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (unlikely(key_hash == ((PyASCIIObject*)name_str)->hash)) { + if (__Pyx_UnicodeKeywordsEqual(name_str, key)) + goto arg_passed_twice; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + if (unlikely(name_str == key)) goto arg_passed_twice; + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + } + #endif + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +bad: + return -1; +} +static int __Pyx_MatchKeywordArg_nostr( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + if (unlikely(!PyUnicode_Check(key))) goto invalid_keyword_type; + name = first_kw_arg; + while (*name) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (cmp == 1) { + *index_found = (size_t) (name - argnames); + return 1; + } + if (unlikely(cmp == -1)) goto bad; + name++; + } + name = argnames; + while (name != first_kw_arg) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (unlikely(cmp != 0)) { + if (cmp == 1) goto arg_passed_twice; + else goto bad; + } + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +bad: + return -1; +} +static CYTHON_INLINE int __Pyx_MatchKeywordArg( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + return likely(PyUnicode_CheckExact(key)) ? + __Pyx_MatchKeywordArg_str(key, argnames, first_kw_arg, index_found, function_name) : + __Pyx_MatchKeywordArg_nostr(key, argnames, first_kw_arg, index_found, function_name); +} +static void __Pyx_RejectUnknownKeyword( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char *function_name) +{ + #if CYTHON_AVOID_BORROWED_REFS + PyObject *pos = NULL; + #else + Py_ssize_t pos = 0; + #endif + PyObject *key = NULL; + __Pyx_BEGIN_CRITICAL_SECTION(kwds); + #if CYTHON_AVOID_BORROWED_REFS + while (__Pyx_PyDict_NextRef(kwds, &pos, &key, NULL)) + #else + (void) __Pyx_PyDict_NextRef; + while (PyDict_Next(kwds, &pos, &key, NULL)) + #endif + { + PyObject** const *name = first_kw_arg; + while (*name && (**name != key)) name++; + if (!*name) { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp != 1) { + if (cmp == 0) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + break; + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + } + __Pyx_END_CRITICAL_SECTION(); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(pos); + #endif + assert(PyErr_Occurred()); +} +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t extracted = 0; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + name = first_kw_arg; + while (*name && num_kwargs > extracted) { + PyObject * key = **name; + PyObject *value; + int found = 0; + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + found = PyDict_GetItemRef(kwds, key, &value); + #else + value = PyDict_GetItemWithError(kwds, key); + if (value) { + Py_INCREF(value); + found = 1; + } else { + if (unlikely(PyErr_Occurred())) goto bad; + } + #endif + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + extracted++; + } + name++; + } + if (num_kwargs > extracted) { + if (ignore_unknown_kwargs) { + if (unlikely(__Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name) == -1)) + goto bad; + } else { + __Pyx_RejectUnknownKeyword(kwds, argnames, first_kw_arg, function_name); + goto bad; + } + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t len; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + if (PyDict_Update(kwds2, kwds) < 0) goto bad; + name = first_kw_arg; + while (*name) { + PyObject *key = **name; + PyObject *value; +#if !CYTHON_COMPILING_IN_LIMITED_API && (PY_VERSION_HEX >= 0x030d00A2 || defined(PyDict_Pop)) + int found = PyDict_Pop(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + } +#elif __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + int found = PyDict_GetItemRef(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + if (unlikely(PyDict_DelItem(kwds2, key) < 0)) goto bad; + } +#else + #if CYTHON_COMPILING_IN_CPYTHON + value = _PyDict_Pop(kwds2, key, kwds2); + #else + value = __Pyx_CallUnboundCMethod2(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_pop, kwds2, key, kwds2); + #endif + if (value == kwds2) { + Py_DECREF(value); + } else { + if (unlikely(!value)) goto bad; + values[name-argnames] = value; + } +#endif + name++; + } + len = PyDict_Size(kwds2); + if (len > 0) { + return __Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name); + } else if (unlikely(len == -1)) { + goto bad; + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject *key = NULL; + PyObject** const * name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + for (Py_ssize_t pos = 0; pos < num_kwargs; pos++) { +#if CYTHON_AVOID_BORROWED_REFS + key = __Pyx_PySequence_ITEM(kwds, pos); +#else + key = __Pyx_PyTuple_GET_ITEM(kwds, pos); +#endif +#if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!key)) goto bad; +#endif + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + PyObject *value = kwvalues[pos]; + values[name-argnames] = __Pyx_NewRef(value); + } else { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp == 1) { + PyObject *value = kwvalues[pos]; + values[index_found] = __Pyx_NewRef(value); + } else { + if (unlikely(cmp == -1)) goto bad; + if (kwds2) { + PyObject *value = kwvalues[pos]; + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else if (!ignore_unknown_kwargs) { + goto invalid_keyword; + } + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + key = NULL; + #endif + } + return 0; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + goto bad; +bad: + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(key); + #endif + return -1; +} + +/* ParseKeywords */ +static int __Pyx_ParseKeywords( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + if (CYTHON_VECTORCALL && likely(PyTuple_Check(kwds))) + return __Pyx_ParseKeywordsTuple(kwds, kwvalues, argnames, kwds2, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); + else if (kwds2) + return __Pyx_ParseKeywordDictToDict(kwds, argnames, kwds2, values, num_pos_args, function_name); + else + return __Pyx_ParseKeywordDict(kwds, argnames, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); +} + +/* RaiseArgTupleInvalid */ +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +/* PyFrozenDict (used by GetItemInt) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE PyObject* __Pyx__PyFrozenDict_New(PyObject* frozendict_type, PyObject* it) { + return PyObject_CallFunctionObjArgs(frozendict_type, it, NULL); +} +#endif + +/* GettItemInt_wraparound (used by GetItemInt) */ +#if CYTHON_USE_TYPE_SLOTS && !CYTHON_COMPILING_IN_PYPY +static int __Pyx_GetItemInt_wraparound(PyObject *o, PySequenceMethods *sm, Py_ssize_t *i) { + assert(*i < 0); + if (likely(sm->sq_length)) { + Py_ssize_t l = sm->sq_length(o); + if (likely(l >= 0)) { + *i += l; + } else { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return -1; + PyErr_Clear(); + } + } + return 0; +} +#endif + +/* GetItemInt */ +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (unlikely(!j)) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static PyObject *__Pyx_GetItemInt_Generic_size(PyObject *o, Py_ssize_t i) { + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_AVOID_BORROWED_REFS + CYTHON_UNUSED_VAR(boundscheck); + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + Py_ssize_t size = __Pyx_PyList_GET_SIZE(o); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(size < 0)) return NULL; + #endif + wrapped_i += size; + } + return __Pyx_PyList_GetItemRef(o, wrapped_i); +#elif CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + Py_ssize_t wrapped_i = i; + Py_ssize_t size = (wraparound | boundscheck) ? PyList_GET_SIZE(o) : -1; + if (wraparound & unlikely(i < 0)) { + wrapped_i += size; + } + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, size))) { + return __Pyx_PyList_GET_ITEM_REF(o, wrapped_i, unsafe_shared); + } + return __Pyx_GetItemInt_Generic_size(o, i); +#else + (void)wraparound; + (void)boundscheck; + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_AVOID_BORROWED_REFS + CYTHON_UNUSED_VAR(boundscheck); + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + Py_ssize_t size = __Pyx_PyTuple_GET_SIZE(o); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(size < 0)) return NULL; + #endif + wrapped_i += size; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_COMPILING_IN_LIMITED_API + return PySequence_ITEM(o, wrapped_i); + #else + if (unlikely(wrapped_i < 0)) { + PyErr_SetString(PyExc_IndexError, "tuple index out of range"); + return NULL; + } + return PySequence_GetItem(o, wrapped_i); + #endif +#elif CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + Py_ssize_t wrapped_i = i; + Py_ssize_t size = (wraparound | boundscheck) ? PyTuple_GET_SIZE(o) : -1; + if (wraparound & unlikely(i < 0)) { + wrapped_i += size; + } + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, size))) { + return __Pyx_NewRef(__Pyx_PyTuple_GET_ITEM(o, wrapped_i)); + } + return __Pyx_GetItemInt_Generic_size(o, i); +#else + (void)wraparound; + (void)boundscheck; + return PySequence_GetItem(o, i); +#endif +} +#if CYTHON_USE_TYPE_SLOTS && !CYTHON_COMPILING_IN_PYPY +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast_mapping(PyObject *o, binaryfunc getitem, Py_ssize_t i) { + PyObject *r, *key = PyLong_FromSsize_t(i); + if (unlikely(!key)) return NULL; + r = getitem(o, key); + Py_DECREF(key); + return r; +} +#endif +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_SIZE + if (PyList_CheckExact(o)) { + return __Pyx_GetItemInt_List_Fast(o, i, wraparound, boundscheck, unsafe_shared); + } else + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (PyTuple_CheckExact(o)) { + return __Pyx_GetItemInt_Tuple_Fast(o, i, wraparound, boundscheck, unsafe_shared); + } else + #endif +#else + if ((!wraparound || i >= 0) & PyList_CheckExact(o)) { + return boundscheck ? __Pyx_PyList_GetItemRef(o, i) : __Pyx_PyList_GET_ITEM_REF(o, i, unsafe_shared); + } else +#endif +#if CYTHON_USE_TYPE_SLOTS && !CYTHON_COMPILING_IN_PYPY + if (PyDict_CheckExact(o)) { + return __Pyx_GetItemInt_Fast_mapping(o, PyDict_Type.tp_as_mapping->mp_subscript, i); + #if defined(PyFrozenDict_CheckExact) + } else if (PyFrozenDict_CheckExact(o)) { + return __Pyx_GetItemInt_Fast_mapping(o, PyFrozenDict_Type.tp_as_mapping->mp_subscript, i); + #endif + } else + { + PyTypeObject *obj_type = Py_TYPE(o); + int seq_or_mapping = __Pyx_PyType_GetFlags(obj_type) & (Py_TPFLAGS_SEQUENCE|Py_TPFLAGS_MAPPING); + if (seq_or_mapping != Py_TPFLAGS_SEQUENCE) { + PyMappingMethods *mm = obj_type->tp_as_mapping; + if (mm && mm->mp_subscript) + return __Pyx_GetItemInt_Fast_mapping(o, mm->mp_subscript, i); + } + PySequenceMethods *sm = obj_type->tp_as_sequence; + if (likely(sm && sm->sq_item)) { + if (wraparound && (i < 0) && unlikely(__Pyx_GetItemInt_wraparound(o, sm, &i) == -1)) + return NULL; + return sm->sq_item(o, i); + } + if (seq_or_mapping == Py_TPFLAGS_SEQUENCE) { + PyMappingMethods *mm = obj_type->tp_as_mapping; + if (likely(mm && mm->mp_subscript)) + return __Pyx_GetItemInt_Fast_mapping(o, mm->mp_subscript, i); + } + } +#else + if (!PyMapping_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + (void)wraparound; + (void)boundscheck; + return __Pyx_GetItemInt_Generic_size(o, i); +} + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareStrStrBoolEq +#define __Pyx_DEFINED_PyObject_CompareStrStrBoolEq +static CYTHON_INLINE int __Pyx_PyObject_CompareStrStrBoolEq(PyObject* s1, PyObject* s2) { + #if __PYX_LIMITED_VERSION_HEX >= 0x030e0000 + int result = PyUnicode_Equal(s1, s2); + #if !CYTHON_COMPILING_IN_CPYTHON + if (unlikely(result == -1)) return -1; + #endif + if (result == 0) goto __pyx_return_false; else goto __pyx_return_true; + #else + int result = PyUnicode_Compare(s1, s2); + if (unlikely((result == -1) && PyErr_Occurred())) return -1; + if (result == 0) goto __pyx_return_true; else goto __pyx_return_false; + #endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyBytesPyBytesBoolEq +#define __Pyx_DEFINED_PyObject_ComparePyBytesPyBytesBoolEq +static CYTHON_INLINE int __Pyx_PyObject_ComparePyBytesPyBytesBoolEq(PyObject* s1, PyObject* s2) { + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) goto __pyx_return_false; + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + #else + char *ps1, *ps2; + Py_ssize_t length, length2; + if (unlikely(PyBytes_AsStringAndSize(s1, &ps1, &length) == -1)) return -1; + if (unlikely(PyBytes_AsStringAndSize(s2, &ps2, &length2) == -1)) return -1; + if (length != length2) goto __pyx_return_false; + #endif + if (ps1[0] != ps2[0]) goto __pyx_return_false; + if (length == 1) goto __pyx_return_true; + { + int cmp; +#if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000) + Py_hash_t hash1 = ((PyBytesObject*)s1)->ob_shash; + Py_hash_t hash2 = ((PyBytesObject*)s2)->ob_shash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) goto __pyx_return_false; +#endif + cmp = memcmp(ps1, ps2, (size_t)length); + if (cmp == 0) goto __pyx_return_true; else goto __pyx_return_false; + } +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyBytesPyByteArrayBoolEq +#define __Pyx_DEFINED_PyObject_ComparePyBytesPyByteArrayBoolEq +static CYTHON_INLINE int __Pyx_PyObject_ComparePyBytesPyByteArrayBoolEq(PyObject* s1, PyObject* s2) { + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyByteArray_GET_SIZE(s2)) goto __pyx_return_false; + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyByteArray_AS_STRING(s2); + #else + char *ps1, *ps2; + Py_ssize_t length, length2; + if (unlikely(PyBytes_AsStringAndSize(s1, &ps1, &length) == -1)) return -1; + ps2 = __Pyx_PyByteArray_AsString(s2); if (unlikely(!ps2)) return -1; + length2 = __Pyx_PyByteArray_GET_SIZE(s2); if (unlikely(length2 == -1)) return -1; + if (length != length2) goto __pyx_return_false; + #endif + if (ps1[0] != ps2[0]) goto __pyx_return_false; + if (length == 1) goto __pyx_return_true; + { + int cmp; + cmp = memcmp(ps1, ps2, (size_t)length); + if (cmp == 0) goto __pyx_return_true; else goto __pyx_return_false; + } +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyByteArrayPyBytesBoolEq +#define __Pyx_DEFINED_PyObject_ComparePyByteArrayPyBytesBoolEq +static CYTHON_INLINE int __Pyx_PyObject_ComparePyByteArrayPyBytesBoolEq(PyObject* s1, PyObject* s2) { + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + Py_ssize_t length = PyByteArray_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) goto __pyx_return_false; + ps1 = PyByteArray_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + #else + char *ps1, *ps2; + Py_ssize_t length, length2; + ps1 = __Pyx_PyByteArray_AsString(s1); if (unlikely(!ps1)) return -1; + length = __Pyx_PyByteArray_GET_SIZE(s1); if (unlikely(length == -1)) return -1; + if (unlikely(PyBytes_AsStringAndSize(s2, &ps2, &length2) == -1)) return -1; + if (length != length2) goto __pyx_return_false; + #endif + if (length == 0) goto __pyx_return_true; + if (ps1[0] != ps2[0]) goto __pyx_return_false; + if (length == 1) goto __pyx_return_true; + { + int cmp; + cmp = memcmp(ps1, ps2, (size_t)length); + if (cmp == 0) goto __pyx_return_true; else goto __pyx_return_false; + } +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyByteArrayPyByteArrayBoolEq +#define __Pyx_DEFINED_PyObject_ComparePyByteArrayPyByteArrayBoolEq +static CYTHON_INLINE int __Pyx_PyObject_ComparePyByteArrayPyByteArrayBoolEq(PyObject* s1, PyObject* s2) { + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + Py_ssize_t length = PyByteArray_GET_SIZE(s1); + if (length != PyByteArray_GET_SIZE(s2)) goto __pyx_return_false; + ps1 = PyByteArray_AS_STRING(s1); + ps2 = PyByteArray_AS_STRING(s2); + #else + char *ps1, *ps2; + Py_ssize_t length, length2; + ps1 = __Pyx_PyByteArray_AsString(s1); if (unlikely(!ps1)) return -1; + length = __Pyx_PyByteArray_GET_SIZE(s1); if (unlikely(length == -1)) return -1; + ps2 = __Pyx_PyByteArray_AsString(s2); if (unlikely(!ps2)) return -1; + length2 = __Pyx_PyByteArray_GET_SIZE(s2); if (unlikely(length2 == -1)) return -1; + if (length != length2) goto __pyx_return_false; + #endif + if (length == 0) goto __pyx_return_true; + if (ps1[0] != ps2[0]) goto __pyx_return_false; + if (length == 1) goto __pyx_return_true; + { + int cmp; + cmp = memcmp(ps1, ps2, (size_t)length); + if (cmp == 0) goto __pyx_return_true; else goto __pyx_return_false; + } +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareFloatIntBoolEq +#define __Pyx_DEFINED_PyObject_CompareFloatIntBoolEq +static int __Pyx_PyObject_CompareFloatIntBoolEq(PyObject *op1, PyObject *op2) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t iop2 = __Pyx_PyLong_CompactValue(op2); + if (float_op1 == ((double)iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op1))) { + if (float_op1 == 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign2 = __Pyx_PyLong_Sign(op2); + if (float_op1 >= 0.) { + if (sign2 < 0) goto __pyx_return_false; + if (float_op1 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } else { + if (sign2 > 0) goto __pyx_return_false; + if (float_op1 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } + } + #else + if (unlikely(!isfinite(float_op1))) { + if (float_op1 == 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow2; + long iop2 = PyLong_AsLongAndOverflow(op2, &overflow2); + if (likely(!overflow2)) { + if ((long long) iop2 >= (1LL << 53)) { + overflow2 = 1; + } else if ((long long) iop2 <= - (1LL << 53)) { + overflow2 = -1; + } else { + if (float_op1 == ((double) iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow2 > 0) { + if (float_op1 < ((double) (1LL << 53))) goto __pyx_return_false; + } else { + if (float_op1 > - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntFloatBoolEq +#define __Pyx_DEFINED_PyObject_CompareIntFloatBoolEq +static int __Pyx_PyObject_CompareIntFloatBoolEq(PyObject *op1, PyObject *op2) { + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t iop1 = __Pyx_PyLong_CompactValue(op1); + if (((double)iop1) == float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op2))) { + if (0.0 == float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign1 = __Pyx_PyLong_Sign(op1); + if (float_op2 >= 0.) { + if (sign1 < 0) goto __pyx_return_false; + if (float_op2 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } else { + if (sign1 > 0) goto __pyx_return_false; + if (float_op2 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } + } + #else + if (unlikely(!isfinite(float_op2))) { + if (0.0 == float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow1; + long iop1 = PyLong_AsLongAndOverflow(op1, &overflow1); + if (likely(!overflow1)) { + if ((long long) iop1 >= (1LL << 53)) { + overflow1 = 1; + } else if ((long long) iop1 <= - (1LL << 53)) { + overflow1 = -1; + } else { + if (((double) iop1) == float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow1 < 0) { + if (float_op2 > ((double) (1LL << 53))) goto __pyx_return_false; + } else { + if (float_op2 < - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntIntBoolEq +#define __Pyx_DEFINED_PyObject_CompareIntIntBoolEq +static int __Pyx_PyObject_CompareIntIntBoolEq(PyObject *op1, PyObject *op2) { +#if CYTHON_USE_PYLONG_INTERNALS + Py_ssize_t cmp = __Pyx_PyLong_CompareSignAndSize(op1, op2); + if (cmp == 0) { + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + if (size > 0) { + const digit* digits1 = __Pyx_PyLong_Digits(op1); + const digit* digits2 = __Pyx_PyLong_Digits(op2); + if (size == 1) { + cmp = (Py_ssize_t) digits1[0] - (Py_ssize_t) digits2[0]; + } else if ((size == 2) && (8 * sizeof(Py_ssize_t) >= 2 * PyLong_SHIFT)) { + cmp = (Py_ssize_t) (((((size_t)digits1[1]) << PyLong_SHIFT) | (size_t)digits1[0])) - (Py_ssize_t) (((((size_t)digits2[1]) << PyLong_SHIFT) | (size_t)digits2[0])); + } else { + for (Py_ssize_t i=size-1; i >= 0 && !cmp; --i) { + cmp = (Py_ssize_t) digits1[i] - (Py_ssize_t) digits2[i]; + } + } + } + if (cmp == 0) goto __pyx_return_true; + if (__Pyx_PyLong_IsNeg(op1)) cmp = -cmp; + } + goto __pyx_return_false; +#else + int overflow1, overflow2; + long long iop1 = PyLong_AsLongLongAndOverflow(op1, &overflow1); + long long iop2 = PyLong_AsLongLongAndOverflow(op2, &overflow2); + if (likely(!(overflow1 | overflow2))) { + if (iop1 == iop2) goto __pyx_return_true; else goto __pyx_return_false; + } else if (overflow1 != overflow2) { + if (overflow1 == overflow2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); + } +#endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolEq_object_object(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (PyFloat_CheckExact(op1)) { + if (PyFloat_CheckExact(op2)) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + if (float_op1 == float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (PyLong_CheckExact(op2)) { + return __Pyx_PyObject_CompareFloatIntBoolEq(op1, op2); + } + goto __pyx_richcmp; + } + if (PyLong_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_true; + if (PyLong_CheckExact(op2)) { + return __Pyx_PyObject_CompareIntIntBoolEq(op1, op2); + } + if (PyFloat_CheckExact(op2)) { + return __Pyx_PyObject_CompareIntFloatBoolEq(op1, op2); + } + goto __pyx_richcmp; + } + + if (PyUnicode_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_true; + if (PyUnicode_CheckExact(op2)) { + return __Pyx_PyObject_CompareStrStrBoolEq(op1, op2); + } + goto __pyx_richcmp; + } + + #if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) + if (PyBytes_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_true; + if (PyBytes_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyBytesPyBytesBoolEq(op1, op2); + } + if (PyByteArray_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyBytesPyByteArrayBoolEq(op1, op2); + } + goto __pyx_richcmp; + } + #endif + #if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) + if (PyByteArray_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_true; + if (PyByteArray_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyByteArrayPyByteArrayBoolEq(op1, op2); + } + if (PyBytes_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyByteArrayPyBytesBoolEq(op1, op2); + } + goto __pyx_richcmp; + } + #endif + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* RaiseException */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + int is_subclass = PyObject_IsSubclass(instance_class, type); + if (!is_subclass) { + instance_class = NULL; + } else if (unlikely(is_subclass == -1)) { + goto bad; + } else { + type = instance_class; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } + if (cause) { + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyException_SetTraceback(value, tb); +#elif CYTHON_FAST_THREAD_STATE + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#endif + } +bad: + Py_XDECREF(owned_instance); + return; +} + +/* py_abs */ +#if CYTHON_USE_PYLONG_INTERNALS +static PyObject *__Pyx_PyLong_AbsNeg(PyObject *n) { +#if PY_VERSION_HEX >= 0x030C00A7 + if (likely(__Pyx_PyLong_IsCompact(n))) { + return PyLong_FromSize_t(__Pyx_PyLong_CompactValueUnsigned(n)); + } +#else + if (likely(Py_SIZE(n) == -1)) { + return PyLong_FromUnsignedLong(__Pyx_PyLong_Digits(n)[0]); + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON + { + PyObject *copy = _PyLong_Copy((PyLongObject*)n); + if (likely(copy)) { + #if PY_VERSION_HEX >= 0x030C00A7 + ((PyLongObject*)copy)->long_value.lv_tag ^= ((PyLongObject*)copy)->long_value.lv_tag & _PyLong_SIGN_MASK; + #else + Py_SET_SIZE(copy, -Py_SIZE(copy)); + #endif + } + return copy; + } +#else + return PyNumber_Negative(n); +#endif +} +#endif + +/* FormatTypeName (used by RaiseErrorWithObjectTypes) */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static __Pyx_TypeName +__Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp) +{ + PyObject *module = NULL, *name = NULL, *result = NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + name = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_qualname); + #else + name = PyType_GetQualName(tp); + #endif + if (unlikely(name == NULL) || unlikely(!PyUnicode_Check(name))) goto bad; + module = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_module); + if (unlikely(module == NULL) || unlikely(!PyUnicode_Check(module))) goto bad; + if (PyUnicode_CompareWithASCIIString(module, "builtins") == 0) { + result = name; + name = NULL; + goto done; + } + result = PyUnicode_FromFormat("%U.%U", module, name); + if (unlikely(result == NULL)) goto bad; + done: + Py_XDECREF(name); + Py_XDECREF(module); + return result; + bad: + PyErr_Clear(); + if (name) { + result = name; + name = NULL; + } else { + result = __Pyx_NewRef(__pyx_mstate_global->__pyx_kp_u_); + } + goto done; +} +#endif + +/* RaiseErrorWithObjectTypes (used by PyNumberBinop) */ +static void __Pyx_RaiseErrorWithTypes1(PyObject* exc_type, const char *message, const char *arg, PyTypeObject *type_obj1, PyTypeObject *type_obj2) { + __Pyx_TypeName type_name1 = __Pyx_PyType_GetFullyQualifiedName(type_obj1); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 + if (unlikely(!type_name1)) return; + #endif + __Pyx_TypeName type_name2 = __Pyx_PyType_GetFullyQualifiedName(type_obj2); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 + if (unlikely(!type_name2)) goto type2_failed; + #endif + PyErr_Format(exc_type, message, arg, type_name1, type_name2); + __Pyx_DECREF_TypeName(type_name2); +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 +type2_failed: +#endif + __Pyx_DECREF_TypeName(type_name1); +} + +/* PyNumberBinop */ +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API) +#if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#ifndef __Pyx_DEFINED_BinopTypeError +#define __Pyx_DEFINED_BinopTypeError +static void __Pyx_BinopTypeError(PyObject *op1, PyObject *op2, const char* op, int inplace) { + char opname[4] = {op[0], op[1], 0, 0}; + if (inplace) { + opname[op[1] ? 2 : 1] = '='; + } + __Pyx_RaiseErrorWithObjectTypes1( + PyExc_TypeError, + "unsupported operand type(s) for %.3s: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", + opname, op1, op2); +} +#endif +#endif +#ifndef __Pyx_DEFINED_PyNumber_Subtract_xfloat_object +#define __Pyx_DEFINED_PyNumber_Subtract_xfloat_object +static PyObject* __Pyx_PyNumber_Subtract_xfloat_object(PyObject *op1, PyObject *op2, int inplace) { + if (PyLong_CheckExact(op2)) { + double int_op2; + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t compact_op2 = __Pyx_PyLong_CompactValue(op2); + if (compact_op2 == 0) return __Pyx_NewRef(op1); + int_op2 = (double) compact_op2; + } else + #endif + { + int_op2 = PyLong_AsDouble(op2); + if (unlikely((int_op2 == -1.) && PyErr_Occurred())) return NULL; + #if !CYTHON_USE_PYLONG_INTERNALS + if (int_op2 == 0.) return __Pyx_NewRef(op1); + #endif + } + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op1 == -1.) && PyErr_Occurred())) return NULL; + #endif + return PyFloat_FromDouble(float_op1 - int_op2); + } + if (PyLong_Check(op2)) { + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(&PyFloat_Type, tp_as_number, nb_subtract, binaryfunc); + if (likely(slot_func)) { + return slot_func(op1, op2); + } + } + #if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + { + PyTypeObject *type_op2 = Py_TYPE(op2); + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(type_op2, tp_as_number, nb_subtract, binaryfunc); + if (likely(slot_func)) { + PyObject *result = slot_func(op1, op2); + if (likely(result != Py_NotImplemented)) { + return result; + } + Py_DECREF(result); + } + __Pyx_BinopTypeError(op1, op2, "-", inplace); + return NULL; + } + #else + return (inplace) ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2); + #endif +} +#endif +#ifndef __Pyx_DEFINED_PyNumber_Subtract_xint_object +#define __Pyx_DEFINED_PyNumber_Subtract_xint_object +static PyObject* __Pyx_PyNumber_Subtract_xint_object(PyObject *op1, PyObject *op2, int inplace) { + if (PyFloat_CheckExact(op2)) { + double int_op1; + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t compact_op1 = __Pyx_PyLong_CompactValue(op1); + int_op1 = (double) compact_op1; + } else + #endif + { + int_op1 = PyLong_AsDouble(op1); + if (unlikely((int_op1 == -1.) && PyErr_Occurred())) return NULL; + } + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op2 == -1.) && PyErr_Occurred())) return NULL; + #endif + return PyFloat_FromDouble(int_op1 - float_op2); + } + #if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + { + PyTypeObject *type_op2 = Py_TYPE(op2); + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(type_op2, tp_as_number, nb_subtract, binaryfunc); + if (likely(slot_func)) { + PyObject *result = slot_func(op1, op2); + if (likely(result != Py_NotImplemented)) { + return result; + } + Py_DECREF(result); + } + __Pyx_BinopTypeError(op1, op2, "-", inplace); + return NULL; + } + #else + return (inplace) ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2); + #endif +} +#endif +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Subtract_object_object(PyObject *op1, PyObject *op2, int inplace) { + if (PyFloat_CheckExact(op1)) { + if (PyFloat_CheckExact(op2)) { + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op2 == -1.) && PyErr_Occurred())) return NULL; + #endif + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op1 == -1.) && PyErr_Occurred())) return NULL; + #endif + return PyFloat_FromDouble(float_op1 - float_op2); + } + return __Pyx_PyNumber_Subtract_xfloat_object(op1, op2, inplace); + } + if (PyLong_CheckExact(op1)) { + if (PyLong_CheckExact(op2)) { + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t int_op1 = __Pyx_PyLong_CompactValue(op1); + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t int_op2 = __Pyx_PyLong_CompactValue(op2); + if (int_op2 == 0) return __Pyx_NewRef(op1); + return PyLong_FromSsize_t(int_op1 - int_op2); + } + } + else if (__Pyx_PyLong_IsZero(op2)) return __Pyx_NewRef(op1); + #endif + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(&PyLong_Type, tp_as_number, nb_subtract, binaryfunc); + if (likely(slot_func)) { + return slot_func(op1, op2); + } + } + return __Pyx_PyNumber_Subtract_xint_object(op1, op2, inplace); + } + return (inplace) ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2); +} +#endif + +/* ListAppendAndDecrefInternal (used by ListAppend) */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE +static CYTHON_INLINE void __Pyx__ListComp_AppendAndDecref(PyObject* list, Py_ssize_t len, PyObject* x) { + PyList_SET_ITEM(list, len, x); + Py_SET_SIZE(list, len + 1); +} +#endif + +/* ListAppend */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + __Pyx__ListComp_AppendAndDecref(list, len, x); + return 0; + } + return PyList_Append(list, x); +} +#endif + +/* TupleOrListFromArrayImpl (used by ListFromArray) */ +CYTHON_UNUSED static PyObject * +__Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n) { + PyObject *res = PyList_New(n); + if (unlikely(res == NULL)) return NULL; + #if CYTHON_COMPILING_IN_CPYTHON + __Pyx_copy_object_array(src, ((PyListObject*)res)->ob_item, n); + #else + Py_ssize_t i; + for (i = 0; i < n; i++) { + Py_INCREF(src[i]); + if (unlikely(__Pyx_PyList_SET_ITEM(res, i, src[i]) < (0))) { + Py_DECREF(res); + return NULL; + } + } + #endif + return res; +} + +/* SliceTupleAndList */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_crop_slice(Py_ssize_t* _start, Py_ssize_t* _stop, Py_ssize_t* _length) { + Py_ssize_t start = *_start, stop = *_stop, length = *_length; + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + else if (stop > length) + stop = length; + *_length = stop - start; + *_start = start; + *_stop = stop; +} +static CYTHON_INLINE PyObject* __Pyx_PyTuple_GetSlice( + PyObject* src, Py_ssize_t start, Py_ssize_t stop) { + Py_ssize_t length = PyTuple_GET_SIZE(src); + __Pyx_crop_slice(&start, &stop, &length); + return __Pyx_PyTuple_FromArray(((PyTupleObject*)src)->ob_item + start, length); +} +static CYTHON_INLINE PyObject* __Pyx_PyList_GetSlice_locked( + PyObject* src, Py_ssize_t start, Py_ssize_t stop) { + Py_ssize_t length = PyList_GET_SIZE(src); + __Pyx_crop_slice(&start, &stop, &length); + if (length <= 0) { + return PyList_New(0); + } + return __Pyx_PyList_FromArray(((PyListObject*)src)->ob_item + start, length); +} +static CYTHON_INLINE PyObject* __Pyx_PyList_GetSlice( + PyObject* src, Py_ssize_t start, Py_ssize_t stop) { + PyObject *result; + __Pyx_BEGIN_CRITICAL_SECTION(src); + result = __Pyx_PyList_GetSlice_locked(src, start, stop); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +#endif // CYTHON_COMPILING_IN_CPYTHON + +/* ListCompAppendAndDecref */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE +static CYTHON_INLINE int __Pyx_ListComp_AppendAndDecref(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + __Pyx__ListComp_AppendAndDecref(list, len, x); + return 0; + } + int result = PyList_Append(list, x); + Py_DECREF(x); + return result; +} +#else +static CYTHON_INLINE int __Pyx_ListComp_AppendAndDecref(PyObject* list, PyObject* x) { + int result = PyList_Append(list, x); + Py_DECREF(x); + return result; +} +#endif + +/* PyLongBinop */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject* __Pyx_Fallback___Pyx_PyLong_SubtractCObj(PyObject *op1, PyObject *op2, int inplace) { + return (inplace ? PyNumber_InPlaceSubtract : PyNumber_Subtract)(op1, op2); +} +#if CYTHON_USE_PYLONG_INTERNALS +static PyObject* __Pyx_Unpacked___Pyx_PyLong_SubtractCObj(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check) { + CYTHON_MAYBE_UNUSED_VAR(inplace); + CYTHON_UNUSED_VAR(zerodivision_check); + const long a = intval; + long b; + const PY_LONG_LONG lla = intval; + PY_LONG_LONG llb; + if (unlikely(__Pyx_PyLong_IsZero(op2))) { + return __Pyx_NewRef(op1); + } + const int is_positive = __Pyx_PyLong_IsPos(op2); + const digit* digits = __Pyx_PyLong_Digits(op2); + const Py_ssize_t size = __Pyx_PyLong_DigitCount(op2); + if (likely(size == 1)) { + b = (long) digits[0]; + if (!is_positive) b *= -1; + } else { + if (size == 2 && 8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + b = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + if (!is_positive) b *= -1; + goto calculate_long; + } else if (size == 2 && 8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + llb = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + if (!is_positive) llb *= -1; + goto calculate_long_long; + } else + if (size == 3 && 8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + b = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + if (!is_positive) b *= -1; + goto calculate_long; + } else if (size == 3 && 8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + llb = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + if (!is_positive) llb *= -1; + goto calculate_long_long; + } else + if (size == 4 && 8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + b = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + if (!is_positive) b *= -1; + goto calculate_long; + } else if (size == 4 && 8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + llb = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + if (!is_positive) llb *= -1; + goto calculate_long_long; + } else + {} + return PyLong_Type.tp_as_number->nb_subtract(op1, op2); + } + calculate_long: + { + long x; + x = a - b; + return PyLong_FromLong(x); + } + calculate_long_long: + { + PY_LONG_LONG llx; + llx = lla - llb; + return PyLong_FromLongLong(llx); + } + +} +#endif +static PyObject* __Pyx_Float___Pyx_PyLong_SubtractCObj(PyObject *float_val, long intval, int zerodivision_check) { + CYTHON_UNUSED_VAR(zerodivision_check); + const long a = intval; + double b = __Pyx_PyFloat_AS_DOUBLE(float_val); + double result; + + result = ((double)a) - (double)b; + return PyFloat_FromDouble(result); +} +static CYTHON_INLINE PyObject* __Pyx_PyLong_SubtractCObj(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check) { + CYTHON_MAYBE_UNUSED_VAR(intval); + CYTHON_UNUSED_VAR(zerodivision_check); + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(PyLong_CheckExact(op2))) { + return __Pyx_Unpacked___Pyx_PyLong_SubtractCObj(op1, op2, intval, inplace, zerodivision_check); + } + #endif + if (PyFloat_CheckExact(op2)) { + return __Pyx_Float___Pyx_PyLong_SubtractCObj(op2, intval, zerodivision_check); + } + return __Pyx_Fallback___Pyx_PyLong_SubtractCObj(op1, op2, inplace); +} +#endif + +/* PyObjectFormatAndDecref */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_FormatSimpleAndDecref(PyObject* s, PyObject* f) { + if (unlikely(!s)) return NULL; + if (likely(PyUnicode_CheckExact(s))) return s; + return __Pyx_PyObject_FormatAndDecref(s, f); +} +static CYTHON_INLINE PyObject* __Pyx_PyObject_FormatAndDecref(PyObject* s, PyObject* f) { + PyObject *result; + if (unlikely(!s)) return NULL; + result = PyObject_Format(s, f); + Py_DECREF(s); + return result; +} + +/* JoinPyUnicode */ +static PyObject* __Pyx_PyUnicode_Join(PyObject** values, Py_ssize_t value_count, Py_ssize_t result_ulength, int kind) { +#if __Pyx_PyUnicode_Join_CAN_USE_KIND_AND_LENGTH && CYTHON_USE_UNICODE_INTERNALS + PyObject *result_uval; + int result_ukind, kind_shift; + Py_ssize_t i, char_pos; + void *result_udata; + static const Py_UCS4 max_char[5] = {0x7fU, 0xffU, 0xffffU, 0xffffU, 0x10ffffU}; + assert (kind >= 0); + if (kind > PyUnicode_4BYTE_KIND) kind = PyUnicode_4BYTE_KIND; + result_uval = PyUnicode_New(result_ulength, max_char[kind]); + if (unlikely(!result_uval)) return NULL; + kind_shift = kind >> 1; // 0, 1, 2 + result_ukind = 1 << kind_shift; // 1, 2, 4 + result_udata = PyUnicode_DATA(result_uval); + assert(kind_shift == 2 || kind_shift == 1 || kind_shift == 0); + if (unlikely((PY_SSIZE_T_MAX >> kind_shift) - result_ulength < 0)) + goto overflow; + char_pos = 0; + for (i=0; i < value_count; i++) { + int ukind; + Py_ssize_t ulength; + void *udata; + PyObject *uval = values[i]; + if (__Pyx_PyUnicode_READY(uval) == (-1)) + goto bad; + ulength = __Pyx_PyUnicode_GET_LENGTH(uval); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(ulength < 0)) goto bad; + #endif + if (unlikely(!ulength)) + continue; + if (unlikely((PY_SSIZE_T_MAX >> kind_shift) - ulength < char_pos)) + goto overflow; + ukind = __Pyx_PyUnicode_KIND(uval); + udata = __Pyx_PyUnicode_DATA(uval); + if (ukind == result_ukind) { + memcpy((char *)result_udata + (char_pos << kind_shift), udata, (size_t) (ulength << kind_shift)); + } else { + #if PY_VERSION_HEX >= 0x030d0000 + if (unlikely(PyUnicode_CopyCharacters(result_uval, char_pos, uval, 0, ulength) < 0)) goto bad; + #elif CYTHON_COMPILING_IN_CPYTHON || defined(_PyUnicode_FastCopyCharacters) + _PyUnicode_FastCopyCharacters(result_uval, char_pos, uval, 0, ulength); + #else + Py_ssize_t j; + for (j=0; j < ulength; j++) { + Py_UCS4 uchar = __Pyx_PyUnicode_READ(ukind, udata, j); + __Pyx_PyUnicode_WRITE(result_ukind, result_udata, char_pos+j, uchar); + } + #endif + } + char_pos += ulength; + } + return result_uval; +overflow: + PyErr_SetString(PyExc_OverflowError, "join() result is too long for a Python string"); +bad: + Py_DECREF(result_uval); + return NULL; +#else + Py_ssize_t i; + PyObject *result = NULL; + PyObject *value_tuple = PyTuple_New(value_count); + if (unlikely(!value_tuple)) return NULL; + CYTHON_UNUSED_VAR(kind); + CYTHON_UNUSED_VAR(result_ulength); + for (i=0; i__pyx_empty_unicode, value_tuple); +bad: + Py_DECREF(value_tuple); + return result; +#endif +} + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareFloatIntBoolLe +#define __Pyx_DEFINED_PyObject_CompareFloatIntBoolLe +static int __Pyx_PyObject_CompareFloatIntBoolLe(PyObject *op1, PyObject *op2) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t iop2 = __Pyx_PyLong_CompactValue(op2); + if (float_op1 <= ((double)iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op1))) { + if (float_op1 <= 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign2 = __Pyx_PyLong_Sign(op2); + if (float_op1 >= 0.) { + if (sign2 < 0) goto __pyx_return_false; + if (float_op1 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } else { + if (sign2 > 0) goto __pyx_return_true; + if (float_op1 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } + } + #else + if (unlikely(!isfinite(float_op1))) { + if (float_op1 <= 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow2; + long iop2 = PyLong_AsLongAndOverflow(op2, &overflow2); + if (likely(!overflow2)) { + if ((long long) iop2 >= (1LL << 53)) { + overflow2 = 1; + } else if ((long long) iop2 <= - (1LL << 53)) { + overflow2 = -1; + } else { + if (float_op1 <= ((double) iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow2 > 0) { + if (float_op1 < ((double) (1LL << 53))) goto __pyx_return_true; + } else { + if (float_op1 > - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LE); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntIntBoolLe +#define __Pyx_DEFINED_PyObject_CompareIntIntBoolLe +static int __Pyx_PyObject_CompareIntIntBoolLe(PyObject *op1, PyObject *op2) { +#if CYTHON_USE_PYLONG_INTERNALS + Py_ssize_t cmp = __Pyx_PyLong_CompareSignAndSize(op1, op2); + if (cmp == 0) { + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + if (size > 0) { + const digit* digits1 = __Pyx_PyLong_Digits(op1); + const digit* digits2 = __Pyx_PyLong_Digits(op2); + if (size == 1) { + cmp = (Py_ssize_t) digits1[0] - (Py_ssize_t) digits2[0]; + } else if ((size == 2) && (8 * sizeof(Py_ssize_t) >= 2 * PyLong_SHIFT)) { + cmp = (Py_ssize_t) (((((size_t)digits1[1]) << PyLong_SHIFT) | (size_t)digits1[0])) - (Py_ssize_t) (((((size_t)digits2[1]) << PyLong_SHIFT) | (size_t)digits2[0])); + } else { + for (Py_ssize_t i=size-1; i >= 0 && !cmp; --i) { + cmp = (Py_ssize_t) digits1[i] - (Py_ssize_t) digits2[i]; + } + } + } + if (cmp == 0) goto __pyx_return_true; + if (__Pyx_PyLong_IsNeg(op1)) cmp = -cmp; + } + if (cmp < 0) goto __pyx_return_true; else goto __pyx_return_false; +#else + int overflow1, overflow2; + long long iop1 = PyLong_AsLongLongAndOverflow(op1, &overflow1); + long long iop2 = PyLong_AsLongLongAndOverflow(op2, &overflow2); + if (likely(!(overflow1 | overflow2))) { + if (iop1 <= iop2) goto __pyx_return_true; else goto __pyx_return_false; + } else if (overflow1 != overflow2) { + if (overflow1 <= overflow2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LE); + } +#endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolLe_object_int(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (unlikely(op2 == Py_None)) { + goto __pyx_richcmp; + } + if (op1 == op2) goto __pyx_return_true; + if (PyFloat_CheckExact(op1)) { + if (likely(op2 != Py_None)) { + return __Pyx_PyObject_CompareFloatIntBoolLe(op1, op2); + } + goto __pyx_richcmp; + } + if (likely(PyLong_CheckExact(op1))) { + if (op1 == op2) goto __pyx_return_true; + if (likely(op2 != Py_None)) { + return __Pyx_PyObject_CompareIntIntBoolLe(op1, op2); + } + goto __pyx_richcmp; + } + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LE); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* ArgTypeTestError (used by ArgTypeTest) */ +static void __Pyx_ArgTypeError(PyObject *obj, PyTypeObject *type, const char *name, int exact) +{ + __Pyx_TypeName type_name; + __Pyx_TypeName obj_type_name; + PyObject *extra_info = __pyx_mstate_global->__pyx_empty_unicode; + int from_annotation_subclass = 0; + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return; + } else if (exact == 2) { + if (__Pyx_TypeCheck(obj, type)) { + from_annotation_subclass = 1; + extra_info = __pyx_mstate_global->__pyx_kp_u_Note_that_Cython_is_deliberately; + } + } + type_name = __Pyx_PyType_GetFullyQualifiedName(type); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 + if (unlikely(!type_name)) return; + #endif + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 + if (unlikely(!obj_type_name)) goto obj_type_name_failed; + #endif + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected " __Pyx_FMT_TYPENAME ", got " __Pyx_FMT_TYPENAME ")" +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + "%s%U" +#endif + , name, type_name, obj_type_name +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + , (from_annotation_subclass ? ". " : ""), extra_info +#endif + ); +#if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + if (exact == 2 && from_annotation_subclass) { + PyObject *res; + PyObject *vargs[2]; + vargs[0] = PyErr_GetRaisedException(); + vargs[1] = extra_info; + res = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_kp_u_add_note, vargs, 2, NULL); + Py_XDECREF(res); + PyErr_SetRaisedException(vargs[0]); + } +#endif + __Pyx_DECREF_TypeName(obj_type_name); +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 +obj_type_name_failed: +#endif + __Pyx_DECREF_TypeName(type_name); + return; +} + +/* ArgTypeTest */ +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact) { + if (likely(Py_IS_TYPE(obj, type) | (none_allowed && (obj == Py_None)))) + return 1; + if (!exact && likely(type) && likely(__Pyx_TypeCheck(obj, type))) + return 1; + __Pyx_ArgTypeError(obj, type, name, exact); + return 0; +} + +/* RaiseUnboundLocalError */ +static void __Pyx_RaiseUnboundLocalError(const char *varname) { + PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); +} + +/* GetException (used by pep479) */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) +#endif +{ + PyObject *local_type = NULL, *local_value, *local_tb = NULL; +#if CYTHON_FAST_THREAD_STATE + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if PY_VERSION_HEX >= 0x030C0000 + local_value = tstate->current_exception; + tstate->current_exception = 0; + #else + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + #endif +#elif __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + local_value = PyErr_GetRaisedException(); +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif +#if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + if (likely(local_value)) { + local_type = (PyObject*) Py_TYPE(local_value); + Py_INCREF(local_type); + local_tb = PyException_GetTraceback(local_value); + } +#else + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_FAST_THREAD_STATE + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } +#endif // __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_FAST_THREAD_STATE + #if CYTHON_USE_EXC_INFO_STACK + { + _PyErr_StackItem *exc_info = tstate->exc_info; + #if PY_VERSION_HEX >= 0x030B00a4 + tmp_value = exc_info->exc_value; + exc_info->exc_value = local_value; + tmp_type = NULL; + tmp_tb = NULL; + Py_XDECREF(local_type); + Py_XDECREF(local_tb); + #else + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = local_type; + exc_info->exc_value = local_value; + exc_info->exc_traceback = local_tb; + #endif + } + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#elif __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + PyErr_SetHandledException(local_value); + Py_XDECREF(local_value); + Py_XDECREF(local_type); + Py_XDECREF(local_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +#endif +} + +/* pep479 */ +static void __Pyx_Generator_Replace_StopIteration(int in_async_gen) { + PyObject *exc, *val, *tb, *cur_exc, *new_exc; + __Pyx_PyThreadState_declare + int is_async_stopiteration = 0; + CYTHON_MAYBE_UNUSED_VAR(in_async_gen); + __Pyx_PyThreadState_assign + cur_exc = __Pyx_PyErr_CurrentExceptionType(); + if (likely(!__Pyx_PyErr_GivenExceptionMatches(cur_exc, PyExc_StopIteration))) { + if (in_async_gen && unlikely(__Pyx_PyErr_GivenExceptionMatches(cur_exc, PyExc_StopAsyncIteration))) { + is_async_stopiteration = 1; + } else { + return; + } + } + __Pyx_GetException(&exc, &val, &tb); + Py_XDECREF(exc); + Py_XDECREF(tb); + new_exc = PyObject_CallFunction(PyExc_RuntimeError, "s", + is_async_stopiteration ? "async generator raised StopAsyncIteration" : + in_async_gen ? "async generator raised StopIteration" : + "generator raised StopIteration"); + if (!new_exc) { + Py_XDECREF(val); + return; + } + PyException_SetCause(new_exc, val); // steals ref to val + PyErr_SetObject(PyExc_RuntimeError, new_exc); + Py_DECREF(new_exc); +} + +/* PyDictVersioning (used by GetModuleGlobalName) */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { + PyObject **dictptr = NULL; + Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; + if (offset) { +#if CYTHON_COMPILING_IN_CPYTHON + dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); +#else + dictptr = _PyObject_GetDictPtr(obj); +#endif + } + return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; +} +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) + return 0; + return obj_dict_version == __Pyx_get_object_dict_version(obj); +} +#endif + +/* GetModuleGlobalName */ +#if CYTHON_USE_DICT_VERSIONS +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) +#else +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) +#endif +{ + PyObject *result; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(!__pyx_m)) { + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_NameError); + return NULL; + } + result = PyObject_GetAttr(__pyx_m, name); + if (likely(result)) { + return result; + } + if (!__Pyx_IgnoreException(PyExc_Exception)) { + return NULL; // BaseException + } +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + if (unlikely(__Pyx_PyDict_GetItemRef(__pyx_mstate_global->__pyx_d, name, &result) == -1)) { + if (!__Pyx_IgnoreException(PyExc_Exception)) { + return NULL; // BaseException + } + } + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return result; + } +#else + result = _PyDict_GetItem_KnownHash(__pyx_mstate_global->__pyx_d, name, ((PyASCIIObject *) name)->hash); + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } + PyObject *exc = PyErr_Occurred(); + if (unlikely(exc) && !__Pyx_IgnoreGivenException(exc, PyExc_Exception)) { + return NULL; // BaseException + } +#endif + return __Pyx_GetBuiltinName(name); +} + +/* RaiseTooManyValuesToUnpack */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +/* RaiseNeedMoreValuesToUnpack */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +/* IterFinish */ +static CYTHON_INLINE int __Pyx_IterFinish(void) { + PyObject* exc_type; + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + exc_type = __Pyx_PyErr_CurrentExceptionType(); + if (unlikely(exc_type)) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) + return -1; + __Pyx_PyErr_Clear(); + return 0; + } + return 0; +} + +/* UnpackItemEndCheck */ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } + return __Pyx_IterFinish(); +} + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareStrStrBoolNe +#define __Pyx_DEFINED_PyObject_CompareStrStrBoolNe +static CYTHON_INLINE int __Pyx_PyObject_CompareStrStrBoolNe(PyObject* s1, PyObject* s2) { + #if __PYX_LIMITED_VERSION_HEX >= 0x030e0000 + int result = PyUnicode_Equal(s1, s2); + #if !CYTHON_COMPILING_IN_CPYTHON + if (unlikely(result == -1)) return -1; + #endif + if (result != 0) goto __pyx_return_false; else goto __pyx_return_true; + #else + int result = PyUnicode_Compare(s1, s2); + if (unlikely((result == -1) && PyErr_Occurred())) return -1; + if (result != 0) goto __pyx_return_true; else goto __pyx_return_false; + #endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyBytesPyBytesBoolNe +#define __Pyx_DEFINED_PyObject_ComparePyBytesPyBytesBoolNe +static CYTHON_INLINE int __Pyx_PyObject_ComparePyBytesPyBytesBoolNe(PyObject* s1, PyObject* s2) { + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) goto __pyx_return_true; + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + #else + char *ps1, *ps2; + Py_ssize_t length, length2; + if (unlikely(PyBytes_AsStringAndSize(s1, &ps1, &length) == -1)) return -1; + if (unlikely(PyBytes_AsStringAndSize(s2, &ps2, &length2) == -1)) return -1; + if (length != length2) goto __pyx_return_true; + #endif + if (ps1[0] != ps2[0]) goto __pyx_return_true; + if (length == 1) goto __pyx_return_false; + { + int cmp; +#if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000) + Py_hash_t hash1 = ((PyBytesObject*)s1)->ob_shash; + Py_hash_t hash2 = ((PyBytesObject*)s2)->ob_shash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) goto __pyx_return_true; +#endif + cmp = memcmp(ps1, ps2, (size_t)length); + if (cmp != 0) goto __pyx_return_true; else goto __pyx_return_false; + } +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyBytesPyByteArrayBoolNe +#define __Pyx_DEFINED_PyObject_ComparePyBytesPyByteArrayBoolNe +static CYTHON_INLINE int __Pyx_PyObject_ComparePyBytesPyByteArrayBoolNe(PyObject* s1, PyObject* s2) { + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyByteArray_GET_SIZE(s2)) goto __pyx_return_true; + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyByteArray_AS_STRING(s2); + #else + char *ps1, *ps2; + Py_ssize_t length, length2; + if (unlikely(PyBytes_AsStringAndSize(s1, &ps1, &length) == -1)) return -1; + ps2 = __Pyx_PyByteArray_AsString(s2); if (unlikely(!ps2)) return -1; + length2 = __Pyx_PyByteArray_GET_SIZE(s2); if (unlikely(length2 == -1)) return -1; + if (length != length2) goto __pyx_return_true; + #endif + if (ps1[0] != ps2[0]) goto __pyx_return_true; + if (length == 1) goto __pyx_return_false; + { + int cmp; + cmp = memcmp(ps1, ps2, (size_t)length); + if (cmp != 0) goto __pyx_return_true; else goto __pyx_return_false; + } +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyByteArrayPyBytesBoolNe +#define __Pyx_DEFINED_PyObject_ComparePyByteArrayPyBytesBoolNe +static CYTHON_INLINE int __Pyx_PyObject_ComparePyByteArrayPyBytesBoolNe(PyObject* s1, PyObject* s2) { + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + Py_ssize_t length = PyByteArray_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) goto __pyx_return_true; + ps1 = PyByteArray_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + #else + char *ps1, *ps2; + Py_ssize_t length, length2; + ps1 = __Pyx_PyByteArray_AsString(s1); if (unlikely(!ps1)) return -1; + length = __Pyx_PyByteArray_GET_SIZE(s1); if (unlikely(length == -1)) return -1; + if (unlikely(PyBytes_AsStringAndSize(s2, &ps2, &length2) == -1)) return -1; + if (length != length2) goto __pyx_return_true; + #endif + if (length == 0) goto __pyx_return_false; + if (ps1[0] != ps2[0]) goto __pyx_return_true; + if (length == 1) goto __pyx_return_false; + { + int cmp; + cmp = memcmp(ps1, ps2, (size_t)length); + if (cmp != 0) goto __pyx_return_true; else goto __pyx_return_false; + } +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyByteArrayPyByteArrayBoolNe +#define __Pyx_DEFINED_PyObject_ComparePyByteArrayPyByteArrayBoolNe +static CYTHON_INLINE int __Pyx_PyObject_ComparePyByteArrayPyByteArrayBoolNe(PyObject* s1, PyObject* s2) { + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + Py_ssize_t length = PyByteArray_GET_SIZE(s1); + if (length != PyByteArray_GET_SIZE(s2)) goto __pyx_return_true; + ps1 = PyByteArray_AS_STRING(s1); + ps2 = PyByteArray_AS_STRING(s2); + #else + char *ps1, *ps2; + Py_ssize_t length, length2; + ps1 = __Pyx_PyByteArray_AsString(s1); if (unlikely(!ps1)) return -1; + length = __Pyx_PyByteArray_GET_SIZE(s1); if (unlikely(length == -1)) return -1; + ps2 = __Pyx_PyByteArray_AsString(s2); if (unlikely(!ps2)) return -1; + length2 = __Pyx_PyByteArray_GET_SIZE(s2); if (unlikely(length2 == -1)) return -1; + if (length != length2) goto __pyx_return_true; + #endif + if (length == 0) goto __pyx_return_false; + if (ps1[0] != ps2[0]) goto __pyx_return_true; + if (length == 1) goto __pyx_return_false; + { + int cmp; + cmp = memcmp(ps1, ps2, (size_t)length); + if (cmp != 0) goto __pyx_return_true; else goto __pyx_return_false; + } +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareFloatIntBoolNe +#define __Pyx_DEFINED_PyObject_CompareFloatIntBoolNe +static int __Pyx_PyObject_CompareFloatIntBoolNe(PyObject *op1, PyObject *op2) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t iop2 = __Pyx_PyLong_CompactValue(op2); + if (float_op1 != ((double)iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op1))) { + if (float_op1 != 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign2 = __Pyx_PyLong_Sign(op2); + if (float_op1 >= 0.) { + if (sign2 < 0) goto __pyx_return_true; + if (float_op1 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } else { + if (sign2 > 0) goto __pyx_return_true; + if (float_op1 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } + } + #else + if (unlikely(!isfinite(float_op1))) { + if (float_op1 != 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow2; + long iop2 = PyLong_AsLongAndOverflow(op2, &overflow2); + if (likely(!overflow2)) { + if ((long long) iop2 >= (1LL << 53)) { + overflow2 = 1; + } else if ((long long) iop2 <= - (1LL << 53)) { + overflow2 = -1; + } else { + if (float_op1 != ((double) iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow2 > 0) { + if (float_op1 < ((double) (1LL << 53))) goto __pyx_return_true; + } else { + if (float_op1 > - ((double) (1LL << 53))) goto __pyx_return_true; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_NE); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntFloatBoolNe +#define __Pyx_DEFINED_PyObject_CompareIntFloatBoolNe +static int __Pyx_PyObject_CompareIntFloatBoolNe(PyObject *op1, PyObject *op2) { + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t iop1 = __Pyx_PyLong_CompactValue(op1); + if (((double)iop1) != float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op2))) { + if (0.0 != float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign1 = __Pyx_PyLong_Sign(op1); + if (float_op2 >= 0.) { + if (sign1 < 0) goto __pyx_return_true; + if (float_op2 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } else { + if (sign1 > 0) goto __pyx_return_true; + if (float_op2 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } + } + #else + if (unlikely(!isfinite(float_op2))) { + if (0.0 != float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow1; + long iop1 = PyLong_AsLongAndOverflow(op1, &overflow1); + if (likely(!overflow1)) { + if ((long long) iop1 >= (1LL << 53)) { + overflow1 = 1; + } else if ((long long) iop1 <= - (1LL << 53)) { + overflow1 = -1; + } else { + if (((double) iop1) != float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow1 < 0) { + if (float_op2 > ((double) (1LL << 53))) goto __pyx_return_true; + } else { + if (float_op2 < - ((double) (1LL << 53))) goto __pyx_return_true; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_NE); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntIntBoolNe +#define __Pyx_DEFINED_PyObject_CompareIntIntBoolNe +static int __Pyx_PyObject_CompareIntIntBoolNe(PyObject *op1, PyObject *op2) { +#if CYTHON_USE_PYLONG_INTERNALS + Py_ssize_t cmp = __Pyx_PyLong_CompareSignAndSize(op1, op2); + if (cmp == 0) { + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + if (size > 0) { + const digit* digits1 = __Pyx_PyLong_Digits(op1); + const digit* digits2 = __Pyx_PyLong_Digits(op2); + if (size == 1) { + cmp = (Py_ssize_t) digits1[0] - (Py_ssize_t) digits2[0]; + } else if ((size == 2) && (8 * sizeof(Py_ssize_t) >= 2 * PyLong_SHIFT)) { + cmp = (Py_ssize_t) (((((size_t)digits1[1]) << PyLong_SHIFT) | (size_t)digits1[0])) - (Py_ssize_t) (((((size_t)digits2[1]) << PyLong_SHIFT) | (size_t)digits2[0])); + } else { + for (Py_ssize_t i=size-1; i >= 0 && !cmp; --i) { + cmp = (Py_ssize_t) digits1[i] - (Py_ssize_t) digits2[i]; + } + } + } + if (cmp == 0) goto __pyx_return_false; + if (__Pyx_PyLong_IsNeg(op1)) cmp = -cmp; + } + goto __pyx_return_true; +#else + int overflow1, overflow2; + long long iop1 = PyLong_AsLongLongAndOverflow(op1, &overflow1); + long long iop2 = PyLong_AsLongLongAndOverflow(op2, &overflow2); + if (likely(!(overflow1 | overflow2))) { + if (iop1 != iop2) goto __pyx_return_true; else goto __pyx_return_false; + } else if (overflow1 != overflow2) { + if (overflow1 != overflow2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_NE); + } +#endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolNe_object_object(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (PyFloat_CheckExact(op1)) { + if (PyFloat_CheckExact(op2)) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + if (float_op1 != float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (PyLong_CheckExact(op2)) { + return __Pyx_PyObject_CompareFloatIntBoolNe(op1, op2); + } + goto __pyx_richcmp; + } + if (PyLong_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_false; + if (PyLong_CheckExact(op2)) { + return __Pyx_PyObject_CompareIntIntBoolNe(op1, op2); + } + if (PyFloat_CheckExact(op2)) { + return __Pyx_PyObject_CompareIntFloatBoolNe(op1, op2); + } + goto __pyx_richcmp; + } + + if (PyUnicode_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_false; + if (PyUnicode_CheckExact(op2)) { + return __Pyx_PyObject_CompareStrStrBoolNe(op1, op2); + } + goto __pyx_richcmp; + } + + #if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) + if (PyBytes_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_false; + if (PyBytes_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyBytesPyBytesBoolNe(op1, op2); + } + if (PyByteArray_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyBytesPyByteArrayBoolNe(op1, op2); + } + goto __pyx_richcmp; + } + #endif + #if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) + if (PyByteArray_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_false; + if (PyByteArray_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyByteArrayPyByteArrayBoolNe(op1, op2); + } + if (PyBytes_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyByteArrayPyBytesBoolNe(op1, op2); + } + goto __pyx_richcmp; + } + #endif + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_NE); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* RaiseErrorWithObjectType (used by SliceObject) */ +static void __Pyx_RaiseErrorWithType(PyObject* exc_type, const char* message, PyTypeObject *type_obj) { + __Pyx_TypeName type_name = __Pyx_PyType_GetFullyQualifiedName(type_obj); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 + if (unlikely(!type_name)) return; + #endif + PyErr_Format(exc_type, message, type_name); + __Pyx_DECREF_TypeName(type_name); +} + +/* SliceObject */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice(PyObject* obj, + Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, + int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { +#if CYTHON_USE_TYPE_SLOTS + PyMappingMethods* mp = Py_TYPE(obj)->tp_as_mapping; + if (likely(mp && mp->mp_subscript)) +#else + if ((1)) +#endif + { + PyObject* result; + PyObject *py_slice, *py_start, *py_stop; + if (_py_slice) { + py_slice = *_py_slice; + } else { + PyObject* owned_start = NULL; + PyObject* owned_stop = NULL; + if (_py_start) { + py_start = *_py_start; + } else { + if (has_cstart) { + owned_start = py_start = PyLong_FromSsize_t(cstart); + if (unlikely(!py_start)) goto bad; + } else + py_start = Py_None; + } + if (_py_stop) { + py_stop = *_py_stop; + } else { + if (has_cstop) { + owned_stop = py_stop = PyLong_FromSsize_t(cstop); + if (unlikely(!py_stop)) { + Py_XDECREF(owned_start); + goto bad; + } + } else + py_stop = Py_None; + } + py_slice = PySlice_New(py_start, py_stop, Py_None); + Py_XDECREF(owned_start); + Py_XDECREF(owned_stop); + if (unlikely(!py_slice)) goto bad; + } +#if CYTHON_USE_TYPE_SLOTS + result = mp->mp_subscript(obj, py_slice); +#else + result = PyObject_GetItem(obj, py_slice); +#endif + if (!_py_slice) { + Py_DECREF(py_slice); + } + return result; + } else { + __Pyx_RaiseTypeErrorWithObjectType( + "'" __Pyx_FMT_TYPENAME "' object is unsliceable", obj); + } +bad: + return NULL; +} + +/* PyObjectCallMethod0 (used by pop) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { +#if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || !CYTHON_COMPILING_IN_LIMITED_API) + return PyObject_VectorcallMethod(method_name, &obj, 1 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#elif CYTHON_COMPILING_IN_LIMITED_API + return PyObject_CallMethodObjArgs(obj, method_name, NULL); +#else + return PyObject_CallMethodNoArgs(obj, method_name); +#endif +} + +/* pop */ +static CYTHON_INLINE PyObject* __Pyx__PyObject_Pop(PyObject* L) { + if (Py_IS_TYPE(L, &PySet_Type)) { + return PySet_Pop(L); + } + return __Pyx_PyObject_CallMethod0(L, __pyx_mstate_global->__pyx_n_u_pop); +} +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE +static CYTHON_INLINE PyObject* __Pyx_PyList_Pop(PyObject* L) { + if (likely(PyList_GET_SIZE(L) > (((PyListObject*)L)->allocated >> 1))) { + Py_SET_SIZE(L, Py_SIZE(L) - 1); + return PyList_GET_ITEM(L, PyList_GET_SIZE(L)); + } + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyList_Type_pop, L); +} +#endif + +/* ListExtend */ +#if (CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030d0000) && !defined(PyList_Extend) +static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject* none = _PyList_Extend((PyListObject*)L, v); + if (unlikely(!none)) + return -1; + Py_DECREF(none); + return 0; +#else + return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); +#endif +} +#endif + +/* RaiseErrorWithObjectType1 (used by RaiseUnexpectedTypeError) */ +static void __Pyx_RaiseErrorWithType1(PyObject* exc_type, const char* message, const char *arg, PyTypeObject *type_obj) { + __Pyx_TypeName type_name = __Pyx_PyType_GetFullyQualifiedName(type_obj); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 + if (unlikely(!type_name)) return; + #endif + PyErr_Format(exc_type, message, arg, type_name); + __Pyx_DECREF_TypeName(type_name); +} + +/* RaiseUnexpectedTypeError */ +static int __Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj) { + __Pyx_RaiseTypeErrorWithObjectType1( + "Expected %.42s, got " __Pyx_FMT_TYPENAME, + expected, obj); + return 0; +} + +/* PyLongBinop */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject* __Pyx_Fallback___Pyx_PyLong_AddObjC(PyObject *op1, PyObject *op2, int inplace) { + return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); +} +#if CYTHON_USE_PYLONG_INTERNALS +static PyObject* __Pyx_Unpacked___Pyx_PyLong_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check) { + CYTHON_MAYBE_UNUSED_VAR(inplace); + CYTHON_UNUSED_VAR(zerodivision_check); + const long b = intval; + long a; + const PY_LONG_LONG llb = intval; + PY_LONG_LONG lla; + if (unlikely(__Pyx_PyLong_IsZero(op1))) { + return __Pyx_NewRef(op2); + } + const int is_positive = __Pyx_PyLong_IsPos(op1); + const digit* digits = __Pyx_PyLong_Digits(op1); + const Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + if (likely(size == 1)) { + a = (long) digits[0]; + if (!is_positive) a *= -1; + } else { + if (size == 2 && 8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + if (!is_positive) a *= -1; + goto calculate_long; + } else if (size == 2 && 8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + if (!is_positive) lla *= -1; + goto calculate_long_long; + } else + if (size == 3 && 8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + if (!is_positive) a *= -1; + goto calculate_long; + } else if (size == 3 && 8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + if (!is_positive) lla *= -1; + goto calculate_long_long; + } else + if (size == 4 && 8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + if (!is_positive) a *= -1; + goto calculate_long; + } else if (size == 4 && 8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + if (!is_positive) lla *= -1; + goto calculate_long_long; + } else + {} + return PyLong_Type.tp_as_number->nb_add(op1, op2); + } + calculate_long: + { + long x; + x = a + b; + return PyLong_FromLong(x); + } + calculate_long_long: + { + PY_LONG_LONG llx; + llx = lla + llb; + return PyLong_FromLongLong(llx); + } + +} +#endif +static PyObject* __Pyx_Float___Pyx_PyLong_AddObjC(PyObject *float_val, long intval, int zerodivision_check) { + CYTHON_UNUSED_VAR(zerodivision_check); + const long b = intval; + double a = __Pyx_PyFloat_AS_DOUBLE(float_val); + double result; + + result = ((double)a) + (double)b; + return PyFloat_FromDouble(result); +} +static CYTHON_INLINE PyObject* __Pyx_PyLong_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check) { + CYTHON_MAYBE_UNUSED_VAR(intval); + CYTHON_UNUSED_VAR(zerodivision_check); + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(PyLong_CheckExact(op1))) { + return __Pyx_Unpacked___Pyx_PyLong_AddObjC(op1, op2, intval, inplace, zerodivision_check); + } + #endif + if (PyFloat_CheckExact(op1)) { + return __Pyx_Float___Pyx_PyLong_AddObjC(op1, intval, zerodivision_check); + } + return __Pyx_Fallback___Pyx_PyLong_AddObjC(op1, op2, inplace); +} +#endif + +/* PyNumberBinop */ +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API) +#if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#ifndef __Pyx_DEFINED_BinopTypeError +#define __Pyx_DEFINED_BinopTypeError +static void __Pyx_BinopTypeError(PyObject *op1, PyObject *op2, const char* op, int inplace) { + char opname[4] = {op[0], op[1], 0, 0}; + if (inplace) { + opname[op[1] ? 2 : 1] = '='; + } + __Pyx_RaiseErrorWithObjectTypes1( + PyExc_TypeError, + "unsupported operand type(s) for %.3s: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", + opname, op1, op2); +} +#endif +#endif +#ifndef __Pyx_DEFINED_PyNumber_Add_xint_object +#define __Pyx_DEFINED_PyNumber_Add_xint_object +static PyObject* __Pyx_PyNumber_Add_xint_object(PyObject *op1, PyObject *op2, int inplace) { + if (PyFloat_CheckExact(op2)) { + double int_op1; + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t compact_op1 = __Pyx_PyLong_CompactValue(op1); + if (compact_op1 == 0) return __Pyx_NewRef(op2); + int_op1 = (double) compact_op1; + } else + #endif + { + int_op1 = PyLong_AsDouble(op1); + if (unlikely((int_op1 == -1.) && PyErr_Occurred())) return NULL; + #if !CYTHON_USE_PYLONG_INTERNALS + if (int_op1 == 0.) return __Pyx_NewRef(op2); + #endif + } + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op2 == -1.) && PyErr_Occurred())) return NULL; + #endif + return PyFloat_FromDouble(int_op1 + float_op2); + } + #if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + { + PyTypeObject *type_op2 = Py_TYPE(op2); + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(type_op2, tp_as_number, nb_add, binaryfunc); + if (likely(slot_func)) { + PyObject *result = slot_func(op1, op2); + if (likely(result != Py_NotImplemented)) { + return result; + } + Py_DECREF(result); + } + __Pyx_BinopTypeError(op1, op2, "+", inplace); + return NULL; + } + #else + return (inplace) ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2); + #endif +} +#endif +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Add_int_object(PyObject *op1, PyObject *op2, int inplace) { + if (likely(op1 != Py_None)) { + if (likely(PyLong_CheckExact(op2))) { + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t int_op1 = __Pyx_PyLong_CompactValue(op1); + if (int_op1 == 0) return __Pyx_NewRef(op2); + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t int_op2 = __Pyx_PyLong_CompactValue(op2); + if (int_op2 == 0) return __Pyx_NewRef(op1); + return PyLong_FromSsize_t(int_op1 + int_op2); + } + } + else if (__Pyx_PyLong_IsZero(op2)) return __Pyx_NewRef(op1); + #endif + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(&PyLong_Type, tp_as_number, nb_add, binaryfunc); + if (likely(slot_func)) { + return slot_func(op1, op2); + } + } + return __Pyx_PyNumber_Add_xint_object(op1, op2, inplace); + } + return (inplace) ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2); +} +#endif + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareStrStrBoolLt +#define __Pyx_DEFINED_PyObject_CompareStrStrBoolLt +static CYTHON_INLINE int __Pyx_PyObject_CompareStrStrBoolLt(PyObject* s1, PyObject* s2) { + int result = PyUnicode_Compare(s1, s2); + if (unlikely((result == -1) && PyErr_Occurred())) return -1; + if (result < 0) goto __pyx_return_true; else goto __pyx_return_false; +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyBytesPyBytesBoolLt +#define __Pyx_DEFINED_PyObject_ComparePyBytesPyBytesBoolLt +static CYTHON_INLINE int __Pyx_PyObject_ComparePyBytesPyBytesBoolLt(PyObject* s1, PyObject* s2) { + Py_ssize_t cmp; + Py_ssize_t length1, length2, short_length; + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + length1 = __Pyx_PyBytes_GET_SIZE(s1); + length2 = __Pyx_PyBytes_GET_SIZE(s2); + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + #else + char *ps1, *ps2; + if (unlikely(PyBytes_AsStringAndSize(s1, &ps1, &length1) == -1)) return -1; + if (unlikely(PyBytes_AsStringAndSize(s2, &ps2, &length2) == -1)) return -1; + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + #endif + cmp = (Py_ssize_t) ((const unsigned char*) ps1)[0] - (Py_ssize_t) ((const unsigned char*) ps2)[0]; + if (cmp == 0 && short_length > 1) { + cmp = memcmp(ps1, ps2, (size_t)short_length); + } + if (cmp == 0) cmp = (length1 - length2); + if (cmp < 0) goto __pyx_return_true; else goto __pyx_return_false; +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyBytesPyByteArrayBoolLt +#define __Pyx_DEFINED_PyObject_ComparePyBytesPyByteArrayBoolLt +static CYTHON_INLINE int __Pyx_PyObject_ComparePyBytesPyByteArrayBoolLt(PyObject* s1, PyObject* s2) { + Py_ssize_t cmp; + Py_ssize_t length1, length2, short_length; + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + length1 = __Pyx_PyBytes_GET_SIZE(s1); + length2 = __Pyx_PyByteArray_GET_SIZE(s2); + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyByteArray_AS_STRING(s2); + #else + char *ps1, *ps2; + if (unlikely(PyBytes_AsStringAndSize(s1, &ps1, &length1) == -1)) return -1; + ps2 = __Pyx_PyByteArray_AsString(s2); if (unlikely(!ps2)) return -1; + length2 = __Pyx_PyByteArray_GET_SIZE(s2); if (unlikely(length2 == -1)) return -1; + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + #endif + cmp = (Py_ssize_t) ((const unsigned char*) ps1)[0] - (Py_ssize_t) ((const unsigned char*) ps2)[0]; + if (cmp == 0 && short_length > 1) { + cmp = memcmp(ps1, ps2, (size_t)short_length); + } + if (cmp == 0) cmp = (length1 - length2); + if (cmp < 0) goto __pyx_return_true; else goto __pyx_return_false; +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyByteArrayPyBytesBoolLt +#define __Pyx_DEFINED_PyObject_ComparePyByteArrayPyBytesBoolLt +static CYTHON_INLINE int __Pyx_PyObject_ComparePyByteArrayPyBytesBoolLt(PyObject* s1, PyObject* s2) { + Py_ssize_t cmp; + Py_ssize_t length1, length2, short_length; + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + length1 = __Pyx_PyByteArray_GET_SIZE(s1); + length2 = __Pyx_PyBytes_GET_SIZE(s2); + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + ps1 = PyByteArray_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + #else + char *ps1, *ps2; + ps1 = __Pyx_PyByteArray_AsString(s1); if (unlikely(!ps1)) return -1; + length1 = __Pyx_PyByteArray_GET_SIZE(s1); if (unlikely(length1 == -1)) return -1; + if (unlikely(PyBytes_AsStringAndSize(s2, &ps2, &length2) == -1)) return -1; + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + #endif + cmp = (Py_ssize_t) ((const unsigned char*) ps1)[0] - (Py_ssize_t) ((const unsigned char*) ps2)[0]; + if (cmp == 0 && short_length > 1) { + cmp = memcmp(ps1, ps2, (size_t)short_length); + } + if (cmp == 0) cmp = (length1 - length2); + if (cmp < 0) goto __pyx_return_true; else goto __pyx_return_false; +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyByteArrayPyByteArrayBoolLt +#define __Pyx_DEFINED_PyObject_ComparePyByteArrayPyByteArrayBoolLt +static CYTHON_INLINE int __Pyx_PyObject_ComparePyByteArrayPyByteArrayBoolLt(PyObject* s1, PyObject* s2) { + Py_ssize_t cmp; + Py_ssize_t length1, length2, short_length; + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + length1 = __Pyx_PyByteArray_GET_SIZE(s1); + length2 = __Pyx_PyByteArray_GET_SIZE(s2); + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + ps1 = PyByteArray_AS_STRING(s1); + ps2 = PyByteArray_AS_STRING(s2); + #else + char *ps1, *ps2; + ps1 = __Pyx_PyByteArray_AsString(s1); if (unlikely(!ps1)) return -1; + length1 = __Pyx_PyByteArray_GET_SIZE(s1); if (unlikely(length1 == -1)) return -1; + ps2 = __Pyx_PyByteArray_AsString(s2); if (unlikely(!ps2)) return -1; + length2 = __Pyx_PyByteArray_GET_SIZE(s2); if (unlikely(length2 == -1)) return -1; + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + #endif + cmp = (Py_ssize_t) ((const unsigned char*) ps1)[0] - (Py_ssize_t) ((const unsigned char*) ps2)[0]; + if (cmp == 0 && short_length > 1) { + cmp = memcmp(ps1, ps2, (size_t)short_length); + } + if (cmp == 0) cmp = (length1 - length2); + if (cmp < 0) goto __pyx_return_true; else goto __pyx_return_false; +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareFloatIntBoolLt +#define __Pyx_DEFINED_PyObject_CompareFloatIntBoolLt +static int __Pyx_PyObject_CompareFloatIntBoolLt(PyObject *op1, PyObject *op2) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t iop2 = __Pyx_PyLong_CompactValue(op2); + if (float_op1 < ((double)iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op1))) { + if (float_op1 < 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign2 = __Pyx_PyLong_Sign(op2); + if (float_op1 >= 0.) { + if (sign2 < 0) goto __pyx_return_false; + if (float_op1 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } else { + if (sign2 > 0) goto __pyx_return_true; + if (float_op1 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } + } + #else + if (unlikely(!isfinite(float_op1))) { + if (float_op1 < 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow2; + long iop2 = PyLong_AsLongAndOverflow(op2, &overflow2); + if (likely(!overflow2)) { + if ((long long) iop2 >= (1LL << 53)) { + overflow2 = 1; + } else if ((long long) iop2 <= - (1LL << 53)) { + overflow2 = -1; + } else { + if (float_op1 < ((double) iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow2 > 0) { + if (float_op1 < ((double) (1LL << 53))) goto __pyx_return_true; + } else { + if (float_op1 > - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LT); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntFloatBoolLt +#define __Pyx_DEFINED_PyObject_CompareIntFloatBoolLt +static int __Pyx_PyObject_CompareIntFloatBoolLt(PyObject *op1, PyObject *op2) { + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t iop1 = __Pyx_PyLong_CompactValue(op1); + if (((double)iop1) < float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op2))) { + if (0.0 < float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign1 = __Pyx_PyLong_Sign(op1); + if (float_op2 >= 0.) { + if (sign1 < 0) goto __pyx_return_true; + if (float_op2 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } else { + if (sign1 > 0) goto __pyx_return_false; + if (float_op2 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } + } + #else + if (unlikely(!isfinite(float_op2))) { + if (0.0 < float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow1; + long iop1 = PyLong_AsLongAndOverflow(op1, &overflow1); + if (likely(!overflow1)) { + if ((long long) iop1 >= (1LL << 53)) { + overflow1 = 1; + } else if ((long long) iop1 <= - (1LL << 53)) { + overflow1 = -1; + } else { + if (((double) iop1) < float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow1 < 0) { + if (float_op2 > ((double) (1LL << 53))) goto __pyx_return_true; + } else { + if (float_op2 < - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LT); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntIntBoolLt +#define __Pyx_DEFINED_PyObject_CompareIntIntBoolLt +static int __Pyx_PyObject_CompareIntIntBoolLt(PyObject *op1, PyObject *op2) { +#if CYTHON_USE_PYLONG_INTERNALS + Py_ssize_t cmp = __Pyx_PyLong_CompareSignAndSize(op1, op2); + if (cmp == 0) { + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + if (size > 0) { + const digit* digits1 = __Pyx_PyLong_Digits(op1); + const digit* digits2 = __Pyx_PyLong_Digits(op2); + if (size == 1) { + cmp = (Py_ssize_t) digits1[0] - (Py_ssize_t) digits2[0]; + } else if ((size == 2) && (8 * sizeof(Py_ssize_t) >= 2 * PyLong_SHIFT)) { + cmp = (Py_ssize_t) (((((size_t)digits1[1]) << PyLong_SHIFT) | (size_t)digits1[0])) - (Py_ssize_t) (((((size_t)digits2[1]) << PyLong_SHIFT) | (size_t)digits2[0])); + } else { + for (Py_ssize_t i=size-1; i >= 0 && !cmp; --i) { + cmp = (Py_ssize_t) digits1[i] - (Py_ssize_t) digits2[i]; + } + } + } + if (cmp == 0) goto __pyx_return_false; + if (__Pyx_PyLong_IsNeg(op1)) cmp = -cmp; + } + if (cmp < 0) goto __pyx_return_true; else goto __pyx_return_false; +#else + int overflow1, overflow2; + long long iop1 = PyLong_AsLongLongAndOverflow(op1, &overflow1); + long long iop2 = PyLong_AsLongLongAndOverflow(op2, &overflow2); + if (likely(!(overflow1 | overflow2))) { + if (iop1 < iop2) goto __pyx_return_true; else goto __pyx_return_false; + } else if (overflow1 != overflow2) { + if (overflow1 < overflow2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LT); + } +#endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolLt_object_object(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (PyFloat_CheckExact(op1)) { + if (PyFloat_CheckExact(op2)) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + if (float_op1 < float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (PyLong_CheckExact(op2)) { + return __Pyx_PyObject_CompareFloatIntBoolLt(op1, op2); + } + goto __pyx_richcmp; + } + if (PyLong_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_false; + if (PyLong_CheckExact(op2)) { + return __Pyx_PyObject_CompareIntIntBoolLt(op1, op2); + } + if (PyFloat_CheckExact(op2)) { + return __Pyx_PyObject_CompareIntFloatBoolLt(op1, op2); + } + goto __pyx_richcmp; + } + + if (PyUnicode_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_false; + if (PyUnicode_CheckExact(op2)) { + return __Pyx_PyObject_CompareStrStrBoolLt(op1, op2); + } + goto __pyx_richcmp; + } + + #if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) + if (PyBytes_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_false; + if (PyBytes_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyBytesPyBytesBoolLt(op1, op2); + } + if (PyByteArray_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyBytesPyByteArrayBoolLt(op1, op2); + } + goto __pyx_richcmp; + } + #endif + #if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) + if (PyByteArray_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_false; + if (PyByteArray_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyByteArrayPyByteArrayBoolLt(op1, op2); + } + if (PyBytes_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyByteArrayPyBytesBoolLt(op1, op2); + } + goto __pyx_richcmp; + } + #endif + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LT); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* GetTopmostException (used by SaveResetException) */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * +__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) +{ + _PyErr_StackItem *exc_info = tstate->exc_info; + while ((exc_info->exc_value == NULL || exc_info->exc_value == Py_None) && + exc_info->previous_item != NULL) + { + exc_info = exc_info->previous_item; + } + return exc_info; +} +#endif + +/* SaveResetException */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + PyObject *exc_value = exc_info->exc_value; + if (exc_value == NULL || exc_value == Py_None) { + *value = NULL; + *type = NULL; + *tb = NULL; + } else { + *value = exc_value; + Py_INCREF(*value); + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + *tb = PyException_GetTraceback(exc_value); + } + #elif CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + *type = exc_info->exc_type; + *value = exc_info->exc_value; + *tb = exc_info->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #else + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #endif +} +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = tstate->exc_info; + PyObject *tmp_value = exc_info->exc_value; + exc_info->exc_value = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); + #else + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = type; + exc_info->exc_value = value; + exc_info->exc_traceback = tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); + #endif +} +#endif + +/* pyfrozenset_new (used by PySetContains) */ +static PyObject* __Pyx_PyFrozenSet_New(PyObject* it) { + PyObject* result; + if (PyFrozenSet_CheckExact(it)) { + Py_INCREF(it); + return it; + } + result = PyFrozenSet_New(it); + if (unlikely(!result)) { + return NULL; + } + if ((__PYX_LIMITED_VERSION_HEX >= 0x030A0000) +#if CYTHON_COMPILING_IN_LIMITED_API + || likely(__Pyx_get_runtime_version() >= 0x030A0000) +#endif + ) + return result; + Py_ssize_t size = __Pyx_PySet_GET_SIZE(result); + if (likely(size > 0)) + return result; +#if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(size < 0)) { + Py_DECREF(result); + return NULL; + } +#endif + Py_DECREF(result); + return PyFrozenSet_New(NULL); +} + +/* PySetContains */ +static int __Pyx_PySet_ContainsUnhashable(PyObject *set, PyObject *key) { + int result = -1; + if (PySet_Check(key) && PyErr_ExceptionMatches(PyExc_TypeError)) { + PyObject *tmpkey; + PyErr_Clear(); + tmpkey = __Pyx_PyFrozenSet_New(key); + if (tmpkey != NULL) { + result = PySet_Contains(set, tmpkey); + Py_DECREF(tmpkey); + } + } + return result; +} +static CYTHON_INLINE int __Pyx_PySet_ContainsTF(PyObject* key, PyObject* set, int eq) { + int result = PySet_Contains(set, key); + if (unlikely(result < 0)) { + result = __Pyx_PySet_ContainsUnhashable(set, key); + } + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + +/* HasAttr (used by ImportImpl) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { + PyObject *r; + if (unlikely(!PyUnicode_Check(n))) { + PyErr_SetString(PyExc_TypeError, + "hasattr(): attribute name must be string"); + return -1; + } + r = __Pyx_PyObject_GetAttrStrNoError(o, n); + if (!r) { + return (unlikely(PyErr_Occurred())) ? -1 : 0; + } else { + Py_DECREF(r); + return 1; + } +} +#endif + +/* ImportImpl (used by Import) */ +static int __Pyx__Import_GetModule(PyObject *qualname, PyObject **module) { + PyObject *imported_module = PyImport_GetModule(qualname); + if (unlikely(!imported_module)) { + *module = NULL; + if (PyErr_Occurred()) { + return -1; + } + return 0; + } + *module = imported_module; + return 1; +} +static int __Pyx__Import_Lookup(PyObject *qualname, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject **module) { + PyObject *imported_module; + PyObject *top_level_package_name; + Py_ssize_t i; + int status, module_found; + Py_ssize_t dot_index; + module_found = __Pyx__Import_GetModule(qualname, &imported_module); + if (unlikely(!module_found || module_found == -1)) { + *module = NULL; + return module_found; + } + if (imported_names) { + for (i = 0; i < len_imported_names; i++) { + PyObject *imported_name = imported_names[i]; +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 + int has_imported_attribute = PyObject_HasAttr(imported_module, imported_name); +#else + int has_imported_attribute = PyObject_HasAttrWithError(imported_module, imported_name); + if (unlikely(has_imported_attribute == -1)) goto error; +#endif + if (!has_imported_attribute) { + goto not_found; + } + } + *module = imported_module; + return 1; + } + dot_index = PyUnicode_FindChar(qualname, '.', 0, PY_SSIZE_T_MAX, 1); + if (dot_index == -1) { + *module = imported_module; + return 1; + } + if (unlikely(dot_index == -2)) goto error; + top_level_package_name = PyUnicode_Substring(qualname, 0, dot_index); + if (unlikely(!top_level_package_name)) goto error; + Py_DECREF(imported_module); + status = __Pyx__Import_GetModule(top_level_package_name, module); + Py_DECREF(top_level_package_name); + return status; +error: + Py_DECREF(imported_module); + *module = NULL; + return -1; +not_found: + Py_DECREF(imported_module); + *module = NULL; + return 0; +} +static PyObject *__Pyx__Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, PyObject *moddict, int level) { + PyObject *module = 0; + PyObject *empty_dict = 0; + PyObject *from_list = 0; + int module_found; + if (!qualname) { + qualname = name; + } + module_found = __Pyx__Import_Lookup(qualname, imported_names, len_imported_names, &module); + if (likely(module_found == 1)) { + return module; + } else if (unlikely(module_found == -1)) { + return NULL; + } + #if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030f00a6 + empty_dict = PyFrozenDict_New(NULL); + #else + empty_dict = PyDict_New(); + #endif + if (unlikely(!empty_dict)) + goto bad; + if (imported_names) { + from_list = __Pyx_PyList_FromArray(imported_names, len_imported_names); + if (unlikely(!from_list)) + goto bad; + } + if (level == -1) { + const char* package_sep = strchr(__Pyx_MODULE_NAME, '.'); + if (package_sep != (0)) { + module = PyImport_ImportModuleLevelObject( + name, moddict, empty_dict, from_list, 1); + if (unlikely(!module)) { + if (unlikely(!PyErr_ExceptionMatches(PyExc_ImportError))) + goto bad; + PyErr_Clear(); + } + } + level = 0; + } + if (!module) { + module = PyImport_ImportModuleLevelObject( + name, moddict, empty_dict, from_list, level); + } +bad: + Py_XDECREF(from_list); + Py_XDECREF(empty_dict); + return module; +} + +/* Import */ +static PyObject *__Pyx_Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, int level) { + return __Pyx__Import(name, imported_names, len_imported_names, qualname, __pyx_mstate_global->__pyx_d, level); +} + +/* ImportFrom */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + const char* module_name_str = 0; + PyObject* module_name = 0; + PyObject* module_dot = 0; + PyObject* full_name = 0; + PyErr_Clear(); + module_name_str = PyModule_GetName(module); + if (unlikely(!module_name_str)) { goto modbad; } + module_name = PyUnicode_FromString(module_name_str); + if (unlikely(!module_name)) { goto modbad; } + module_dot = PyUnicode_Concat(module_name, __pyx_mstate_global->__pyx_kp_u__2); + if (unlikely(!module_dot)) { goto modbad; } + full_name = PyUnicode_Concat(module_dot, name); + if (unlikely(!full_name)) { goto modbad; } + #if (CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM < 0x07030400) ||\ + CYTHON_COMPILING_IN_GRAAL + { + PyObject *modules = PyImport_GetModuleDict(); + if (unlikely(!modules)) + goto modbad; + value = PyObject_GetItem(modules, full_name); + } + #else + value = PyImport_GetModule(full_name); + #endif + modbad: + Py_XDECREF(full_name); + Py_XDECREF(module_dot); + Py_XDECREF(module_name); + } + if (unlikely(!value)) { + PyErr_Format(PyExc_ImportError, "cannot import name %S", name); + } + return value; +} + +/* AllocateExtensionType */ +static PyObject *__Pyx_AllocateExtensionType(PyTypeObject *t, int is_final) { + if (is_final || likely(!__Pyx_PyType_HasFeature(t, Py_TPFLAGS_IS_ABSTRACT))) { + allocfunc alloc_func = __Pyx_PyType_GetSlot(t, tp_alloc, allocfunc); + return alloc_func(t, 0); + } else { + newfunc tp_new = __Pyx_PyType_TryGetSlot(&PyBaseObject_Type, tp_new, newfunc); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + if (!tp_new) { + PyObject *new_str = PyUnicode_FromString("__new__"); + if (likely(new_str)) { + PyObject *o = PyObject_CallMethodObjArgs((PyObject *)&PyBaseObject_Type, new_str, t, NULL); + Py_DECREF(new_str); + return o; + } else + return NULL; + } else + #endif + return tp_new(t, __pyx_mstate_global->__pyx_empty_tuple, 0); + } +} + +/* CallSlotAsVectorcallUnpackDict (used by CallSlotAsVectorcall) */ +static CYTHON_INLINE int __Pyx_CallSlotAsVectorcallUnpackDict(Py_ssize_t args_size, PyObject *keys_dict, PyObject **args, PyObject *kwnames) { + Py_ssize_t pos = 0, i = 0; + PyObject *key, *value; + while (PyDict_Next(keys_dict, &pos, &key, &value)) { + Py_INCREF(value); + args[args_size+i] = value; + Py_INCREF(key); + if (unlikely(__Pyx_PyTuple_SET_ITEM(kwnames, i, key) == -1)) { + return -1; + } + ++i; + } + return 0; +} + +/* CallSlotAsVectorcall */ +#if CYTHON_VECTORCALL_TPNEW +static PyObject * __Pyx_CallTpnewAsVectorcall(__Pyx_tpnewvectorcallfunc f, PyTypeObject* o, PyObject *a, PyObject *k) { + Py_ssize_t k_size = k ? __Pyx_PyDict_GET_SIZE(k) : 0; +#if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(k_size < 0)) return NULL; +#endif + Py_ssize_t a_size = __Pyx_PyTuple_GET_SIZE(a); +#if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(a_size < 0)) return NULL; +#endif +#if CYTHON_ASSUME_SAFE_MACROS + if (k_size == 0) { + return f(o, &PyTuple_GET_ITEM(a, 0), a_size, NULL); + } +#else + if (k_size == 0 && a_size == 0) { + return f(o, NULL, 0, NULL); + } +#endif + PyObject *stack_args[5]; + PyObject **args = stack_args; + Py_ssize_t maxnargs = PY_SSIZE_T_MAX / sizeof(PyObject*) - 1; + if (a_size > maxnargs - k_size) { + PyErr_NoMemory(); + return NULL; + } + Py_ssize_t total_size = a_size + k_size; + if (total_size > 5) { + args = (PyObject**)PyMem_Malloc(((size_t)total_size)*sizeof(PyObject*)); + if (unlikely(!args)) { + PyErr_NoMemory(); + return NULL; + } + } + PyObject * result = NULL; + PyObject *kwnames = NULL; + int unpack_dict_result; + Py_ssize_t i = 0; + for (; i < a_size; ++i) { + args[i] = __Pyx_PyTuple_GET_ITEM(a, i); +#if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!args[i])) goto cleanup; +#endif + } +#if !CYTHON_ASSUME_SAFE_MACROS + if (k) // There's a specific shortcut earlier for ASSUME_SAFE_MACROS with no keywords +#endif + { + kwnames = PyTuple_New(k_size); + if (unlikely(!kwnames)) goto cleanup; + __Pyx_BEGIN_CRITICAL_SECTION(k); + unpack_dict_result = __Pyx_CallSlotAsVectorcallUnpackDict(a_size, k, args, kwnames); + __Pyx_END_CRITICAL_SECTION(); + if (unlikely(unpack_dict_result == -1)) goto cleanup; + } + result = f(o, args, a_size, kwnames); + cleanup: + Py_XDECREF(kwnames); + for (i=a_size; i__pyx_empty_tuple); + } + result = tp_new(t, args_tuple, kwds_dict); + if (unlikely(!result)) { + goto end; + } + if (PyObject_TypeCheck(result, t)) { + initproc tp_init = __Pyx_PyObject_GetSlot(result, tp_init, initproc); + if (tp_init && unlikely(tp_init(result, args_tuple, kwds_dict) < 0)) { + Py_CLEAR(result); + } + } + end: + Py_XDECREF(args_tuple); + Py_XDECREF(kwds_dict); + return result; +} +#endif + +/* CallTypeTraverse */ +#if !CYTHON_USE_TYPE_SPECS +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg) { + if (!always_call) { + PyTypeObject *base = __Pyx_PyObject_GetSlot(o, tp_base, PyTypeObject*); + unsigned long flags = PyType_GetFlags(base); + if (flags & Py_TPFLAGS_HEAPTYPE) { + return 0; + } + } + Py_VISIT((PyObject*)Py_TYPE(o)); + return 0; +} +#endif + +/* GetTypeDictOffset (used by ValidateBasesTuple) */ +#if !CYTHON_USE_TYPE_SLOTS +CYTHON_UNUSED static Py_ssize_t __Pyx_GetTypeDictOffset(PyObject *tp, int require_cython_valid_result) { + PyObject *tp_dictoffset_o; + Py_ssize_t tp_dictoffset; + tp_dictoffset_o = PyObject_GetAttrString(tp, "__dictoffset__"); + if (unlikely(!tp_dictoffset_o)) return -1; + tp_dictoffset = PyLong_AsSsize_t(tp_dictoffset_o); + Py_DECREF(tp_dictoffset_o); + if (unlikely(require_cython_valid_result && tp_dictoffset == 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' doesn't have a dictoffset"); + return -1; + } else if (unlikely(require_cython_valid_result && tp_dictoffset < 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' has an unexpected negative dictoffset. " + "Please report this as Cython bug"); + return -1; + } + return tp_dictoffset; +} +#endif + +/* ValidateBasesTuple (used by PyType_Ready) */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, int has_dictoffset, PyObject *bases) { + Py_ssize_t i, n; +#if CYTHON_ASSUME_SAFE_SIZE + n = PyTuple_GET_SIZE(bases); +#else + n = PyTuple_Size(bases); + if (unlikely(n < 0)) return -1; +#endif + if (!has_dictoffset) { + PyObject *b; +#if CYTHON_AVOID_BORROWED_REFS + b = PySequence_GetItem(bases, 0); + if (!b) return -1; +#elif CYTHON_ASSUME_SAFE_MACROS + b = PyTuple_GET_ITEM(bases, 0); +#else + b = PyTuple_GetItem(bases, 0); + if (!b) return -1; +#endif +#if CYTHON_USE_TYPE_SLOTS + has_dictoffset = ((PyTypeObject*)b)->tp_dictoffset != 0; +#else + Py_ssize_t dictoffset = __Pyx_GetTypeDictOffset(b, 0); + has_dictoffset = dictoffset != 0; +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b); +#endif +#if !CYTHON_USE_TYPE_SLOTS + if (dictoffset == -1 && PyErr_Occurred()) return -1; +#endif + } + for (i = 1; i < n; i++) + { + PyTypeObject *b; +#if CYTHON_AVOID_BORROWED_REFS + PyObject *b0 = PySequence_GetItem(bases, i); + if (!b0) return -1; +#elif CYTHON_ASSUME_SAFE_MACROS + PyObject *b0 = PyTuple_GET_ITEM(bases, i); +#else + PyObject *b0 = PyTuple_GetItem(bases, i); + if (!b0) return -1; +#endif + b = (PyTypeObject*) b0; + if (!__Pyx_PyType_HasFeature(b, Py_TPFLAGS_HEAPTYPE)) + { + __Pyx_RaiseErrorWithType( + PyExc_TypeError, "base class '" __Pyx_FMT_TYPENAME "' is not a heap type", b); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + if (!has_dictoffset) + { + Py_ssize_t b_dictoffset = 0; +#if CYTHON_USE_TYPE_SLOTS + b_dictoffset = b->tp_dictoffset; +#else + b_dictoffset = __Pyx_GetTypeDictOffset((PyObject*)b, 0); + if (b_dictoffset == -1 && PyErr_Occurred()) goto dictoffset_return; +#endif + if (b_dictoffset) { + __Pyx_RaiseErrorWithType1( + PyExc_TypeError, + "extension type '%.200s' has no __dict__ slot, " + "but base type '" __Pyx_FMT_TYPENAME "' has: " + "either add 'cdef dict __dict__' to the extension type " + "or add '__slots__ = [...]' to the base type", + type_name, b); +#if !CYTHON_USE_TYPE_SLOTS + dictoffset_return: +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + } +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + } + return 0; +} +#endif + +/* PyType_Ready */ +CYTHON_UNUSED static int __Pyx_PyType_HasMultipleInheritance(PyTypeObject *t) { + while (t) { + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases) { + return 1; + } + t = __Pyx_PyType_GetSlot(t, tp_base, PyTypeObject*); + } + return 0; +} +static int __Pyx_PyType_Ready(PyTypeObject *t) { +#if CYTHON_USE_TYPE_SPECS || !CYTHON_COMPILING_IN_CPYTHON + (void)__Pyx_PyObject_CallMethod0; +#if CYTHON_USE_TYPE_SPECS + (void)__Pyx_validate_bases_tuple; +#endif + return PyType_Ready(t); +#else + int r; + if (!__Pyx_PyType_HasMultipleInheritance(t)) { + return PyType_Ready(t); + } + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases && unlikely(__Pyx_validate_bases_tuple(t->tp_name, t->tp_dictoffset != 0, bases) == -1)) + return -1; + { + int gc_was_enabled; + #if PY_VERSION_HEX >= 0x030A00b1 + gc_was_enabled = PyGC_Disable(); + (void)__Pyx_PyObject_CallMethod0; + #else + PyObject *ret, *py_status; + PyObject *gc = NULL; + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM+0 >= 0x07030400) &&\ + !CYTHON_COMPILING_IN_GRAAL + gc = PyImport_GetModule(__pyx_mstate_global->__pyx_kp_u_gc); + #endif + if (unlikely(!gc)) gc = PyImport_Import(__pyx_mstate_global->__pyx_kp_u_gc); + if (unlikely(!gc)) return -1; + py_status = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_isenabled); + if (unlikely(!py_status)) { + Py_DECREF(gc); + return -1; + } + gc_was_enabled = __Pyx_PyObject_IsTrue(py_status); + Py_DECREF(py_status); + if (gc_was_enabled > 0) { + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_disable); + if (unlikely(!ret)) { + Py_DECREF(gc); + return -1; + } + Py_DECREF(ret); + } else if (unlikely(gc_was_enabled == -1)) { + Py_DECREF(gc); + return -1; + } + #endif + t->tp_flags |= Py_TPFLAGS_HEAPTYPE; +#if PY_VERSION_HEX >= 0x030A0000 + t->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE; +#endif + r = PyType_Ready(t); + t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE; + #if PY_VERSION_HEX >= 0x030A00b1 + if (gc_was_enabled) + PyGC_Enable(); + #else + if (gc_was_enabled) { + PyObject *tp, *v, *tb; + PyErr_Fetch(&tp, &v, &tb); + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_enable); + if (likely(ret || r == -1)) { + Py_XDECREF(ret); + PyErr_Restore(tp, v, tb); + } else { + Py_XDECREF(tp); + Py_XDECREF(v); + Py_XDECREF(tb); + r = -1; + } + } + Py_DECREF(gc); + #endif + } + return r; +#endif +} + +/* dict_setdefault (used by FetchCommonType) */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value) { + PyObject* value; +#if __PYX_LIMITED_VERSION_HEX >= 0x030F0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4) + PyDict_SetDefaultRef(d, key, default_value, &value); +#elif CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + PyObject *args[] = {d, key, default_value}; + value = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_n_u_setdefault, args, 3 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#elif CYTHON_COMPILING_IN_LIMITED_API + value = PyObject_CallMethodObjArgs(d, __pyx_mstate_global->__pyx_n_u_setdefault, key, default_value, NULL); +#else + value = PyDict_SetDefault(d, key, default_value); + if (unlikely(!value)) return NULL; + Py_INCREF(value); +#endif + return value; +} + +/* AddModuleRef (used by FetchSharedCythonModule) */ +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && PY_VERSION_HEX < 0x030F00a3 + static PyObject *__Pyx_PyImport_AddModuleObjectRef(PyObject *name) { + PyObject *module_dict = PyImport_GetModuleDict(); + PyObject *m; + if (PyMapping_GetOptionalItem(module_dict, name, &m) < 0) { + return NULL; + } + if (m != NULL && PyModule_Check(m)) { + return m; + } + Py_XDECREF(m); + m = PyModule_NewObject(name); + if (m == NULL) + return NULL; + if (PyDict_CheckExact(module_dict)) { + PyObject *new_m; + (void)PyDict_SetDefaultRef(module_dict, name, m, &new_m); + Py_DECREF(m); + return new_m; + } else { + if (PyObject_SetItem(module_dict, name, m) != 0) { + Py_DECREF(m); + return NULL; + } + return m; + } + } + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + if ((PY_VERSION_HEX >= 0x030E0000) && Py_Version >= 0x030E0100) { + return PyImport_AddModuleRef(name); + } + PyObject *py_name = PyUnicode_FromString(name); + if (!py_name) return NULL; + PyObject *module = __Pyx_PyImport_AddModuleObjectRef(py_name); + Py_DECREF(py_name); + return module; + } +#elif __PYX_LIMITED_VERSION_HEX < 0x030d0000 + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *module = PyImport_AddModule(name); + Py_XINCREF(module); + return module; + } +#endif + +/* FetchSharedCythonModule (used by FetchCommonType) */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void) { + return __Pyx_PyImport_AddModuleRef(__PYX_ABI_MODULE_NAME); +} + +/* VerifyCachedType (used by FetchCommonType) */ +static int __Pyx_VerifyCachedType(PyObject *cached_type, + const char *name, + Py_ssize_t expected_basicsize) { + Py_ssize_t basicsize; + if (!PyType_Check(cached_type)) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s is not a type object", name); + return -1; + } + if (expected_basicsize == 0) { + return 0; // size is inherited, nothing useful to check + } +#if CYTHON_COMPILING_IN_LIMITED_API && CYTHON_OPAQUE_OBJECTS + if (expected_basicsize < 0) { + basicsize = PyType_GetTypeDataSize((PyTypeObject*)cached_type); + } else +#endif + { + #if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_basicsize; + py_basicsize = PyObject_GetAttrString(cached_type, "__basicsize__"); + if (unlikely(!py_basicsize)) return -1; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = NULL; + if (unlikely(basicsize == (Py_ssize_t)-1) && PyErr_Occurred()) return -1; + #else + basicsize = ((PyTypeObject*) cached_type)->tp_basicsize; + #endif + } + if ((expected_basicsize >= 0) ? + (basicsize != expected_basicsize) : + (basicsize < -expected_basicsize)) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s has the wrong size, try recompiling", + name); + return -1; + } + return 0; +} + +/* FetchCommonType (used by CommonTypesMetaclass) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject* __Pyx_PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *result = __Pyx_PyType_FromModuleAndSpec(module, spec, bases); + if (result && metaclass) { + PyObject *old_tp = (PyObject*)Py_TYPE(result); + Py_INCREF((PyObject*)metaclass); + Py_SET_TYPE(result, metaclass); + Py_DECREF(old_tp); + PyType_Modified((PyTypeObject*)result); + } + return result; +} +#else +#define __Pyx_PyType_FromMetaclass(me, mo, s, b) PyType_FromMetaclass(me, mo, s, b) +#endif +static PyTypeObject *__Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *abi_module = NULL, *cached_type = NULL, *abi_module_dict, *new_cached_type, *py_object_name; + int get_item_ref_result; + const char* object_name = strrchr(spec->name, '.'); + object_name = object_name ? object_name+1 : spec->name; + py_object_name = PyUnicode_FromString(object_name); + if (!py_object_name) return NULL; + abi_module = __Pyx_FetchSharedCythonABIModule(); + if (!abi_module) goto done; + abi_module_dict = PyModule_GetDict(abi_module); + if (!abi_module_dict) goto done; + get_item_ref_result = __Pyx_PyDict_GetItemRef(abi_module_dict, py_object_name, &cached_type); + if (get_item_ref_result == 1) { + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else if (unlikely(get_item_ref_result == -1)) { + goto bad; + } + cached_type = __Pyx_PyType_FromMetaclass( + metaclass, + CYTHON_USE_MODULE_STATE ? module : abi_module, + spec, bases); + if (unlikely(!cached_type)) goto bad; + new_cached_type = __Pyx_PyDict_SetDefault(abi_module_dict, py_object_name, cached_type); + if (unlikely(new_cached_type != cached_type)) { + if (unlikely(!new_cached_type)) goto bad; + Py_DECREF(cached_type); + cached_type = new_cached_type; + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else { + Py_DECREF(new_cached_type); + } +done: + Py_XDECREF(abi_module); + Py_DECREF(py_object_name); + assert(cached_type == NULL || PyType_Check(cached_type)); + return (PyTypeObject *) cached_type; +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} + +/* CommonTypesMetaclass (used by CythonFunctionShared) */ +static PyObject* __pyx_CommonTypesMetaclass_get_module(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED void* context) { + return PyUnicode_FromString(__PYX_ABI_MODULE_NAME); +} +#if __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject* __pyx_CommonTypesMetaclass_call(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *args, CYTHON_UNUSED PyObject *kwds) { + PyErr_SetString(PyExc_TypeError, "Cannot instantiate Cython internal types"); + return NULL; +} +static int __pyx_CommonTypesMetaclass_setattr(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *attr, CYTHON_UNUSED PyObject *value) { + PyErr_SetString(PyExc_TypeError, "Cython internal types are immutable"); + return -1; +} +#endif +static PyGetSetDef __pyx_CommonTypesMetaclass_getset[] = { + {"__module__", __pyx_CommonTypesMetaclass_get_module, NULL, NULL, NULL}, + {0, 0, 0, 0, 0} +}; +static PyType_Slot __pyx_CommonTypesMetaclass_slots[] = { + {Py_tp_getset, (void *)__pyx_CommonTypesMetaclass_getset}, + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + {Py_tp_call, (void*)__pyx_CommonTypesMetaclass_call}, + {Py_tp_new, (void*)__pyx_CommonTypesMetaclass_call}, + {Py_tp_setattro, (void*)__pyx_CommonTypesMetaclass_setattr}, + #endif + {0, 0} +}; +static PyType_Spec __pyx_CommonTypesMetaclass_spec = { + __PYX_TYPE_MODULE_PREFIX "_common_types_metatype", + 0, + 0, + Py_TPFLAGS_IMMUTABLETYPE | + Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT, + __pyx_CommonTypesMetaclass_slots +}; +static int __pyx_CommonTypesMetaclass_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + PyObject *bases = PyTuple_Pack(1, &PyType_Type); + if (unlikely(!bases)) { + return -1; + } + mstate->__pyx_CommonTypesMetaclassType = __Pyx_FetchCommonTypeFromSpec(NULL, module, &__pyx_CommonTypesMetaclass_spec, bases); + Py_DECREF(bases); + if (unlikely(mstate->__pyx_CommonTypesMetaclassType == NULL)) { + return -1; + } + return 0; +} + +/* CythonFunctionPerModule (used by CythonFunctionShared) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunctionNoMethod(PyObject *func, void (*cfunc)(void)) { + if (__Pyx_CyFunction_Check(func)) { + return __Pyx_as_CyFunctionObject(func)->func_methoddef->ml_meth == (PyCFunction) cfunc; + } else if (PyCFunction_Check(func)) { + return PyCFunction_GetFunction(func) == (PyCFunction) cfunc; + } + return 0; +} +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if ((PyObject*)Py_TYPE(func) == __pyx_mstate_global->__Pyx_CachedMethodType) { + int result; + PyObject *newFunc = PyObject_GetAttr(func, __pyx_mstate_global->__pyx_n_u_func); + if (unlikely(!newFunc)) { + PyErr_Clear(); // It's only an optimization, so don't throw an error + return 0; + } + result = __Pyx__IsSameCyOrCFunctionNoMethod(newFunc, cfunc); + Py_DECREF(newFunc); + return result; + } + return __Pyx__IsSameCyOrCFunctionNoMethod(func, cfunc); +} +#else +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if (PyMethod_Check(func)) { + func = PyMethod_GET_FUNCTION(func); + } + return __Pyx_CyOrPyCFunction_Check(func) && __Pyx_CyOrPyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +} +#endif +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj) { +#if CYTHON_COMPILING_IN_LIMITED_API + __Pyx_Py_XDECREF_SET( + __Pyx__CyFunction_GetClassObj(f), + ((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#else + __Pyx_Py_XDECREF_SET( + ((PyCMethodObject *) (f))->mm_class, + (PyTypeObject*)((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, PyTypeObject *defaults_type) { + __pyx_CyFunctionObject *m = __Pyx_as_CyFunctionObject(func); + m->defaults = PyObject_CallObject((PyObject*)defaults_type, NULL); // _PyObject_New(defaults_type); + if (unlikely(!m->defaults)) + return NULL; + return m->defaults; +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { + __pyx_CyFunctionObject *m = __Pyx_as_CyFunctionObject(func); + m->defaults_tuple = tuple; + Py_INCREF(tuple); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = __Pyx_as_CyFunctionObject(func); + m->defaults_kwdict = dict; + Py_INCREF(dict); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = __Pyx_as_CyFunctionObject(func); + m->func_annotations = dict; + Py_INCREF(dict); +} + +/* PyMethodNew (used by CythonFunctionShared) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + PyObject *result; + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + #if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + { + PyObject *args[] = {func, self}; + result = PyObject_Vectorcall(__pyx_mstate_global->__Pyx_CachedMethodType, args, 2, NULL); + } + #else + result = PyObject_CallFunctionObjArgs(__pyx_mstate_global->__Pyx_CachedMethodType, func, self, NULL); + #endif + return result; +} +#else +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + return PyMethod_New(func, self); +} +#endif + +/* PyVectorcallFastCallDict (used by CythonFunctionShared) */ +#if CYTHON_VECTORCALL +static PyObject *__Pyx_PyVectorcall_FastCallDict_kw(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + PyObject *res = NULL; + PyObject *kwnames; + PyObject **newargs; + PyObject **kwvalues; + Py_ssize_t i; + #if CYTHON_AVOID_BORROWED_REFS + PyObject *pos; + #else + Py_ssize_t pos; + #endif + size_t j; + PyObject *key, *value; + unsigned long keys_are_strings; + #if !CYTHON_ASSUME_SAFE_SIZE + Py_ssize_t nkw = PyDict_Size(kw); + if (unlikely(nkw == -1)) return NULL; + #else + Py_ssize_t nkw = PyDict_GET_SIZE(kw); + #endif + newargs = (PyObject **)PyMem_Malloc((nargs + (size_t)nkw) * sizeof(args[0])); + if (unlikely(newargs == NULL)) { + PyErr_NoMemory(); + return NULL; + } + for (j = 0; j < nargs; j++) newargs[j] = args[j]; + kwnames = PyTuple_New(nkw); + if (unlikely(kwnames == NULL)) { + PyMem_Free(newargs); + return NULL; + } + kwvalues = newargs + nargs; + pos = 0; + i = 0; + keys_are_strings = Py_TPFLAGS_UNICODE_SUBCLASS; + while (__Pyx_PyDict_NextRef(kw, &pos, &key, &value)) { + keys_are_strings &= + #if CYTHON_COMPILING_IN_LIMITED_API + PyType_GetFlags(Py_TYPE(key)); + #else + Py_TYPE(key)->tp_flags; + #endif + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(PyTuple_SetItem(kwnames, i, key) < 0)) goto cleanup; + #else + PyTuple_SET_ITEM(kwnames, i, key); + #endif + kwvalues[i] = value; + i++; + } + if (unlikely(!keys_are_strings)) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + goto cleanup; + } + res = vc(func, newargs, nargs, kwnames); +cleanup: + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(pos); + #endif + Py_DECREF(kwnames); + for (i = 0; i < nkw; i++) + Py_DECREF(kwvalues[i]); + PyMem_Free(newargs); + return res; +} +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + Py_ssize_t kw_size = + likely(kw == NULL) ? + 0 : +#if !CYTHON_ASSUME_SAFE_SIZE + PyDict_Size(kw); +#else + PyDict_GET_SIZE(kw); +#endif + if (kw_size == 0) { + return vc(func, args, nargs, NULL); + } +#if !CYTHON_ASSUME_SAFE_SIZE + else if (unlikely(kw_size == -1)) { + return NULL; + } +#endif + return __Pyx_PyVectorcall_FastCallDict_kw(func, vc, args, nargs, kw); +} +#endif + +/* CythonFunctionShared (used by CythonFunction) */ +static PyObject * +__Pyx_CyFunction_get_doc_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_doc == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + const char *doc = op->func_methoddef->ml_doc; +#else + const char *doc = ((PyCFunctionObject*)op)->m_ml->ml_doc; +#endif + if (doc) { + op->func_doc = PyUnicode_FromString(doc); + if (unlikely(op->func_doc == NULL)) + return NULL; + } else { + Py_INCREF(Py_None); + return Py_None; + } + } + Py_INCREF(op->func_doc); + return op->func_doc; +} +static PyObject * +__Pyx_CyFunction_get_doc(PyObject *op_in, void *closure) { + PyObject *result; + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + CYTHON_UNUSED_VAR(closure); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + result = __Pyx_CyFunction_get_doc_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_doc(PyObject *op_in, PyObject *value, void *context) +{ + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + CYTHON_UNUSED_VAR(context); + if (value == NULL) { + value = Py_None; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + __Pyx_Py_XDECREF_SET(op->func_doc, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_name_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_name == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + const char *name = op->func_methoddef->ml_name; +#else + const char *name = ((PyCFunctionObject*)op)->m_ml->ml_name; +#endif + op->func_name = PyUnicode_InternFromString(name); + if (unlikely(op->func_name == NULL)) + return NULL; + } + Py_INCREF(op->func_name); + return op->func_name; +} +static PyObject * +__Pyx_CyFunction_get_name(PyObject *op, void *context) +{ + PyObject *result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_name_locked(__Pyx_as_CyFunctionObject(op)); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_name(PyObject *op_in, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + __Pyx_Py_XDECREF_SET(op->func_name, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_qualname(PyObject *op_in, void *context) +{ + CYTHON_UNUSED_VAR(context); + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + PyObject *result; + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + Py_INCREF(op->func_qualname); + result = op->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_qualname(PyObject *op_in, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + __Pyx_Py_XDECREF_SET(op->func_qualname, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject * +__Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(op->func_dict == NULL)) { + op->func_dict = PyDict_New(); + if (unlikely(op->func_dict == NULL)) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; +} +#endif +static PyObject * +__Pyx_CyFunction_get_globals(PyObject *op_in, void *context) +{ + CYTHON_UNUSED_VAR(context); + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + Py_INCREF(op->func_globals); + return op->func_globals; +} +static PyObject * +__Pyx_CyFunction_get_closure(PyObject *op, void *context) +{ + CYTHON_UNUSED_VAR(op); + CYTHON_UNUSED_VAR(context); + Py_INCREF(Py_None); + return Py_None; +} +static PyObject * +__Pyx_CyFunction_get_code(PyObject *op_in, void *context) +{ + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + PyObject* result = (op->func_code) ? op->func_code : Py_None; + CYTHON_UNUSED_VAR(context); + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op, PyObject *op_obj) { + int result = 0; + PyObject *res = op->defaults_getter(op_obj); + if (unlikely(!res)) + return -1; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + op->defaults_tuple = PyTuple_GET_ITEM(res, 0); + Py_INCREF(op->defaults_tuple); + op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); + Py_INCREF(op->defaults_kwdict); + #else + op->defaults_tuple = __Pyx_PySequence_ITEM(res, 0); + if (unlikely(!op->defaults_tuple)) result = -1; + else { + op->defaults_kwdict = __Pyx_PySequence_ITEM(res, 1); + if (unlikely(!op->defaults_kwdict)) result = -1; + } + #endif + Py_DECREF(res); + return result; +} +static int +__Pyx_CyFunction_set_defaults(PyObject *op_in, PyObject* value, void *context) { + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyTuple_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__defaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + __Pyx_Py_XDECREF_SET(op->defaults_tuple, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_defaults_locked(PyObject *op_in) { + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + PyObject* result = op->defaults_tuple; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op, op_in) < 0)) return NULL; + result = op->defaults_tuple; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_defaults(PyObject *op, void *context) { + PyObject* result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_defaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_kwdefaults(PyObject *op_in, PyObject* value, void *context) { + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__kwdefaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + __Pyx_Py_XDECREF_SET(op->defaults_kwdict, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults_locked(PyObject *op_in) { + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + PyObject* result = op->defaults_kwdict; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op, op_in) < 0)) return NULL; + result = op->defaults_kwdict; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults(PyObject *op, void *context) { + PyObject* result; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_kwdefaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int __Pyx_CyFunction_set_annotate_in_dict_if_exists(PyObject *op_in, PyObject *value); +static int +__Pyx_CyFunction_set_annotations(PyObject *op_in, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value || value == Py_None) { + value = NULL; + } else if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + Py_XINCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + __Pyx_Py_XDECREF_SET(op->func_annotations, value); + __Pyx_END_CRITICAL_SECTION(); + if (unlikely(__Pyx_CyFunction_set_annotate_in_dict_if_exists(op_in, Py_None) < 0)) return -1; + return 0; +} +static int +__Pyx_CyFunction_get_dict_if_exists(PyObject *op_in, PyObject **dict) { + /* Return 1 if the function dict exists, 0 otherwise. This cannot fail: + * _PyObject_GetDictPtr() may clear errors internally, but never reports them. */ +#if CYTHON_COMPILING_IN_PYPY + *dict = PyObject_GenericGetDict(op_in, NULL); +#elif CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030C0000 + *dict = __Pyx_as_CyFunctionObject(op_in)->func_dict; +#else + PyObject **dictptr = _PyObject_GetDictPtr(op_in); + *dict = likely(dictptr) ? *dictptr : NULL; +#endif + return *dict ? 1 : 0; +} +static int +__Pyx_CyFunction_get_annotate_from_dict_if_exists(PyObject *op_in, PyObject **annotate) { + PyObject *dict; + int dict_found; + *annotate = NULL; + dict_found = __Pyx_CyFunction_get_dict_if_exists(op_in, &dict); + if (!dict_found) return 0; + return __Pyx_PyDict_GetItemRef(dict, __pyx_mstate_global->__pyx_n_u_annotate, annotate); +} +static int +__Pyx_CyFunction_set_annotate_in_dict_if_exists(PyObject *op_in, PyObject *value) { + PyObject *dict; + int dict_found; + dict_found = __Pyx_CyFunction_get_dict_if_exists(op_in, &dict); + if (!dict_found) return 0; + if (value) { + return PyDict_SetItem(dict, __pyx_mstate_global->__pyx_n_u_annotate, value); + } else { +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 + return PyDict_Pop(dict, __pyx_mstate_global->__pyx_n_u_annotate, NULL); +#else + int result = PyDict_Contains(dict, __pyx_mstate_global->__pyx_n_u_annotate); + if (result == 1) { + result = PyDict_DelItem(dict, __pyx_mstate_global->__pyx_n_u_annotate); + } + return result; +#endif + } +} +static int +__Pyx_CyFunction_set_annotate_in_dict(PyObject *op_in, PyObject *value) { + PyObject *dict; + int result; +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + dict = __Pyx_CyFunction_get_dict(__Pyx_as_CyFunctionObject(op_in), NULL); +#else + dict = PyObject_GenericGetDict(op_in, NULL); +#endif + if (unlikely(!dict)) return -1; + result = PyDict_SetItem(dict, __pyx_mstate_global->__pyx_n_u_annotate, value); + Py_DECREF(dict); + return result; +} +static PyObject * +__Pyx_CyFunction_get_annotations_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->func_annotations; + if (unlikely(!result)) { + result = PyDict_New(); + if (unlikely(!result)) return NULL; + op->func_annotations = result; + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_annotations(PyObject *op_in, void *context) { + PyObject *annotate = NULL; + PyObject *result = NULL; + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + result = __Pyx_XNewRef(op->func_annotations); + __Pyx_END_CRITICAL_SECTION(); + if (result) return result; + if (unlikely(__Pyx_CyFunction_get_annotate_from_dict_if_exists(op_in, &annotate) < 0)) return NULL; + if (!annotate || annotate == Py_None) { + Py_XDECREF(annotate); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + result = __Pyx_CyFunction_get_annotations_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; + } + PyObject *format = PyLong_FromLong(1L); // annotationlib.Format.VALUE + if (likely(format)) { + if (!Py_EnterRecursiveCall(" cyfunction __annotations__.__get__")) { + result = __Pyx_PyObject_CallOneArg(annotate, format); + Py_LeaveRecursiveCall(); + Py_DECREF(format); + } + } + Py_DECREF(annotate); + if (unlikely(!result)) return NULL; + if (unlikely(!PyDict_Check(result))) { + PyErr_SetString(PyExc_TypeError, "__annotate__ must return a dict"); + Py_DECREF(result); + return NULL; + } + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + __Pyx_Py_XDECREF_SET(op->func_annotations, __Pyx_NewRef(result)); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyObject *__Pyx_CyFunction_annotate_impl(PyObject *self, PyObject *arg) { + CYTHON_UNUSED_VAR(arg); + if (unlikely(!self)) { + PyErr_SetString(PyExc_SystemError, "cython __annotate__ called without 'self' argument"); + return NULL; + } + PyObject *result; + if (Py_EnterRecursiveCall(" in cyfunction annotate")) { + return NULL; + } + result = __Pyx_CyFunction_get_annotations(self, NULL); + Py_LeaveRecursiveCall(); + return result; +} +static PyObject * +__Pyx_CyFunction_get_annotate(PyObject *op_in, void *context); +static int +__Pyx_CyFunction_set_annotate(PyObject *op_in, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, "__annotate__ cannot be deleted"); + return -1; + } + if (unlikely(value != Py_None && !PyCallable_Check(value))) { + PyErr_SetString(PyExc_TypeError, "__annotate__ must be callable or None"); + return -1; + } + if (unlikely(__Pyx_TypeCheck(value, &PyCFunction_Type))) { +#if !CYTHON_ASSUME_SAFE_MACROS && !CYTHON_COMPILING_IN_PYPY + PyCFunction cfunction = PyCFunction_GetFunction(value); + if (unlikely(!cfunction)) return -1; + PyObject *value_self = PyCFunction_GetSelf(value); + if (unlikely(!value_self && PyErr_Occurred())) return -1; +#else + PyCFunction cfunction = PyCFunction_GET_FUNCTION(value); + PyObject *value_self = PyCFunction_GET_SELF(value); +#endif + if (cfunction == __Pyx_CyFunction_annotate_impl && value_self == op_in) { + return __Pyx_CyFunction_set_annotate_in_dict_if_exists(op_in, NULL); + } + } + if (value != Py_None) { + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + Py_CLEAR(op->func_annotations); + __Pyx_END_CRITICAL_SECTION(); + } + return __Pyx_CyFunction_set_annotate_in_dict(op_in, value); +} +#if __PYX_LIMITED_VERSION_HEX < 0x030B0000 +static PyObject * +__Pyx_CyFunction_get_is_coroutine_value(__pyx_CyFunctionObject *op) { + int is_coroutine = op->flags & __Pyx_CYFUNCTION_COROUTINE; + if (is_coroutine) { + PyObject *is_coroutine_value, *module, *fromlist, *marker = __pyx_mstate_global->__pyx_n_u_is_coroutine; + fromlist = PyList_New(1); + if (unlikely(!fromlist)) return NULL; + Py_INCREF(marker); +#if CYTHON_ASSUME_SAFE_MACROS + PyList_SET_ITEM(fromlist, 0, marker); +#else + if (unlikely(PyList_SetItem(fromlist, 0, marker) < 0)) { + Py_DECREF(fromlist); + return NULL; + } +#endif + module = PyImport_ImportModuleLevelObject(__pyx_mstate_global->__pyx_n_u_asyncio_coroutines, NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + if (unlikely(!module)) { + goto ignore_or_error; + } + is_coroutine_value = __Pyx_PyObject_GetAttrStr(module, marker); + Py_DECREF(module); + if (likely(is_coroutine_value)) { + return is_coroutine_value; + } +ignore_or_error: + if (!__Pyx_IgnoreException(PyExc_Exception)) { + return NULL; + } + } + return __Pyx_PyBool_FromLong(is_coroutine); +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine(PyObject *op_in, void *context) { + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + PyObject *result; + CYTHON_UNUSED_VAR(context); + if (op->func_is_coroutine) { + return __Pyx_NewRef(op->func_is_coroutine); + } + result = __Pyx_CyFunction_get_is_coroutine_value(op); + if (unlikely(!result)) + return NULL; + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + if (op->func_is_coroutine) { + Py_DECREF(result); + result = __Pyx_NewRef(op->func_is_coroutine); + } else { + op->func_is_coroutine = __Pyx_NewRef(result); + } + __Pyx_END_CRITICAL_SECTION(); + return result; +} +#endif +static void __Pyx_CyFunction_raise_argument_count_error(PyObject *func, const char* message, Py_ssize_t size) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + py_name, message, size); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + name, message, size); +#endif +} +static void __Pyx_CyFunction_raise_type_error(PyObject *func, const char* message) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s", + py_name, message); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s", + name, message); +#endif +} +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject * +__Pyx_CyFunction_get_module(PyObject *op_in, void *context) { + CYTHON_UNUSED_VAR(context); + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + Py_INCREF(op->func_module); + return op->func_module; +} +static int +__Pyx_CyFunction_set_module(PyObject *op_in, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + if (value == NULL) { + value = Py_None; + } + Py_INCREF(value); + PyObject *old = op->func_module; + op->func_module = value; + Py_DECREF(old); + return 0; +} +#endif +static PyGetSetDef __pyx_CyFunction_getsets[] = { + {"func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + {"func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)PyObject_GenericSetDict, 0, 0}, + {"__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)PyObject_GenericSetDict, 0, 0}, +#else + {"func_dict", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0}, + {"__dict__", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0}, +#endif + {"func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, + {"__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, + {"__annotate__", (getter)__Pyx_CyFunction_get_annotate, (setter)__Pyx_CyFunction_set_annotate, 0, 0}, +#if __PYX_LIMITED_VERSION_HEX < 0x030B0000 + {"_is_coroutine", (getter)__Pyx_CyFunction_get_is_coroutine, 0, 0, 0}, +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + {"__module__", (getter)__Pyx_CyFunction_get_module, (setter)__Pyx_CyFunction_set_module, 0, 0}, +#endif + {0, 0, 0, 0, 0} +}; +static PyMemberDef __pyx_CyFunction_members[] = { +#if !CYTHON_COMPILING_IN_LIMITED_API + {"__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), 0, 0}, +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + {"__dictoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_dict), + __PYX_SHARED_RELATIVE_OFFSET | READONLY, 0}, +#endif +#if CYTHON_VECTORCALL +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + {"__vectorcalloffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_vectorcall), + __PYX_SHARED_RELATIVE_OFFSET | READONLY, 0}, +#else + {"__vectorcalloffset__", T_PYSSIZET, offsetof(PyCFunctionObject, vectorcall), READONLY, 0}, +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + {"__weaklistoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_weakreflist), + __PYX_SHARED_RELATIVE_OFFSET | READONLY, 0}, +#else + {"__weaklistoffset__", T_PYSSIZET, offsetof(PyCFunctionObject, m_weakreflist), READONLY, 0}, +#endif +#endif + {0, 0, 0, 0, 0} +}; +static PyObject * +__Pyx_CyFunction_reduce(PyObject *m_in, PyObject *args) +{ + PyObject *result = NULL; + __pyx_CyFunctionObject *m = __Pyx_as_CyFunctionObject(m_in); + CYTHON_UNUSED_VAR(args); + __Pyx_BEGIN_CRITICAL_SECTION(m_in); + Py_INCREF(m->func_qualname); + result = m->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyMethodDef __pyx_CyFunction_methods[] = { + {"__annotate_cython__", __Pyx_CyFunction_annotate_impl, METH_O, + "Placeholder __annotate__ function to allow 'functools.wraps' to work " + "on Cython functions."}, + {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; +static PyObject * +__Pyx_CyFunction_get_annotate(PyObject *op_in, void *context) { + PyObject *annotate = NULL; + CYTHON_UNUSED_VAR(context); + if (unlikely(__Pyx_CyFunction_get_annotate_from_dict_if_exists(op_in, &annotate) < 0)) return NULL; + if (annotate) return annotate; + PyObject *method = PyCFunction_New( + &__pyx_CyFunction_methods[0], + op_in); + return method; +} +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) +#else +#define __Pyx_CyFunction_weakreflist(cyfunc) (((PyCFunctionObject*)cyfunc)->m_weakreflist) +#endif +static PyObject *__Pyx_CyFunction_Init(PyObject *op_in, + PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { + __pyx_CyFunctionObject* op = __Pyx_as_CyFunctionObject(op_in); +#if !CYTHON_COMPILING_IN_LIMITED_API + PyCFunctionObject *cf = (PyCFunctionObject*) op; +#endif + if (unlikely(op == NULL)) + return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_methoddef = ml; + Py_INCREF(module); + op->func_module = module; +#endif + op->flags = flags; + __Pyx_CyFunction_weakreflist(op) = NULL; +#if !CYTHON_COMPILING_IN_LIMITED_API + cf->m_ml = ml; + cf->m_self = (PyObject *) op; +#endif + Py_XINCREF(closure); + op->func_closure = closure; +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_XINCREF(module); + cf->m_module = module; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + op->func_dict = NULL; +#endif + op->func_name = NULL; + Py_INCREF(qualname); + op->func_qualname = qualname; + op->func_doc = NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_classobj = NULL; +#else + ((PyCMethodObject*)op)->mm_class = NULL; +#endif + op->func_globals = globals; + Py_INCREF(op->func_globals); + Py_XINCREF(code); + op->func_code = code; + op->defaults = NULL; + op->defaults_tuple = NULL; + op->defaults_kwdict = NULL; + op->defaults_getter = NULL; + op->func_annotations = NULL; +#if __PYX_LIMITED_VERSION_HEX < 0x030B0000 + op->func_is_coroutine = NULL; +#endif +#if CYTHON_VECTORCALL + switch (ml->ml_flags & (METH_VARARGS | METH_FASTCALL | METH_NOARGS | METH_O | METH_KEYWORDS | METH_METHOD)) { + case METH_NOARGS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_NOARGS; + break; + case METH_O: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_O; + break; + case METH_METHOD | METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD; + break; + case METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS; + break; + case METH_VARARGS | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = NULL; + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + Py_DECREF(op_in); + return NULL; + } +#endif + return op_in; +} +static int __Pyx__CyFunction_clear(__pyx_CyFunctionObject *m) +{ + Py_CLEAR(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func_module); +#else + Py_CLEAR(((PyCFunctionObject*)m)->m_module); +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func_dict); +#elif PY_VERSION_HEX < 0x030d0000 + _PyObject_ClearManagedDict((PyObject*)m); +#else + PyObject_ClearManagedDict((PyObject*)m); +#endif + Py_CLEAR(m->func_name); + Py_CLEAR(m->func_qualname); + Py_CLEAR(m->func_doc); + Py_CLEAR(m->func_globals); + Py_CLEAR(m->func_code); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func_classobj); +#else + { + PyObject *cls = (PyObject*) ((PyCMethodObject *) (m))->mm_class; + ((PyCMethodObject *) (m))->mm_class = NULL; + Py_XDECREF(cls); + } +#endif + Py_CLEAR(m->defaults_tuple); + Py_CLEAR(m->defaults_kwdict); + Py_CLEAR(m->func_annotations); +#if __PYX_LIMITED_VERSION_HEX < 0x030B0000 + Py_CLEAR(m->func_is_coroutine); +#endif + Py_CLEAR(m->defaults); + return 0; +} +static int +__Pyx_CyFunction_clear(PyObject *m) +{ + return __Pyx__CyFunction_clear(__Pyx_as_CyFunctionObject(m)); +} +static void __Pyx__CyFunction_dealloc(PyObject *m) +{ + __pyx_CyFunctionObject *cyfunc = __Pyx_as_CyFunctionObject(m); + if (__Pyx_CyFunction_weakreflist(cyfunc) != NULL) + PyObject_ClearWeakRefs(m); + __Pyx__CyFunction_clear(cyfunc); + __Pyx_PyHeapTypeObject_GC_Del(m); +} +static void __Pyx_CyFunction_dealloc(PyObject *m) +{ + PyObject_GC_UnTrack(m); + __Pyx__CyFunction_dealloc(m); +} +static int __Pyx_CyFunction_traverse(PyObject *m_in, visitproc visit, void *arg) +{ + __pyx_CyFunctionObject *m = __Pyx_as_CyFunctionObject(m_in); + { + int e = __Pyx_call_type_traverse(m_in, 1, visit, arg); + if (e) return e; + } + Py_VISIT(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func_module); +#else + Py_VISIT(((PyCFunctionObject*)m)->m_module); +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func_dict); +#else + { + int e = +#if PY_VERSION_HEX < 0x030d0000 + _PyObject_VisitManagedDict +#else + PyObject_VisitManagedDict +#endif + ((PyObject*)m, visit, arg); + if (e != 0) return e; + } +#endif + __Pyx_VISIT_CONST(m->func_name); + __Pyx_VISIT_CONST(m->func_qualname); + Py_VISIT(m->func_doc); + Py_VISIT(m->func_globals); + __Pyx_VISIT_CONST(m->func_code); + Py_VISIT(__Pyx__CyFunction_GetClassObj(m)); + Py_VISIT(m->defaults_tuple); + Py_VISIT(m->defaults_kwdict); + Py_VISIT(m->func_annotations); +#if __PYX_LIMITED_VERSION_HEX < 0x030B0000 + Py_VISIT(m->func_is_coroutine); +#endif + Py_VISIT(m->defaults); + return 0; +} +static PyObject* +__Pyx_CyFunction_repr(PyObject *op_in) +{ + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + PyObject *repr; + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + repr = PyUnicode_FromFormat("", + op->func_qualname, (void *)op); + __Pyx_END_CRITICAL_SECTION(); + return repr; +} +static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { +#if CYTHON_COMPILING_IN_LIMITED_API + __pyx_CyFunctionObject *cyfunc = __Pyx_as_CyFunctionObject(func); + PyCFunction meth = cyfunc->func_methoddef->ml_meth; + int flags = cyfunc->func_methoddef->ml_flags; +#else + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = f->m_ml->ml_meth; + int flags = f->m_ml->ml_flags; +#endif + Py_ssize_t size; + switch (flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { + case METH_VARARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)(void(*)(void))meth)(self, arg, kw); + case METH_NOARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 0)) + return (*meth)(self, NULL); + __Pyx_CyFunction_raise_argument_count_error( + func, + "takes no arguments", size); + return NULL; + } + break; + case METH_O: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 1)) { + PyObject *result, *arg0; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + arg0 = PyTuple_GET_ITEM(arg, 0); + #else + arg0 = __Pyx_PySequence_ITEM(arg, 0); if (unlikely(!arg0)) return NULL; + #endif + result = (*meth)(self, arg0); + #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_DECREF(arg0); + #endif + return result; + } + __Pyx_CyFunction_raise_argument_count_error( + func, + "takes exactly one argument", size); + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + return NULL; + } + __Pyx_CyFunction_raise_type_error( + func, "takes no keyword arguments"); + return NULL; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + result = __Pyx_CyFunction_CallMethod(func, func, arg, kw); + return result; +} +static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { + PyObject *result; + __pyx_CyFunctionObject *cyfunc = __Pyx_as_CyFunctionObject(func); +#if CYTHON_VECTORCALL + __pyx_vectorcallfunc vc = __Pyx_CyFunction_func_vectorcall(cyfunc); + if (vc) { +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE + return __Pyx_PyVectorcall_FastCallDict(func, vc, &PyTuple_GET_ITEM(args, 0), (size_t)PyTuple_GET_SIZE(args), kw); +#else + (void) &__Pyx_PyVectorcall_FastCallDict; + return PyVectorcall_Call(func, args, kw); +#endif + } +#endif + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + Py_ssize_t argc; + PyObject *new_args; + PyObject *self; +#if CYTHON_ASSUME_SAFE_SIZE + argc = PyTuple_GET_SIZE(args); +#else + argc = PyTuple_Size(args); + if (unlikely(argc < 0)) return NULL; +#endif + new_args = PyTuple_GetSlice(args, 1, argc); + if (unlikely(!new_args)) + return NULL; + self = PyTuple_GetItem(args, 0); + if (unlikely(!self)) { + Py_DECREF(new_args); + PyErr_Format(PyExc_TypeError, + "unbound method %.200S() needs an argument", + cyfunc->func_qualname); + return NULL; + } + result = __Pyx_CyFunction_CallMethod(func, self, new_args, kw); + Py_DECREF(new_args); + } else { + result = __Pyx_CyFunction_Call(func, args, kw); + } + return result; +} +#if CYTHON_VECTORCALL +static CYTHON_INLINE int __Pyx_CyFunction_Vectorcall_CheckArgs(PyObject *func, __pyx_CyFunctionObject *cyfunc, Py_ssize_t nargs, PyObject *kwnames) +{ + int ret = 0; + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + if (unlikely(nargs < 1)) { + __Pyx_CyFunction_raise_type_error( + func, "needs an argument"); + return -1; + } + ret = 1; + } + if (unlikely(kwnames) && unlikely(__Pyx_PyTuple_GET_SIZE(kwnames))) { + __Pyx_CyFunction_raise_type_error( + func, "takes no keyword arguments"); + return -1; + } + return ret; +} +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = __Pyx_as_CyFunctionObject(func); + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = cyfunc->func_methoddef->ml_meth; + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(func, cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = func; + break; + default: + return NULL; + } + if (unlikely(nargs != 0)) { + __Pyx_CyFunction_raise_argument_count_error( + func, "takes no arguments", nargs); + return NULL; + } + return meth(self, NULL); +} +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = __Pyx_as_CyFunctionObject(func); + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = cyfunc->func_methoddef->ml_meth; + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(func, cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = func; + break; + default: + return NULL; + } + if (unlikely(nargs != 1)) { + __Pyx_CyFunction_raise_argument_count_error( + func, "takes exactly one argument", nargs); + return NULL; + } + return meth(self, args[0]); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = __Pyx_as_CyFunctionObject(func); + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = cyfunc->func_methoddef->ml_meth; + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(func, cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = func; + break; + default: + return NULL; + } + return ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))meth)(self, args, nargs, kwnames); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = __Pyx_as_CyFunctionObject(func); + PyTypeObject *cls = (PyTypeObject *) __Pyx__CyFunction_GetClassObj(cyfunc); + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = cyfunc->func_methoddef->ml_meth; + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(func, cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = func; + break; + default: + return NULL; + } + #if PY_VERSION_HEX < 0x030e00A6 + size_t nargs_value = (size_t) nargs; + #else + Py_ssize_t nargs_value = nargs; + #endif + return ((__Pyx_PyCMethod)(void(*)(void))meth)(self, cls, args, nargs_value, kwnames); +} +#endif +static PyType_Slot __pyx_CyFunctionType_slots[] = { + {Py_tp_dealloc, (void *)__Pyx_CyFunction_dealloc}, + {Py_tp_repr, (void *)__Pyx_CyFunction_repr}, + {Py_tp_call, (void *)__Pyx_CyFunction_CallAsMethod}, + {Py_tp_traverse, (void *)__Pyx_CyFunction_traverse}, + {Py_tp_clear, (void *)__Pyx_CyFunction_clear}, + {Py_tp_methods, (void *)__pyx_CyFunction_methods}, + {Py_tp_members, (void *)__pyx_CyFunction_members}, + {Py_tp_getset, (void *)__pyx_CyFunction_getsets}, + {Py_tp_descr_get, (void *)__Pyx_PyMethod_New}, + {0, 0}, +}; +static PyType_Spec __pyx_CyFunctionType_spec = { + __PYX_TYPE_MODULE_PREFIX "cython_function_or_method", + __PYX_SHARED_SIZEOF(__pyx_CyFunctionObject), + 0, +#ifdef Py_TPFLAGS_METHOD_DESCRIPTOR + Py_TPFLAGS_METHOD_DESCRIPTOR | +#endif +#if CYTHON_VECTORCALL +#if defined(Py_TPFLAGS_HAVE_VECTORCALL) + Py_TPFLAGS_HAVE_VECTORCALL | +#elif defined(_Py_TPFLAGS_HAVE_VECTORCALL) + _Py_TPFLAGS_HAVE_VECTORCALL | +#endif +#endif // CYTHON_VECTORCALL +#if PY_VERSION_HEX >= 0x030C0000 && !CYTHON_COMPILING_IN_LIMITED_API + Py_TPFLAGS_MANAGED_DICT | +#endif + Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, + __pyx_CyFunctionType_slots +}; +static int __pyx_CyFunction_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + mstate->__pyx_CyFunctionType = __Pyx_FetchCommonTypeFromSpec( + mstate->__pyx_CommonTypesMetaclassType, module, &__pyx_CyFunctionType_spec, NULL); + if (unlikely(mstate->__pyx_CyFunctionType == NULL)) { + return -1; + } + return 0; +} + +/* CythonFunction */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { + (void)&__Pyx_Get_CyFunction_Type; + PyObject *op = __Pyx_CyFunction_Init( + PyObject_GC_New(PyObject, __pyx_mstate_global->__pyx_CyFunctionType), + ml, flags, qualname, closure, module, globals, code + ); + if (likely(op)) { + PyObject_GC_Track(op); + } + return op; +} +static PyTypeObject *__Pyx_Get_CyFunction_Type(void) { + PyTypeObject *tp = __pyx_mstate_global->__pyx_CyFunctionType; + Py_INCREF((PyObject*)tp); + return tp; +} + +/* ObjectGetItem */ +#if CYTHON_USE_TYPE_SLOTS +static PyObject *__Pyx_PyObject_GetIndex(PyObject *obj, PyObject *index) { + PyObject *runerr = NULL; + Py_ssize_t key_value; + key_value = __Pyx_PyIndex_AsSsize_t(index); + if (likely(key_value != -1 || !(runerr = PyErr_Occurred()))) { + return __Pyx_GetItemInt_Fast(obj, key_value, 1, 1, 1); + } + if (PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) { + PyErr_Clear(); + __Pyx_RaiseErrorWithObjectType( + PyExc_IndexError, + "cannot fit '" __Pyx_FMT_TYPENAME "' into an index-sized integer", + index); + } + return NULL; +} +static PyObject *__Pyx_PyObject_GetItem_Slow(PyObject *obj, PyObject *key) { + if (likely(PyType_Check(obj))) { + if ((PyTypeObject*)obj == &PyType_Type) { + return Py_GenericAlias(obj, key); + } + PyObject *meth = __Pyx_PyObject_GetAttrStrNoError(obj, __pyx_mstate_global->__pyx_n_u_class_getitem); + if (!meth) { + if (PyErr_Occurred()) { + return NULL; + } + } else { + PyObject *result = __Pyx_PyObject_CallOneArg(meth, key); + Py_DECREF(meth); + return result; + } + } + __Pyx_RaiseTypeErrorWithObjectType( + "'" __Pyx_FMT_TYPENAME "' object is not subscriptable", obj); + return NULL; +} +static PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject *key) { + PyTypeObject *tp = Py_TYPE(obj); + PyMappingMethods *mm = tp->tp_as_mapping; + PySequenceMethods *sm = tp->tp_as_sequence; + if (likely(mm && mm->mp_subscript)) { + return mm->mp_subscript(obj, key); + } + if (likely(sm && sm->sq_item)) { + return __Pyx_PyObject_GetIndex(obj, key); + } + return __Pyx_PyObject_GetItem_Slow(obj, key); +} +#endif + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareStrStrBoolEq +#define __Pyx_DEFINED_PyObject_CompareStrStrBoolEq +static CYTHON_INLINE int __Pyx_PyObject_CompareStrStrBoolEq(PyObject* s1, PyObject* s2) { + #if __PYX_LIMITED_VERSION_HEX >= 0x030e0000 + int result = PyUnicode_Equal(s1, s2); + #if !CYTHON_COMPILING_IN_CPYTHON + if (unlikely(result == -1)) return -1; + #endif + if (result == 0) goto __pyx_return_false; else goto __pyx_return_true; + #else + int result = PyUnicode_Compare(s1, s2); + if (unlikely((result == -1) && PyErr_Occurred())) return -1; + if (result == 0) goto __pyx_return_true; else goto __pyx_return_false; + #endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolEq_object_str(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (unlikely(op2 == Py_None)) { + if (op1 == Py_None) goto __pyx_return_true; else goto __pyx_richcmp; + } + if (PyFloat_CheckExact(op1)) { + goto __pyx_richcmp; + } + if (PyLong_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_true; + goto __pyx_richcmp; + } + + if (likely(PyUnicode_CheckExact(op1))) { + if (op1 == op2) goto __pyx_return_true; + if (likely(op2 != Py_None)) { + return __Pyx_PyObject_CompareStrStrBoolEq(op1, op2); + } + goto __pyx_richcmp; + } + + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* CLineInTraceback (used by AddTraceback) */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +#define __Pyx_PyProbablyModule_GetDict(o) __Pyx_XNewRef(PyModule_GetDict(o)) +#elif !CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyProbablyModule_GetDict(o) PyObject_GenericGetDict(o, NULL); +#else +PyObject* __Pyx_PyProbablyModule_GetDict(PyObject *o) { + PyObject **dict_ptr = _PyObject_GetDictPtr(o); + return dict_ptr ? __Pyx_XNewRef(*dict_ptr) : NULL; +} +#endif +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line) { + PyObject *use_cline = NULL; + PyObject *ptype, *pvalue, *ptraceback; + PyObject *cython_runtime_dict; + CYTHON_MAYBE_UNUSED_VAR(tstate); + if (unlikely(!__pyx_mstate_global->__pyx_cython_runtime)) { + return c_line; + } + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + cython_runtime_dict = __Pyx_PyProbablyModule_GetDict(__pyx_mstate_global->__pyx_cython_runtime); + if (likely(cython_runtime_dict)) { + __PYX_PY_DICT_LOOKUP_IF_MODIFIED( + use_cline, cython_runtime_dict, + __Pyx_PyDict_SetDefault(cython_runtime_dict, __pyx_mstate_global->__pyx_n_u_cline_in_traceback, Py_False)) + } + if (use_cline == NULL || use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { + c_line = 0; + } + Py_XDECREF(use_cline); + Py_XDECREF(cython_runtime_dict); + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + return c_line; +} +#endif + +/* CodeObjectCache (used by AddTraceback) */ +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = start + (end - start) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static __Pyx_CachedCodeObjectType *__pyx__find_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line) { + __Pyx_CachedCodeObjectType* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!code_cache->entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if (unlikely(pos >= code_cache->count) || unlikely(code_cache->entries[pos].code_line != code_line)) { + return NULL; + } + code_object = code_cache->entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__find_code_object; + return NULL; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just miss. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type old_count = __pyx_atomic_incr_acq_rel(&code_cache->accessor_count); + if (old_count < 0) { + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); + return NULL; + } +#endif + __Pyx_CachedCodeObjectType *result = __pyx__find_code_object(code_cache, code_line); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); +#endif + return result; +#endif +} +static void __pyx__insert_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line, __Pyx_CachedCodeObjectType* code_object) +{ + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = code_cache->entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + code_cache->entries = entries; + code_cache->max_count = 64; + code_cache->count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if ((pos < code_cache->count) && unlikely(code_cache->entries[pos].code_line == code_line)) { + __Pyx_CachedCodeObjectType* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_INCREF(code_object); + Py_DECREF(tmp); + return; + } + if (code_cache->count == code_cache->max_count) { + int new_max = code_cache->max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + code_cache->entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + code_cache->entries = entries; + code_cache->max_count = new_max; + } + for (i=code_cache->count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + code_cache->count++; + Py_INCREF(code_object); +} +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__insert_code_object; + return; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just fail. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type expected = 0; + if (!__pyx_atomic_int_cmp_exchange(&code_cache->accessor_count, &expected, INT_MIN)) { + return; + } +#endif + __pyx__insert_code_object(code_cache, code_line, code_object); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_sub(&code_cache->accessor_count, INT_MIN); +#endif +#endif +} + +/* AddTraceback */ +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +#if PY_VERSION_HEX >= 0x030b00a6 && !CYTHON_COMPILING_IN_LIMITED_API && !defined(PYPY_VERSION) + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyCode_Replace_For_AddTraceback(PyObject *code, PyObject *scratch_dict, + PyObject *firstlineno, PyObject *name) { + PyObject *replace = NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_firstlineno", firstlineno))) return NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_name", name))) return NULL; + replace = PyObject_GetAttrString(code, "replace"); + if (likely(replace)) { + PyObject *result = PyObject_Call(replace, __pyx_mstate_global->__pyx_empty_tuple, scratch_dict); + Py_DECREF(replace); + return result; + } + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyObject *code_object = NULL, *py_py_line = NULL, *py_funcname = NULL, *dict = NULL; + PyObject *replace = NULL, *getframe = NULL, *frame = NULL; + PyObject *exc_type, *exc_value, *exc_traceback; + int success = 0; + if (c_line) { + c_line = __Pyx_CLineForTraceback(__Pyx_PyThreadState_Current, c_line); + } + __Pyx_PyErr_FetchException(&exc_type, &exc_value, &exc_traceback); + code_object = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!code_object) { + code_object = Py_CompileString("_getframe()", filename, Py_eval_input); + if (unlikely(!code_object)) goto bad; + py_py_line = PyLong_FromLong(py_line); + if (unlikely(!py_py_line)) goto bad; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + } else { + py_funcname = PyUnicode_FromString(funcname); + } + if (unlikely(!py_funcname)) goto bad; + dict = PyDict_New(); + if (unlikely(!dict)) goto bad; + { + PyObject *old_code_object = code_object; + code_object = __Pyx_PyCode_Replace_For_AddTraceback(code_object, dict, py_py_line, py_funcname); + Py_DECREF(old_code_object); + } + if (unlikely(!code_object)) goto bad; + __pyx_insert_code_object(c_line ? -c_line : py_line, code_object); + } else { + dict = PyDict_New(); + } + getframe = PySys_GetObject("_getframe"); + if (unlikely(!getframe)) goto bad; + if (unlikely(PyDict_SetItemString(dict, "_getframe", getframe))) goto bad; + frame = PyEval_EvalCode(code_object, dict, dict); + if (unlikely(!frame) || frame == Py_None) goto bad; + success = 1; + bad: + __Pyx_PyErr_RestoreException(exc_type, exc_value, exc_traceback); + Py_XDECREF(code_object); + Py_XDECREF(py_py_line); + Py_XDECREF(py_funcname); + Py_XDECREF(dict); + Py_XDECREF(replace); + if (success) { + PyTraceBack_Here( + (struct _frame*)frame); + } + Py_XDECREF(frame); +} +#else +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = NULL; + PyObject *py_funcname = NULL; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + funcname = PyUnicode_AsUTF8(py_funcname); + if (!funcname) goto bad; + } + py_code = PyCode_NewEmpty(filename, funcname, py_line); + Py_XDECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject *ptype, *pvalue, *ptraceback; + if (c_line) { + c_line = __Pyx_CLineForTraceback(tstate, c_line); + } + py_code = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!py_code) { + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) { + /* If the code object creation fails, then we should clear the + fetched exception references and propagate the new exception */ + Py_XDECREF(ptype); + Py_XDECREF(pvalue); + Py_XDECREF(ptraceback); + goto bad; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); + } + py_frame = PyFrame_New( + tstate, /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_mstate_global->__pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + __Pyx_PyFrame_SetLineNumber(py_frame, py_line); + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} +#endif + +/* Declarations */ +#if CYTHON_CCOMPLEX && (1) && (!0 || __cplusplus) + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return ::std::complex< double >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return x + y*(__pyx_t_double_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + __pyx_t_double_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +/* Arithmetic */ +#if CYTHON_CCOMPLEX && (1) && (!0 || __cplusplus) +#else + static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + #if 1 + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { + if (b.imag == 0) { + return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); + } else if (fabs(b.real) >= fabs(b.imag)) { + if (b.real == 0 && b.imag == 0) { + return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.imag); + } else { + double r = b.imag / b.real; + double s = (double)(1.0) / (b.real + b.imag * r); + return __pyx_t_double_complex_from_parts( + (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); + } + } else { + double r = b.real / b.imag; + double s = (double)(1.0) / (b.imag + b.real * r); + return __pyx_t_double_complex_from_parts( + (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); + } + } + #else + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { + if (b.imag == 0) { + return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); + } else { + double denom = b.real * b.real + b.imag * b.imag; + return __pyx_t_double_complex_from_parts( + (a.real * b.real + a.imag * b.imag) / denom, + (a.imag * b.real - a.real * b.imag) / denom); + } + } + #endif + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrt(z.real*z.real + z.imag*z.imag); + #else + return hypot(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + double denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + return __Pyx_c_prod_double(a, a); + case 3: + z = __Pyx_c_prod_double(a, a); + return __Pyx_c_prod_double(z, a); + case 4: + z = __Pyx_c_prod_double(a, a); + return __Pyx_c_prod_double(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } else if ((b.imag == 0) && (a.real >= 0)) { + z.real = pow(a.real, b.real); + z.imag = 0; + return z; + } else if (a.real > 0) { + r = a.real; + theta = 0; + } else { + r = -a.real; + theta = atan2(0.0, -1.0); + } + } else { + r = __Pyx_c_abs_double(a); + theta = atan2(a.imag, a.real); + } + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; + } + #endif +#endif + +/* FromPy */ +static __pyx_t_double_complex __Pyx_PyComplex_As___pyx_t_double_complex(PyObject* o) { +#if CYTHON_COMPILING_IN_LIMITED_API + double real=-1.0, imag=-1.0; + real = PyComplex_RealAsDouble(o); + if (unlikely(real == -1.0 && PyErr_Occurred())) goto end; + imag = PyComplex_ImagAsDouble(o); + end: + return __pyx_t_double_complex_from_parts( + (double)real, (double)imag + ); +#else + Py_complex cval; +#if !CYTHON_COMPILING_IN_PYPY && !CYTHON_COMPILING_IN_GRAAL + if (PyComplex_CheckExact(o)) + cval = ((PyComplexObject *)o)->cval; + else +#endif + cval = PyComplex_AsCComplex(o); + return __pyx_t_double_complex_from_parts( + (double)cval.real, + (double)cval.imag); +#endif +} + +/* CIntFromPyVerify */ +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) +#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) +#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ + {\ + func_type value = func_value;\ + if (sizeof(target_type) < sizeof(func_type)) {\ + if (unlikely(value != (func_type) (target_type) value)) {\ + func_type zero = 0;\ + if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ + return (target_type) -1;\ + if (is_unsigned && unlikely(value < zero))\ + goto raise_neg_overflow;\ + else\ + goto raise_overflow;\ + }\ + }\ + return (target_type) value;\ + } + +/* CIntFromPy */ +static int __Pyx_LargePyLong___Pyx_PyLong_As_int(PyObject *x); +static int __Pyx_raise_neg_overflow___Pyx_PyLong_As_int(void) { + const char* type_name = "int"; + PyErr_Format(PyExc_OverflowError, + "can't convert negative value to %.200s", type_name); + return (int) -1; +} +static int __Pyx_raise_overflow___Pyx_PyLong_As_int(void) { + const char* type_name = "int"; + PyErr_Format(PyExc_OverflowError, + "value too large to convert to %.200s", type_name); + return (int) -1; +} +static CYTHON_INLINE int __Pyx_PyULong___Pyx_PyLong_As_int(PyObject *x) { + const int is_unsigned = 1; +#if CYTHON_USE_PYLONG_INTERNALS + { + const digit* digits = __Pyx_PyLong_Digits(x); + const Py_ssize_t size = __Pyx_PyLong_DigitCount(x); + if (size == 2 && (8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 2 * PyLong_SHIFT)) { + return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } else + if (size == 3 && (8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 3 * PyLong_SHIFT)) { + return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } else + if (size == 4 && (8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 4 * PyLong_SHIFT)) { + return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } else + {} + } +#elif CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(int) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + return __Pyx_LargePyLong___Pyx_PyLong_As_int(x); +raise_neg_overflow: + return __Pyx_raise_neg_overflow___Pyx_PyLong_As_int(); +raise_overflow: + return __Pyx_raise_overflow___Pyx_PyLong_As_int(); +} +static CYTHON_INLINE int __Pyx_PySLong___Pyx_PyLong_As_int(PyObject *x) { + const int is_unsigned = 0; +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsNeg(x)) { + const Py_ssize_t size = __Pyx_PyLong_DigitCount(x); + const digit* digits = __Pyx_PyLong_Digits(x); + if (size == 2 && (8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + long ival = - (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + __PYX_VERIFY_RETURN_INT(int, long, ival) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) (((int) -1) * (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } else + if (size == 3 && (8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + long ival = - (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + __PYX_VERIFY_RETURN_INT(int, long, ival) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) (((int) -1) * (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } else + if (size == 4 && (8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 4 * PyLong_SHIFT)) { + long ival = - (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + __PYX_VERIFY_RETURN_INT(int, long, ival) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) (((int) -1) * (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } else + {} + } else { + const Py_ssize_t size = __Pyx_PyLong_DigitCount(x); + const digit* digits = __Pyx_PyLong_Digits(x); + if (size == 2 && (8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } else + if (size == 3 && (8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } else + if (size == 4 && (8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } else + {} + } +#endif + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + if ((sizeof(int) <= sizeof(int)) && (sizeof(int) < sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, int, PyLong_AsInt(x)) + } else + #endif + if ((sizeof(int) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) + } else if ((sizeof(int) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + return __Pyx_LargePyLong___Pyx_PyLong_As_int(x); +raise_neg_overflow: + return __Pyx_raise_neg_overflow___Pyx_PyLong_As_int(); +raise_overflow: + return __Pyx_raise_overflow___Pyx_PyLong_As_int(); +} +static int __Pyx_LargePyLong___Pyx_PyLong_As_int(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + int val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); + if ((0)) goto raise_overflow; +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (int) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (int) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (int) -1; + } else { + stepval = v; + } + v = NULL; + val = (int) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((int) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((int) 1) << (sizeof(int) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; +done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (int) -1; + return val; +raise_overflow: + return __Pyx_raise_overflow___Pyx_PyLong_As_int(); +} +static CYTHON_INLINE int __Pyx_PyLong___Pyx_PyLong_As_int(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + #if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else + #endif + { + return __Pyx_PyULong___Pyx_PyLong_As_int(x); + } + } else { + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else + #endif + { + return __Pyx_PySLong___Pyx_PyLong_As_int(x); + } + } +#if CYTHON_USE_PYLONG_INTERNALS +raise_neg_overflow: + return __Pyx_raise_neg_overflow___Pyx_PyLong_As_int(); +raise_overflow: + return __Pyx_raise_overflow___Pyx_PyLong_As_int(); +#endif +} +static int __Pyx_NonPyLong___Pyx_PyLong_As_int(PyObject *x) { + int val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (int) -1; + val = __Pyx_PyLong_As_int(tmp); + Py_DECREF(tmp); + return val; +} +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *x) { + if (likely(PyLong_Check(x))) { + return __Pyx_PyLong___Pyx_PyLong_As_int(x); + } else { + return __Pyx_NonPyLong___Pyx_PyLong_As_int(x); + } +} + +/* PyObjectVectorcallKwds (used by PyObjectVectorcallMethodKwds) */ +#if CYTHON_VECTORCALL +CYTHON_UNUSED static int __Pyx_CheckVectorcallKwarg(PyObject *kwnames, Py_ssize_t i) { + PyObject *key = __Pyx_PyTuple_GET_ITEM(kwnames, i); +#if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!key)) return -1; +#endif + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return 0; +} +#else +CYTHON_UNUSED static PyObject *__Pyx_MakeKwargDict(PyObject **keys, PyObject **values, Py_ssize_t n) { + PyObject *out = PyDict_New(); + if (unlikely(!out)) return NULL; + for (Py_ssize_t i=0; i const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL, *from_bytes_str = NULL;; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(int)); + if (!py_bytes) goto limited_bad; + from_bytes_str = PyUnicode_FromStringAndSize("from_bytes", 10); + if (!from_bytes_str) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[] = { (PyObject*)&PyLong_Type, py_bytes, order_str, Py_True }; + if (!is_unsigned) { + PyObject *signed_str = PyUnicode_FromStringAndSize("signed", 6); + if (!signed_str) goto limited_bad; +#if CYTHON_VECTORCALL + kwds = PyTuple_Pack(1, signed_str); +#else + { + PyObject *keys[] = {signed_str}; + PyObject *values[] = {Py_True}; + kwds = __Pyx_MakeKwargDict(keys, values, 1); + } +#endif + Py_DECREF(signed_str); + if (unlikely(!kwds)) goto limited_bad; + } + result = __Pyx_Object_VectorcallMethodKwds(from_bytes_str, args, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes_str); + return result; +#endif + } +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL, *from_bytes_str = NULL;; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(long)); + if (!py_bytes) goto limited_bad; + from_bytes_str = PyUnicode_FromStringAndSize("from_bytes", 10); + if (!from_bytes_str) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[] = { (PyObject*)&PyLong_Type, py_bytes, order_str, Py_True }; + if (!is_unsigned) { + PyObject *signed_str = PyUnicode_FromStringAndSize("signed", 6); + if (!signed_str) goto limited_bad; +#if CYTHON_VECTORCALL + kwds = PyTuple_Pack(1, signed_str); +#else + { + PyObject *keys[] = {signed_str}; + PyObject *values[] = {Py_True}; + kwds = __Pyx_MakeKwargDict(keys, values, 1); + } +#endif + Py_DECREF(signed_str); + if (unlikely(!kwds)) goto limited_bad; + } + result = __Pyx_Object_VectorcallMethodKwds(from_bytes_str, args, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes_str); + return result; +#endif + } +} + +/* CIntFromPy */ +static long __Pyx_LargePyLong___Pyx_PyLong_As_long(PyObject *x); +static long __Pyx_raise_neg_overflow___Pyx_PyLong_As_long(void) { + const char* type_name = "long"; + PyErr_Format(PyExc_OverflowError, + "can't convert negative value to %.200s", type_name); + return (long) -1; +} +static long __Pyx_raise_overflow___Pyx_PyLong_As_long(void) { + const char* type_name = "long"; + PyErr_Format(PyExc_OverflowError, + "value too large to convert to %.200s", type_name); + return (long) -1; +} +static CYTHON_INLINE long __Pyx_PyULong___Pyx_PyLong_As_long(PyObject *x) { + const int is_unsigned = 1; +#if CYTHON_USE_PYLONG_INTERNALS + { + const digit* digits = __Pyx_PyLong_Digits(x); + const Py_ssize_t size = __Pyx_PyLong_DigitCount(x); + if (size == 2 && (8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 2 * PyLong_SHIFT)) { + return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } else + if (size == 3 && (8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 3 * PyLong_SHIFT)) { + return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } else + if (size == 4 && (8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 4 * PyLong_SHIFT)) { + return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } else + {} + } +#elif CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(long) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(long) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + return __Pyx_LargePyLong___Pyx_PyLong_As_long(x); +raise_neg_overflow: + return __Pyx_raise_neg_overflow___Pyx_PyLong_As_long(); +raise_overflow: + return __Pyx_raise_overflow___Pyx_PyLong_As_long(); +} +static CYTHON_INLINE long __Pyx_PySLong___Pyx_PyLong_As_long(PyObject *x) { + const int is_unsigned = 0; +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsNeg(x)) { + const Py_ssize_t size = __Pyx_PyLong_DigitCount(x); + const digit* digits = __Pyx_PyLong_Digits(x); + if (size == 2 && (8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + long ival = - (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + __PYX_VERIFY_RETURN_INT(long, long, ival) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) (((long) -1) * (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } else + if (size == 3 && (8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + long ival = - (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + __PYX_VERIFY_RETURN_INT(long, long, ival) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) (((long) -1) * (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } else + if (size == 4 && (8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 4 * PyLong_SHIFT)) { + long ival = - (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + __PYX_VERIFY_RETURN_INT(long, long, ival) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) (((long) -1) * (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } else + {} + } else { + const Py_ssize_t size = __Pyx_PyLong_DigitCount(x); + const digit* digits = __Pyx_PyLong_Digits(x); + if (size == 2 && (8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } else + if (size == 3 && (8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } else + if (size == 4 && (8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } else + {} + } +#endif + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + if ((sizeof(long) <= sizeof(int)) && (sizeof(int) < sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, int, PyLong_AsInt(x)) + } else + #endif + if ((sizeof(long) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) + } else if ((sizeof(long) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + return __Pyx_LargePyLong___Pyx_PyLong_As_long(x); +raise_neg_overflow: + return __Pyx_raise_neg_overflow___Pyx_PyLong_As_long(); +raise_overflow: + return __Pyx_raise_overflow___Pyx_PyLong_As_long(); +} +static long __Pyx_LargePyLong___Pyx_PyLong_As_long(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + long val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); + if ((0)) goto raise_overflow; +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (long) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (long) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (long) -1; + } else { + stepval = v; + } + v = NULL; + val = (long) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(long) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((long) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(long) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((long) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((long) 1) << (sizeof(long) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; +done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (long) -1; + return val; +raise_overflow: + return __Pyx_raise_overflow___Pyx_PyLong_As_long(); +} +static CYTHON_INLINE long __Pyx_PyLong___Pyx_PyLong_As_long(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + #if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else + #endif + { + return __Pyx_PyULong___Pyx_PyLong_As_long(x); + } + } else { + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else + #endif + { + return __Pyx_PySLong___Pyx_PyLong_As_long(x); + } + } +#if CYTHON_USE_PYLONG_INTERNALS +raise_neg_overflow: + return __Pyx_raise_neg_overflow___Pyx_PyLong_As_long(); +raise_overflow: + return __Pyx_raise_overflow___Pyx_PyLong_As_long(); +#endif +} +static long __Pyx_NonPyLong___Pyx_PyLong_As_long(PyObject *x) { + long val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (long) -1; + val = __Pyx_PyLong_As_long(tmp); + Py_DECREF(tmp); + return val; +} +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *x) { + if (likely(PyLong_Check(x))) { + return __Pyx_PyLong___Pyx_PyLong_As_long(x); + } else { + return __Pyx_NonPyLong___Pyx_PyLong_As_long(x); + } +} + +/* GetRuntimeVersion */ +#if __PYX_LIMITED_VERSION_HEX < 0x030b0000 +void __Pyx_init_runtime_version(void) { + if (__Pyx_cached_runtime_version == 0) { + const char* rt_version = Py_GetVersion(); + unsigned long version = 0; + unsigned long factor = 0x01000000UL; + unsigned int digit = 0; + int i = 0; + while (factor) { + while ('0' <= rt_version[i] && rt_version[i] <= '9') { + digit = digit * 10 + (unsigned int) (rt_version[i] - '0'); + ++i; + } + version += factor * digit; + if (rt_version[i] != '.') + break; + digit = 0; + factor >>= 8; + ++i; + } + __Pyx_cached_runtime_version = version; + } +} +#endif +static unsigned long __Pyx_get_runtime_version(void) { +#if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + return Py_Version & ~0xFFUL; +#else + return __Pyx_cached_runtime_version; +#endif +} + +/* SwapException (used by CoroutineBase) */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_value = exc_info->exc_value; + exc_info->exc_value = *value; + if (tmp_value == NULL || tmp_value == Py_None) { + Py_XDECREF(tmp_value); + tmp_value = NULL; + tmp_type = NULL; + tmp_tb = NULL; + } else { + tmp_type = (PyObject*) Py_TYPE(tmp_value); + Py_INCREF(tmp_type); + #if CYTHON_COMPILING_IN_CPYTHON + tmp_tb = ((PyBaseExceptionObject*) tmp_value)->traceback; + Py_XINCREF(tmp_tb); + #else + tmp_tb = PyException_GetTraceback(tmp_value); + #endif + } + #elif CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = *type; + exc_info->exc_value = *value; + exc_info->exc_traceback = *tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; + #endif + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} +#else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); + PyErr_SetExcInfo(*type, *value, *tb); + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} +#endif + +/* IterNextPlain (used by CoroutineBase) */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject *__Pyx_GetBuiltinNext_LimitedAPI(void) { + if (unlikely(!__pyx_mstate_global->__Pyx_GetBuiltinNext_LimitedAPI_cache)) + __pyx_mstate_global->__Pyx_GetBuiltinNext_LimitedAPI_cache = __Pyx_GetBuiltinName(__pyx_mstate_global->__pyx_n_u_next); + return __pyx_mstate_global->__Pyx_GetBuiltinNext_LimitedAPI_cache; +} +#endif +static CYTHON_INLINE PyObject *__Pyx_PyIter_Next_Plain(PyObject *iterator) { +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + PyObject *result; + PyObject *next = __Pyx_GetBuiltinNext_LimitedAPI(); + if (unlikely(!next)) return NULL; + result = PyObject_CallFunctionObjArgs(next, iterator, NULL); + return result; +#else + (void)__Pyx_GetBuiltinName; // only for early limited API + iternextfunc iternext = __Pyx_PyObject_GetIterNextFunc(iterator); + assert(iternext); + return iternext(iterator); +#endif +} + +/* PyObjectCallMethod1 (used by CoroutineBase) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg) { +#if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || !CYTHON_COMPILING_IN_LIMITED_API) + PyObject *args[2] = {obj, arg}; + return PyObject_VectorcallMethod(method_name, args, 2 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#elif CYTHON_COMPILING_IN_LIMITED_API + return PyObject_CallMethodObjArgs(obj, method_name, arg, NULL); +#else + return PyObject_CallMethodOneArg(obj, method_name, arg); +#endif +} + +/* PyObjectCallNoArg (used by CoroutineBase) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { + PyObject *arg[2] = {NULL, NULL}; + return __Pyx_PyObject_FastCall(func, arg + 1, 0 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* ReturnWithStopIteration (used by CoroutineBase) */ +static void __Pyx__ReturnWithStopIteration(PyObject* value, int async); +static CYTHON_INLINE void __Pyx_ReturnWithStopIteration(PyObject* value, int async, int iternext) { + if (value == Py_None) { + if (async || !iternext) + PyErr_SetNone(async ? PyExc_StopAsyncIteration : PyExc_StopIteration); + return; + } + __Pyx__ReturnWithStopIteration(value, async); +} +static void __Pyx__ReturnWithStopIteration(PyObject* value, int async) { +#if CYTHON_COMPILING_IN_CPYTHON + __Pyx_PyThreadState_declare +#endif + PyObject *exc; + PyObject *exc_type = async ? PyExc_StopAsyncIteration : PyExc_StopIteration; +#if CYTHON_COMPILING_IN_CPYTHON + if ((PY_VERSION_HEX >= (0x030C00A6)) || unlikely(PyTuple_Check(value) || PyExceptionInstance_Check(value))) { + if (PY_VERSION_HEX >= (0x030e00A1)) { + exc = __Pyx_PyObject_CallOneArg(exc_type, value); + } else { + PyObject *args_tuple = PyTuple_New(1); + if (unlikely(!args_tuple)) return; + Py_INCREF(value); + PyTuple_SET_ITEM(args_tuple, 0, value); + exc = PyObject_Call(exc_type, args_tuple, NULL); + Py_DECREF(args_tuple); + } + if (unlikely(!exc)) return; + } else { + Py_INCREF(value); + exc = value; + } + #if CYTHON_FAST_THREAD_STATE + __Pyx_PyThreadState_assign + #if CYTHON_USE_EXC_INFO_STACK + if (!__pyx_tstate->exc_info->exc_value) + #else + if (!__pyx_tstate->exc_type) + #endif + { + Py_INCREF(exc_type); + __Pyx_ErrRestore(exc_type, exc, NULL); + return; + } + #endif +#else + exc = __Pyx_PyObject_CallOneArg(exc_type, value); + if (unlikely(!exc)) return; +#endif + PyErr_SetObject(exc_type, exc); + Py_DECREF(exc); +} + +/* CoroutineBase (used by Generator) */ +#if !CYTHON_COMPILING_IN_LIMITED_API +#include +#if PY_VERSION_HEX >= 0x030b00a6 && !defined(PYPY_VERSION) + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif +#endif // CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE void +__Pyx_Coroutine_Undelegate(__pyx_CoroutineObject *gen) { +#if CYTHON_USE_AM_SEND + gen->yieldfrom_am_send = NULL; +#endif + Py_CLEAR(gen->yieldfrom); +} +static int __Pyx_PyGen__FetchStopIterationValue(PyThreadState *__pyx_tstate, PyObject **pvalue) { + PyObject *et, *ev, *tb; + PyObject *value = NULL; + CYTHON_UNUSED_VAR(__pyx_tstate); + __Pyx_ErrFetch(&et, &ev, &tb); + if (!et) { + Py_XDECREF(tb); + Py_XDECREF(ev); + Py_INCREF(Py_None); + *pvalue = Py_None; + return 0; + } + if (likely(et == PyExc_StopIteration)) { + if (!ev) { + Py_INCREF(Py_None); + value = Py_None; + } + else if (likely(Py_IS_TYPE(ev, (PyTypeObject*)PyExc_StopIteration))) { + #if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL + value = PyObject_GetAttr(ev, __pyx_mstate_global->__pyx_n_u_value); + if (unlikely(!value)) goto limited_api_failure; + #else + value = ((PyStopIterationObject *)ev)->value; + Py_INCREF(value); + #endif + Py_DECREF(ev); + } + else if (unlikely(PyTuple_Check(ev))) { + Py_ssize_t tuple_size = __Pyx_PyTuple_GET_SIZE(ev); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(tuple_size < 0)) { + Py_XDECREF(tb); + Py_DECREF(ev); + Py_DECREF(et); + return -1; + } + #endif + if (tuple_size >= 1) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + value = PyTuple_GET_ITEM(ev, 0); + Py_INCREF(value); +#elif CYTHON_ASSUME_SAFE_MACROS + value = PySequence_ITEM(ev, 0); +#else + value = PySequence_GetItem(ev, 0); + if (!value) goto limited_api_failure; +#endif + } else { + Py_INCREF(Py_None); + value = Py_None; + } + Py_DECREF(ev); + } + else if (!__Pyx_TypeCheck(ev, (PyTypeObject*)PyExc_StopIteration)) { + value = ev; + } + if (likely(value)) { + Py_XDECREF(tb); + Py_DECREF(et); + *pvalue = value; + return 0; + } + } else if (!__Pyx_PyErr_GivenExceptionMatches(et, PyExc_StopIteration)) { + __Pyx_ErrRestore(et, ev, tb); + return -1; + } + PyErr_NormalizeException(&et, &ev, &tb); + if (unlikely(!PyObject_TypeCheck(ev, (PyTypeObject*)PyExc_StopIteration))) { + __Pyx_ErrRestore(et, ev, tb); + return -1; + } + Py_XDECREF(tb); + Py_DECREF(et); +#if CYTHON_COMPILING_IN_LIMITED_API + value = PyObject_GetAttr(ev, __pyx_mstate_global->__pyx_n_u_value); +#else + value = ((PyStopIterationObject *)ev)->value; + Py_INCREF(value); +#endif + Py_DECREF(ev); +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(!value)) return -1; +#endif + *pvalue = value; + return 0; +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL || !CYTHON_ASSUME_SAFE_MACROS + limited_api_failure: + Py_XDECREF(et); + Py_XDECREF(tb); + Py_XDECREF(ev); + return -1; +#endif +} +static CYTHON_INLINE +__Pyx_PySendResult __Pyx_Coroutine_status_from_result(PyObject **retval) { + if (*retval) { + return PYGEN_NEXT; + } else if (likely(__Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, retval) == 0)) { + return PYGEN_RETURN; + } else { + return PYGEN_ERROR; + } +} +static CYTHON_INLINE +void __Pyx_Coroutine_ExceptionClear(__Pyx_ExcInfoStruct *exc_state) { +#if PY_VERSION_HEX >= 0x030B00a4 + Py_CLEAR(exc_state->exc_value); +#else + PyObject *t, *v, *tb; + t = exc_state->exc_type; + v = exc_state->exc_value; + tb = exc_state->exc_traceback; + exc_state->exc_type = NULL; + exc_state->exc_value = NULL; + exc_state->exc_traceback = NULL; + Py_XDECREF(t); + Py_XDECREF(v); + Py_XDECREF(tb); +#endif +} +#define __Pyx_Coroutine_AlreadyRunningError(gen) (__Pyx__Coroutine_AlreadyRunningError(gen), (PyObject*)NULL) +static void __Pyx__Coroutine_AlreadyRunningError(__pyx_CoroutineObject *gen) { + const char *msg; + CYTHON_MAYBE_UNUSED_VAR(gen); + if ((0)) { + #ifdef __Pyx_Coroutine_USED + } else if (__Pyx_Coroutine_Check((PyObject*)gen)) { + msg = "coroutine already executing"; + #endif + #ifdef __Pyx_AsyncGen_USED + } else if (__Pyx_AsyncGen_CheckExact((PyObject*)gen)) { + msg = "async generator already executing"; + #endif + } else { + msg = "generator already executing"; + } + PyErr_SetString(PyExc_ValueError, msg); +} +static void __Pyx_Coroutine_AlreadyTerminatedError(PyObject *gen, PyObject *value, int closing) { + CYTHON_MAYBE_UNUSED_VAR(gen); + CYTHON_MAYBE_UNUSED_VAR(closing); + #ifdef __Pyx_Coroutine_USED + if (!closing && __Pyx_Coroutine_Check(gen)) { + PyErr_SetString(PyExc_RuntimeError, "cannot reuse already awaited coroutine"); + } else + #endif + if (value) { + #ifdef __Pyx_AsyncGen_USED + if (__Pyx_AsyncGen_CheckExact(gen)) + PyErr_SetNone(PyExc_StopAsyncIteration); + else + #endif + PyErr_SetNone(PyExc_StopIteration); + } +} +static +__Pyx_PySendResult __Pyx_Coroutine_SendEx(__pyx_CoroutineObject *self, PyObject *value, PyObject **result, int closing) { + __Pyx_PyThreadState_declare + PyThreadState *tstate; + __Pyx_ExcInfoStruct *exc_state; + PyObject *retval; + assert(__Pyx_Coroutine_get_is_running(self)); // Callers should ensure is_running + if (unlikely(self->resume_label == -1)) { + __Pyx_Coroutine_AlreadyTerminatedError((PyObject*)self, value, closing); + return PYGEN_ERROR; + } +#if CYTHON_FAST_THREAD_STATE + __Pyx_PyThreadState_assign + tstate = __pyx_tstate; +#else + tstate = __Pyx_PyThreadState_Current; +#endif + exc_state = &self->gi_exc_state; + if (exc_state->exc_value) { + #if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + #else + PyObject *exc_tb; + #if PY_VERSION_HEX >= 0x030B00a4 && !CYTHON_COMPILING_IN_CPYTHON + exc_tb = PyException_GetTraceback(exc_state->exc_value); + #elif PY_VERSION_HEX >= 0x030B00a4 + exc_tb = ((PyBaseExceptionObject*) exc_state->exc_value)->traceback; + #else + exc_tb = exc_state->exc_traceback; + #endif + if (exc_tb) { + PyTracebackObject *tb = (PyTracebackObject *) exc_tb; + PyFrameObject *f = tb->tb_frame; + assert(f->f_back == NULL); + #if PY_VERSION_HEX >= 0x030B00A1 + f->f_back = PyThreadState_GetFrame(tstate); + #else + Py_XINCREF(tstate->frame); + f->f_back = tstate->frame; + #endif + #if PY_VERSION_HEX >= 0x030B00a4 && !CYTHON_COMPILING_IN_CPYTHON + Py_DECREF(exc_tb); + #endif + } + #endif + } +#if CYTHON_USE_EXC_INFO_STACK + exc_state->previous_item = tstate->exc_info; + tstate->exc_info = exc_state; +#else + if (exc_state->exc_type) { + __Pyx_ExceptionSwap(&exc_state->exc_type, &exc_state->exc_value, &exc_state->exc_traceback); + } else { + __Pyx_Coroutine_ExceptionClear(exc_state); + __Pyx_ExceptionSave(&exc_state->exc_type, &exc_state->exc_value, &exc_state->exc_traceback); + } +#endif + retval = self->body(self, tstate, value); +#if CYTHON_USE_EXC_INFO_STACK + exc_state = &self->gi_exc_state; + tstate->exc_info = exc_state->previous_item; + exc_state->previous_item = NULL; + __Pyx_Coroutine_ResetFrameBackpointer(exc_state); +#endif + *result = retval; + if (self->resume_label == -1) { + return likely(retval) ? PYGEN_RETURN : PYGEN_ERROR; + } + return PYGEN_NEXT; +} +static CYTHON_INLINE void __Pyx_Coroutine_ResetFrameBackpointer(__Pyx_ExcInfoStruct *exc_state) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API + CYTHON_UNUSED_VAR(exc_state); +#else + PyObject *exc_tb; + #if PY_VERSION_HEX >= 0x030B00a4 + if (!exc_state->exc_value) return; + exc_tb = PyException_GetTraceback(exc_state->exc_value); + #else + exc_tb = exc_state->exc_traceback; + #endif + if (likely(exc_tb)) { + PyTracebackObject *tb = (PyTracebackObject *) exc_tb; + PyFrameObject *f = tb->tb_frame; + Py_CLEAR(f->f_back); + #if PY_VERSION_HEX >= 0x030B00a4 + Py_DECREF(exc_tb); + #endif + } +#endif +} +#define __Pyx_Coroutine_MethodReturnFromResult(gen, result, retval, iternext)\ + ((result) == PYGEN_NEXT ? (retval) : __Pyx__Coroutine_MethodReturnFromResult(gen, result, retval, iternext)) +static PyObject * +__Pyx__Coroutine_MethodReturnFromResult(PyObject* gen, __Pyx_PySendResult result, PyObject *retval, int iternext) { + CYTHON_MAYBE_UNUSED_VAR(gen); + if (likely(result == PYGEN_RETURN)) { + int is_async = 0; + #ifdef __Pyx_AsyncGen_USED + is_async = __Pyx_AsyncGen_CheckExact(gen); + #endif + __Pyx_ReturnWithStopIteration(retval, is_async, iternext); + Py_XDECREF(retval); + } + return NULL; +} +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE +PyObject *__Pyx_PyGen_Send(PyGenObject *gen, PyObject *arg) { +#if PY_VERSION_HEX <= 0x030A00A1 + return _PyGen_Send(gen, arg); +#else + PyObject *result; + if (PyIter_Send((PyObject*)gen, arg ? arg : Py_None, &result) == PYGEN_RETURN) { + if (PyAsyncGen_CheckExact(gen)) { + assert(result == Py_None); + PyErr_SetNone(PyExc_StopAsyncIteration); + } + else if (result == Py_None) { + PyErr_SetNone(PyExc_StopIteration); + } + else { +#if PY_VERSION_HEX < 0x030d00A1 + _PyGen_SetStopIterationValue(result); +#else + if (!PyTuple_Check(result) && !PyExceptionInstance_Check(result)) { + PyErr_SetObject(PyExc_StopIteration, result); + } else { + PyObject *exc = __Pyx_PyObject_CallOneArg(PyExc_StopIteration, result); + if (likely(exc != NULL)) { + PyErr_SetObject(PyExc_StopIteration, exc); + Py_DECREF(exc); + } + } +#endif + } + Py_DECREF(result); + result = NULL; + } + return result; +#endif +} +#endif +static CYTHON_INLINE __Pyx_PySendResult +__Pyx_Coroutine_FinishDelegation(__pyx_CoroutineObject *gen, PyObject** retval) { + __Pyx_PySendResult result; + PyObject *val = NULL; + assert(__Pyx_Coroutine_get_is_running(gen)); + __Pyx_Coroutine_Undelegate(gen); + __Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, &val); + result = __Pyx_Coroutine_SendEx(gen, val, retval, 0); + Py_XDECREF(val); + return result; +} +#if CYTHON_USE_AM_SEND +static __Pyx_PySendResult +__Pyx_Coroutine_SendToDelegate(__pyx_CoroutineObject *gen, __Pyx_pyiter_sendfunc gen_am_send, PyObject *value, PyObject **retval) { + PyObject *ret = NULL; + __Pyx_PySendResult delegate_result, result; + assert(__Pyx_Coroutine_get_is_running(gen)); + delegate_result = gen_am_send(gen->yieldfrom, value, &ret); + if (delegate_result == PYGEN_NEXT) { + assert (ret != NULL); + *retval = ret; + return PYGEN_NEXT; + } + assert (delegate_result != PYGEN_ERROR || ret == NULL); + __Pyx_Coroutine_Undelegate(gen); + result = __Pyx_Coroutine_SendEx(gen, ret, retval, 0); + Py_XDECREF(ret); + return result; +} +#endif +static PyObject *__Pyx_Coroutine_Send(PyObject *self, PyObject *value) { + PyObject *retval = NULL; + __Pyx_PySendResult result = __Pyx_Coroutine_AmSend(self, value, &retval); + return __Pyx_Coroutine_MethodReturnFromResult(self, result, retval, 0); +} +static __Pyx_PySendResult +__Pyx_Coroutine_AmSend(PyObject *self, PyObject *value, PyObject **retval) { + __Pyx_PySendResult result; + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self; + if (unlikely(__Pyx_Coroutine_test_and_set_is_running(gen))) { + *retval = __Pyx_Coroutine_AlreadyRunningError(gen); + return PYGEN_ERROR; + } + #if CYTHON_USE_AM_SEND + if (gen->yieldfrom_am_send) { + result = __Pyx_Coroutine_SendToDelegate(gen, gen->yieldfrom_am_send, value, retval); + } else + #endif + if (gen->yieldfrom) { + PyObject *yf = gen->yieldfrom; + PyObject *ret; + #if !CYTHON_USE_AM_SEND + #ifdef __Pyx_Generator_USED + if (__Pyx_Generator_CheckExact(yf)) { + ret = __Pyx_Coroutine_Send(yf, value); + } else + #endif + #ifdef __Pyx_Coroutine_USED + if (__Pyx_Coroutine_Check(yf)) { + ret = __Pyx_Coroutine_Send(yf, value); + } else + #endif + #ifdef __Pyx_AsyncGen_USED + if (__pyx_PyAsyncGenASend_CheckExact(yf)) { + ret = __Pyx_async_gen_asend_send(yf, value); + } else + #endif + #if CYTHON_COMPILING_IN_CPYTHON + if (PyGen_CheckExact(yf)) { + ret = __Pyx_PyGen_Send((PyGenObject*)yf, value == Py_None ? NULL : value); + } else + if (PyCoro_CheckExact(yf)) { + ret = __Pyx_PyGen_Send((PyGenObject*)yf, value == Py_None ? NULL : value); + } else + #endif + #endif + { + if (value == Py_None && PyIter_Check(yf)) + ret = __Pyx_PyIter_Next_Plain(yf); + else + ret = __Pyx_PyObject_CallMethod1(yf, __pyx_mstate_global->__pyx_n_u_send, value); + } + if (likely(ret)) { + __Pyx_Coroutine_unset_is_running(gen); + *retval = ret; + return PYGEN_NEXT; + } + result = __Pyx_Coroutine_FinishDelegation(gen, retval); + } else { + result = __Pyx_Coroutine_SendEx(gen, value, retval, 0); + } + __Pyx_Coroutine_unset_is_running(gen); + return result; +} +static int __Pyx_Coroutine_CloseIter(__pyx_CoroutineObject *gen, PyObject *yf) { + __Pyx_PySendResult result; + PyObject *retval = NULL; + CYTHON_UNUSED_VAR(gen); + assert(__Pyx_Coroutine_get_is_running(gen)); + #ifdef __Pyx_Generator_USED + if (__Pyx_Generator_CheckExact(yf)) { + result = __Pyx_Coroutine_Close(yf, &retval); + } else + #endif + #ifdef __Pyx_Coroutine_USED + if (__Pyx_Coroutine_Check(yf)) { + result = __Pyx_Coroutine_Close(yf, &retval); + } else + if (__Pyx_CoroutineAwait_CheckExact(yf)) { + result = __Pyx_CoroutineAwait_Close((__pyx_CoroutineAwaitObject*)yf); + } else + #endif + #ifdef __Pyx_AsyncGen_USED + if (__pyx_PyAsyncGenASend_CheckExact(yf)) { + retval = __Pyx_async_gen_asend_close(yf, NULL); + result = PYGEN_RETURN; + } else + if (__pyx_PyAsyncGenAThrow_CheckExact(yf)) { + retval = __Pyx_async_gen_athrow_close(yf, NULL); + result = PYGEN_RETURN; + } else + #endif + { + PyObject *meth; + result = PYGEN_RETURN; + meth = __Pyx_PyObject_GetAttrStrNoError(yf, __pyx_mstate_global->__pyx_n_u_close); + if (unlikely(!meth)) { + if (unlikely(PyErr_Occurred())) { + PyErr_WriteUnraisable(yf); + } + } else { + retval = __Pyx_PyObject_CallNoArg(meth); + Py_DECREF(meth); + if (unlikely(!retval)) { + result = PYGEN_ERROR; + } + } + } + Py_XDECREF(retval); + return result == PYGEN_ERROR ? -1 : 0; +} +static PyObject *__Pyx_Generator_Next(PyObject *self) { + __Pyx_PySendResult result; + PyObject *retval = NULL; + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self; + if (unlikely(__Pyx_Coroutine_test_and_set_is_running(gen))) { + return __Pyx_Coroutine_AlreadyRunningError(gen); + } + #if CYTHON_USE_AM_SEND + if (gen->yieldfrom_am_send) { + result = __Pyx_Coroutine_SendToDelegate(gen, gen->yieldfrom_am_send, Py_None, &retval); + } else + #endif + if (gen->yieldfrom) { + PyObject *yf = gen->yieldfrom; + PyObject *ret; + #ifdef __Pyx_Generator_USED + if (__Pyx_Generator_CheckExact(yf)) { + ret = __Pyx_Generator_Next(yf); + } else + #endif + #ifdef __Pyx_Coroutine_USED + if (__Pyx_Coroutine_CheckExact(yf)) { + ret = __Pyx_Coroutine_Send(yf, Py_None); + } else + #endif + #if CYTHON_COMPILING_IN_CPYTHON && (PY_VERSION_HEX < 0x030A00A3 || !CYTHON_USE_AM_SEND) + if (PyGen_CheckExact(yf)) { + ret = __Pyx_PyGen_Send((PyGenObject*)yf, NULL); + } else + #endif + ret = __Pyx_PyIter_Next_Plain(yf); + if (likely(ret)) { + __Pyx_Coroutine_unset_is_running(gen); + return ret; + } + result = __Pyx_Coroutine_FinishDelegation(gen, &retval); + } else { + result = __Pyx_Coroutine_SendEx(gen, Py_None, &retval, 0); + } + __Pyx_Coroutine_unset_is_running(gen); + return __Pyx_Coroutine_MethodReturnFromResult(self, result, retval, 1); +} +static PyObject *__Pyx_Coroutine_Close_Method(PyObject *self, PyObject *arg) { + PyObject *retval = NULL; + __Pyx_PySendResult result; + CYTHON_UNUSED_VAR(arg); + result = __Pyx_Coroutine_Close(self, &retval); + if (unlikely(result == PYGEN_ERROR)) + return NULL; + Py_XDECREF(retval); + Py_RETURN_NONE; +} +static __Pyx_PySendResult +__Pyx_Coroutine_Close(PyObject *self, PyObject **retval) { + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; + __Pyx_PySendResult result; + PyObject *yf; + int err = 0; + if (unlikely(__Pyx_Coroutine_test_and_set_is_running(gen))) { + *retval = __Pyx_Coroutine_AlreadyRunningError(gen); + return PYGEN_ERROR; + } + yf = gen->yieldfrom; + if (yf) { + Py_INCREF(yf); + err = __Pyx_Coroutine_CloseIter(gen, yf); + __Pyx_Coroutine_Undelegate(gen); + Py_DECREF(yf); + } + if (err == 0) + PyErr_SetNone(PyExc_GeneratorExit); + result = __Pyx_Coroutine_SendEx(gen, NULL, retval, 1); + if (result == PYGEN_ERROR) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_Coroutine_unset_is_running(gen); + if (!__Pyx_PyErr_Occurred()) { + return PYGEN_RETURN; + } else if (likely(__Pyx_PyErr_ExceptionMatches2(PyExc_GeneratorExit, PyExc_StopIteration))) { + __Pyx_PyErr_Clear(); + return PYGEN_RETURN; + } + return PYGEN_ERROR; + } else if (likely(result == PYGEN_RETURN && *retval == Py_None)) { + __Pyx_Coroutine_unset_is_running(gen); + return PYGEN_RETURN; + } else { + const char *msg; + Py_DECREF(*retval); + *retval = NULL; + if ((0)) { + #ifdef __Pyx_Coroutine_USED + } else if (__Pyx_Coroutine_Check(self)) { + msg = "coroutine ignored GeneratorExit"; + #endif + #ifdef __Pyx_AsyncGen_USED + } else if (__Pyx_AsyncGen_CheckExact(self)) { + msg = "async generator ignored GeneratorExit"; + #endif + } else { + msg = "generator ignored GeneratorExit"; + } + PyErr_SetString(PyExc_RuntimeError, msg); + __Pyx_Coroutine_unset_is_running(gen); + return PYGEN_ERROR; + } +} +static PyObject *__Pyx__Coroutine_Throw(PyObject *self, PyObject *typ, PyObject *val, PyObject *tb, + PyObject *args, int close_on_genexit) { + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; + PyObject *yf; + if (unlikely(__Pyx_Coroutine_test_and_set_is_running(gen))) + return __Pyx_Coroutine_AlreadyRunningError(gen); + yf = gen->yieldfrom; + if (yf) { + __Pyx_PySendResult result; + PyObject *ret; + Py_INCREF(yf); + if (__Pyx_PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) && close_on_genexit) { + int err = __Pyx_Coroutine_CloseIter(gen, yf); + Py_DECREF(yf); + __Pyx_Coroutine_Undelegate(gen); + if (err < 0) + goto propagate_exception; + goto throw_here; + } + if (0 + #ifdef __Pyx_Generator_USED + || __Pyx_Generator_CheckExact(yf) + #endif + #ifdef __Pyx_Coroutine_USED + || __Pyx_Coroutine_Check(yf) + #endif + ) { + ret = __Pyx__Coroutine_Throw(yf, typ, val, tb, args, close_on_genexit); + #ifdef __Pyx_Coroutine_USED + } else if (__Pyx_CoroutineAwait_CheckExact(yf)) { + ret = __Pyx__Coroutine_Throw(((__pyx_CoroutineAwaitObject*)yf)->coroutine, typ, val, tb, args, close_on_genexit); + #endif + } else { + PyObject *meth = __Pyx_PyObject_GetAttrStrNoError(yf, __pyx_mstate_global->__pyx_n_u_throw); + if (unlikely(!meth)) { + Py_DECREF(yf); + if (unlikely(PyErr_Occurred())) { + __Pyx_Coroutine_unset_is_running(gen); + return NULL; + } + __Pyx_Coroutine_Undelegate(gen); + goto throw_here; + } + if (args) { + ret = __Pyx_PyObject_Call(meth, args, NULL); + } else { + PyObject *cargs[4] = {NULL, typ, val, tb}; + size_t nargs = 1U + (val != NULL) + (tb != NULL); + ret = __Pyx_PyObject_FastCall(meth, cargs+1, nargs | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); + } + Py_DECREF(meth); + } + Py_DECREF(yf); + if (ret) { + __Pyx_Coroutine_unset_is_running(gen); + return ret; + } + result = __Pyx_Coroutine_FinishDelegation(gen, &ret); + __Pyx_Coroutine_unset_is_running(gen); + return __Pyx_Coroutine_MethodReturnFromResult(self, result, ret, 0); + } +throw_here: + __Pyx_Raise(typ, val, tb, NULL); +propagate_exception: + { + PyObject *retval = NULL; + __Pyx_PySendResult result = __Pyx_Coroutine_SendEx(gen, NULL, &retval, 0); + __Pyx_Coroutine_unset_is_running(gen); + return __Pyx_Coroutine_MethodReturnFromResult(self, result, retval, 0); + } +} +static PyObject *__Pyx_Coroutine_Throw(PyObject *self, +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + PyObject *args +#else + PyObject *const *args, Py_ssize_t nargs +#endif +) { + PyObject *typ; + PyObject *val = NULL; + PyObject *tb = NULL; +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + if (unlikely(!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb))) + return NULL; +#else + switch (nargs) { + case 3: + tb = args[2]; + CYTHON_FALLTHROUGH; + case 2: + val = args[1]; + CYTHON_FALLTHROUGH; + case 1: + typ = args[0]; + break; + default: + PyErr_SetString(PyExc_TypeError, "throw takes between 1 and 3 positional arguments"); + return NULL; + } +#endif + return __Pyx__Coroutine_Throw(self, typ, val, tb, +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + args, +#else + NULL, +#endif + 1); +} +static CYTHON_INLINE int __Pyx_Coroutine_traverse_excstate(__Pyx_ExcInfoStruct *exc_state, visitproc visit, void *arg) { +#if PY_VERSION_HEX >= 0x030B00a4 + Py_VISIT(exc_state->exc_value); +#else + Py_VISIT(exc_state->exc_type); + Py_VISIT(exc_state->exc_value); + Py_VISIT(exc_state->exc_traceback); +#endif + return 0; +} +static int __Pyx_Coroutine_traverse(__pyx_CoroutineObject *gen, visitproc visit, void *arg) { + { + int e = __Pyx_call_type_traverse((PyObject*)gen, 1, visit, arg); + if (e) return e; + } + Py_VISIT(gen->closure); + Py_VISIT(gen->classobj); + Py_VISIT(gen->yieldfrom); + return __Pyx_Coroutine_traverse_excstate(&gen->gi_exc_state, visit, arg); +} +static int __Pyx_Coroutine_clear(PyObject *self) { + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; + Py_CLEAR(gen->closure); + Py_CLEAR(gen->classobj); + __Pyx_Coroutine_Undelegate(gen); + __Pyx_Coroutine_ExceptionClear(&gen->gi_exc_state); +#ifdef __Pyx_AsyncGen_USED + if (__Pyx_AsyncGen_CheckExact(self)) { + Py_CLEAR(((__pyx_PyAsyncGenObject*)gen)->ag_finalizer); + } +#endif + Py_CLEAR(gen->gi_code); + Py_CLEAR(gen->gi_frame); + Py_CLEAR(gen->gi_name); + Py_CLEAR(gen->gi_qualname); + Py_CLEAR(gen->gi_modulename); + return 0; +} +static void __Pyx_Coroutine_dealloc(PyObject *self) { + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; + PyObject_GC_UnTrack(gen); + #if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + if (gen->gi_weakreflist != NULL) + #endif + PyObject_ClearWeakRefs(self); + if (gen->resume_label >= 0) { +#if CYTHON_USE_TP_FINALIZE + PyObject_GC_Track(self); + if (unlikely(PyObject_CallFinalizerFromDealloc(self))) + { + return; + } + PyObject_GC_UnTrack(self); +#endif + } +#ifdef __Pyx_AsyncGen_USED + if (__Pyx_AsyncGen_CheckExact(self)) { + /* We have to handle this case for asynchronous generators + right here, because this code has to be between UNTRACK + and GC_Del. */ + Py_CLEAR(((__pyx_PyAsyncGenObject*)self)->ag_finalizer); + } +#endif + __Pyx_Coroutine_clear(self); + __Pyx_PyHeapTypeObject_GC_Del(gen); +} +#if CYTHON_USE_TP_FINALIZE +static void __Pyx_Coroutine_del(PyObject *self) { + PyObject *error_type, *error_value, *error_traceback; + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; + __Pyx_PyThreadState_declare + if (gen->resume_label < 0) { + return; + } + __Pyx_PyThreadState_assign + __Pyx_ErrFetch(&error_type, &error_value, &error_traceback); +#ifdef __Pyx_AsyncGen_USED + if (__Pyx_AsyncGen_CheckExact(self)) { + __pyx_PyAsyncGenObject *agen = (__pyx_PyAsyncGenObject*)self; + PyObject *finalizer = agen->ag_finalizer; + if (finalizer && !agen->ag_closed) { + PyObject *res = __Pyx_PyObject_CallOneArg(finalizer, self); + if (unlikely(!res)) { + PyErr_WriteUnraisable(self); + } else { + Py_DECREF(res); + } + __Pyx_ErrRestore(error_type, error_value, error_traceback); + return; + } + } +#endif + if (unlikely(gen->resume_label == 0 && !error_value)) { +#ifdef __Pyx_Coroutine_USED +#ifdef __Pyx_Generator_USED + if (!__Pyx_Generator_CheckExact(self)) +#endif + { + PyObject_GC_UnTrack(self); + if (unlikely(PyErr_WarnFormat(PyExc_RuntimeWarning, 1, "coroutine '%.50S' was never awaited", gen->gi_qualname) < 0)) + PyErr_WriteUnraisable(self); + PyObject_GC_Track(self); + } +#endif + } else { + PyObject *retval = NULL; + __Pyx_PySendResult result = __Pyx_Coroutine_Close(self, &retval); + if (result == PYGEN_ERROR) { + PyErr_WriteUnraisable(self); + } else { + Py_XDECREF(retval); + } + } + __Pyx_ErrRestore(error_type, error_value, error_traceback); +} +#endif +static PyObject * +__Pyx_Coroutine_get_name(__pyx_CoroutineObject *self, void *context) +{ + PyObject *name = self->gi_name; + CYTHON_UNUSED_VAR(context); + if (unlikely(!name)) name = Py_None; + Py_INCREF(name); + return name; +} +static int +__Pyx_Coroutine_set_name(__pyx_CoroutineObject *self, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(self->gi_name, value); + return 0; +} +static PyObject * +__Pyx_Coroutine_get_qualname(__pyx_CoroutineObject *self, void *context) +{ + PyObject *name = self->gi_qualname; + CYTHON_UNUSED_VAR(context); + if (unlikely(!name)) name = Py_None; + Py_INCREF(name); + return name; +} +static int +__Pyx_Coroutine_set_qualname(__pyx_CoroutineObject *self, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(self->gi_qualname, value); + return 0; +} +#if !CYTHON_COMPILING_IN_LIMITED_API +static PyObject * +__Pyx__Coroutine_get_frame_locked(__pyx_CoroutineObject *self) { + PyObject *frame; + frame = self->gi_frame; + if (!frame) { + if (unlikely(!self->gi_code)) { + Py_RETURN_NONE; + } + PyObject *globals = PyDict_New(); + if (unlikely(!globals)) return NULL; + frame = (PyObject *) PyFrame_New( + PyThreadState_Get(), /*PyThreadState *tstate,*/ + (PyCodeObject*) self->gi_code, /*PyCodeObject *code,*/ + globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + Py_DECREF(globals); + if (unlikely(!frame)) + return NULL; + if (unlikely(self->gi_frame)) { + Py_DECREF(frame); + frame = self->gi_frame; + } else { + self->gi_frame = frame; + } + } + Py_INCREF(frame); + return frame; +} +#endif +static PyObject * +__Pyx__Coroutine_get_frame(__pyx_CoroutineObject *self) +{ +#if !CYTHON_COMPILING_IN_LIMITED_API + PyObject *frame; + __Pyx_BEGIN_CRITICAL_SECTION((PyObject*)self); + frame = __Pyx__Coroutine_get_frame_locked(self); + __Pyx_END_CRITICAL_SECTION(); + return frame; +#else + CYTHON_UNUSED_VAR(self); + Py_RETURN_NONE; +#endif +} +static PyObject * +__Pyx_Coroutine_get_frame(__pyx_CoroutineObject *self, void *context) { + CYTHON_UNUSED_VAR(context); + PyObject *frame = self->gi_frame; + if (frame) + return __Pyx_NewRef(frame); + return __Pyx__Coroutine_get_frame(self); +} +static __pyx_CoroutineObject *__Pyx__Coroutine_New( + PyTypeObject* type, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, + PyObject *name, PyObject *qualname, PyObject *module_name) { + __pyx_CoroutineObject *gen = PyObject_GC_New(__pyx_CoroutineObject, type); + if (unlikely(!gen)) + return NULL; + return __Pyx__Coroutine_NewInit(gen, body, code, closure, name, qualname, module_name); +} +static __pyx_CoroutineObject *__Pyx__Coroutine_NewInit( + __pyx_CoroutineObject *gen, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, + PyObject *name, PyObject *qualname, PyObject *module_name) { + gen->body = body; + gen->closure = closure; + Py_XINCREF(closure); + gen->is_running = 0; + gen->resume_label = 0; + gen->classobj = NULL; + gen->yieldfrom = NULL; + gen->yieldfrom_am_send = NULL; + #if PY_VERSION_HEX >= 0x030B00a4 && !CYTHON_COMPILING_IN_LIMITED_API + gen->gi_exc_state.exc_value = NULL; + #else + gen->gi_exc_state.exc_type = NULL; + gen->gi_exc_state.exc_value = NULL; + gen->gi_exc_state.exc_traceback = NULL; + #endif +#if CYTHON_USE_EXC_INFO_STACK + gen->gi_exc_state.previous_item = NULL; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + gen->gi_weakreflist = NULL; +#endif + Py_XINCREF(qualname); + gen->gi_qualname = qualname; + Py_XINCREF(name); + gen->gi_name = name; + Py_XINCREF(module_name); + gen->gi_modulename = module_name; + Py_XINCREF(code); + gen->gi_code = code; + gen->gi_frame = NULL; +#if CYTHON_USE_SYS_MONITORING && (CYTHON_PROFILE || CYTHON_TRACE) + memset(gen->__pyx_pymonitoring_state, 0, sizeof(gen->__pyx_pymonitoring_state)); + gen->__pyx_pymonitoring_version = 0; +#endif + PyObject_GC_Track(gen); + return gen; +} +static char __Pyx_Coroutine_test_and_set_is_running(__pyx_CoroutineObject *gen) { + char result; + __Pyx_BEGIN_CRITICAL_SECTION((PyObject*)gen); + result = gen->is_running; + gen->is_running = 1; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static void __Pyx_Coroutine_unset_is_running(__pyx_CoroutineObject *gen) { + __Pyx_BEGIN_CRITICAL_SECTION((PyObject*)gen); + assert(gen->is_running); + gen->is_running = 0; + __Pyx_END_CRITICAL_SECTION(); +} +static char __Pyx_Coroutine_get_is_running(__pyx_CoroutineObject *gen) { + char result; + __Pyx_BEGIN_CRITICAL_SECTION((PyObject*)gen); + result = gen->is_running; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyObject *__Pyx_Coroutine_get_is_running_getter(PyObject *gen, void *closure) { + CYTHON_UNUSED_VAR(closure); + char result = __Pyx_Coroutine_get_is_running((__pyx_CoroutineObject*)gen); + if (result) Py_RETURN_TRUE; + else Py_RETURN_FALSE; +} +#if __PYX_HAS_PY_AM_SEND == 2 +static void __Pyx_SetBackportTypeAmSend(PyTypeObject *type, __Pyx_PyAsyncMethodsStruct *static_amsend_methods, __Pyx_pyiter_sendfunc am_send) { + Py_ssize_t ptr_offset = (char*)(type->tp_as_async) - (char*)type; + if (ptr_offset < 0 || ptr_offset > type->tp_basicsize) { + return; + } + memcpy((void*)static_amsend_methods, (void*)(type->tp_as_async), sizeof(*type->tp_as_async)); + static_amsend_methods->am_send = am_send; + type->tp_as_async = __Pyx_SlotTpAsAsync(static_amsend_methods); +} +#endif +static PyObject *__Pyx_Coroutine_fail_reduce_ex(PyObject *self, PyObject *arg) { + CYTHON_UNUSED_VAR(arg); + __Pyx_RaiseTypeErrorWithObjectType( + "cannot pickle '" __Pyx_FMT_TYPENAME "' object", self); + return NULL; +} + +/* Generator */ +static PyMethodDef __pyx_Generator_methods[] = { + {"send", (PyCFunction) __Pyx_Coroutine_Send, METH_O, + PyDoc_STR("send(arg) -> send 'arg' into generator,\nreturn next yielded value or raise StopIteration.")}, + {"throw", __PYX_REINTERPRET_FUNCION(PyCFunction, __Pyx_Coroutine_Throw), +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + METH_VARARGS, +#else + METH_FASTCALL, +#endif + PyDoc_STR("throw(typ[,val[,tb]]) -> raise exception in generator,\nreturn next yielded value or raise StopIteration.")}, + {"close", (PyCFunction) __Pyx_Coroutine_Close_Method, METH_NOARGS, + PyDoc_STR("close() -> raise GeneratorExit inside generator.")}, + {"__reduce_ex__", (PyCFunction) __Pyx_Coroutine_fail_reduce_ex, METH_O, 0}, + {"__reduce__", (PyCFunction) __Pyx_Coroutine_fail_reduce_ex, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; +static PyMemberDef __pyx_Generator_memberlist[] = { + {"gi_yieldfrom", T_OBJECT, offsetof(__pyx_CoroutineObject, yieldfrom), READONLY, + PyDoc_STR("object being iterated by 'yield from', or None")}, + {"gi_code", T_OBJECT, offsetof(__pyx_CoroutineObject, gi_code), READONLY, NULL}, + {"__module__", T_OBJECT, offsetof(__pyx_CoroutineObject, gi_modulename), 0, 0}, +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + {"__weaklistoffset__", T_PYSSIZET, offsetof(__pyx_CoroutineObject, gi_weakreflist), READONLY, 0}, +#endif + {0, 0, 0, 0, 0} +}; +static PyGetSetDef __pyx_Generator_getsets[] = { + {"__name__", (getter)__Pyx_Coroutine_get_name, (setter)__Pyx_Coroutine_set_name, + PyDoc_STR("name of the generator"), 0}, + {"__qualname__", (getter)__Pyx_Coroutine_get_qualname, (setter)__Pyx_Coroutine_set_qualname, + PyDoc_STR("qualified name of the generator"), 0}, + {"gi_frame", (getter)__Pyx_Coroutine_get_frame, NULL, + PyDoc_STR("Frame of the generator"), 0}, + {"gi_running", __Pyx_Coroutine_get_is_running_getter, NULL, NULL, NULL}, + {0, 0, 0, 0, 0} +}; +static PyType_Slot __pyx_GeneratorType_slots[] = { + {Py_tp_dealloc, (void *)__Pyx_Coroutine_dealloc}, + {Py_tp_traverse, (void *)__Pyx_Coroutine_traverse}, + {Py_tp_iter, (void *)PyObject_SelfIter}, + {Py_tp_iternext, (void *)__Pyx_Generator_Next}, + {Py_tp_methods, (void *)__pyx_Generator_methods}, + {Py_tp_members, (void *)__pyx_Generator_memberlist}, + {Py_tp_getset, (void *)__pyx_Generator_getsets}, + {Py_tp_getattro, (void *) PyObject_GenericGetAttr}, +#if CYTHON_USE_TP_FINALIZE + {Py_tp_finalize, (void *)__Pyx_Coroutine_del}, +#endif +#if __PYX_HAS_PY_AM_SEND == 1 + {Py_am_send, (void *)__Pyx_Coroutine_AmSend}, +#endif + {0, 0}, +}; +static PyType_Spec __pyx_GeneratorType_spec = { + __PYX_TYPE_MODULE_PREFIX "generator", + sizeof(__pyx_CoroutineObject), + 0, +#if PY_VERSION_HEX >= 0x030C0000 && !CYTHON_COMPILING_IN_LIMITED_API + Py_TPFLAGS_MANAGED_WEAKREF | +#endif + Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | __Pyx_TPFLAGS_HAVE_AM_SEND, + __pyx_GeneratorType_slots +}; +#if __PYX_HAS_PY_AM_SEND == 2 +static __Pyx_PyAsyncMethodsStruct __pyx_Generator_as_async; +#endif +static int __pyx_Generator_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + mstate->__pyx_GeneratorType = __Pyx_FetchCommonTypeFromSpec( + mstate->__pyx_CommonTypesMetaclassType, module, &__pyx_GeneratorType_spec, NULL); + if (unlikely(!mstate->__pyx_GeneratorType)) { + return -1; + } +#if __PYX_HAS_PY_AM_SEND == 2 + __Pyx_SetBackportTypeAmSend(mstate->__pyx_GeneratorType, &__pyx_Generator_as_async, &__Pyx_Coroutine_AmSend); +#endif + return 0; +} +static PyObject *__Pyx_Generator_GetInlinedResult(PyObject *self) { + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self; + PyObject *retval = NULL; + if (unlikely(__Pyx_Coroutine_test_and_set_is_running(gen))) { + return __Pyx_Coroutine_AlreadyRunningError(gen); + } + __Pyx_PySendResult result = __Pyx_Coroutine_SendEx(gen, Py_None, &retval, 0); + __Pyx_Coroutine_unset_is_running(gen); + (void) result; + assert (result == PYGEN_RETURN || result == PYGEN_ERROR); + assert ((result == PYGEN_RETURN && retval != NULL) || (result == PYGEN_ERROR && retval == NULL)); + return retval; +} + +/* CheckBinaryVersion */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer) { + const unsigned long MAJOR_MINOR = 0xFFFF0000UL; + if ((rt_version & MAJOR_MINOR) == (ct_version & MAJOR_MINOR)) + return 0; + if (likely(allow_newer && (rt_version & MAJOR_MINOR) > (ct_version & MAJOR_MINOR))) + return 1; + { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compile time Python version %d.%d " + "of module '%.100s' " + "%s " + "runtime version %d.%d", + (int) (ct_version >> 24), (int) ((ct_version >> 16) & 0xFF), + __Pyx_MODULE_NAME, + (allow_newer) ? "was newer than" : "does not match", + (int) (rt_version >> 24), (int) ((rt_version >> 16) & 0xFF) + ); + return PyErr_WarnEx(NULL, message, 1); + } +} + +/* NewCodeObj */ +#if CYTHON_COMPILING_IN_LIMITED_API + static PyObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyObject *exception_table = NULL; + PyObject *types_module=NULL, *code_type=NULL, *result=NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + PyObject *version_info; + PyObject *py_minor_version = NULL; + #endif + long minor_version = 0; + #if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + minor_version = 11; + #else + if (!(version_info = PySys_GetObject("version_info"))) goto end; + if (!(py_minor_version = PySequence_GetItem(version_info, 1))) goto end; + minor_version = PyLong_AsLong(py_minor_version); + Py_DECREF(py_minor_version); + if (minor_version == -1 && PyErr_Occurred()) goto end; + #endif + if (!(types_module = PyImport_ImportModule("types"))) goto end; + if (!(code_type = PyObject_GetAttrString(types_module, "CodeType"))) goto end; + if (minor_version <= 10) { + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOiOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else { + if (!(exception_table = PyBytes_FromStringAndSize(NULL, 0))) goto end; + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOOiOOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, name, fline, lnos, exception_table, fv, cell); + } + end: + Py_XDECREF(code_type); + Py_XDECREF(exception_table); + Py_XDECREF(types_module); + if (!result) { + PyObject *exc_type, *exc_value, *exc_tb; + PyErr_Fetch(&exc_type, &exc_value, &exc_tb); + if (PyErr_WarnFormat( + PyExc_RuntimeWarning, 1, + "Code object creation failed in Cython module: %S\nTry recompiling with a more recent version of Cython.", + exc_value ? exc_value : exc_type) == 0) { + result = Py_None; + Py_INCREF(result); + } + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + } + return result; + } +#elif PY_VERSION_HEX >= 0x030B0000 + static PyCodeObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyCodeObject *result; + result = + #if PY_VERSION_HEX >= 0x030C0000 + PyUnstable_Code_NewWithPosOnlyArgs + #else + PyCode_NewWithPosOnlyArgs + #endif + (a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, name, fline, lnos, __pyx_mstate_global->__pyx_empty_bytes); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030c00A1 + if (likely(result)) + result->_co_firsttraceable = 0; + #endif + return result; + } +#elif !CYTHON_COMPILING_IN_PYPY + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_NewWithPosOnlyArgs(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + PyObject *line_table, + PyObject *tuple_dedup_map +) { + PyObject *code_obj = NULL, *varnames_tuple_dedup = NULL, *code_bytes = NULL; + Py_ssize_t var_count = (Py_ssize_t) descr.nlocals; + PyObject *varnames_tuple = PyTuple_New(var_count); + if (unlikely(!varnames_tuple)) return NULL; + for (Py_ssize_t i=0; i < var_count; i++) { + Py_INCREF(varnames[i]); + if (__Pyx_PyTuple_SET_ITEM(varnames_tuple, i, varnames[i]) != (0)) goto done; + } + #if CYTHON_COMPILING_IN_LIMITED_API + varnames_tuple_dedup = PyDict_GetItem(tuple_dedup_map, varnames_tuple); + if (!varnames_tuple_dedup) { + if (unlikely(PyDict_SetItem(tuple_dedup_map, varnames_tuple, varnames_tuple) < 0)) goto done; + varnames_tuple_dedup = varnames_tuple; + } + #else + varnames_tuple_dedup = PyDict_SetDefault(tuple_dedup_map, varnames_tuple, varnames_tuple); + if (unlikely(!varnames_tuple_dedup)) goto done; + #endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(varnames_tuple_dedup); + #endif + if (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table != NULL && !CYTHON_COMPILING_IN_GRAAL) { + Py_ssize_t line_table_length = __Pyx_PyBytes_GET_SIZE(line_table); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(line_table_length == -1)) goto done; + #endif + Py_ssize_t code_len = (line_table_length * 2 + 4) & ~3LL; + code_bytes = PyBytes_FromStringAndSize(NULL, code_len); + if (unlikely(!code_bytes)) goto done; + char* c_code_bytes = PyBytes_AsString(code_bytes); + if (unlikely(!c_code_bytes)) goto done; + memset(c_code_bytes, 0, (size_t) code_len); + } + code_obj = (PyObject*) __Pyx__PyCode_New( + (int) descr.argcount, + (int) descr.num_posonly_args, + (int) descr.num_kwonly_args, + (int) descr.nlocals, + 0, + (int) descr.flags, + code_bytes ? code_bytes : __pyx_mstate_global->__pyx_empty_bytes, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + varnames_tuple_dedup, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + filename, + funcname, + (int) descr.first_line, + (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table) ? line_table : __pyx_mstate_global->__pyx_empty_bytes + ); +done: + Py_XDECREF(code_bytes); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(varnames_tuple_dedup); + #endif + Py_DECREF(varnames_tuple); + return code_obj; +} + +/* DecompressString */ +CYTHON_UNUSED +static CYTHON_SMALL_CODE PyObject *__Pyx_DecompressString(const char *s, Py_ssize_t length, int algo) { +#ifdef __Pyx_DecompressString_UNUSED + CYTHON_UNUSED_VAR(s); + CYTHON_UNUSED_VAR(length); + CYTHON_UNUSED_VAR(algo); + return NULL; +#else + PyObject *module = NULL, *decompress, *compressed_bytes, *decompressed; + const char* module_name = algo == 3 ? "compression.zstd" : algo == 2 ? "bz2" : "zlib"; + PyObject *methodname = PyUnicode_FromString("decompress"); + if (unlikely(!methodname)) return NULL; + #if __PYX_LIMITED_VERSION_HEX >= 0x030e0000 + if (algo == 3) { + PyObject *fromlist = Py_BuildValue("[O]", methodname); + if (unlikely(!fromlist)) goto bad; + module = PyImport_ImportModuleLevel("compression.zstd", NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + } else + #endif + module = PyImport_ImportModule(module_name); + if (unlikely(!module)) goto import_failed; + decompress = PyObject_GetAttr(module, methodname); + if (unlikely(!decompress)) goto import_failed; + { + #ifdef __cplusplus + char *memview_bytes = const_cast(s); + #else + #if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wcast-qual" + #elif !defined(__INTEL_COMPILER) && defined(__GNUC__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-qual" + #endif + char *memview_bytes = (char*) s; + #if defined(__clang__) + #pragma clang diagnostic pop + #elif !defined(__INTEL_COMPILER) && defined(__GNUC__) + #pragma GCC diagnostic pop + #endif + #endif + #if CYTHON_COMPILING_IN_LIMITED_API && !defined(PyBUF_READ) + int memview_flags = 0x100; + #else + int memview_flags = PyBUF_READ; + #endif + compressed_bytes = PyMemoryView_FromMemory(memview_bytes, length, memview_flags); + } + if (unlikely(!compressed_bytes)) { + Py_DECREF(decompress); + goto bad; + } + decompressed = PyObject_CallFunctionObjArgs(decompress, compressed_bytes, NULL); + Py_DECREF(compressed_bytes); + Py_DECREF(decompress); + Py_DECREF(module); + Py_DECREF(methodname); + return decompressed; +import_failed: + PyErr_Format(PyExc_ImportError, + "Failed to import '%.20s.decompress' - cannot initialise module strings. " + "String compression was configured with the C macro 'CYTHON_COMPRESS_STRINGS=%d'.", + module_name, algo); +bad: + Py_XDECREF(module); + Py_DECREF(methodname); + return NULL; +#endif +} + +/* DecompressString_LZSS */ +#ifndef __Pyx_DecompressString_LZSS_UNUSED +CYTHON_UNUSED +static CYTHON_SMALL_CODE size_t __pyx_lzss_decompress(const uint8_t* src, uint8_t* dst, size_t dst_len) { + size_t pos = 0, out_pos = 0; + while (1) { + uint32_t flags = src[pos++] | 0xFF00; + while (flags & 0x100) { + if (flags & 1) { + dst[out_pos++] = src[pos++]; + } else { + uint32_t lo = src[pos++], hi = src[pos++]; + uint32_t end_offset_of_last_occurrence, match_length; + if (!(lo & 0x80)) { + end_offset_of_last_occurrence = lo; + match_length = hi; + } else if (!(hi & 0x80)) { + end_offset_of_last_occurrence = 0x80 + (((hi << 2) & 0x180) | (lo & 0x7F)); + match_length = hi & 0x1F; + } else { + end_offset_of_last_occurrence = 0x80 + ((hi & 0x7F) << 7 | (lo & 0x7F)); + match_length = src[pos++]; + } + match_length += 3; + size_t ref_pos = out_pos - end_offset_of_last_occurrence - match_length; + memcpy(dst + out_pos, dst + ref_pos, match_length); + out_pos += match_length; + } + if (out_pos >= dst_len) return pos; + flags >>= 1; + } + } +} +#endif +static CYTHON_SMALL_CODE PyObject *__Pyx_DecompressString_LZSS(const char *s, size_t compressed_length, size_t uncompressed_length) { +#ifdef __Pyx_DecompressString_LZSS_UNUSED + CYTHON_UNUSED_VAR(s); + CYTHON_UNUSED_VAR(compressed_length); + CYTHON_UNUSED_VAR(uncompressed_length); + return NULL; +#else + PyObject *result; + unsigned char *result_data; + size_t src_length; + result = PyBytes_FromStringAndSize(NULL, (Py_ssize_t) uncompressed_length); + if (unlikely(!result)) return NULL; + result_data = __Pyx_PyBytes_AsWritableUString(result); + if (unlikely(!result_data)) goto bad; + src_length = __pyx_lzss_decompress((const uint8_t*) s, result_data, uncompressed_length); + if (unlikely(src_length != compressed_length)) goto decompression_failed; + return result; +decompression_failed: + PyErr_SetString(PyExc_RuntimeError, "LZSS string data decompression failed"); +bad: + Py_DECREF(result); + return NULL; +#endif +} + +#include +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s) { + size_t len = strlen(s); + if (unlikely(len > (size_t) PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, "byte string is too long"); + return -1; + } + return (Py_ssize_t) len; +} +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return __Pyx_PyUnicode_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return PyByteArray_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 +static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + { + const char* result; + Py_ssize_t unicode_length; + CYTHON_MAYBE_UNUSED_VAR(unicode_length); // only for __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + if (unlikely(PyArg_Parse(o, "s#", &result, length) < 0)) return NULL; + #else + result = PyUnicode_AsUTF8AndSize(o, length); + #endif + #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + unicode_length = PyUnicode_GetLength(o); + if (unlikely(unicode_length < 0)) return NULL; + if (unlikely(unicode_length != *length)) { + PyUnicode_AsASCIIString(o); + return NULL; + } + #endif + return result; + } +#else +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (likely(PyUnicode_IS_ASCII(o))) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif +} +#endif +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + if (PyUnicode_Check(o)) { + return __Pyx_PyUnicode_AsStringAndSize(o, length); + } else +#endif + if (PyByteArray_Check(o)) { +#if (CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) || (CYTHON_COMPILING_IN_PYPY && (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))) + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); +#else + *length = PyByteArray_Size(o); + if (*length == -1) return NULL; + return PyByteArray_AsString(o); +#endif + } else + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { + int retval; + if (unlikely(!x)) return -1; + retval = __Pyx_PyObject_IsTrue(x); + Py_DECREF(x); + return retval; +} +static PyObject* __Pyx_PyNumber_LongWrongResultType(PyObject* result) { + __Pyx_TypeName result_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(result)); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 + if (unlikely(!result_type_name)) goto bad; + #endif + if (PyLong_Check(result)) { + if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME "). " + "The ability to return an instance of a strict subclass of int is deprecated, " + "and may be removed in a future version of Python.", + result_type_name)) { + __Pyx_DECREF_TypeName(result_type_name); + goto bad; + } + __Pyx_DECREF_TypeName(result_type_name); + return result; + } + PyErr_Format(PyExc_TypeError, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME ")", + result_type_name); + __Pyx_DECREF_TypeName(result_type_name); +bad: + Py_DECREF(result); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x) { +#if CYTHON_USE_TYPE_SLOTS + PyNumberMethods *m; +#endif + PyObject *res = NULL; + if (likely(PyLong_Check(x))) + return __Pyx_NewRef(x); +#if CYTHON_USE_TYPE_SLOTS + m = Py_TYPE(x)->tp_as_number; + if (likely(m && m->nb_int)) { + res = m->nb_int(x); + } +#else + if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { + res = PyNumber_Long(x); + } +#endif + if (likely(res)) { + if (unlikely(!PyLong_CheckExact(res))) { + return __Pyx_PyNumber_LongWrongResultType(res); + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyLong_AsSsize_t(PyObject* b) { + #if CYTHON_USE_PYLONG_INTERNALS + Py_ssize_t ival; + const Py_ssize_t size = __Pyx_PyLong_DigitCount(b); + const int is_neg = __Pyx_PyLong_IsNeg(b); + const digit* digits = __Pyx_PyLong_Digits(b); + if (size == 0) return 0; + #if SIZEOF_SIZE_T * 8 > 1 * PyLong_SHIFT + if (size == 1) { + ival = (Py_ssize_t) (((size_t)digits[0])); + } else + #endif + #if SIZEOF_SIZE_T * 8 > 2 * PyLong_SHIFT + if (size == 2) { + ival = (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } else + #endif + #if SIZEOF_SIZE_T * 8 > 3 * PyLong_SHIFT + if (size == 3) { + ival = (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } else + #endif + #if SIZEOF_SIZE_T * 8 > 4 * PyLong_SHIFT + if (size == 4) { + ival = (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } else + #endif + return PyLong_AsSsize_t(b); + return is_neg ? -ival : ival; + #else + return PyLong_AsSsize_t(b); + #endif +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + if (likely(PyLong_Check(b))) { + return __Pyx_PyLong_AsSsize_t(b); + } else { + Py_ssize_t ival; + PyObject *x = PyNumber_Index(b); + if (unlikely(!x)) return -1; + ival = __Pyx_PyLong_AsSsize_t(x); + Py_DECREF(x); + return ival; + } +} +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { + if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { + return (Py_hash_t) __Pyx_PyIndex_AsSsize_t(o); + } else { + Py_ssize_t ival; + PyObject *x; + x = PyNumber_Index(o); + if (!x) return -1; + ival = PyLong_AsLong(x); + Py_DECREF(x); + return ival; + } +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b) { + CYTHON_UNUSED_VAR(b); + return __Pyx_NewRef(Py_None); +} +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { + return __Pyx_NewRef(b ? Py_True: Py_False); +} +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t ival) { + return PyLong_FromSize_t(ival); +} + + +/* MultiPhaseInitModuleState */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +#ifndef CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#if (CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX >= 0x030C0000) + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 1 +#else + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 0 +#endif +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE && !CYTHON_ATOMICS +#error "Module state with PEP489 requires atomics. Currently that's one of\ + C11, C++11, gcc atomic intrinsics or MSVC atomic intrinsics" +#endif +#if !CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#define __Pyx_ModuleStateLookup_Lock() +#define __Pyx_ModuleStateLookup_Unlock() +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 +static PyMutex __Pyx_ModuleStateLookup_mutex = {0}; +#define __Pyx_ModuleStateLookup_Lock() PyMutex_Lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() PyMutex_Unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(__cplusplus) && __cplusplus >= 201103L +#include +static std::mutex __Pyx_ModuleStateLookup_mutex; +#define __Pyx_ModuleStateLookup_Lock() __Pyx_ModuleStateLookup_mutex.lock() +#define __Pyx_ModuleStateLookup_Unlock() __Pyx_ModuleStateLookup_mutex.unlock() +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ > 201112L) && !defined(__STDC_NO_THREADS__) +#include +static mtx_t __Pyx_ModuleStateLookup_mutex; +static once_flag __Pyx_ModuleStateLookup_mutex_once_flag = ONCE_FLAG_INIT; +static void __Pyx_ModuleStateLookup_initialize_mutex(void) { + mtx_init(&__Pyx_ModuleStateLookup_mutex, mtx_plain); +} +#define __Pyx_ModuleStateLookup_Lock()\ + call_once(&__Pyx_ModuleStateLookup_mutex_once_flag, __Pyx_ModuleStateLookup_initialize_mutex);\ + mtx_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() mtx_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(HAVE_PTHREAD_H) +#include +static pthread_mutex_t __Pyx_ModuleStateLookup_mutex = PTHREAD_MUTEX_INITIALIZER; +#define __Pyx_ModuleStateLookup_Lock() pthread_mutex_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() pthread_mutex_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(_WIN32) +#include // synchapi.h on its own doesn't work +static SRWLOCK __Pyx_ModuleStateLookup_mutex = SRWLOCK_INIT; +#define __Pyx_ModuleStateLookup_Lock() AcquireSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() ReleaseSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#else +#error "No suitable lock available for CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE.\ + Requires C standard >= C11, or C++ standard >= C++11,\ + or pthreads, or the Windows 32 API, or Python >= 3.13." +#endif +typedef struct { + int64_t id; + PyObject *module; +} __Pyx_InterpreterIdAndModule; +typedef struct { + char interpreter_id_as_index; + Py_ssize_t count; + Py_ssize_t allocated; + __Pyx_InterpreterIdAndModule table[1]; +} __Pyx_ModuleStateLookupData; +#define __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE 32 +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_int_type __Pyx_ModuleStateLookup_read_counter = 0; +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_ptr_type __Pyx_ModuleStateLookup_data = 0; +#else +static __Pyx_ModuleStateLookupData* __Pyx_ModuleStateLookup_data = NULL; +#endif +static __Pyx_InterpreterIdAndModule* __Pyx_State_FindModuleStateLookupTableLowerBound( + __Pyx_InterpreterIdAndModule* table, + Py_ssize_t count, + int64_t interpreterId) { + __Pyx_InterpreterIdAndModule* begin = table; + __Pyx_InterpreterIdAndModule* end = begin + count; + if (begin->id == interpreterId) { + return begin; + } + while ((end - begin) > __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + __Pyx_InterpreterIdAndModule* halfway = begin + (end - begin)/2; + if (halfway->id == interpreterId) { + return halfway; + } + if (halfway->id < interpreterId) { + begin = halfway; + } else { + end = halfway; + } + } + for (; begin < end; ++begin) { + if (begin->id >= interpreterId) return begin; + } + return begin; +} +static PyObject *__Pyx_State_FindModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(PyInterpreterState_Get()); + if (interpreter_id == -1) return NULL; +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData* data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + { + __pyx_atomic_incr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + if (likely(data)) { + __Pyx_ModuleStateLookupData* new_data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_acquire(&__Pyx_ModuleStateLookup_data); + if (likely(data == new_data)) { + goto read_finished; + } + } + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + __Pyx_ModuleStateLookup_Lock(); + __pyx_atomic_incr_relaxed(&__Pyx_ModuleStateLookup_read_counter); + data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + __Pyx_ModuleStateLookup_Unlock(); + } + read_finished:; +#else + __Pyx_ModuleStateLookupData* data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_InterpreterIdAndModule* found = NULL; + if (unlikely(!data)) goto end; + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + found = data->table+interpreter_id; + } + } else { + found = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + } + end: + { + PyObject *result=NULL; + if (found && found->id == interpreter_id) { + result = found->module; + } +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); +#endif + return result; + } +} +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static void __Pyx_ModuleStateLookup_wait_until_no_readers(void) { + while (__pyx_atomic_load(&__Pyx_ModuleStateLookup_read_counter) != 0); +} +#else +#define __Pyx_ModuleStateLookup_wait_until_no_readers() +#endif +static int __Pyx_State_AddModuleInterpIdAsIndex(__Pyx_ModuleStateLookupData **old_data, PyObject* module, int64_t interpreter_id) { + Py_ssize_t to_allocate = (*old_data)->allocated; + while (to_allocate <= interpreter_id) { + if (to_allocate == 0) to_allocate = 1; + else to_allocate *= 2; + } + __Pyx_ModuleStateLookupData *new_data = *old_data; + if (to_allocate != (*old_data)->allocated) { + new_data = (__Pyx_ModuleStateLookupData *)realloc( + *old_data, + sizeof(__Pyx_ModuleStateLookupData)+(to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + PyErr_NoMemory(); + return -1; + } + for (Py_ssize_t i = new_data->allocated; i < to_allocate; ++i) { + new_data->table[i].id = i; + new_data->table[i].module = NULL; + } + new_data->allocated = to_allocate; + } + new_data->table[interpreter_id].module = module; + if (new_data->count < interpreter_id+1) { + new_data->count = interpreter_id+1; + } + *old_data = new_data; + return 0; +} +static void __Pyx_State_ConvertFromInterpIdAsIndex(__Pyx_ModuleStateLookupData *data) { + __Pyx_InterpreterIdAndModule *read = data->table; + __Pyx_InterpreterIdAndModule *write = data->table; + __Pyx_InterpreterIdAndModule *end = read + data->count; + for (; readmodule) { + write->id = read->id; + write->module = read->module; + ++write; + } + } + data->count = write - data->table; + for (; writeid = 0; + write->module = NULL; + } + data->interpreter_id_as_index = 0; +} +static int __Pyx_State_AddModule(PyObject* module, CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + int result = 0; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *old_data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *old_data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_ModuleStateLookupData *new_data = old_data; + if (!new_data) { + new_data = (__Pyx_ModuleStateLookupData *)calloc(1, sizeof(__Pyx_ModuleStateLookupData)); + if (!new_data) { + result = -1; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = 1; + new_data->interpreter_id_as_index = 1; + } + __Pyx_ModuleStateLookup_wait_until_no_readers(); + if (new_data->interpreter_id_as_index) { + if (interpreter_id < __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + result = __Pyx_State_AddModuleInterpIdAsIndex(&new_data, module, interpreter_id); + goto end; + } + __Pyx_State_ConvertFromInterpIdAsIndex(new_data); + } + { + Py_ssize_t insert_at = 0; + { + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + new_data->table, new_data->count, interpreter_id); + assert(lower_bound); + insert_at = lower_bound - new_data->table; + if (unlikely(insert_at < new_data->count && lower_bound->id == interpreter_id)) { + lower_bound->module = module; + goto end; // already in table, nothing more to do + } + } + if (new_data->count+1 >= new_data->allocated) { + Py_ssize_t to_allocate = (new_data->count+1)*2; + new_data = + (__Pyx_ModuleStateLookupData*)realloc( + new_data, + sizeof(__Pyx_ModuleStateLookupData) + + (to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + result = -1; + new_data = old_data; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = to_allocate; + } + ++new_data->count; + int64_t last_id = interpreter_id; + PyObject *last_module = module; + for (Py_ssize_t i=insert_at; icount; ++i) { + int64_t current_id = new_data->table[i].id; + new_data->table[i].id = last_id; + last_id = current_id; + PyObject *current_module = new_data->table[i].module; + new_data->table[i].module = last_module; + last_module = current_module; + } + } + end: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, new_data); +#else + __Pyx_ModuleStateLookup_data = new_data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return result; +} +static int __Pyx_State_RemoveModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *data = __Pyx_ModuleStateLookup_data; +#endif + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + data->table[interpreter_id].module = NULL; + } + goto done; + } + { + __Pyx_ModuleStateLookup_wait_until_no_readers(); + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + if (!lower_bound) goto done; + if (lower_bound->id != interpreter_id) goto done; + __Pyx_InterpreterIdAndModule *end = data->table+data->count; + for (;lower_boundid = (lower_bound+1)->id; + lower_bound->module = (lower_bound+1)->module; + } + } + --data->count; + if (data->count == 0) { + free(data); + data = NULL; + } + done: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, data); +#else + __Pyx_ModuleStateLookup_data = data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return 0; +} +#endif + +/* #### Code section: utility_code_pragmas_end ### */ +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + + + +/* #### Code section: end ### */ +#endif /* Py_PYTHON_H */ diff --git a/shared/package-files/71/715ea55a1ef4994fd6e6e04397f572c1922e80825a440bbd221a10d91b61ce3a/edgelist.py b/shared/package-files/71/715ea55a1ef4994fd6e6e04397f572c1922e80825a440bbd221a10d91b61ce3a/edgelist.py new file mode 100644 index 0000000000000000000000000000000000000000..558cbaea903859a2c651beb00e9b91f78696fbfb --- /dev/null +++ b/shared/package-files/71/715ea55a1ef4994fd6e6e04397f572c1922e80825a440bbd221a10d91b61ce3a/edgelist.py @@ -0,0 +1,486 @@ +""" +********** +Edge Lists +********** +Read and write NetworkX graphs as edge lists. + +The multi-line adjacency list format is useful for graphs with nodes +that can be meaningfully represented as strings. With the edgelist +format simple edge data can be stored but node or graph data is not. +There is no way of representing isolated nodes unless the node has a +self-loop edge. + +Format +------ +You can read or write three formats of edge lists with these functions. + +Node pairs with no data:: + + 1 2 + +Python dictionary as data:: + + 1 2 {'weight':7, 'color':'green'} + +Arbitrary data:: + + 1 2 7 green +""" + +__all__ = [ + "generate_edgelist", + "write_edgelist", + "parse_edgelist", + "read_edgelist", + "read_weighted_edgelist", + "write_weighted_edgelist", +] + +import networkx as nx +from networkx.utils import open_file + + +def generate_edgelist(G, delimiter=" ", data=True): + """Generate a single line of the graph G in edge list format. + + Parameters + ---------- + G : NetworkX graph + + delimiter : string, optional + Separator for node labels + + data : bool or list of keys + If False generate no edge data. If True use a dictionary + representation of edge data. If a list of keys use a list of data + values corresponding to the keys. + + Returns + ------- + lines : string + Lines of data in adjlist format. + + Examples + -------- + >>> G = nx.lollipop_graph(4, 3) + >>> G[1][2]["weight"] = 3 + >>> G[3][4]["capacity"] = 12 + >>> for line in nx.generate_edgelist(G, data=False): + ... print(line) + 0 1 + 0 2 + 0 3 + 1 2 + 1 3 + 2 3 + 3 4 + 4 5 + 5 6 + + >>> for line in nx.generate_edgelist(G): + ... print(line) + 0 1 {} + 0 2 {} + 0 3 {} + 1 2 {'weight': 3} + 1 3 {} + 2 3 {} + 3 4 {'capacity': 12} + 4 5 {} + 5 6 {} + + >>> for line in nx.generate_edgelist(G, data=["weight"]): + ... print(line) + 0 1 + 0 2 + 0 3 + 1 2 3 + 1 3 + 2 3 + 3 4 + 4 5 + 5 6 + + See Also + -------- + write_adjlist, read_adjlist + """ + if data is True: + for u, v, d in G.edges(data=True): + e = u, v, dict(d) + yield delimiter.join(map(str, e)) + elif data is False: + for u, v in G.edges(data=False): + e = u, v + yield delimiter.join(map(str, e)) + else: + for u, v, d in G.edges(data=True): + e = [u, v] + try: + e.extend(d[k] for k in data) + except KeyError: + pass # missing data for this edge, should warn? + yield delimiter.join(map(str, e)) + + +@open_file(1, mode="wb") +def write_edgelist(G, path, comments="#", delimiter=" ", data=True, encoding="utf-8"): + """Write graph as a list of edges. + + Parameters + ---------- + G : graph + A NetworkX graph + path : file or string + File or filename to write. If a file is provided, it must be + opened in 'wb' mode. Filenames ending in .gz or .bz2 will be compressed. + comments : string, optional + The character used to indicate the start of a comment + delimiter : string, optional + The string used to separate values. The default is whitespace. + data : bool or list, optional + If False write no edge data. + If True write a string representation of the edge data dictionary.. + If a list (or other iterable) is provided, write the keys specified + in the list. + encoding: string, optional + Specify which encoding to use when writing file. + + Examples + -------- + >>> G = nx.path_graph(4) + >>> nx.write_edgelist(G, "test.edgelist") + >>> G = nx.path_graph(4) + >>> fh = open("test.edgelist", "wb") + >>> nx.write_edgelist(G, fh) + >>> nx.write_edgelist(G, "test.edgelist.gz") + >>> nx.write_edgelist(G, "test.edgelist.gz", data=False) + + >>> G = nx.Graph() + >>> G.add_edge(1, 2, weight=7, color="red") + >>> nx.write_edgelist(G, "test.edgelist", data=False) + >>> nx.write_edgelist(G, "test.edgelist", data=["color"]) + >>> nx.write_edgelist(G, "test.edgelist", data=["color", "weight"]) + + See Also + -------- + read_edgelist + write_weighted_edgelist + """ + + for line in generate_edgelist(G, delimiter, data): + line += "\n" + path.write(line.encode(encoding)) + + +def parse_edgelist( + lines, comments="#", delimiter=None, create_using=None, nodetype=None, data=True +): + """Parse lines of an edge list representation of a graph. + + Parameters + ---------- + lines : list or iterator of strings + Input data in edgelist format + comments : string, optional + Marker for comment lines. Default is `'#'`. To specify that no character + should be treated as a comment, use ``comments=None``. + delimiter : string, optional + Separator for node labels. Default is `None`, meaning any whitespace. + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + nodetype : Python type, optional + Convert nodes to this type. Default is `None`, meaning no conversion is + performed. + data : bool or list of (label,type) tuples + If `False` generate no edge data or if `True` use a dictionary + representation of edge data or a list tuples specifying dictionary + key names and types for edge data. + + Returns + ------- + G: NetworkX Graph + The graph corresponding to lines + + Examples + -------- + Edgelist with no data: + + >>> lines = ["1 2", "2 3", "3 4"] + >>> G = nx.parse_edgelist(lines, nodetype=int) + >>> list(G) + [1, 2, 3, 4] + >>> list(G.edges()) + [(1, 2), (2, 3), (3, 4)] + + Edgelist with data in Python dictionary representation: + + >>> lines = ["1 2 {'weight': 3}", "2 3 {'weight': 27}", "3 4 {'weight': 3.0}"] + >>> G = nx.parse_edgelist(lines, nodetype=int) + >>> list(G) + [1, 2, 3, 4] + >>> list(G.edges(data=True)) + [(1, 2, {'weight': 3}), (2, 3, {'weight': 27}), (3, 4, {'weight': 3.0})] + + Edgelist with data in a list: + + >>> lines = ["1 2 3", "2 3 27", "3 4 3.0"] + >>> G = nx.parse_edgelist(lines, nodetype=int, data=(("weight", float),)) + >>> list(G) + [1, 2, 3, 4] + >>> list(G.edges(data=True)) + [(1, 2, {'weight': 3.0}), (2, 3, {'weight': 27.0}), (3, 4, {'weight': 3.0})] + + See Also + -------- + read_weighted_edgelist + """ + from ast import literal_eval + + G = nx.empty_graph(0, create_using) + for line in lines: + if comments is not None: + p = line.find(comments) + if p >= 0: + line = line[:p] + if not line: + continue + # split line, should have 2 or more + s = line.strip().split(delimiter) + if len(s) < 2: + continue + u = s.pop(0) + v = s.pop(0) + d = s + if nodetype is not None: + try: + u = nodetype(u) + v = nodetype(v) + except Exception as err: + raise TypeError( + f"Failed to convert nodes {u},{v} to type {nodetype}." + ) from err + + if len(d) == 0 or data is False: + # no data or data type specified + edgedata = {} + elif data is True: + # no edge types specified + try: # try to evaluate as dictionary + if delimiter == ",": + edgedata_str = ",".join(d) + else: + edgedata_str = " ".join(d) + edgedata = dict(literal_eval(edgedata_str.strip())) + except Exception as err: + raise TypeError( + f"Failed to convert edge data ({d}) to dictionary." + ) from err + else: + # convert edge data to dictionary with specified keys and type + if len(d) != len(data): + raise IndexError( + f"Edge data {d} and data_keys {data} are not the same length" + ) + edgedata = {} + for (edge_key, edge_type), edge_value in zip(data, d): + try: + edge_value = edge_type(edge_value) + except Exception as err: + raise TypeError( + f"Failed to convert {edge_key} data {edge_value} " + f"to type {edge_type}." + ) from err + edgedata.update({edge_key: edge_value}) + G.add_edge(u, v, **edgedata) + return G + + +@open_file(0, mode="rb") +def read_edgelist( + path, + comments="#", + delimiter=None, + create_using=None, + nodetype=None, + data=True, + edgetype=None, + encoding="utf-8", +): + """Read a graph from a list of edges. + + Parameters + ---------- + path : file or string + File or filename to read. If a file is provided, it must be + opened in 'rb' mode. + Filenames ending in .gz or .bz2 will be uncompressed. + comments : string, optional + The character used to indicate the start of a comment. To specify that + no character should be treated as a comment, use ``comments=None``. + delimiter : string, optional + The string used to separate values. The default is whitespace. + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + nodetype : int, float, str, Python type, optional + Convert node data from strings to specified type + data : bool or list of (label,type) tuples + Tuples specifying dictionary key names and types for edge data + edgetype : int, float, str, Python type, optional OBSOLETE + Convert edge data from strings to specified type and use as 'weight' + encoding: string, optional + Specify which encoding to use when reading file. + + Returns + ------- + G : graph + A networkx Graph or other type specified with create_using + + Examples + -------- + >>> nx.write_edgelist(nx.path_graph(4), "test.edgelist") + >>> G = nx.read_edgelist("test.edgelist") + + >>> fh = open("test.edgelist", "rb") + >>> G = nx.read_edgelist(fh) + >>> fh.close() + + >>> G = nx.read_edgelist("test.edgelist", nodetype=int) + >>> G = nx.read_edgelist("test.edgelist", create_using=nx.DiGraph) + + Edgelist with data in a list: + + >>> textline = "1 2 3" + >>> fh = open("test.edgelist", "w") + >>> d = fh.write(textline) + >>> fh.close() + >>> G = nx.read_edgelist("test.edgelist", nodetype=int, data=(("weight", float),)) + >>> list(G) + [1, 2] + >>> list(G.edges(data=True)) + [(1, 2, {'weight': 3.0})] + + See parse_edgelist() for more examples of formatting. + + See Also + -------- + parse_edgelist + write_edgelist + + Notes + ----- + Since nodes must be hashable, the function nodetype must return hashable + types (e.g. int, float, str, frozenset - or tuples of those, etc.) + """ + lines = (line if isinstance(line, str) else line.decode(encoding) for line in path) + return parse_edgelist( + lines, + comments=comments, + delimiter=delimiter, + create_using=create_using, + nodetype=nodetype, + data=data, + ) + + +def write_weighted_edgelist(G, path, comments="#", delimiter=" ", encoding="utf-8"): + """Write graph G as a list of edges with numeric weights. + + Parameters + ---------- + G : graph + A NetworkX graph + path : file or string + File or filename to write. If a file is provided, it must be + opened in 'wb' mode. + Filenames ending in .gz or .bz2 will be compressed. + comments : string, optional + The character used to indicate the start of a comment + delimiter : string, optional + The string used to separate values. The default is whitespace. + encoding: string, optional + Specify which encoding to use when writing file. + + Examples + -------- + >>> G = nx.Graph() + >>> G.add_edge(1, 2, weight=7) + >>> nx.write_weighted_edgelist(G, "test.weighted.edgelist") + + See Also + -------- + read_edgelist + write_edgelist + read_weighted_edgelist + """ + write_edgelist( + G, + path, + comments=comments, + delimiter=delimiter, + data=("weight",), + encoding=encoding, + ) + + +def read_weighted_edgelist( + path, + comments="#", + delimiter=None, + create_using=None, + nodetype=None, + encoding="utf-8", +): + """Read a graph as list of edges with numeric weights. + + Parameters + ---------- + path : file or string + File or filename to read. If a file is provided, it must be + opened in 'rb' mode. + Filenames ending in .gz or .bz2 will be uncompressed. + comments : string, optional + The character used to indicate the start of a comment. + delimiter : string, optional + The string used to separate values. The default is whitespace. + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + nodetype : int, float, str, Python type, optional + Convert node data from strings to specified type + encoding: string, optional + Specify which encoding to use when reading file. + + Returns + ------- + G : graph + A networkx Graph or other type specified with create_using + + Notes + ----- + Since nodes must be hashable, the function nodetype must return hashable + types (e.g. int, float, str, frozenset - or tuples of those, etc.) + + Example edgelist file format. + + With numeric edge data:: + + # read with + # >>> G=nx.read_weighted_edgelist(fh) + # source target data + a b 1 + a c 3.14159 + d e 42 + + See Also + -------- + write_weighted_edgelist + """ + return read_edgelist( + path, + comments=comments, + delimiter=delimiter, + create_using=create_using, + nodetype=nodetype, + data=(("weight", float),), + encoding=encoding, + ) diff --git a/shared/package-files/71/71657412b15519240704dad8c0ad03baec7b0fcbaf06f3fba11534cef4ce2bdc/dynamic_type.h b/shared/package-files/71/71657412b15519240704dad8c0ad03baec7b0fcbaf06f3fba11534cef4ce2bdc/dynamic_type.h new file mode 100644 index 0000000000000000000000000000000000000000..ecfb6a999bc2e29e41660a819e82276398a9041b --- /dev/null +++ b/shared/package-files/71/71657412b15519240704dad8c0ad03baec7b0fcbaf06f3fba11534cef4ce2bdc/dynamic_type.h @@ -0,0 +1,239 @@ +#pragma once + +#include +#include +#include + +#include +#include + +namespace c10 { + +using DynamicTypeBits = std::uint32_t; +#define DYNAMIC_TYPE_BIT(x) (1u << x) + +constexpr DynamicTypeBits kDynamicCovariantTypeBit = DYNAMIC_TYPE_BIT(31); +constexpr DynamicTypeBits kDynamicAnyTypeBit = DYNAMIC_TYPE_BIT(30); + +constexpr DynamicTypeBits kDynamicNoneTypeBit = DYNAMIC_TYPE_BIT(1); +constexpr DynamicTypeBits kDynamicIntTypeBit = DYNAMIC_TYPE_BIT(3); +constexpr DynamicTypeBits kDynamicFloatTypeBit = DYNAMIC_TYPE_BIT(4); +constexpr DynamicTypeBits kDynamicComplexTypeBit = DYNAMIC_TYPE_BIT(5); +constexpr DynamicTypeBits kDynamicListTypeBit = DYNAMIC_TYPE_BIT(7); +constexpr DynamicTypeBits kDynamicTupleTypeBit = DYNAMIC_TYPE_BIT(8); +constexpr DynamicTypeBits kDynamicClassTypeBit = DYNAMIC_TYPE_BIT(10); + +#define FORALL_DYNAMIC_TYPES(_) \ + _(Tensor, DYNAMIC_TYPE_BIT(0), 1) \ + _(None, kDynamicNoneTypeBit, 1) \ + _(Bool, DYNAMIC_TYPE_BIT(2), 1) \ + _(Int, kDynamicIntTypeBit, 1) \ + _(Float, kDynamicFloatTypeBit, 1) \ + _(Complex, kDynamicComplexTypeBit, 1) \ + _(Number, \ + (kDynamicIntTypeBit | kDynamicFloatTypeBit | kDynamicComplexTypeBit), \ + 1) \ + _(String, DYNAMIC_TYPE_BIT(6), 1) \ + _(List, kDynamicListTypeBit, 0) \ + _(Tuple, (kDynamicTupleTypeBit | kDynamicCovariantTypeBit), 0) \ + _(Dict, DYNAMIC_TYPE_BIT(9), 0) \ + _(Class, kDynamicClassTypeBit, 0) \ + _(Optional, \ + (DYNAMIC_TYPE_BIT(11) | kDynamicNoneTypeBit | kDynamicCovariantTypeBit), \ + 0) \ + _(AnyList, (kDynamicListTypeBit | kDynamicAnyTypeBit), 1) \ + _(AnyTuple, \ + (kDynamicTupleTypeBit | kDynamicCovariantTypeBit | kDynamicAnyTypeBit), \ + 1) \ + _(DeviceObj, DYNAMIC_TYPE_BIT(12), 1) \ + _(StreamObj, DYNAMIC_TYPE_BIT(13), 1) \ + _(Capsule, DYNAMIC_TYPE_BIT(14), 1) \ + _(Generator, DYNAMIC_TYPE_BIT(15), 1) \ + _(Storage, DYNAMIC_TYPE_BIT(16), 1) \ + _(Var, DYNAMIC_TYPE_BIT(17), 0) \ + _(AnyClass, (kDynamicClassTypeBit | kDynamicAnyTypeBit), 1) \ + _(QScheme, DYNAMIC_TYPE_BIT(18), 1) \ + _(Quantizer, DYNAMIC_TYPE_BIT(19), 1) \ + _(AnyEnum, DYNAMIC_TYPE_BIT(20), 1) \ + _(RRef, DYNAMIC_TYPE_BIT(21), 0) \ + _(Future, DYNAMIC_TYPE_BIT(22), 0) \ + _(Await, DYNAMIC_TYPE_BIT(23), 0) \ + _(Any, 0xffffffff, 1) + +#define FORALL_DYNAMIC_TYPES_FAKE(_) \ + _(ScalarType, kDynamicIntTypeBit, 1) \ + _(Layout, kDynamicIntTypeBit, 1) \ + _(SymInt, kDynamicIntTypeBit, 1) \ + _(MemoryFormat, kDynamicIntTypeBit, 1) + +#define FORWARD_DECL_TYPE(NAME, _, __) struct NAME ## Type; + FORALL_DYNAMIC_TYPES(FORWARD_DECL_TYPE) + FORALL_DYNAMIC_TYPES_FAKE(FORWARD_DECL_TYPE) +#undef FORWARD_DECL_TYPE + +class DynamicType; +using DynamicTypePtr = std::shared_ptr; + +/** + * DynamicType is designed as a low dependency type system for TorchScript. The + * existing JIT types are used for both compilation and runtime, which makes + * sense for server contexts because we often compile and run the model in + * the same process, however this doesn't hold for mobile devices where we + * always compiles a model ahead of time, therefore there will be dependencies + * which are not needed, but built with mobile runtime causing binary size + * bloat, by design. Every basic type like Int, Bool or String will bring their + * vtable, typeinfo, constructor, destructor and even more data from their + * specializations for STL types to the binary causing a long tail bloat. + * + * The core problem is about the complexity to implement and maintain a single + * type system for both analysis and execution purposes. Although they should + * have the exactly same semantics, in practice implement a unified abstraction + * adds conceptual and representational overhead for both sides of the world. + * + * To address the issues, DynamicType implements a minimal subset of JIT types + * and uses a generic algorithm to test all subtyping relations. To achieve + * this, we assign each dynamic type a single integer tag to represent its + * semantics. More specifically, a dynamic type is defined as a set of "control + * bits" and "data bits", where control bits describe the special behavior when + * testing a type and data bits map to identity of each nominal type. We use bit + * operations to perform all the tests. + * + * For example, a "covariant bit" is a control bit used to describe if a type + * is covariant, right now the most used one is tuple type, and in addition to + * the control bit, tuple type's data bit is the 8th bit from the LSB. Control + * bits start from MSB and data bits start from LSB. + * + * If two types are equal, then they are subtype of each other, also if the bits + * from one type tag is subset of the other tag, it automatically becomes a + * subtype of the other. This simplifies the subtyping logic a lot, and over the + * long term it is possible to adopt this scheme on the server side as well. + * Special cases can be added but they generally should not take too much code + * size. + * + * DynamicType may or may not inherit from c10::Type because it's not the core + * requirement of DynamicType to interface with existing JIT types, but we might + * want to inherit from c10::Type to reduce the migration cost. + */ +class DynamicType : public SharedType { + using ClassTypePtr = std::shared_ptr; + + /** + * A implementation detail to support NamedTuple. + */ + struct LabeledDynamicType { + c10::optional label; + DynamicTypePtr ty; + explicit LabeledDynamicType(DynamicTypePtr t) : ty(std::move(t)) {} + + bool equals(const LabeledDynamicType& other) const; + bool isSubtypeOf(const LabeledDynamicType& other) const; + }; + + public: + // TODO Change Ptr to DynamicTypePtr when all migrations are done. + using Ptr = TypePtr; + using ElementType = DynamicType; + ~DynamicType() override; + + struct Arguments { + Arguments() = default; + Arguments(c10::ArrayRef); + Arguments(const std::vector&, c10::ArrayRef); + std::vector elems; + }; + + enum class Tag : DynamicTypeBits { +#define DYNAMIC_TYPE_ITEM(NAME, VAL, _) NAME = VAL, + FORALL_DYNAMIC_TYPES(DYNAMIC_TYPE_ITEM) + FORALL_DYNAMIC_TYPES_FAKE(DYNAMIC_TYPE_ITEM) +#undef DYNAMIC_TYPE_ITEM + }; + + bool equals(const Type& rhs) const override; + bool isSubtypeOfExt(const Type& rhs, std::ostream* why_not) const override; + std::string str() const override; + static const TypeKind Kind = TypeKind::DynamicType; + static TORCH_API DynamicTypePtr create(Type& ty); + + explicit DynamicType(Tag, Arguments); + explicit DynamicType(Tag, c10::string_view, Arguments); + + TypePtr containedType(size_t) const override; + size_t containedTypeSize() const override; + Tag tag() const { + return tag_; + } + const c10::optional& name() const { + return name_; + } + const Arguments& arguments() const { + return arguments_; + } + TORCH_API TypeKind dynamicKind() const; + + // Should be used only on the server side to restore static type information. +#ifndef C10_MOBILE + TORCH_API +#endif + TypePtr fallback() const; + + private: + bool symmetric() const override { + return false; + } + friend struct Type; + static std::shared_ptr create(const Type& ty); + DynamicType(const Type& other); + bool equals(const DynamicType& other) const; + + template + bool compareArguments(const DynamicType& other, F&& f) const { + if (arguments_.elems.size() != other.arguments_.elems.size()) { + return false; + } + for (size_t i = 0; i < arguments_.elems.size(); i++) { + if (!f(arguments_.elems[i], other.arguments_.elems[i])) { + return false; + } + } + return true; + } + + Tag tag_; + c10::optional name_; + union { + Arguments arguments_; + ClassTypePtr class_; + }; +}; + +template +struct DynamicTypeTrait { + C10_NOINLINE static auto tagValue() { + TORCH_CHECK(false); + return DynamicType::Tag::Any; + } +}; + +namespace detail { +C10_NOINLINE DynamicTypePtr makeBaseType(DynamicType::Tag tag); +} + +#define DYNAMIC_TYPE_TAG_VALUE(NAME, _, IS_BASE_TYPE) \ + template <> \ + struct TORCH_API DynamicTypeTrait { \ + C10_ERASE static auto tagValue() { \ + return DynamicType::Tag::NAME; \ + } \ + static constexpr bool isBaseType = IS_BASE_TYPE; \ + template \ + static std::enable_if_t getBaseType() { \ + static auto type = detail::makeBaseType(tagValue()); \ + return type; \ + } \ + }; // namespace c10 +FORALL_DYNAMIC_TYPES(DYNAMIC_TYPE_TAG_VALUE) +FORALL_DYNAMIC_TYPES_FAKE(DYNAMIC_TYPE_TAG_VALUE) +#undef DYNAMIC_TYPE_TAG_VALUE + +} // namespace c10 diff --git a/shared/package-files/71/7167b521bdfb4fa6721db47afe13eecc08e8b4c9a2df6cbe90307e8b6f22caa1/_afm.py b/shared/package-files/71/7167b521bdfb4fa6721db47afe13eecc08e8b4c9a2df6cbe90307e8b6f22caa1/_afm.py new file mode 100644 index 0000000000000000000000000000000000000000..558efe16392f7d386f642c86a8b028d10a778f25 --- /dev/null +++ b/shared/package-files/71/7167b521bdfb4fa6721db47afe13eecc08e8b4c9a2df6cbe90307e8b6f22caa1/_afm.py @@ -0,0 +1,532 @@ +""" +A python interface to Adobe Font Metrics Files. + +Although a number of other Python implementations exist, and may be more +complete than this, it was decided not to go with them because they were +either: + +1) copyrighted or used a non-BSD compatible license +2) had too many dependencies and a free standing lib was needed +3) did more than needed and it was easier to write afresh rather than + figure out how to get just what was needed. + +It is pretty easy to use, and has no external dependencies: + +>>> import matplotlib as mpl +>>> from pathlib import Path +>>> afm_path = Path(mpl.get_data_path(), 'fonts', 'afm', 'ptmr8a.afm') +>>> +>>> from matplotlib.afm import AFM +>>> with afm_path.open('rb') as fh: +... afm = AFM(fh) +>>> afm.string_width_height('What the heck?') +(6220.0, 694) +>>> afm.get_fontname() +'Times-Roman' +>>> afm.get_kern_dist('A', 'f') +0 +>>> afm.get_kern_dist('A', 'y') +-92.0 +>>> afm.get_bbox_char('!') +[130, -9, 238, 676] + +As in the Adobe Font Metrics File Format Specification, all dimensions +are given in units of 1/1000 of the scale factor (point size) of the font +being used. +""" + +from collections import namedtuple +import logging +import re + +from ._mathtext_data import uni2type1 + + +_log = logging.getLogger(__name__) + + +def _to_int(x): + # Some AFM files have floats where we are expecting ints -- there is + # probably a better way to handle this (support floats, round rather than + # truncate). But I don't know what the best approach is now and this + # change to _to_int should at least prevent Matplotlib from crashing on + # these. JDH (2009-11-06) + return int(float(x)) + + +def _to_float(x): + # Some AFM files use "," instead of "." as decimal separator -- this + # shouldn't be ambiguous (unless someone is wicked enough to use "," as + # thousands separator...). + if isinstance(x, bytes): + # Encoding doesn't really matter -- if we have codepoints >127 the call + # to float() will error anyways. + x = x.decode('latin-1') + return float(x.replace(',', '.')) + + +def _to_str(x): + return x.decode('utf8') + + +def _to_list_of_ints(s): + s = s.replace(b',', b' ') + return [_to_int(val) for val in s.split()] + + +def _to_list_of_floats(s): + return [_to_float(val) for val in s.split()] + + +def _to_bool(s): + if s.lower().strip() in (b'false', b'0', b'no'): + return False + else: + return True + + +def _parse_header(fh): + """ + Read the font metrics header (up to the char metrics) and returns + a dictionary mapping *key* to *val*. *val* will be converted to the + appropriate python type as necessary; e.g.: + + * 'False'->False + * '0'->0 + * '-168 -218 1000 898'-> [-168, -218, 1000, 898] + + Dictionary keys are + + StartFontMetrics, FontName, FullName, FamilyName, Weight, + ItalicAngle, IsFixedPitch, FontBBox, UnderlinePosition, + UnderlineThickness, Version, Notice, EncodingScheme, CapHeight, + XHeight, Ascender, Descender, StartCharMetrics + """ + header_converters = { + b'StartFontMetrics': _to_float, + b'FontName': _to_str, + b'FullName': _to_str, + b'FamilyName': _to_str, + b'Weight': _to_str, + b'ItalicAngle': _to_float, + b'IsFixedPitch': _to_bool, + b'FontBBox': _to_list_of_ints, + b'UnderlinePosition': _to_float, + b'UnderlineThickness': _to_float, + b'Version': _to_str, + # Some AFM files have non-ASCII characters (which are not allowed by + # the spec). Given that there is actually no public API to even access + # this field, just return it as straight bytes. + b'Notice': lambda x: x, + b'EncodingScheme': _to_str, + b'CapHeight': _to_float, # Is the second version a mistake, or + b'Capheight': _to_float, # do some AFM files contain 'Capheight'? -JKS + b'XHeight': _to_float, + b'Ascender': _to_float, + b'Descender': _to_float, + b'StdHW': _to_float, + b'StdVW': _to_float, + b'StartCharMetrics': _to_int, + b'CharacterSet': _to_str, + b'Characters': _to_int, + } + d = {} + first_line = True + for line in fh: + line = line.rstrip() + if line.startswith(b'Comment'): + continue + lst = line.split(b' ', 1) + key = lst[0] + if first_line: + # AFM spec, Section 4: The StartFontMetrics keyword + # [followed by a version number] must be the first line in + # the file, and the EndFontMetrics keyword must be the + # last non-empty line in the file. We just check the + # first header entry. + if key != b'StartFontMetrics': + raise RuntimeError('Not an AFM file') + first_line = False + if len(lst) == 2: + val = lst[1] + else: + val = b'' + try: + converter = header_converters[key] + except KeyError: + _log.error("Found an unknown keyword in AFM header (was %r)", key) + continue + try: + d[key] = converter(val) + except ValueError: + _log.error('Value error parsing header in AFM: %s, %s', key, val) + continue + if key == b'StartCharMetrics': + break + else: + raise RuntimeError('Bad parse') + return d + + +CharMetrics = namedtuple('CharMetrics', 'width, name, bbox') +CharMetrics.__doc__ = """ + Represents the character metrics of a single character. + + Notes + ----- + The fields do currently only describe a subset of character metrics + information defined in the AFM standard. + """ +CharMetrics.width.__doc__ = """The character width (WX).""" +CharMetrics.name.__doc__ = """The character name (N).""" +CharMetrics.bbox.__doc__ = """ + The bbox of the character (B) as a tuple (*llx*, *lly*, *urx*, *ury*).""" + + +def _parse_char_metrics(fh): + """ + Parse the given filehandle for character metrics information and return + the information as dicts. + + It is assumed that the file cursor is on the line behind + 'StartCharMetrics'. + + Returns + ------- + ascii_d : dict + A mapping "ASCII num of the character" to `.CharMetrics`. + name_d : dict + A mapping "character name" to `.CharMetrics`. + + Notes + ----- + This function is incomplete per the standard, but thus far parses + all the sample afm files tried. + """ + required_keys = {'C', 'WX', 'N', 'B'} + + ascii_d = {} + name_d = {} + for line in fh: + # We are defensively letting values be utf8. The spec requires + # ascii, but there are non-compliant fonts in circulation + line = _to_str(line.rstrip()) # Convert from byte-literal + if line.startswith('EndCharMetrics'): + return ascii_d, name_d + # Split the metric line into a dictionary, keyed by metric identifiers + vals = dict(s.strip().split(' ', 1) for s in line.split(';') if s) + # There may be other metrics present, but only these are needed + if not required_keys.issubset(vals): + raise RuntimeError('Bad char metrics line: %s' % line) + num = _to_int(vals['C']) + wx = _to_float(vals['WX']) + name = vals['N'] + bbox = _to_list_of_floats(vals['B']) + bbox = list(map(int, bbox)) + metrics = CharMetrics(wx, name, bbox) + # Workaround: If the character name is 'Euro', give it the + # corresponding character code, according to WinAnsiEncoding (see PDF + # Reference). + if name == 'Euro': + num = 128 + elif name == 'minus': + num = ord("\N{MINUS SIGN}") # 0x2212 + if num != -1: + ascii_d[num] = metrics + name_d[name] = metrics + raise RuntimeError('Bad parse') + + +def _parse_kern_pairs(fh): + """ + Return a kern pairs dictionary; keys are (*char1*, *char2*) tuples and + values are the kern pair value. For example, a kern pairs line like + ``KPX A y -50`` + + will be represented as:: + + d[ ('A', 'y') ] = -50 + + """ + + line = next(fh) + if not line.startswith(b'StartKernPairs'): + raise RuntimeError('Bad start of kern pairs data: %s' % line) + + d = {} + for line in fh: + line = line.rstrip() + if not line: + continue + if line.startswith(b'EndKernPairs'): + next(fh) # EndKernData + return d + vals = line.split() + if len(vals) != 4 or vals[0] != b'KPX': + raise RuntimeError('Bad kern pairs line: %s' % line) + c1, c2, val = _to_str(vals[1]), _to_str(vals[2]), _to_float(vals[3]) + d[(c1, c2)] = val + raise RuntimeError('Bad kern pairs parse') + + +CompositePart = namedtuple('CompositePart', 'name, dx, dy') +CompositePart.__doc__ = """ + Represents the information on a composite element of a composite char.""" +CompositePart.name.__doc__ = """Name of the part, e.g. 'acute'.""" +CompositePart.dx.__doc__ = """x-displacement of the part from the origin.""" +CompositePart.dy.__doc__ = """y-displacement of the part from the origin.""" + + +def _parse_composites(fh): + """ + Parse the given filehandle for composites information return them as a + dict. + + It is assumed that the file cursor is on the line behind 'StartComposites'. + + Returns + ------- + dict + A dict mapping composite character names to a parts list. The parts + list is a list of `.CompositePart` entries describing the parts of + the composite. + + Examples + -------- + A composite definition line:: + + CC Aacute 2 ; PCC A 0 0 ; PCC acute 160 170 ; + + will be represented as:: + + composites['Aacute'] = [CompositePart(name='A', dx=0, dy=0), + CompositePart(name='acute', dx=160, dy=170)] + + """ + composites = {} + for line in fh: + line = line.rstrip() + if not line: + continue + if line.startswith(b'EndComposites'): + return composites + vals = line.split(b';') + cc = vals[0].split() + name, _num_parts = cc[1], _to_int(cc[2]) + pccParts = [] + for s in vals[1:-1]: + pcc = s.split() + part = CompositePart(pcc[1], _to_float(pcc[2]), _to_float(pcc[3])) + pccParts.append(part) + composites[name] = pccParts + + raise RuntimeError('Bad composites parse') + + +def _parse_optional(fh): + """ + Parse the optional fields for kern pair data and composites. + + Returns + ------- + kern_data : dict + A dict containing kerning information. May be empty. + See `._parse_kern_pairs`. + composites : dict + A dict containing composite information. May be empty. + See `._parse_composites`. + """ + optional = { + b'StartKernData': _parse_kern_pairs, + b'StartComposites': _parse_composites, + } + + d = {b'StartKernData': {}, + b'StartComposites': {}} + for line in fh: + line = line.rstrip() + if not line: + continue + key = line.split()[0] + + if key in optional: + d[key] = optional[key](fh) + + return d[b'StartKernData'], d[b'StartComposites'] + + +class AFM: + + def __init__(self, fh): + """Parse the AFM file in file object *fh*.""" + self._header = _parse_header(fh) + self._metrics, self._metrics_by_name = _parse_char_metrics(fh) + self._kern, self._composite = _parse_optional(fh) + + def get_bbox_char(self, c, isord=False): + if not isord: + c = ord(c) + return self._metrics[c].bbox + + def string_width_height(self, s): + """ + Return the string width (including kerning) and string height + as a (*w*, *h*) tuple. + """ + if not len(s): + return 0, 0 + total_width = 0 + namelast = None + miny = 1e9 + maxy = 0 + for c in s: + if c == '\n': + continue + wx, name, bbox = self._metrics[ord(c)] + + total_width += wx + self._kern.get((namelast, name), 0) + l, b, w, h = bbox + miny = min(miny, b) + maxy = max(maxy, b + h) + + namelast = name + + return total_width, maxy - miny + + def get_str_bbox_and_descent(self, s): + """Return the string bounding box and the maximal descent.""" + if not len(s): + return 0, 0, 0, 0, 0 + total_width = 0 + namelast = None + miny = 1e9 + maxy = 0 + left = 0 + if not isinstance(s, str): + s = _to_str(s) + for c in s: + if c == '\n': + continue + name = uni2type1.get(ord(c), f"uni{ord(c):04X}") + try: + wx, _, bbox = self._metrics_by_name[name] + except KeyError: + name = 'question' + wx, _, bbox = self._metrics_by_name[name] + total_width += wx + self._kern.get((namelast, name), 0) + l, b, w, h = bbox + left = min(left, l) + miny = min(miny, b) + maxy = max(maxy, b + h) + + namelast = name + + return left, miny, total_width, maxy - miny, -miny + + def get_str_bbox(self, s): + """Return the string bounding box.""" + return self.get_str_bbox_and_descent(s)[:4] + + def get_name_char(self, c, isord=False): + """Get the name of the character, i.e., ';' is 'semicolon'.""" + if not isord: + c = ord(c) + return self._metrics[c].name + + def get_width_char(self, c, isord=False): + """ + Get the width of the character from the character metric WX field. + """ + if not isord: + c = ord(c) + return self._metrics[c].width + + def get_width_from_char_name(self, name): + """Get the width of the character from a type1 character name.""" + return self._metrics_by_name[name].width + + def get_height_char(self, c, isord=False): + """Get the bounding box (ink) height of character *c* (space is 0).""" + if not isord: + c = ord(c) + return self._metrics[c].bbox[-1] + + def get_kern_dist(self, c1, c2): + """ + Return the kerning pair distance (possibly 0) for chars *c1* and *c2*. + """ + name1, name2 = self.get_name_char(c1), self.get_name_char(c2) + return self.get_kern_dist_from_name(name1, name2) + + def get_kern_dist_from_name(self, name1, name2): + """ + Return the kerning pair distance (possibly 0) for chars + *name1* and *name2*. + """ + return self._kern.get((name1, name2), 0) + + def get_fontname(self): + """Return the font name, e.g., 'Times-Roman'.""" + return self._header[b'FontName'] + + @property + def postscript_name(self): # For consistency with FT2Font. + return self.get_fontname() + + def get_fullname(self): + """Return the font full name, e.g., 'Times-Roman'.""" + name = self._header.get(b'FullName') + if name is None: # use FontName as a substitute + name = self._header[b'FontName'] + return name + + def get_familyname(self): + """Return the font family name, e.g., 'Times'.""" + name = self._header.get(b'FamilyName') + if name is not None: + return name + + # FamilyName not specified so we'll make a guess + name = self.get_fullname() + extras = (r'(?i)([ -](regular|plain|italic|oblique|bold|semibold|' + r'light|ultralight|extra|condensed))+$') + return re.sub(extras, '', name) + + @property + def family_name(self): + """The font family name, e.g., 'Times'.""" + return self.get_familyname() + + def get_weight(self): + """Return the font weight, e.g., 'Bold' or 'Roman'.""" + return self._header[b'Weight'] + + def get_angle(self): + """Return the fontangle as float.""" + return self._header[b'ItalicAngle'] + + def get_capheight(self): + """Return the cap height as float.""" + return self._header[b'CapHeight'] + + def get_xheight(self): + """Return the xheight as float.""" + return self._header[b'XHeight'] + + def get_underline_thickness(self): + """Return the underline thickness as float.""" + return self._header[b'UnderlineThickness'] + + def get_horizontal_stem_width(self): + """ + Return the standard horizontal stem width as float, or *None* if + not specified in AFM file. + """ + return self._header.get(b'StdHW', None) + + def get_vertical_stem_width(self): + """ + Return the standard vertical stem width as float, or *None* if + not specified in AFM file. + """ + return self._header.get(b'StdVW', None) diff --git a/shared/package-files/71/7168f837b01f360ad87062017b15fe52b5b17ddd5b3fd0d336a5262d6509f670/__init__.py b/shared/package-files/71/7168f837b01f360ad87062017b15fe52b5b17ddd5b3fd0d336a5262d6509f670/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8846a99510601c9675103e21ef5a0a1e839fdd11 --- /dev/null +++ b/shared/package-files/71/7168f837b01f360ad87062017b15fe52b5b17ddd5b3fd0d336a5262d6509f670/__init__.py @@ -0,0 +1,19 @@ +from .diffgeom import ( + BaseCovarDerivativeOp, BaseScalarField, BaseVectorField, Commutator, + contravariant_order, CoordSystem, CoordinateSymbol, + CovarDerivativeOp, covariant_order, Differential, intcurve_diffequ, + intcurve_series, LieDerivative, Manifold, metric_to_Christoffel_1st, + metric_to_Christoffel_2nd, metric_to_Ricci_components, + metric_to_Riemann_components, Patch, Point, TensorProduct, twoform_to_matrix, + vectors_in_basis, WedgeProduct, +) + +__all__ = [ + 'BaseCovarDerivativeOp', 'BaseScalarField', 'BaseVectorField', 'Commutator', + 'contravariant_order', 'CoordSystem', 'CoordinateSymbol', + 'CovarDerivativeOp', 'covariant_order', 'Differential', 'intcurve_diffequ', + 'intcurve_series', 'LieDerivative', 'Manifold', 'metric_to_Christoffel_1st', + 'metric_to_Christoffel_2nd', 'metric_to_Ricci_components', + 'metric_to_Riemann_components', 'Patch', 'Point', 'TensorProduct', + 'twoform_to_matrix', 'vectors_in_basis', 'WedgeProduct', +] diff --git a/shared/package-files/71/716a2823142dd8866182d361f19d44307faaebe65162dfd69b8e9b4d9536c25e/file_adapter.h b/shared/package-files/71/716a2823142dd8866182d361f19d44307faaebe65162dfd69b8e9b4d9536c25e/file_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..36bc5de2710034ccaa4ccc9468520dab31cc9786 --- /dev/null +++ b/shared/package-files/71/716a2823142dd8866182d361f19d44307faaebe65162dfd69b8e9b4d9536c25e/file_adapter.h @@ -0,0 +1,36 @@ +#pragma once + +#include +#include +#include + +#include "caffe2/serialize/istream_adapter.h" +#include "caffe2/serialize/read_adapter_interface.h" + +namespace caffe2 { +namespace serialize { + +class TORCH_API FileAdapter final : public ReadAdapterInterface { + public: + C10_DISABLE_COPY_AND_ASSIGN(FileAdapter); + explicit FileAdapter(const std::string& file_name); + size_t size() const override; + size_t read(uint64_t pos, void* buf, size_t n, const char* what = "") + const override; + ~FileAdapter() override; + + private: + // An RAII Wrapper for a FILE pointer. Closes on destruction. + struct RAIIFile { + FILE* fp_; + explicit RAIIFile(const std::string& file_name); + ~RAIIFile(); + }; + + RAIIFile file_; + // The size of the opened file in bytes + uint64_t size_; +}; + +} // namespace serialize +} // namespace caffe2 diff --git a/shared/package-files/71/716a5b662d89296aaaa526be706b04fd7926cea7f768fd8e2f1874a1d0051670/_foreach_clamp_max_compositeexplicitautograd_dispatch.h b/shared/package-files/71/716a5b662d89296aaaa526be706b04fd7926cea7f768fd8e2f1874a1d0051670/_foreach_clamp_max_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..ff2f986e308c93bae339cf1e757d23cf20037d14 --- /dev/null +++ b/shared/package-files/71/716a5b662d89296aaaa526be706b04fd7926cea7f768fd8e2f1874a1d0051670/_foreach_clamp_max_compositeexplicitautograd_dispatch.h @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API void _foreach_clamp_max_out(at::TensorList out, at::TensorList self, const at::Scalar & scalar); +TORCH_API void _foreach_clamp_max_outf(at::TensorList self, const at::Scalar & scalar, at::TensorList out); +TORCH_API void _foreach_clamp_max_out(at::TensorList out, at::TensorList self, at::TensorList other); +TORCH_API void _foreach_clamp_max_outf(at::TensorList self, at::TensorList other, at::TensorList out); +TORCH_API void _foreach_clamp_max_out(at::TensorList out, at::TensorList self, at::ArrayRef scalars); +TORCH_API void _foreach_clamp_max_outf(at::TensorList self, at::ArrayRef scalars, at::TensorList out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/71/716f209dd890bf619ee92c435354d80a67432758e30a944ee01969dc8cd8049e/_operator.pyi b/shared/package-files/71/716f209dd890bf619ee92c435354d80a67432758e30a944ee01969dc8cd8049e/_operator.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bea438861886979a2c92d79b980b05e59a13cf00 --- /dev/null +++ b/shared/package-files/71/716f209dd890bf619ee92c435354d80a67432758e30a944ee01969dc8cd8049e/_operator.pyi @@ -0,0 +1,60 @@ +# In reality the import is the other way around, but this way we can keep the operator stub in 2and3 +from operator import ( + abs as abs, + add as add, + and_ as and_, + attrgetter as attrgetter, + concat as concat, + contains as contains, + countOf as countOf, + delitem as delitem, + eq as eq, + floordiv as floordiv, + ge as ge, + getitem as getitem, + gt as gt, + iadd as iadd, + iand as iand, + iconcat as iconcat, + ifloordiv as ifloordiv, + ilshift as ilshift, + imatmul as imatmul, + imod as imod, + imul as imul, + index as index, + indexOf as indexOf, + inv as inv, + invert as invert, + ior as ior, + ipow as ipow, + irshift as irshift, + is_ as is_, + is_not as is_not, + isub as isub, + itemgetter as itemgetter, + itruediv as itruediv, + ixor as ixor, + le as le, + length_hint as length_hint, + lshift as lshift, + lt as lt, + matmul as matmul, + methodcaller as methodcaller, + mod as mod, + mul as mul, + ne as ne, + neg as neg, + not_ as not_, + or_ as or_, + pos as pos, + pow as pow, + rshift as rshift, + setitem as setitem, + sub as sub, + truediv as truediv, + truth as truth, + xor as xor, +) +from typing import AnyStr + +def _compare_digest(__a: AnyStr, __b: AnyStr) -> bool: ... diff --git a/shared/package-files/71/7170e5bc17c8a3bb78e536c8303fff7fed14cd68cf4f614ba2e61cfff4f3d979/_foreach_neg_cpu_dispatch.h b/shared/package-files/71/7170e5bc17c8a3bb78e536c8303fff7fed14cd68cf4f614ba2e61cfff4f3d979/_foreach_neg_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..91a2c4f171ea18ee957402d8201b50dc41333c4f --- /dev/null +++ b/shared/package-files/71/7170e5bc17c8a3bb78e536c8303fff7fed14cd68cf4f614ba2e61cfff4f3d979/_foreach_neg_cpu_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API ::std::vector _foreach_neg(at::TensorList self); +TORCH_API void _foreach_neg_(at::TensorList self); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/71/7171389d1ed8ac9a56d3de554b51ba05057d3ec750b3909fbcc631222b8e0f0b/_pdist_forward_cuda_dispatch.h b/shared/package-files/71/7171389d1ed8ac9a56d3de554b51ba05057d3ec750b3909fbcc631222b8e0f0b/_pdist_forward_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..a6e98ecfa642f3790c5f84eb12fcff650ca56976 --- /dev/null +++ b/shared/package-files/71/7171389d1ed8ac9a56d3de554b51ba05057d3ec750b3909fbcc631222b8e0f0b/_pdist_forward_cuda_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor _pdist_forward(const at::Tensor & self, double p=2); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/71/7171c06a0cf6660072089302b518900eaa25fcc40d0cd4e7cd189fa45ea28df9/bitwise_xor_compositeexplicitautograd_dispatch.h b/shared/package-files/71/7171c06a0cf6660072089302b518900eaa25fcc40d0cd4e7cd189fa45ea28df9/bitwise_xor_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9cee3e8bd17af37cafca777fc62107d2e975162a --- /dev/null +++ b/shared/package-files/71/7171c06a0cf6660072089302b518900eaa25fcc40d0cd4e7cd189fa45ea28df9/bitwise_xor_compositeexplicitautograd_dispatch.h @@ -0,0 +1,29 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor bitwise_xor(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & bitwise_xor_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & bitwise_xor_outf(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +TORCH_API at::Tensor & bitwise_xor_(at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor bitwise_xor(const at::Scalar & self, const at::Tensor & other); +TORCH_API at::Tensor & bitwise_xor_out(at::Tensor & out, const at::Scalar & self, const at::Tensor & other); +TORCH_API at::Tensor & bitwise_xor_outf(const at::Scalar & self, const at::Tensor & other, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/71/71721a88eda6ba6e8c7d6cb093833248dec7bc42ca17e5fdf007c77f2a9cfb30/split_native.h b/shared/package-files/71/71721a88eda6ba6e8c7d6cb093833248dec7bc42ca17e5fdf007c77f2a9cfb30/split_native.h new file mode 100644 index 0000000000000000000000000000000000000000..4be1adda25194ef6f592d4949b21a0f5e0689afc --- /dev/null +++ b/shared/package-files/71/71721a88eda6ba6e8c7d6cb093833248dec7bc42ca17e5fdf007c77f2a9cfb30/split_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::vector split(const at::Tensor & self, int64_t split_size, int64_t dim=0); +TORCH_API ::std::vector split_symint(const at::Tensor & self, c10::SymIntArrayRef split_size, int64_t dim=0); +} // namespace native +} // namespace at diff --git a/shared/package-files/71/71756a2a51d8cbf302a7599994868fc7964a84d756a5f558311cf3e61fe72982/common_cuda.py b/shared/package-files/71/71756a2a51d8cbf302a7599994868fc7964a84d756a5f558311cf3e61fe72982/common_cuda.py new file mode 100644 index 0000000000000000000000000000000000000000..2a9055597f732982094f24c39c30e7ce02327ac6 --- /dev/null +++ b/shared/package-files/71/71756a2a51d8cbf302a7599994868fc7964a84d756a5f558311cf3e61fe72982/common_cuda.py @@ -0,0 +1,270 @@ +# mypy: ignore-errors + +r"""This file is allowed to initialize CUDA context when imported.""" + +import functools +import torch +import torch.cuda +from torch.testing._internal.common_utils import LazyVal, TEST_NUMBA, TEST_WITH_ROCM, TEST_CUDA, IS_WINDOWS +import inspect +import contextlib +import os + + +CUDA_ALREADY_INITIALIZED_ON_IMPORT = torch.cuda.is_initialized() + + +TEST_MULTIGPU = TEST_CUDA and torch.cuda.device_count() >= 2 +CUDA_DEVICE = torch.device("cuda:0") if TEST_CUDA else None +# note: if ROCm is targeted, TEST_CUDNN is code for TEST_MIOPEN +if TEST_WITH_ROCM: + TEST_CUDNN = LazyVal(lambda: TEST_CUDA) +else: + TEST_CUDNN = LazyVal(lambda: TEST_CUDA and torch.backends.cudnn.is_acceptable(torch.tensor(1., device=CUDA_DEVICE))) + +TEST_CUDNN_VERSION = LazyVal(lambda: torch.backends.cudnn.version() if TEST_CUDNN else 0) + +SM53OrLater = LazyVal(lambda: torch.cuda.is_available() and torch.cuda.get_device_capability() >= (5, 3)) +SM60OrLater = LazyVal(lambda: torch.cuda.is_available() and torch.cuda.get_device_capability() >= (6, 0)) +SM70OrLater = LazyVal(lambda: torch.cuda.is_available() and torch.cuda.get_device_capability() >= (7, 0)) +SM75OrLater = LazyVal(lambda: torch.cuda.is_available() and torch.cuda.get_device_capability() >= (7, 5)) +SM80OrLater = LazyVal(lambda: torch.cuda.is_available() and torch.cuda.get_device_capability() >= (8, 0)) +SM90OrLater = LazyVal(lambda: torch.cuda.is_available() and torch.cuda.get_device_capability() >= (9, 0)) + +def evaluate_gfx_arch_exact(matching_arch): + if not torch.cuda.is_available(): + return False + gcn_arch_name = torch.cuda.get_device_properties('cuda').gcnArchName + arch = os.environ.get('PYTORCH_DEBUG_FLASH_ATTENTION_GCN_ARCH_OVERRIDE', gcn_arch_name) + return arch == matching_arch + +GFX90A_Exact = LazyVal(lambda: evaluate_gfx_arch_exact('gfx90a:sramecc+:xnack-')) +GFX942_Exact = LazyVal(lambda: evaluate_gfx_arch_exact('gfx942:sramecc+:xnack-')) + +def evaluate_platform_supports_flash_attention(): + if TEST_WITH_ROCM: + return evaluate_gfx_arch_exact('gfx90a:sramecc+:xnack-') or evaluate_gfx_arch_exact('gfx942:sramecc+:xnack-') + if TEST_CUDA: + return not IS_WINDOWS and SM80OrLater + return False + +PLATFORM_SUPPORTS_FLASH_ATTENTION: bool = LazyVal(lambda: evaluate_platform_supports_flash_attention()) +PLATFORM_SUPPORTS_MEM_EFF_ATTENTION: bool = LazyVal(lambda: TEST_CUDA and not TEST_WITH_ROCM) +# TODO(eqy): gate this against a cuDNN version +PLATFORM_SUPPORTS_CUDNN_ATTENTION: bool = LazyVal(lambda: TEST_CUDA and not TEST_WITH_ROCM and + torch.backends.cuda.cudnn_sdp_enabled()) +# This condition always evaluates to PLATFORM_SUPPORTS_MEM_EFF_ATTENTION but for logical clarity we keep it separate +PLATFORM_SUPPORTS_FUSED_ATTENTION: bool = LazyVal(lambda: PLATFORM_SUPPORTS_FLASH_ATTENTION or PLATFORM_SUPPORTS_MEM_EFF_ATTENTION) + +PLATFORM_SUPPORTS_FUSED_SDPA: bool = TEST_CUDA and not TEST_WITH_ROCM + +if TEST_NUMBA: + try: + import numba.cuda + TEST_NUMBA_CUDA = numba.cuda.is_available() + except Exception as e: + TEST_NUMBA_CUDA = False + TEST_NUMBA = False +else: + TEST_NUMBA_CUDA = False + +# Used below in `initialize_cuda_context_rng` to ensure that CUDA context and +# RNG have been initialized. +__cuda_ctx_rng_initialized = False + + +# after this call, CUDA context and RNG must have been initialized on each GPU +def initialize_cuda_context_rng(): + global __cuda_ctx_rng_initialized + assert TEST_CUDA, 'CUDA must be available when calling initialize_cuda_context_rng' + if not __cuda_ctx_rng_initialized: + # initialize cuda context and rng for memory tests + for i in range(torch.cuda.device_count()): + torch.randn(1, device=f"cuda:{i}") + __cuda_ctx_rng_initialized = True + + +# Test whether hardware TF32 math mode enabled. It is enabled only on: +# - CUDA >= 11 +# - arch >= Ampere +def tf32_is_not_fp32(): + if not torch.cuda.is_available() or torch.version.cuda is None: + return False + if torch.cuda.get_device_properties(torch.cuda.current_device()).major < 8: + return False + if int(torch.version.cuda.split('.')[0]) < 11: + return False + return True + + +@contextlib.contextmanager +def tf32_off(): + old_allow_tf32_matmul = torch.backends.cuda.matmul.allow_tf32 + try: + torch.backends.cuda.matmul.allow_tf32 = False + with torch.backends.cudnn.flags(enabled=None, benchmark=None, deterministic=None, allow_tf32=False): + yield + finally: + torch.backends.cuda.matmul.allow_tf32 = old_allow_tf32_matmul + + +@contextlib.contextmanager +def tf32_on(self, tf32_precision=1e-5): + old_allow_tf32_matmul = torch.backends.cuda.matmul.allow_tf32 + old_precision = self.precision + try: + torch.backends.cuda.matmul.allow_tf32 = True + self.precision = tf32_precision + with torch.backends.cudnn.flags(enabled=None, benchmark=None, deterministic=None, allow_tf32=True): + yield + finally: + torch.backends.cuda.matmul.allow_tf32 = old_allow_tf32_matmul + self.precision = old_precision + + +# This is a wrapper that wraps a test to run this test twice, one with +# allow_tf32=True, another with allow_tf32=False. When running with +# allow_tf32=True, it will use reduced precision as specified by the +# argument. For example: +# @dtypes(torch.float32, torch.float64, torch.complex64, torch.complex128) +# @tf32_on_and_off(0.005) +# def test_matmul(self, device, dtype): +# a = ...; b = ...; +# c = torch.matmul(a, b) +# self.assertEqual(c, expected) +# In the above example, when testing torch.float32 and torch.complex64 on CUDA +# on a CUDA >= 11 build on an >=Ampere architecture, the matmul will be running at +# TF32 mode and TF32 mode off, and on TF32 mode, the assertEqual will use reduced +# precision to check values. +# +# This decorator can be used for function with or without device/dtype, such as +# @tf32_on_and_off(0.005) +# def test_my_op(self) +# @tf32_on_and_off(0.005) +# def test_my_op(self, device) +# @tf32_on_and_off(0.005) +# def test_my_op(self, device, dtype) +# @tf32_on_and_off(0.005) +# def test_my_op(self, dtype) +# if neither device nor dtype is specified, it will check if the system has ampere device +# if device is specified, it will check if device is cuda +# if dtype is specified, it will check if dtype is float32 or complex64 +# tf32 and fp32 are different only when all the three checks pass +def tf32_on_and_off(tf32_precision=1e-5): + def with_tf32_disabled(self, function_call): + with tf32_off(): + function_call() + + def with_tf32_enabled(self, function_call): + with tf32_on(self, tf32_precision): + function_call() + + def wrapper(f): + params = inspect.signature(f).parameters + arg_names = tuple(params.keys()) + + @functools.wraps(f) + def wrapped(*args, **kwargs): + for k, v in zip(arg_names, args): + kwargs[k] = v + cond = tf32_is_not_fp32() + if 'device' in kwargs: + cond = cond and (torch.device(kwargs['device']).type == 'cuda') + if 'dtype' in kwargs: + cond = cond and (kwargs['dtype'] in {torch.float32, torch.complex64}) + if cond: + with_tf32_disabled(kwargs['self'], lambda: f(**kwargs)) + with_tf32_enabled(kwargs['self'], lambda: f(**kwargs)) + else: + f(**kwargs) + + return wrapped + return wrapper + + +# This is a wrapper that wraps a test to run it with TF32 turned off. +# This wrapper is designed to be used when a test uses matmul or convolutions +# but the purpose of that test is not testing matmul or convolutions. +# Disabling TF32 will enforce torch.float tensors to be always computed +# at full precision. +def with_tf32_off(f): + @functools.wraps(f) + def wrapped(*args, **kwargs): + with tf32_off(): + return f(*args, **kwargs) + + return wrapped + +def _get_magma_version(): + if 'Magma' not in torch.__config__.show(): + return (0, 0) + position = torch.__config__.show().find('Magma ') + version_str = torch.__config__.show()[position + len('Magma '):].split('\n')[0] + return tuple(int(x) for x in version_str.split(".")) + +def _get_torch_cuda_version(): + if torch.version.cuda is None: + return (0, 0) + cuda_version = str(torch.version.cuda) + return tuple(int(x) for x in cuda_version.split(".")) + +def _get_torch_rocm_version(): + if not TEST_WITH_ROCM: + return (0, 0) + rocm_version = str(torch.version.hip) + rocm_version = rocm_version.split("-")[0] # ignore git sha + return tuple(int(x) for x in rocm_version.split(".")) + +def _check_cusparse_generic_available(): + return not TEST_WITH_ROCM + +def _check_hipsparse_generic_available(): + if not TEST_WITH_ROCM: + return False + + rocm_version = str(torch.version.hip) + rocm_version = rocm_version.split("-")[0] # ignore git sha + rocm_version_tuple = tuple(int(x) for x in rocm_version.split(".")) + return not (rocm_version_tuple is None or rocm_version_tuple < (5, 1)) + + +TEST_CUSPARSE_GENERIC = _check_cusparse_generic_available() +TEST_HIPSPARSE_GENERIC = _check_hipsparse_generic_available() + +# Shared by test_torch.py and test_multigpu.py +def _create_scaling_models_optimizers(device="cuda", optimizer_ctor=torch.optim.SGD, optimizer_kwargs=None): + # Create a module+optimizer that will use scaling, and a control module+optimizer + # that will not use scaling, against which the scaling-enabled module+optimizer can be compared. + mod_control = torch.nn.Sequential(torch.nn.Linear(8, 8), torch.nn.Linear(8, 8)).to(device=device) + mod_scaling = torch.nn.Sequential(torch.nn.Linear(8, 8), torch.nn.Linear(8, 8)).to(device=device) + with torch.no_grad(): + for c, s in zip(mod_control.parameters(), mod_scaling.parameters()): + s.copy_(c) + + kwargs = {"lr": 1.0} + if optimizer_kwargs is not None: + kwargs.update(optimizer_kwargs) + opt_control = optimizer_ctor(mod_control.parameters(), **kwargs) + opt_scaling = optimizer_ctor(mod_scaling.parameters(), **kwargs) + + return mod_control, mod_scaling, opt_control, opt_scaling + +# Shared by test_torch.py, test_cuda.py and test_multigpu.py +def _create_scaling_case(device="cuda", dtype=torch.float, optimizer_ctor=torch.optim.SGD, optimizer_kwargs=None): + data = [(torch.randn((8, 8), dtype=dtype, device=device), torch.randn((8, 8), dtype=dtype, device=device)), + (torch.randn((8, 8), dtype=dtype, device=device), torch.randn((8, 8), dtype=dtype, device=device)), + (torch.randn((8, 8), dtype=dtype, device=device), torch.randn((8, 8), dtype=dtype, device=device)), + (torch.randn((8, 8), dtype=dtype, device=device), torch.randn((8, 8), dtype=dtype, device=device))] + + loss_fn = torch.nn.MSELoss().to(device) + + skip_iter = 2 + + return _create_scaling_models_optimizers( + device=device, optimizer_ctor=optimizer_ctor, optimizer_kwargs=optimizer_kwargs, + ) + (data, loss_fn, skip_iter) + + +# Importing this module should NOT eagerly initialize CUDA +if not CUDA_ALREADY_INITIALIZED_ON_IMPORT: + assert not torch.cuda.is_initialized() diff --git a/shared/package-files/71/71758988ceb94644d9c411287a94299a0de3bd8c64a0ef7b8b0f6bf928033262/libgnutlsxx.so b/shared/package-files/71/71758988ceb94644d9c411287a94299a0de3bd8c64a0ef7b8b0f6bf928033262/libgnutlsxx.so new file mode 100644 index 0000000000000000000000000000000000000000..b1b018f890c427905ebbe1773a0c00c96a34735a Binary files /dev/null and b/shared/package-files/71/71758988ceb94644d9c411287a94299a0de3bd8c64a0ef7b8b0f6bf928033262/libgnutlsxx.so differ diff --git a/shared/package-files/71/71758988ceb94644d9c411287a94299a0de3bd8c64a0ef7b8b0f6bf928033262/libgnutlsxx.so.28 b/shared/package-files/71/71758988ceb94644d9c411287a94299a0de3bd8c64a0ef7b8b0f6bf928033262/libgnutlsxx.so.28 new file mode 100644 index 0000000000000000000000000000000000000000..b1b018f890c427905ebbe1773a0c00c96a34735a Binary files /dev/null and b/shared/package-files/71/71758988ceb94644d9c411287a94299a0de3bd8c64a0ef7b8b0f6bf928033262/libgnutlsxx.so.28 differ diff --git a/shared/package-files/71/71758988ceb94644d9c411287a94299a0de3bd8c64a0ef7b8b0f6bf928033262/libgnutlsxx.so.28.1.0 b/shared/package-files/71/71758988ceb94644d9c411287a94299a0de3bd8c64a0ef7b8b0f6bf928033262/libgnutlsxx.so.28.1.0 new file mode 100644 index 0000000000000000000000000000000000000000..b1b018f890c427905ebbe1773a0c00c96a34735a Binary files /dev/null and b/shared/package-files/71/71758988ceb94644d9c411287a94299a0de3bd8c64a0ef7b8b0f6bf928033262/libgnutlsxx.so.28.1.0 differ diff --git a/shared/package-files/71/71767b28a8141271e8f4fc6ee9763dec096790e733c9f25832281c80ffa06595/_to_sparse_semi_structured_ops.h b/shared/package-files/71/71767b28a8141271e8f4fc6ee9763dec096790e733c9f25832281c80ffa06595/_to_sparse_semi_structured_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..2f808ca8f2f80dc3cbdfc5ef80e7f27eb7cc3296 --- /dev/null +++ b/shared/package-files/71/71767b28a8141271e8f4fc6ee9763dec096790e733c9f25832281c80ffa06595/_to_sparse_semi_structured_ops.h @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _to_sparse_semi_structured { + using schema = ::std::tuple (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_to_sparse_semi_structured") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_to_sparse_semi_structured(Tensor dense) -> (Tensor, Tensor)") + static ::std::tuple call(const at::Tensor & dense); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & dense); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/71/7176ab0f68d78bdec518d8aa3620ea4255f483beb8116d8cd4f11baef7889a76/expressionrawdomain.py b/shared/package-files/71/7176ab0f68d78bdec518d8aa3620ea4255f483beb8116d8cd4f11baef7889a76/expressionrawdomain.py new file mode 100644 index 0000000000000000000000000000000000000000..9811ca26c965197a13f56ab8266ad744e4571560 --- /dev/null +++ b/shared/package-files/71/7176ab0f68d78bdec518d8aa3620ea4255f483beb8116d8cd4f11baef7889a76/expressionrawdomain.py @@ -0,0 +1,57 @@ +"""Implementation of :class:`ExpressionRawDomain` class. """ + + +from sympy.core import Expr, S, sympify, Add +from sympy.polys.domains.characteristiczero import CharacteristicZero +from sympy.polys.domains.field import Field +from sympy.polys.domains.simpledomain import SimpleDomain +from sympy.polys.polyerrors import CoercionFailed +from sympy.utilities import public + + +@public +class ExpressionRawDomain(Field, CharacteristicZero, SimpleDomain): + """A class for arbitrary expressions but without automatic simplification. """ + + is_SymbolicRawDomain = is_EXRAW = True + + dtype = Expr + + zero = S.Zero + one = S.One + + rep = 'EXRAW' + + has_assoc_Ring = False + has_assoc_Field = True + + def __init__(self): + pass + + @classmethod + def new(self, a): + return sympify(a) + + def to_sympy(self, a): + """Convert ``a`` to a SymPy object. """ + return a + + def from_sympy(self, a): + """Convert SymPy's expression to ``dtype``. """ + if not isinstance(a, Expr): + raise CoercionFailed(f"Expecting an Expr instance but found: {type(a).__name__}") + return a + + def convert_from(self, a, K): + """Convert a domain element from another domain to EXRAW""" + return K.to_sympy(a) + + def get_field(self): + """Returns a field associated with ``self``. """ + return self + + def sum(self, items): + return Add(*items) + + +EXRAW = ExpressionRawDomain() diff --git a/shared/package-files/71/71770d8ec32ae5c519dad7a982a2d47d3e5b942dad36a3fc1f887912ed94a167/_native_batch_norm_legit_no_training_compositeexplicitautograd_dispatch.h b/shared/package-files/71/71770d8ec32ae5c519dad7a982a2d47d3e5b942dad36a3fc1f887912ed94a167/_native_batch_norm_legit_no_training_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..ced73ac79993a2dab989280be77d865b74663bfd --- /dev/null +++ b/shared/package-files/71/71770d8ec32ae5c519dad7a982a2d47d3e5b942dad36a3fc1f887912ed94a167/_native_batch_norm_legit_no_training_compositeexplicitautograd_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API ::std::tuple _native_batch_norm_legit_no_training(const at::Tensor & input, const c10::optional & weight, const c10::optional & bias, const at::Tensor & running_mean, const at::Tensor & running_var, double momentum, double eps); +TORCH_API ::std::tuple _native_batch_norm_legit_no_training_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & input, const c10::optional & weight, const c10::optional & bias, const at::Tensor & running_mean, const at::Tensor & running_var, double momentum, double eps); +TORCH_API ::std::tuple _native_batch_norm_legit_no_training_outf(const at::Tensor & input, const c10::optional & weight, const c10::optional & bias, const at::Tensor & running_mean, const at::Tensor & running_var, double momentum, double eps, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/71/717ae41c794fca862cb432ff389d79fb9e6c64e39e0cd5b6389dca5a106ff8a9/array_float32_pointer_4d.sav b/shared/package-files/71/717ae41c794fca862cb432ff389d79fb9e6c64e39e0cd5b6389dca5a106ff8a9/array_float32_pointer_4d.sav new file mode 100644 index 0000000000000000000000000000000000000000..d99fa48f0a43ec06c3101560f9cade829c8b1940 Binary files /dev/null and b/shared/package-files/71/717ae41c794fca862cb432ff389d79fb9e6c64e39e0cd5b6389dca5a106ff8a9/array_float32_pointer_4d.sav differ diff --git a/shared/package-files/71/71843a3f8a3bad8c8973a8cd4d5ebafa49cd2a8d3607e6a73770ad71cbe99699/test_literal_dispatch.py b/shared/package-files/71/71843a3f8a3bad8c8973a8cd4d5ebafa49cd2a8d3607e6a73770ad71cbe99699/test_literal_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..6d759f06e70c66ac50b3e5359dc9c9d7013f75c5 --- /dev/null +++ b/shared/package-files/71/71843a3f8a3bad8c8973a8cd4d5ebafa49cd2a8d3607e6a73770ad71cbe99699/test_literal_dispatch.py @@ -0,0 +1,400 @@ +import numpy as np + +import numba +import unittest +from numba.tests.support import TestCase +from numba import njit +from numba.core import types, errors, cgutils +from numba.core.typing import signature +from numba.core.datamodel import models +from numba.core.extending import ( + overload, SentryLiteralArgs, overload_method, register_model, intrinsic, +) +from numba.misc.special import literally + + +class TestLiteralDispatch(TestCase): + def check_literal_basic(self, literal_args): + @njit + def foo(x): + return literally(x) + + # Test with int + for lit in literal_args: + self.assertEqual(foo(lit), lit) + + for lit, sig in zip(literal_args, foo.signatures): + self.assertEqual(sig[0].literal_value, lit) + + def test_literal_basic(self): + self.check_literal_basic([123, 321]) + self.check_literal_basic(["abc", "cb123"]) + + def test_literal_nested(self): + @njit + def foo(x): + return literally(x) * 2 + + @njit + def bar(y, x): + return foo(y) + x + + y, x = 3, 7 + self.assertEqual(bar(y, x), y * 2 + x) + [foo_sig] = foo.signatures + self.assertEqual(foo_sig[0], types.literal(y)) + [bar_sig] = bar.signatures + self.assertEqual(bar_sig[0], types.literal(y)) + self.assertNotIsInstance(bar_sig[1], types.Literal) + + def test_literally_freevar(self): + # Try referring to numba.literally not in the globals + import numba + + @njit + def foo(x): + return numba.literally(x) + + self.assertEqual(foo(123), 123) + self.assertEqual(foo.signatures[0][0], types.literal(123)) + + def test_mutual_recursion_literal(self): + def get_functions(decor): + @decor + def outer_fac(n, value): + if n < 1: + return value + return n * inner_fac(n - 1, value) + + @decor + def inner_fac(n, value): + if n < 1: + return literally(value) + return n * outer_fac(n - 1, value) + + return outer_fac, inner_fac + + ref_outer_fac, ref_inner_fac = get_functions(lambda x: x) + outer_fac, inner_fac = get_functions(njit) + + self.assertEqual(outer_fac(10, 12), ref_outer_fac(10, 12)) + self.assertEqual(outer_fac.signatures[0][1].literal_value, 12) + self.assertEqual(inner_fac.signatures[0][1].literal_value, 12) + + self.assertEqual(inner_fac(11, 13), ref_inner_fac(11, 13)) + self.assertEqual(outer_fac.signatures[1][1].literal_value, 13) + self.assertEqual(inner_fac.signatures[1][1].literal_value, 13) + + def test_literal_nested_multi_arg(self): + @njit + def foo(a, b, c): + return inner(a, c) + + @njit + def inner(x, y): + return x + literally(y) + + kwargs = dict(a=1, b=2, c=3) + got = foo(**kwargs) + expect = (lambda a, b, c: a + c)(**kwargs) + self.assertEqual(got, expect) + [foo_sig] = foo.signatures + self.assertEqual(foo_sig[2], types.literal(3)) + + def test_unsupported_literal_type(self): + @njit + def foo(a, b, c): + return inner(a, c) + + @njit + def inner(x, y): + return x + literally(y) + + arr = np.arange(10) + with self.assertRaises(errors.LiteralTypingError) as raises: + foo(a=1, b=2, c=arr) + self.assertIn("numpy.ndarray", str(raises.exception)) + + def test_biliteral(self): + # Test usecase with more than one literal call + @njit + def foo(a, b, c): + return inner(a, b) + inner(b, c) + + @njit + def inner(x, y): + return x + literally(y) + + kwargs = dict(a=1, b=2, c=3) + got = foo(**kwargs) + expect = (lambda a, b, c: a + b + b + c)(**kwargs) + self.assertEqual(got, expect) + [(type_a, type_b, type_c)] = foo.signatures + self.assertNotIsInstance(type_a, types.Literal) + self.assertIsInstance(type_b, types.Literal) + self.assertEqual(type_b.literal_value, 2) + self.assertIsInstance(type_c, types.Literal) + self.assertEqual(type_c.literal_value, 3) + + def test_literally_varargs(self): + @njit + def foo(a, *args): + return literally(args) + + with self.assertRaises(errors.LiteralTypingError): + foo(1, 2, 3) + + @njit + def bar(a, b): + foo(a, b) + + with self.assertRaises(errors.TypingError) as raises: + bar(1, 2) + self.assertIn( + "Cannot request literal type", + str(raises.exception), + ) + + @unittest.expectedFailure + def test_literally_defaults(self): + # Problem with OmittedArg + @njit + def foo(a, b=1): + return (a, literally(b)) + foo(a=1) + + @unittest.expectedFailure + def test_literally_defaults_inner(self): + # Problem with Omitted + @njit + def foo(a, b=1): + return (a, literally(b)) + + @njit + def bar(a): + return foo(a) + 1 + + bar(1) + + def test_literally_from_module(self): + # Problem with Omitted + @njit + def foo(x): + return numba.literally(x) + + got = foo(123) + self.assertEqual(got, foo.py_func(123)) + self.assertIsInstance(foo.signatures[0][0], types.Literal) + + def test_non_literal(self): + @njit + def foo(a, b): + return literally(1 + a) + + with self.assertRaises(errors.TypingError) as raises: + foo(1, 2) + self.assertIn( + "Invalid use of non-Literal type", + str(raises.exception), + ) + + def test_inlined_literal(self): + # Check that literally accepts inlined literal + @njit + def foo(a, b): + v = 1000 + return a + literally(v) + literally(b) + + got = foo(1, 2) + self.assertEqual(got, foo.py_func(1, 2)) + + @njit + def bar(): + a = 100 + b = 9 + return foo(a=b, b=a) + + got = bar() + self.assertEqual(got, bar.py_func()) + + def test_aliased_variable(self): + @njit + def foo(a, b, c): + def closure(d): + return literally(d) + 10 * inner(a, b) + # The inlining of the closure will create an alias to c + return closure(c) + + @njit + def inner(x, y): + return x + literally(y) + + kwargs = dict(a=1, b=2, c=3) + got = foo(**kwargs) + expect = (lambda a, b, c: c + 10 * (a + b))(**kwargs) + self.assertEqual(got, expect) + [(type_a, type_b, type_c)] = foo.signatures + self.assertNotIsInstance(type_a, types.Literal) + self.assertIsInstance(type_b, types.Literal) + self.assertEqual(type_b.literal_value, 2) + self.assertIsInstance(type_c, types.Literal) + self.assertEqual(type_c.literal_value, 3) + + def test_overload_explicit(self): + # This test represents a more controlled usage with ensuring literal + # typing for an argument. + def do_this(x, y): + return x + y + + @overload(do_this) + def ov_do_this(x, y): + SentryLiteralArgs(['x']).for_function(ov_do_this).bind(x, y) + return lambda x, y: x + y + + @njit + def foo(a, b): + return do_this(a, b) + + a = 123 + b = 321 + r = foo(a, b) + self.assertEqual(r, a + b) + [type_a, type_b] = foo.signatures[0] + self.assertIsInstance(type_a, types.Literal) + self.assertEqual(type_a.literal_value, a) + self.assertNotIsInstance(type_b, types.Literal) + + def test_overload_implicit(self): + # This test represents the preferred usage style for using literally + # in overload. Here, literally() is used inside the "implementation" + # function of the overload. + def do_this(x, y): + return x + y + + @njit + def hidden(x, y): + return literally(x) + y + + @overload(do_this) + def ov_do_this(x, y): + if isinstance(x, types.Integer): + # At this point, `x` can be a literal or not + return lambda x, y: hidden(x, y) + + @njit + def foo(a, b): + return do_this(a, b) + + a = 123 + b = 321 + r = foo(a, b) + self.assertEqual(r, a + b) + [type_a, type_b] = foo.signatures[0] + self.assertIsInstance(type_a, types.Literal) + self.assertEqual(type_a.literal_value, a) + self.assertNotIsInstance(type_b, types.Literal) + + def test_overload_error_loop(self): + # Test a case where a infinite compiling loop is caused because a + # literal type is requested but an error would raise for the + # literal-ized code path. This causes the overload resolution to + # retry by "de-literal-izing" the values. + def do_this(x, y): + return x + y + + @njit + def hidden(x, y): + return literally(x) + y + + @overload(do_this) + def ov_do_this(x, y): + if isinstance(y, types.IntegerLiteral): + # This error is however suppressed because a non-literal + # version is valid. + raise errors.NumbaValueError("oops") + else: + def impl(x, y): + return hidden(x, y) + return impl + + @njit + def foo(a, b): + return do_this(a, literally(b)) + + # Expect raising CompilerError to stop re-compiling with duplicated + # literal typing request. + with self.assertRaises(errors.CompilerError) as raises: + foo(a=123, b=321) + self.assertIn("Repeated literal typing request", + str(raises.exception)) + + +class TestLiteralDispatchWithCustomType(TestCase): + def make_dummy_type(self): + class Dummy(object): + def lit(self, a): + return a + + class DummyType(types.Type): + def __init__(self): + super(DummyType, self).__init__(name="dummy") + + @register_model(DummyType) + class DummyTypeModel(models.StructModel): + def __init__(self, dmm, fe_type): + members = [] + super(DummyTypeModel, self).__init__(dmm, fe_type, members) + + @intrinsic + def init_dummy(typingctx): + def codegen(context, builder, signature, args): + dummy = cgutils.create_struct_proxy( + signature.return_type)(context, builder) + + return dummy._getvalue() + + sig = signature(DummyType()) + return sig, codegen + + @overload(Dummy) + def dummy_overload(): + def ctor(): + return init_dummy() + + return ctor + + return (DummyType, Dummy) + + def test_overload_method(self): + # from issue #5011 + DummyType, Dummy = self.make_dummy_type() + + @overload_method(DummyType, 'lit') + def lit_overload(self, a): + def impl(self, a): + return literally(a) # <-- using literally here + + return impl + + @njit + def test_impl(a): + d = Dummy() + + return d.lit(a) + + # Successful case + self.assertEqual(test_impl(5), 5) + + # Failing case + @njit + def inside(a): + return test_impl(a + 1) + + with self.assertRaises(errors.TypingError) as raises: + inside(4) + + self.assertIn("Cannot request literal type.", str(raises.exception)) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/71/71853fcb852d3b3fd4175af4cdcb6815b52447643433e00953bc89a75d8ab4ff/PythonTorchFunctionTLS.h b/shared/package-files/71/71853fcb852d3b3fd4175af4cdcb6815b52447643433e00953bc89a75d8ab4ff/PythonTorchFunctionTLS.h new file mode 100644 index 0000000000000000000000000000000000000000..a8efa8eab357b55eb00d997ffe8458b841b0da36 --- /dev/null +++ b/shared/package-files/71/71853fcb852d3b3fd4175af4cdcb6815b52447643433e00953bc89a75d8ab4ff/PythonTorchFunctionTLS.h @@ -0,0 +1,34 @@ +#pragma once + +#include +#include + +namespace at::impl { + +enum TorchFunctionDisabledState { ENABLED, SUBCLASSES_DISABLED, ALL_DISABLED }; + +struct TORCH_API PythonTorchFunctionTLS { + static void set_disabled_state(TorchFunctionDisabledState disabled_state_); + static TorchFunctionDisabledState get_disabled_state(); + + static void push_onto_stack(std::shared_ptr mode); + static const std::shared_ptr pop_stack(); + static const std::shared_ptr& get_stack_at(int64_t idx); + static int64_t stack_len(); + + static const PythonTorchFunctionTLS& get_state(); + static void set_state(const PythonTorchFunctionTLS& state); + + private: + // The mode TLS is split into + // - disabled_state, which says which part of torch function are disabled + // - stack_, which is a vector of modes representing the stack of user + // defined modes + TorchFunctionDisabledState disabled_state_ = + TorchFunctionDisabledState::ENABLED; + std::vector> stack_; +}; + +TORCH_API bool torch_function_mode_enabled(); + +} // namespace at::impl diff --git a/shared/package-files/71/718547e572d9c685bf75f8a9babab2ed6354d534d998af5f7836e5b2f69978c8/generate_bytecode.py b/shared/package-files/71/718547e572d9c685bf75f8a9babab2ed6354d534d998af5f7836e5b2f69978c8/generate_bytecode.py new file mode 100644 index 0000000000000000000000000000000000000000..8e56c7665d1ca68b5bb4a94cf8abc6a1c9bd1666 --- /dev/null +++ b/shared/package-files/71/718547e572d9c685bf75f8a9babab2ed6354d534d998af5f7836e5b2f69978c8/generate_bytecode.py @@ -0,0 +1,33 @@ +from typing import List + +from torch._C import _compile_graph_to_code_table, _generate_upgraders_graph + + +def format_bytecode(table): + # given a nested tuple, convert it to nested list + def listify(content): + if not isinstance(content, tuple): + return content + return [listify(i) for i in content] + + formatted_table = {} + for entry in table: + identifier = entry[0] + content = entry[1] + content = listify(content) + formatted_table[identifier] = content + return formatted_table + + +def generate_upgraders_bytecode() -> List: + yaml_content = [] + upgraders_graph_map = _generate_upgraders_graph() + for upgrader_name, upgrader_graph in upgraders_graph_map.items(): + bytecode_table = _compile_graph_to_code_table(upgrader_name, upgrader_graph) + entry = {upgrader_name: format_bytecode(bytecode_table)} + yaml_content.append(entry) + return yaml_content + + +if __name__ == "__main__": + raise RuntimeError("This file is not meant to be run directly") diff --git a/shared/package-files/71/7187b1ca8f2b65c76a325a5af5f345e5ad88a172d44d9b88be1d090f5429d22e/STIXSizOneSymBol.ttf b/shared/package-files/71/7187b1ca8f2b65c76a325a5af5f345e5ad88a172d44d9b88be1d090f5429d22e/STIXSizOneSymBol.ttf new file mode 100644 index 0000000000000000000000000000000000000000..6ffd35778fd8eebf304a4842edd92ee49398567a Binary files /dev/null and b/shared/package-files/71/7187b1ca8f2b65c76a325a5af5f345e5ad88a172d44d9b88be1d090f5429d22e/STIXSizOneSymBol.ttf differ diff --git a/shared/package-files/71/71882af2572ab7db36e47d927d0fd3b93bd97c614c9692441fac96e37c97fc81/utils.pyi b/shared/package-files/71/71882af2572ab7db36e47d927d0fd3b93bd97c614c9692441fac96e37c97fc81/utils.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3a84c6254547bd010c89744230e2c22dd5fa9a77 --- /dev/null +++ b/shared/package-files/71/71882af2572ab7db36e47d927d0fd3b93bd97c614c9692441fac96e37c97fc81/utils.pyi @@ -0,0 +1,54 @@ +from typing import Any, AnyStr, Dict, Iterable, Mapping, Optional, Text, Tuple + +from . import compat, cookies, exceptions, structures + +OrderedDict = compat.OrderedDict +RequestsCookieJar = cookies.RequestsCookieJar +cookiejar_from_dict = cookies.cookiejar_from_dict +CaseInsensitiveDict = structures.CaseInsensitiveDict +InvalidURL = exceptions.InvalidURL + +NETRC_FILES: Any +DEFAULT_CA_BUNDLE_PATH: Any +DEFAULT_PORTS: Any + +def dict_to_sequence(d): ... +def super_len(o): ... +def get_netrc_auth(url, raise_errors: bool = ...): ... +def guess_filename(obj): ... +def extract_zipped_paths(path): ... +def from_key_val_list(value): ... +def to_key_val_list(value): ... +def parse_list_header(value): ... +def parse_dict_header(value): ... +def unquote_header_value(value, is_filename=...): ... +def dict_from_cookiejar(cj): ... +def add_dict_to_cookiejar(cj, cookie_dict): ... +def get_encodings_from_content(content): ... +def get_encoding_from_headers(headers): ... +def stream_decode_response_unicode(iterator, r): ... +def iter_slices(string, slice_length): ... +def get_unicode_from_response(r): ... + +UNRESERVED_SET: Any + +def unquote_unreserved(uri): ... +def requote_uri(uri): ... +def address_in_network(ip, net): ... +def dotted_netmask(mask): ... +def is_ipv4_address(string_ip): ... +def is_valid_cidr(string_network): ... +def set_environ(env_name, value): ... +def should_bypass_proxies(url, no_proxy: Optional[Iterable[AnyStr]]) -> bool: ... +def get_environ_proxies(url, no_proxy: Optional[Iterable[AnyStr]] = ...) -> Dict[Any, Any]: ... +def select_proxy(url: Text, proxies: Optional[Mapping[Any, Any]]): ... +def default_user_agent(name=...): ... +def default_headers(): ... +def parse_header_links(value): ... +def guess_json_utf(data): ... +def prepend_scheme_if_needed(url, new_scheme): ... +def get_auth_from_url(url): ... +def to_native_string(string, encoding=...): ... +def urldefragauth(url): ... +def rewind_body(prepared_request): ... +def check_header_validity(header: Tuple[AnyStr, AnyStr]) -> None: ... diff --git a/shared/package-files/71/718fd70e81d52695c5bbb5329d91eba035ed3d2d2688ec28c516c5eccad5610c/_sharded_tensor_utils.py b/shared/package-files/71/718fd70e81d52695c5bbb5329d91eba035ed3d2d2688ec28c516c5eccad5610c/_sharded_tensor_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..582dfc069924173b8f7de16a5f05a16fc98397c9 --- /dev/null +++ b/shared/package-files/71/718fd70e81d52695c5bbb5329d91eba035ed3d2d2688ec28c516c5eccad5610c/_sharded_tensor_utils.py @@ -0,0 +1,103 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates + +import copy + +import torch.distributed as dist +from torch.distributed._shard.sharded_tensor import Shard, ShardedTensor, ShardMetadata +from torch.distributed._shard.sharded_tensor.metadata import ShardedTensorMetadata +from torch.distributed.checkpoint.metadata import STATE_DICT_TYPE +from torch.distributed.remote_device import _remote_device + +from ._traverse import OBJ_PATH, set_element, STATE_DICT_ITEM, traverse_state_dict +from .utils import _element_wise_add, _normalize_device_info + + +# TODO: We need to refactor this code. +def _flatten_sharded_tensors(state_dict: STATE_DICT_TYPE) -> STATE_DICT_TYPE: + r""" + Transform ``state_dict`` by flattening all nested ShardedTensor instances found. + + The resulting ShardedTensor instances are only correct regarding the local shard and + MUST not be used for any other purpose but checkpointing, as no operator will work with them. + + This function should be used in conjunction with a state_dict produced by FSDP's + StateDictType.SHARDED_STATE_DICT methods. + """ + new_state_dict: STATE_DICT_TYPE = {} + + def rewrite_dict(path: OBJ_PATH, value: STATE_DICT_ITEM) -> None: + if not isinstance(value, ShardedTensor): + set_element(new_state_dict, path, value) + return + shards = value.local_shards() + + if len(shards) == 0: + return + if len(shards) != 1: + set_element(new_state_dict, path, value) + return + + outer_shard = shards[0] + + inner_st = outer_shard.tensor + if not isinstance(inner_st, ShardedTensor): + set_element(new_state_dict, path, value) + return + + if len(inner_st.local_shards()) != 1: + raise ValueError("Cannot handle inner tensor with more than 1 shard") + inner_shard = inner_st.local_shards()[0] + + local_shards = [ + Shard( + tensor=inner_shard.tensor, + metadata=ShardMetadata( + shard_offsets=_element_wise_add( + outer_shard.metadata.shard_offsets, + inner_shard.metadata.shard_offsets, + ), + shard_sizes=inner_shard.metadata.shard_sizes, + placement=f"rank:{dist.get_rank()}/{inner_shard.tensor.device}", + ), + ) + ] + + st_meta: ShardedTensorMetadata = copy.deepcopy(value.metadata()) + other_rank = 0 if dist.get_rank() > 0 else 1 + device_info = _normalize_device_info(inner_shard.tensor.device.type, 0) + + # Remove the outer ST shard the inner ST covers + for i, shard_md in enumerate(st_meta.shards_metadata): + if shard_md.shard_offsets == outer_shard.metadata.shard_offsets: + st_meta.shards_metadata.pop(i) + break + + # Attribute other rank for the other shards + for shard_md in st_meta.shards_metadata: + shard_md.placement = _remote_device(f"rank:{other_rank}/{device_info}") + + # Add other inner shards from the inner tensor + for inner_md in inner_st.metadata().shards_metadata: + if inner_md.shard_offsets != inner_shard.metadata.shard_offsets: + st_meta.shards_metadata.append( + ShardMetadata( + shard_offsets=_element_wise_add( + outer_shard.metadata.shard_offsets, + inner_md.shard_offsets, + ), + shard_sizes=inner_md.shard_sizes, + placement=f"rank:{other_rank}/{device_info}", + ) + ) + + # Finally add this shard + st_meta.shards_metadata.append(local_shards[0].metadata) + + st = ShardedTensor._init_from_local_shards_and_global_metadata( + local_shards=local_shards, + sharded_tensor_metadata=st_meta, + ) + set_element(new_state_dict, path, st) + + traverse_state_dict(state_dict, rewrite_dict) + return new_state_dict diff --git a/shared/package-files/71/7190fc62924dabf6162f683b8ab4105b8e7aa130df314a309906c795bbf0edb5/charseq.py b/shared/package-files/71/7190fc62924dabf6162f683b8ab4105b8e7aa130df314a309906c795bbf0edb5/charseq.py new file mode 100644 index 0000000000000000000000000000000000000000..b416068cecae68f95c599ccf09c3cd89e6c2c9b8 --- /dev/null +++ b/shared/package-files/71/7190fc62924dabf6162f683b8ab4105b8e7aa130df314a309906c795bbf0edb5/charseq.py @@ -0,0 +1,1014 @@ +"""Implements operations on bytes and str (unicode) array items.""" +import operator +from llvmlite import ir + +import ctypes + +from numba.core import types, cgutils +from numba.core.extending import (overload, intrinsic, overload_method, + lower_cast, register_jitable) +from numba.core.cgutils import is_nonelike +from numba.cpython import unicode + +# bytes and str arrays items are of type CharSeq and UnicodeCharSeq, +# respectively. See numpy/types/npytypes.py for CharSeq, +# UnicodeCharSeq definitions. The corresponding data models are +# defined in numpy/datamodel/models.py. Boxing/unboxing of item types +# are defined in numpy/targets/boxing.py, see box_unicodecharseq, +# unbox_unicodecharseq, box_charseq, unbox_charseq. + +bytes_type = types.Bytes(types.uint8, 1, "C", readonly=True) + +# Currently, NumPy supports only UTF-32 arrays but this may change in +# future and the approach used here for supporting str arrays may need +# a revision depending on how NumPy will support UTF-8 and UTF-16 +# arrays. +unicode_byte_width = ctypes.sizeof(ctypes.c_byte) * 4 + + +# this is modified version of numba.unicode.make_deref_codegen +def make_deref_codegen(bitsize): + def codegen(context, builder, signature, args): + data, idx = args + rawptr = cgutils.alloca_once_value(builder, value=data) + ptr = builder.bitcast(rawptr, ir.IntType(bitsize).as_pointer()) + ch = builder.load(builder.gep(ptr, [idx])) + return builder.zext(ch, ir.IntType(32)) + return codegen + + +@intrinsic +def deref_uint8(typingctx, data, offset): + sig = types.uint32(data, types.intp) + return sig, make_deref_codegen(8) + + +@intrinsic +def deref_uint16(typingctx, data, offset): + sig = types.uint32(data, types.intp) + return sig, make_deref_codegen(16) + + +@intrinsic +def deref_uint32(typingctx, data, offset): + sig = types.uint32(data, types.intp) + return sig, make_deref_codegen(32) + + +@register_jitable(_nrt=False) +def charseq_get_code(a, i): + """Access i-th item of CharSeq object via code value + """ + return deref_uint8(a, i) + + +@register_jitable +def charseq_get_value(a, i): + """Access i-th item of CharSeq object via code value. + + null code is interpreted as IndexError + """ + code = charseq_get_code(a, i) + if code == 0: + raise IndexError('index out of range') + return code + + +@register_jitable(_nrt=False) +def unicode_charseq_get_code(a, i): + """Access i-th item of UnicodeCharSeq object via code value + """ + if unicode_byte_width == 4: + return deref_uint32(a, i) + elif unicode_byte_width == 2: + return deref_uint16(a, i) + elif unicode_byte_width == 1: + return deref_uint8(a, i) + else: + raise NotImplementedError( + 'unicode_charseq_get_code: unicode_byte_width not in [1, 2, 4]') + + +@register_jitable +def unicode_get_code(a, i): + """Access i-th item of UnicodeType object. + """ + return unicode._get_code_point(a, i) + + +@register_jitable +def bytes_get_code(a, i): + """Access i-th item of Bytes object. + """ + return a[i] + + +def _get_code_impl(a): + if isinstance(a, types.CharSeq): + return charseq_get_code + elif isinstance(a, types.Bytes): + return bytes_get_code + elif isinstance(a, types.UnicodeCharSeq): + return unicode_charseq_get_code + elif isinstance(a, types.UnicodeType): + return unicode_get_code + + +def _same_kind(a, b): + for t in [(types.CharSeq, types.Bytes), + (types.UnicodeCharSeq, types.UnicodeType)]: + if isinstance(a, t) and isinstance(b, t): + return True + return False + + +def _is_bytes(a): + return isinstance(a, (types.CharSeq, types.Bytes)) + + +def is_default(x, default): + return x == default or isinstance(x, types.Omitted) + + +@register_jitable +def unicode_charseq_get_value(a, i): + """Access i-th item of UnicodeCharSeq object via unicode value + + null code is interpreted as IndexError + """ + code = unicode_charseq_get_code(a, i) + if code == 0: + raise IndexError('index out of range') + # Return numpy equivalent of `chr(code)` + return chr(code) + + +# +# CAST +# +# Currently, the following casting operations are supported: +# Bytes -> CharSeq (ex: a=np.array(b'abc'); a[()] = b'123') +# UnicodeType -> UnicodeCharSeq (ex: a=np.array('abc'); a[()] = '123') +# CharSeq -> Bytes (ex: a=np.array(b'abc'); b = bytes(a[()])) +# UnicodeType -> Bytes (ex: str('123')._to_bytes()) +# +# The following casting operations can be implemented when required: +# Bytes -> UnicodeCharSeq (ex: a=np.array('abc'); a[()] = b'123') +# UnicodeType -> CharSeq (ex: a=np.array(b'abc'); a[()] = '123') +# UnicodeType -> Bytes (ex: bytes('123', 'utf8')) +# + + +@lower_cast(types.Bytes, types.CharSeq) +def bytes_to_charseq(context, builder, fromty, toty, val): + barr = cgutils.create_struct_proxy(fromty)(context, builder, value=val) + src = builder.bitcast(barr.data, ir.IntType(8).as_pointer()) + src_length = barr.nitems + + lty = context.get_value_type(toty) + dstint_t = ir.IntType(8) + dst_ptr = cgutils.alloca_once(builder, lty) + dst = builder.bitcast(dst_ptr, dstint_t.as_pointer()) + + dst_length = ir.Constant(src_length.type, toty.count) + is_shorter_value = builder.icmp_unsigned('<', src_length, dst_length) + count = builder.select(is_shorter_value, src_length, dst_length) + with builder.if_then(is_shorter_value): + cgutils.memset(builder, + dst, + ir.Constant(src_length.type, + toty.count), 0) + with cgutils.for_range(builder, count) as loop: + in_ptr = builder.gep(src, [loop.index]) + in_val = builder.zext(builder.load(in_ptr), dstint_t) + builder.store(in_val, builder.gep(dst, [loop.index])) + + return builder.load(dst_ptr) + + +def _make_constant_bytes(context, builder, nbytes): + bstr_ctor = cgutils.create_struct_proxy(bytes_type) + bstr = bstr_ctor(context, builder) + + if isinstance(nbytes, int): + nbytes = ir.Constant(bstr.nitems.type, nbytes) + + bstr.meminfo = context.nrt.meminfo_alloc(builder, nbytes) + bstr.nitems = nbytes + bstr.itemsize = ir.Constant(bstr.itemsize.type, 1) + bstr.data = context.nrt.meminfo_data(builder, bstr.meminfo) + bstr.parent = cgutils.get_null_value(bstr.parent.type) + # bstr.shape and bstr.strides are not used + bstr.shape = cgutils.get_null_value(bstr.shape.type) + bstr.strides = cgutils.get_null_value(bstr.strides.type) + return bstr + + +@lower_cast(types.CharSeq, types.Bytes) +def charseq_to_bytes(context, builder, fromty, toty, val): + bstr = _make_constant_bytes(context, builder, val.type.count) + rawptr = cgutils.alloca_once_value(builder, value=val) + ptr = builder.bitcast(rawptr, bstr.data.type) + cgutils.memcpy(builder, bstr.data, ptr, bstr.nitems) + return bstr + + +@lower_cast(types.UnicodeType, types.Bytes) +def unicode_to_bytes_cast(context, builder, fromty, toty, val): + uni_str = cgutils.create_struct_proxy(fromty)(context, builder, value=val) + src1 = builder.bitcast(uni_str.data, ir.IntType(8).as_pointer()) + notkind1 = builder.icmp_unsigned('!=', uni_str.kind, + ir.Constant(uni_str.kind.type, 1)) + src_length = uni_str.length + + with builder.if_then(notkind1): + context.call_conv.return_user_exc( + builder, ValueError, + ("cannot cast higher than 8-bit unicode_type to bytes",)) + + bstr = _make_constant_bytes(context, builder, src_length) + cgutils.memcpy(builder, bstr.data, src1, bstr.nitems) + return bstr + + +@intrinsic +def _unicode_to_bytes(typingctx, s): + # used in _to_bytes method + assert s == types.unicode_type + sig = bytes_type(s) + + def codegen(context, builder, signature, args): + return unicode_to_bytes_cast( + context, builder, s, bytes_type, args[0])._getvalue() + return sig, codegen + + +@lower_cast(types.UnicodeType, types.UnicodeCharSeq) +def unicode_to_unicode_charseq(context, builder, fromty, toty, val): + uni_str = cgutils.create_struct_proxy(fromty)(context, builder, value=val) + src1 = builder.bitcast(uni_str.data, ir.IntType(8).as_pointer()) + src2 = builder.bitcast(uni_str.data, ir.IntType(16).as_pointer()) + src4 = builder.bitcast(uni_str.data, ir.IntType(32).as_pointer()) + kind1 = builder.icmp_unsigned('==', uni_str.kind, + ir.Constant(uni_str.kind.type, 1)) + kind2 = builder.icmp_unsigned('==', uni_str.kind, + ir.Constant(uni_str.kind.type, 2)) + kind4 = builder.icmp_unsigned('==', uni_str.kind, + ir.Constant(uni_str.kind.type, 4)) + src_length = uni_str.length + + lty = context.get_value_type(toty) + dstint_t = ir.IntType(8 * unicode_byte_width) + dst_ptr = cgutils.alloca_once(builder, lty) + dst = builder.bitcast(dst_ptr, dstint_t.as_pointer()) + + dst_length = ir.Constant(src_length.type, toty.count) + is_shorter_value = builder.icmp_unsigned('<', src_length, dst_length) + count = builder.select(is_shorter_value, src_length, dst_length) + with builder.if_then(is_shorter_value): + cgutils.memset(builder, + dst, + ir.Constant(src_length.type, + toty.count * unicode_byte_width), 0) + + with builder.if_then(kind1): + with cgutils.for_range(builder, count) as loop: + in_ptr = builder.gep(src1, [loop.index]) + in_val = builder.zext(builder.load(in_ptr), dstint_t) + builder.store(in_val, builder.gep(dst, [loop.index])) + + with builder.if_then(kind2): + if unicode_byte_width >= 2: + with cgutils.for_range(builder, count) as loop: + in_ptr = builder.gep(src2, [loop.index]) + in_val = builder.zext(builder.load(in_ptr), dstint_t) + builder.store(in_val, builder.gep(dst, [loop.index])) + else: + context.call_conv.return_user_exc( + builder, ValueError, + ("cannot cast 16-bit unicode_type to %s-bit %s" + % (unicode_byte_width * 8, toty))) + + with builder.if_then(kind4): + if unicode_byte_width >= 4: + with cgutils.for_range(builder, count) as loop: + in_ptr = builder.gep(src4, [loop.index]) + in_val = builder.zext(builder.load(in_ptr), dstint_t) + builder.store(in_val, builder.gep(dst, [loop.index])) + else: + context.call_conv.return_user_exc( + builder, ValueError, + ("cannot cast 32-bit unicode_type to %s-bit %s" + % (unicode_byte_width * 8, toty))) + + return builder.load(dst_ptr) + +# +# Operations on bytes/str array items +# +# Implementation note: while some operations need +# CharSeq/UnicodeCharSeq specific implementations (getitem, len, str, +# etc), many operations can be supported by casting +# CharSeq/UnicodeCharSeq objects to Bytes/UnicodeType objects and +# re-use existing operations. +# +# However, in numba more operations are implemented for UnicodeType +# than for Bytes objects, hence the support for operations with bytes +# array items will be less complete than for str arrays. Although, in +# some cases (hash, contains, etc) the UnicodeType implementations can +# be reused for Bytes objects via using `_to_str` method. +# + + +@overload(operator.getitem) +def charseq_getitem(s, i): + get_value = None + if isinstance(i, types.Integer): + if isinstance(s, types.CharSeq): + get_value = charseq_get_value + if isinstance(s, types.UnicodeCharSeq): + get_value = unicode_charseq_get_value + if get_value is not None: + max_i = s.count + msg = 'index out of range [0, %s]' % (max_i - 1) + + def getitem_impl(s, i): + if i < max_i and i >= 0: + return get_value(s, i) + raise IndexError(msg) + return getitem_impl + + +@overload(len) +def charseq_len(s): + if isinstance(s, (types.CharSeq, types.UnicodeCharSeq)): + get_code = _get_code_impl(s) + n = s.count + if n == 0: + def len_impl(s): + return 0 + return len_impl + else: + def len_impl(s): + # return the index of the last non-null value (numpy + # behavior) + i = n + code = 0 + while code == 0: + i = i - 1 + if i < 0: + break + code = get_code(s, i) + return i + 1 + return len_impl + + +@overload(operator.add) +@overload(operator.iadd) +def charseq_concat(a, b): + if not _same_kind(a, b): + return + if (isinstance(a, types.UnicodeCharSeq) and + isinstance(b, types.UnicodeType)): + def impl(a, b): + return str(a) + b + return impl + if (isinstance(b, types.UnicodeCharSeq) and + isinstance(a, types.UnicodeType)): + def impl(a, b): + return a + str(b) + return impl + if (isinstance(a, types.UnicodeCharSeq) and + isinstance(b, types.UnicodeCharSeq)): + def impl(a, b): + return str(a) + str(b) + return impl + if (isinstance(a, (types.CharSeq, types.Bytes)) and + isinstance(b, (types.CharSeq, types.Bytes))): + def impl(a, b): + return (a._to_str() + b._to_str())._to_bytes() + return impl + + +@overload(operator.mul) +def charseq_repeat(a, b): + if isinstance(a, types.UnicodeCharSeq): + def wrap(a, b): + return str(a) * b + return wrap + if isinstance(b, types.UnicodeCharSeq): + def wrap(a, b): + return a * str(b) + return wrap + if isinstance(a, (types.CharSeq, types.Bytes)): + def wrap(a, b): + return (a._to_str() * b)._to_bytes() + return wrap + if isinstance(b, (types.CharSeq, types.Bytes)): + def wrap(a, b): + return (a * b._to_str())._to_bytes() + return wrap + + +@overload(operator.not_) +def charseq_not(a): + if isinstance(a, (types.UnicodeCharSeq, types.CharSeq, types.Bytes)): + def impl(a): + return len(a) == 0 + return impl + + +@overload(operator.eq) +def charseq_eq(a, b): + if not _same_kind(a, b): + return + left_code = _get_code_impl(a) + right_code = _get_code_impl(b) + if left_code is not None and right_code is not None: + def eq_impl(a, b): + n = len(a) + if n != len(b): + return False + for i in range(n): + if left_code(a, i) != right_code(b, i): + return False + return True + return eq_impl + + +@overload(operator.ne) +def charseq_ne(a, b): + if not _same_kind(a, b): + return + left_code = _get_code_impl(a) + right_code = _get_code_impl(b) + if left_code is not None and right_code is not None: + def ne_impl(a, b): + return not (a == b) + return ne_impl + + +@overload(operator.lt) +def charseq_lt(a, b): + if not _same_kind(a, b): + return + left_code = _get_code_impl(a) + right_code = _get_code_impl(b) + if left_code is not None and right_code is not None: + def lt_impl(a, b): + na = len(a) + nb = len(b) + n = min(na, nb) + for i in range(n): + ca, cb = left_code(a, i), right_code(b, i) + if ca != cb: + return ca < cb + return na < nb + return lt_impl + + +@overload(operator.gt) +def charseq_gt(a, b): + if not _same_kind(a, b): + return + left_code = _get_code_impl(a) + right_code = _get_code_impl(b) + if left_code is not None and right_code is not None: + def gt_impl(a, b): + return b < a + return gt_impl + + +@overload(operator.le) +def charseq_le(a, b): + if not _same_kind(a, b): + return + left_code = _get_code_impl(a) + right_code = _get_code_impl(b) + if left_code is not None and right_code is not None: + def le_impl(a, b): + return not (a > b) + return le_impl + + +@overload(operator.ge) +def charseq_ge(a, b): + if not _same_kind(a, b): + return + left_code = _get_code_impl(a) + right_code = _get_code_impl(b) + if left_code is not None and right_code is not None: + def ge_impl(a, b): + return not (a < b) + return ge_impl + + +@overload(operator.contains) +def charseq_contains(a, b): + if not _same_kind(a, b): + return + left_code = _get_code_impl(a) + right_code = _get_code_impl(b) + if left_code is not None and right_code is not None: + if _is_bytes(a): + def contains_impl(a, b): + # Ideally, `return bytes(b) in bytes(a)` would be used + # here, but numba Bytes does not implement + # contains. So, using `unicode_type` implementation + # here: + return b._to_str() in a._to_str() + else: + def contains_impl(a, b): + return str(b) in str(a) + return contains_impl + + +@overload_method(types.UnicodeCharSeq, 'isascii') +@overload_method(types.CharSeq, 'isascii') +@overload_method(types.Bytes, 'isascii') +def charseq_isascii(s): + get_code = _get_code_impl(s) + + def impl(s): + for i in range(len(s)): + if get_code(s, i) > 127: + return False + return True + return impl + + +@overload_method(types.UnicodeCharSeq, '_get_kind') +@overload_method(types.CharSeq, '_get_kind') +def charseq_get_kind(s): + get_code = _get_code_impl(s) + + def impl(s): + max_code = 0 + for i in range(len(s)): + code = get_code(s, i) + if code > max_code: + max_code = code + if max_code > 0xffff: + return unicode.PY_UNICODE_4BYTE_KIND + if max_code > 0xff: + return unicode.PY_UNICODE_2BYTE_KIND + return unicode.PY_UNICODE_1BYTE_KIND + return impl + + +@overload_method(types.UnicodeType, '_to_bytes') +def unicode_to_bytes_mth(s): + """Convert unicode_type object to Bytes object. + + Note: The usage of _to_bytes method can be eliminated once all + Python bytes operations are implemented for numba Bytes objects. + + """ + def impl(s): + return _unicode_to_bytes(s) + return impl + + +@overload_method(types.CharSeq, '_to_str') +@overload_method(types.Bytes, '_to_str') +def charseq_to_str_mth(s): + """Convert bytes array item or bytes instance to UTF-8 str. + + Note: The usage of _to_str method can be eliminated once all + Python bytes operations are implemented for numba Bytes objects. + """ + get_code = _get_code_impl(s) + + def tostr_impl(s): + n = len(s) + is_ascii = s.isascii() + result = unicode._empty_string( + unicode.PY_UNICODE_1BYTE_KIND, n, is_ascii) + for i in range(n): + code = get_code(s, i) + unicode._set_code_point(result, i, code) + return result + return tostr_impl + + +@overload_method(types.UnicodeCharSeq, "__str__") +def charseq_str(s): + get_code = _get_code_impl(s) + + def str_impl(s): + n = len(s) + kind = s._get_kind() + is_ascii = kind == 1 and s.isascii() + result = unicode._empty_string(kind, n, is_ascii) + for i in range(n): + code = get_code(s, i) + unicode._set_code_point(result, i, code) + return result + + return str_impl + + +@overload(bytes) +def charseq_bytes(s): + if isinstance(s, types.CharSeq): + return lambda s: s + + +@overload_method(types.UnicodeCharSeq, '__hash__') +def unicode_charseq_hash(s): + def impl(s): + return hash(str(s)) + return impl + + +@overload_method(types.CharSeq, '__hash__') +def charseq_hash(s): + def impl(s): + # Ideally, `return hash(bytes(s))` would be used here but + # numba Bytes does not implement hash (yet). However, for a + # UTF-8 string `s`, we have hash(bytes(s)) == hash(s), hence, + # we can convert CharSeq object to unicode_type and reuse its + # hash implementation: + return hash(s._to_str()) + return impl + + +@overload_method(types.UnicodeCharSeq, 'isupper') +def unicode_charseq_isupper(s): + def impl(s): + # workaround unicode_type.isupper bug: it returns int value + return not not str(s).isupper() + return impl + + +@overload_method(types.CharSeq, 'isupper') +def charseq_isupper(s): + def impl(s): + # return bytes(s).isupper() # TODO: implement isupper for Bytes + return not not s._to_str().isupper() + return impl + + +@overload_method(types.UnicodeCharSeq, 'upper') +def unicode_charseq_upper(s): + def impl(s): + return str(s).upper() + return impl + + +@overload_method(types.CharSeq, 'upper') +def charseq_upper(s): + def impl(s): + # return bytes(s).upper() # TODO: implement upper for Bytes + return s._to_str().upper()._to_bytes() + return impl + + +@overload_method(types.UnicodeCharSeq, 'find') +@overload_method(types.CharSeq, 'find') +@overload_method(types.Bytes, 'find') +def unicode_charseq_find(a, b): + if isinstance(a, types.UnicodeCharSeq): + if isinstance(b, types.UnicodeCharSeq): + def impl(a, b): + return str(a).find(str(b)) + return impl + if isinstance(b, types.UnicodeType): + def impl(a, b): + return str(a).find(b) + return impl + if isinstance(a, types.CharSeq): + if isinstance(b, (types.CharSeq, types.Bytes)): + def impl(a, b): + return a._to_str().find(b._to_str()) + return impl + if isinstance(a, types.UnicodeType): + if isinstance(b, types.UnicodeCharSeq): + def impl(a, b): + return a.find(str(b)) + return impl + if isinstance(a, types.Bytes): + if isinstance(b, types.CharSeq): + def impl(a, b): + return a._to_str().find(b._to_str()) + return impl + + +@overload_method(types.UnicodeCharSeq, 'rfind') +@overload_method(types.CharSeq, 'rfind') +@overload_method(types.Bytes, 'rfind') +def unicode_charseq_rfind(a, b): + if isinstance(a, types.UnicodeCharSeq): + if isinstance(b, types.UnicodeCharSeq): + def impl(a, b): + return str(a).rfind(str(b)) + return impl + if isinstance(b, types.UnicodeType): + def impl(a, b): + return str(a).rfind(b) + return impl + if isinstance(a, types.CharSeq): + if isinstance(b, (types.CharSeq, types.Bytes)): + def impl(a, b): + return a._to_str().rfind(b._to_str()) + return impl + if isinstance(a, types.UnicodeType): + if isinstance(b, types.UnicodeCharSeq): + def impl(a, b): + return a.rfind(str(b)) + return impl + if isinstance(a, types.Bytes): + if isinstance(b, types.CharSeq): + def impl(a, b): + return a._to_str().rfind(b._to_str()) + return impl + + +@overload_method(types.UnicodeCharSeq, 'startswith') +@overload_method(types.CharSeq, 'startswith') +@overload_method(types.Bytes, 'startswith') +def unicode_charseq_startswith(a, b): + if isinstance(a, types.UnicodeCharSeq): + if isinstance(b, types.UnicodeCharSeq): + def impl(a, b): + return str(a).startswith(str(b)) + return impl + if isinstance(b, types.UnicodeType): + def impl(a, b): + return str(a).startswith(b) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if isinstance(b, (types.CharSeq, types.Bytes)): + def impl(a, b): + return a._to_str().startswith(b._to_str()) + return impl + + +@overload_method(types.UnicodeCharSeq, 'endswith') +@overload_method(types.CharSeq, 'endswith') +@overload_method(types.Bytes, 'endswith') +def unicode_charseq_endswith(a, b): + if isinstance(a, types.UnicodeCharSeq): + if isinstance(b, types.UnicodeCharSeq): + def impl(a, b): + return str(a).endswith(str(b)) + return impl + if isinstance(b, types.UnicodeType): + def impl(a, b): + return str(a).endswith(b) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if isinstance(b, (types.CharSeq, types.Bytes)): + def impl(a, b): + return a._to_str().endswith(b._to_str()) + return impl + + +@register_jitable +def _map_bytes(seq): + return [s._to_bytes() for s in seq] + + +@overload_method(types.UnicodeCharSeq, 'split') +@overload_method(types.CharSeq, 'split') +@overload_method(types.Bytes, 'split') +def unicode_charseq_split(a, sep=None, maxsplit=-1): + if not (maxsplit == -1 or + isinstance(maxsplit, (types.Omitted, types.Integer, + types.IntegerLiteral))): + return None + if isinstance(a, types.UnicodeCharSeq): + if isinstance(sep, types.UnicodeCharSeq): + def impl(a, sep=None, maxsplit=-1): + return str(a).split(sep=str(sep), maxsplit=maxsplit) + return impl + if isinstance(sep, types.UnicodeType): + def impl(a, sep=None, maxsplit=-1): + return str(a).split(sep=sep, maxsplit=maxsplit) + return impl + if is_nonelike(sep): + if is_default(maxsplit, -1): + def impl(a, sep=None, maxsplit=-1): + return str(a).split() + else: + def impl(a, sep=None, maxsplit=-1): + return str(a).split(maxsplit=maxsplit) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if isinstance(sep, (types.CharSeq, types.Bytes)): + def impl(a, sep=None, maxsplit=-1): + return _map_bytes(a._to_str().split(sep._to_str(), + maxsplit=maxsplit)) + return impl + if is_nonelike(sep): + if is_default(maxsplit, -1): + def impl(a, sep=None, maxsplit=-1): + return _map_bytes(a._to_str().split()) + else: + def impl(a, sep=None, maxsplit=-1): + return _map_bytes(a._to_str().split(maxsplit=maxsplit)) + return impl + +# NOT IMPLEMENTED: rsplit + + +@overload_method(types.UnicodeCharSeq, 'ljust') +@overload_method(types.CharSeq, 'ljust') +@overload_method(types.Bytes, 'ljust') +def unicode_charseq_ljust(a, width, fillchar=' '): + if isinstance(a, types.UnicodeCharSeq): + if is_default(fillchar, ' '): + def impl(a, width, fillchar=' '): + return str(a).ljust(width) + return impl + elif isinstance(fillchar, types.UnicodeCharSeq): + def impl(a, width, fillchar=' '): + return str(a).ljust(width, str(fillchar)) + return impl + elif isinstance(fillchar, types.UnicodeType): + def impl(a, width, fillchar=' '): + return str(a).ljust(width, fillchar) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if is_default(fillchar, ' ') or is_default(fillchar, b' '): + def impl(a, width, fillchar=' '): + return a._to_str().ljust(width)._to_bytes() + return impl + elif isinstance(fillchar, (types.CharSeq, types.Bytes)): + def impl(a, width, fillchar=' '): + return a._to_str().ljust(width, fillchar._to_str())._to_bytes() + return impl + + +@overload_method(types.UnicodeCharSeq, 'rjust') +@overload_method(types.CharSeq, 'rjust') +@overload_method(types.Bytes, 'rjust') +def unicode_charseq_rjust(a, width, fillchar=' '): + if isinstance(a, types.UnicodeCharSeq): + if is_default(fillchar, ' '): + def impl(a, width, fillchar=' '): + return str(a).rjust(width) + return impl + elif isinstance(fillchar, types.UnicodeCharSeq): + def impl(a, width, fillchar=' '): + return str(a).rjust(width, str(fillchar)) + return impl + elif isinstance(fillchar, types.UnicodeType): + def impl(a, width, fillchar=' '): + return str(a).rjust(width, fillchar) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if is_default(fillchar, ' ') or is_default(fillchar, b' '): + def impl(a, width, fillchar=' '): + return a._to_str().rjust(width)._to_bytes() + return impl + elif isinstance(fillchar, (types.CharSeq, types.Bytes)): + def impl(a, width, fillchar=' '): + return a._to_str().rjust(width, fillchar._to_str())._to_bytes() + return impl + + +@overload_method(types.UnicodeCharSeq, 'center') +@overload_method(types.CharSeq, 'center') +@overload_method(types.Bytes, 'center') +def unicode_charseq_center(a, width, fillchar=' '): + if isinstance(a, types.UnicodeCharSeq): + if is_default(fillchar, ' '): + def impl(a, width, fillchar=' '): + return str(a).center(width) + return impl + elif isinstance(fillchar, types.UnicodeCharSeq): + def impl(a, width, fillchar=' '): + return str(a).center(width, str(fillchar)) + return impl + elif isinstance(fillchar, types.UnicodeType): + def impl(a, width, fillchar=' '): + return str(a).center(width, fillchar) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if is_default(fillchar, ' ') or is_default(fillchar, b' '): + def impl(a, width, fillchar=' '): + return a._to_str().center(width)._to_bytes() + return impl + elif isinstance(fillchar, (types.CharSeq, types.Bytes)): + def impl(a, width, fillchar=' '): + return a._to_str().center(width, fillchar._to_str())._to_bytes() + return impl + + +@overload_method(types.UnicodeCharSeq, 'zfill') +@overload_method(types.CharSeq, 'zfill') +@overload_method(types.Bytes, 'zfill') +def unicode_charseq_zfill(a, width): + if isinstance(a, types.UnicodeCharSeq): + def impl(a, width): + return str(a).zfill(width) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + def impl(a, width): + return a._to_str().zfill(width)._to_bytes() + return impl + + +@overload_method(types.UnicodeCharSeq, 'lstrip') +@overload_method(types.CharSeq, 'lstrip') +@overload_method(types.Bytes, 'lstrip') +def unicode_charseq_lstrip(a, chars=None): + if isinstance(a, types.UnicodeCharSeq): + if is_nonelike(chars): + def impl(a, chars=None): + return str(a).lstrip() + return impl + elif isinstance(chars, types.UnicodeCharSeq): + def impl(a, chars=None): + return str(a).lstrip(str(chars)) + return impl + elif isinstance(chars, types.UnicodeType): + def impl(a, chars=None): + return str(a).lstrip(chars) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if is_nonelike(chars): + def impl(a, chars=None): + return a._to_str().lstrip()._to_bytes() + return impl + elif isinstance(chars, (types.CharSeq, types.Bytes)): + def impl(a, chars=None): + return a._to_str().lstrip(chars._to_str())._to_bytes() + return impl + + +@overload_method(types.UnicodeCharSeq, 'rstrip') +@overload_method(types.CharSeq, 'rstrip') +@overload_method(types.Bytes, 'rstrip') +def unicode_charseq_rstrip(a, chars=None): + if isinstance(a, types.UnicodeCharSeq): + if is_nonelike(chars): + def impl(a, chars=None): + return str(a).rstrip() + return impl + elif isinstance(chars, types.UnicodeCharSeq): + def impl(a, chars=None): + return str(a).rstrip(str(chars)) + return impl + elif isinstance(chars, types.UnicodeType): + def impl(a, chars=None): + return str(a).rstrip(chars) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if is_nonelike(chars): + def impl(a, chars=None): + return a._to_str().rstrip()._to_bytes() + return impl + elif isinstance(chars, (types.CharSeq, types.Bytes)): + def impl(a, chars=None): + return a._to_str().rstrip(chars._to_str())._to_bytes() + return impl + + +@overload_method(types.UnicodeCharSeq, 'strip') +@overload_method(types.CharSeq, 'strip') +@overload_method(types.Bytes, 'strip') +def unicode_charseq_strip(a, chars=None): + if isinstance(a, types.UnicodeCharSeq): + if is_nonelike(chars): + def impl(a, chars=None): + return str(a).strip() + return impl + elif isinstance(chars, types.UnicodeCharSeq): + def impl(a, chars=None): + return str(a).strip(str(chars)) + return impl + elif isinstance(chars, types.UnicodeType): + def impl(a, chars=None): + return str(a).strip(chars) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if is_nonelike(chars): + def impl(a, chars=None): + return a._to_str().strip()._to_bytes() + return impl + elif isinstance(chars, (types.CharSeq, types.Bytes)): + def impl(a, chars=None): + return a._to_str().strip(chars._to_str())._to_bytes() + return impl + + +@overload_method(types.UnicodeCharSeq, 'join') +@overload_method(types.CharSeq, 'join') +@overload_method(types.Bytes, 'join') +def unicode_charseq_join(a, parts): + + if isinstance(a, types.UnicodeCharSeq): + # assuming parts contains UnicodeCharSeq or UnicodeType objects + def impl(a, parts): + _parts = [str(p) for p in parts] + return str(a).join(_parts) + return impl + + if isinstance(a, (types.CharSeq, types.Bytes)): + # assuming parts contains CharSeq or Bytes objects + def impl(a, parts): + _parts = [p._to_str() for p in parts] + return a._to_str().join(_parts)._to_bytes() + return impl diff --git a/shared/package-files/71/71914a8ade77b3f0c9a34e1d2b82b79b4c09b789c785577a38713d8dfb7c63f5/sizevars.py b/shared/package-files/71/71914a8ade77b3f0c9a34e1d2b82b79b4c09b789c785577a38713d8dfb7c63f5/sizevars.py new file mode 100644 index 0000000000000000000000000000000000000000..ceff1bddc913431ac7fb690e844606843b575220 --- /dev/null +++ b/shared/package-files/71/71914a8ade77b3f0c9a34e1d2b82b79b4c09b789c785577a38713d8dfb7c63f5/sizevars.py @@ -0,0 +1,643 @@ +import functools +import itertools +import logging +from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Union + +import sympy +from sympy import Expr + +from torch.fx.experimental.symbolic_shapes import ShapeEnv +from torch.utils._sympy.functions import FloorDiv, ModularIndexing +from torch.utils._sympy.value_ranges import bound_sympy + +from .utils import sympy_index_symbol, sympy_subs, VarRanges +from .virtualized import V + +log = logging.getLogger(__name__) + + +# This class is a little awkward, because ShapeEnv is doing most of the heavy +# lifting and in some cases we should be directly passing through to ShapeEnv, +# but there is some extra inductor logic that needs to be handled here +class SizeVarAllocator: + def __init__(self, shape_env=None): + super().__init__() + if shape_env is None: + shape_env = ShapeEnv() + self.shape_env = shape_env + self.var_to_val = self.shape_env.var_to_val + self.replacements: Dict[sympy.Symbol, Expr] = self.shape_env.replacements + # Maps of dynamic sizes that have to be precomputed on the host to the kernel args. + # The basic idea is if we have some complicated sympy expression + # f(s0), we may choose to precompute it on the host and then replace + # all occurrences of that sympy expression with ps0, so that when we + # codegen we simply reference ps0 directly without repeating + # f(s0). Unlike regular size variables, ps variables cannot be + # guarded upon; so if we are asked to guard on a Sympy expression + # which potentially could have already had a precomputed replacement + # on it, we are obligated to invert the precomputed replacements + # (inv_precomputed_replacements). + self.precomputed_replacements: Dict[Expr, sympy.Symbol] = dict() + self.inv_precomputed_replacements: Dict[sympy.Symbol, Expr] = dict() + self.stride_vars = self.make_stride_vars_cache() + self.simplify_with_ranges = self.make_simplify_with_ranges_cache() + self._simplify_loops = self.make_simplify_loops_cache() + + def simplify(self, expr: Expr): + return sympy.expand(expr).xreplace(self.replacements) + + def make_simplify_with_ranges_cache(self) -> Callable[[Expr, VarRanges], Expr]: + """ + self._simplify_with_ranges() can be expensive, cache its results + """ + cache: Dict[Tuple[Any, ...], Expr] = dict() + replacement_count = len(self.replacements) + + def simplify_with_ranges(expr: Expr, var_ranges: VarRanges) -> Expr: + nonlocal replacement_count + if replacement_count != len(self.replacements): + # new replacements invalidates cached results + cache.clear() + replacement_count = len(self.replacements) + key = (expr, *var_ranges.items()) + result = cache.get(key, None) + if result is None: + result = self._simplify_with_ranges(expr, var_ranges) + cache[key] = result + return result + + return simplify_with_ranges + + def make_simplify_loops_cache(self): + """ + self._simplify_with_ranges() can be expensive, cache its results + """ + cache: Dict[Tuple[Any, ...], Any] = dict() + replacement_count = len(self.replacements) + + def simplify_loops(index_vars, sizes, index_formulas): + nonlocal replacement_count + if replacement_count != len(self.replacements): + # new replacements invalidates cached results + cache.clear() + replacement_count = len(self.replacements) + key = (*index_vars, *sizes, *index_formulas) + result = cache.get(key, None) + if result is None: + result = self._simplify_loops_impl(index_vars, sizes, index_formulas) + cache[key] = result + return result + + return simplify_loops + + def _simplify_with_ranges(self, expr: Expr, var_ranges: VarRanges) -> Expr: + """ + Simplify indexing expression with knowledge of the ranges of + iteration variables. + """ + + expr = join_dimensions(self.simplify(expr)) + original_expr = expr + + def remove_zero_terms(base, divisor): + """Symbols smaller than the divisor are zero""" + for v in base.free_symbols: + if v in var_ranges: + # var smaller than divisor can be removed + # if the rest is guaranteed to be multiple of divisor + rest = sympy.Wild("_rest", exclude=[v]) + m = base.match(v + rest) + if m and v not in m[rest].free_symbols: + gcd = sympy.gcd(m[rest], divisor) + if gcd == divisor: + if self.statically_known_leq(var_ranges[v], divisor): + base = m[rest] + return base + + def visit_indexing_div(base, divisor): + return FloorDiv(remove_zero_terms(base, divisor), divisor) + + def visit_modular_indexing(base, divisor, modulus): + base = remove_zero_terms(base, divisor) + base_pos = True + if isinstance(base, ModularIndexing): + # for modular indexing, biggest values from the ranges don't necessarily result in + # the biggest result, the biggest result is modulus - 1 + base_s = base.args[2] - 1 + elif not base.has(ModularIndexing): + # actual iteration range is to size-1 + iter_ranges_zero = {k: 0 for k, v in var_ranges.items()} + base_lowest = sympy_subs(base, iter_ranges_zero) + if self.statically_known_leq(0, base_lowest): # type: ignore[arg-type] + # can't replace with indexing div if base can be negative + base_pos = True + else: + base_pos = False + iter_ranges = {k: v - 1 for k, v in var_ranges.items()} + base_s = sympy_subs(base, iter_ranges) + else: + base_s = base + if self.statically_known_lt(base_s, modulus * divisor) and base_pos: + return FloorDiv(base, divisor) + return ModularIndexing(base, divisor, modulus) + + if expr.has(ModularIndexing): + expr = expr.replace( + ModularIndexing( + sympy.Wild("base"), + sympy.Wild("divisor"), + sympy.Wild("modulus"), + ), + visit_modular_indexing, + ) + + if expr.has(FloorDiv): + expr = expr.replace( + FloorDiv( + sympy.Wild("base"), + sympy.Wild("divisor"), + ), + visit_indexing_div, + ) + + if expr != original_expr: + return self._simplify_with_ranges(expr, var_ranges) + return expr + + def _simplify_loops_impl( + self, index_vars: List[sympy.Symbol], sizes, index_formulas + ): + """ + Try to remove as many axis from loop iterations as possible, by: + 1) removing size==1 dimensions + 2) fuse contiguous dimensions into a single loop + If channel_last = True, we will prevent the last dim fused with other dims + """ + sizes = list(map(self.simplify, sizes)) + + strides = [self.stride_vars(x, index_vars) for x in index_formulas] + assert len(sizes) == len(strides[0]), (len(sizes), len(strides[0])) + + for i in range(len(sizes)): + if sizes[i] == 1: + # remove dim + sizes[i] = None + + def can_merge_dims(a, b): + for k in range(len(strides)): + if self.simplify(strides[k][a] * sizes[a]) == self.simplify( + strides[k][b] + ): + # approximate test passed, try sound version + va = index_vars[a] + vb = index_vars[b] + v = sympy_index_symbol("_merge_tester") + expr1 = sympy_subs(index_formulas[k], {va: v * sizes[a], vb: 0}) + expr2 = sympy_subs(index_formulas[k], {va: 0, vb: v}) + if self.simplify(expr1) == self.simplify(expr2): + continue + return False + return True + + changed = True + while changed: + changed = False + for i, j in itertools.product( + reversed(range(len(sizes))), reversed(range(len(sizes))) + ): + if i == j or sizes[i] is None or sizes[j] is None: + continue + if can_merge_dims(i, j): + changed = True + sizes[i] = sizes[i] * sizes[j] + sizes[j] = None + + def reindex(index): + it = list(reversed(index)) + new_index = [] + for size in sizes: + if size is None: + new_index.append(sympy.Integer(0)) + else: + new_index.append(it.pop()) + assert not it + return new_index + + def prune(index): + assert len(index) == len(sizes) + return [i for i, s in zip(index, sizes) if s is not None] + + return [x for x in sizes if x is not None], reindex, prune + + # Note - [On Statically Known] + # + # The statically_known_* family of functions below replaces a prior system, called maybe_guard_*. The prior system + # operated by providing essentially a question, where the size hinted values were evaluated. If the condition was + # true, we add a guard and return True, otherwise, False. + # + # def maybe_guard_foo(args): + # if size_hinted_check(args): + # return False # No guard, no optim + # guard(args) # Make a guard + # return True # Safe to apply optimization + # + # The prior system incurred a guard, and green lit an optimization. + # + # The new system works in reverse - in the new system, if we know that the inputs are static, and evaluate the + # condition as true, we green light the optimization, and we do not incur a guard. If we cannot prove that, we + # return False. + # + # def maybe_guard_foo(args): + # if all_static(args): + # return True # Safe to apply optimization + # else: + # return False # No guard, no optim + + # See Note - [On Statically Known] + + def is_expr_static_and_true(self, expr: Union[Expr, int]) -> bool: + if expr in (True, False): + return bool(expr) + + try: + simplified = self.shape_env._maybe_evaluate_static(expr) + if simplified is not None: + return bool(simplified) + except Exception: + log.debug("Could not simplify %s", expr) + + return False + + def statically_known_equals(self, left: Expr, right: Expr) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left and right are equal. + """ + return self.is_expr_static_and_true(sympy.Eq(left, right)) # type: ignore[arg-type] + + # See Note - [On Statically Known] + def statically_known_list_equals(self, left: List[Expr], right: List[Expr]) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left and right lists are equal. + """ + if len(left) != len(right): + return False + if all(self.statically_known_equals(l, r) for l, r in zip(left, right)): + return True + return False + + # See Note - [On Statically Known] + def statically_known_leq(self, left: Expr, right: Expr) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left is less than or equal to right. + """ + expr = left <= right + return self.is_expr_static_and_true(expr) + + # See Note - [On Statically Known] + def statically_known_lt(self, left: Expr, right: Expr) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left is less than right. + """ + expr = left < right + return self.is_expr_static_and_true(expr) + + # See Note - [On Statically Known] + def statically_known_multiple_of(self, numerator: Expr, denominator: Expr) -> bool: + """ + Return a bool indicating if it is sound to optimize for the numerator being a multiple of the denominator. + """ + expr = sympy.Eq(numerator % denominator, 0) + return self.is_expr_static_and_true(expr) # type: ignore[arg-type] + + # The guard functions require you to ALREADY KNOW that a particular + # condition holds. If you don't know (you want to guard on an expression + # being a particular value, and then get access to that value), use + # the evaluate functions. + + def guard_equals(self, left: Expr, right: Expr) -> Expr: + if isinstance(left, Expr): + left = sympy_subs(left, self.inv_precomputed_replacements) # type: ignore[arg-type] + if isinstance(right, Expr): + right = sympy_subs(right, self.inv_precomputed_replacements) # type: ignore[arg-type] + assert self.shape_env.evaluate_expr(sympy.Eq(left, right)) + return left + + def guard_leq(self, left: Expr, right: Expr) -> None: + return self.guard_lt(left, right + 1) + + def guard_lt(self, left: Expr, right: Expr) -> None: + assert self.shape_env.evaluate_expr(sympy.Lt(left, right)) + + def expect_true(self, expr: Expr, *, msg: str) -> None: + expr = sympy_subs(expr, self.inv_precomputed_replacements) # type: ignore[arg-type] + self.shape_env.defer_runtime_assert(expr, msg, fx_node=None) + + def expect_equals(self, left: Expr, right: Expr, *, msg: str) -> Expr: + # Prefer returning the expression without unbacked symints + if self.shape_env.is_unbacked_symint(left): + self.expect_true(sympy.Eq(left, right), msg=msg) # type: ignore[arg-type] + return right + elif self.shape_env.is_unbacked_symint(right): + self.expect_true(sympy.Eq(left, right), msg=msg) # type: ignore[arg-type] + return left + else: + return self.guard_equals(left, right) + + def guarded_order(self, seq): + """ + Return the order of a sequence as a permutation of range(len(seq)) and guard on that order not changing. + Used for generating block_ptrs. + """ + seq = [*map(self.remove_precomputed_replacements, seq)] + seq = [(self.size_hint(var), orig_idx, var) for orig_idx, var in enumerate(seq)] + seq.sort() + order = [-1] * len(seq) + last_var = None + for new_index, (_, orig_index, var) in enumerate(seq): + order[orig_index] = new_index + if last_var is not None: + self.guard_leq(last_var, var) + last_var = var + return order + + # The evaluate functions evaluate some symbolic sympy expression + # (NB: not necessarily an Expr) and return what the concrete result + # is, guarding on the expression being that result + + # NB: write evaluate_expr(sympy.Lt(a, b)) rather than evaluate_expr(a < b) + # as this will ensure that you actually have a sympy'ified expression, + # and will prevent you from incorrectly writing evaluate_expr(a == b) + # which does the wrong thing if a or b is a sympy expression + def evaluate_expr(self, left: Union[Expr, sympy.logic.boolalg.Boolean]) -> bool: + assert isinstance(left, (Expr, sympy.logic.boolalg.Boolean)), type(left) + return self.shape_env.evaluate_expr(sympy.sympify(left)) + + def evaluate_min(self, left: Expr, right: Expr) -> Expr: + """return the smaller of left and right, and guard on that choice""" + lv = self.size_hint(left) + rv = self.size_hint(right) + if lv <= rv: + self.guard_leq(left, right) + return left + else: + self.guard_leq(right, left) + return right + + def evaluate_max(self, left: Expr, right: Expr) -> Expr: + """return the larger of left and right, and guard on that choice""" + # Always choose the opposite of eval min for consistency + # This means min(a, b) and max(a, b) produce the same guards + min_val = self.evaluate_min(left, right) + return right if min_val is left else left + + def evaluate_static_shape(self, left: Expr) -> int: + right = self.size_hint(left) + self.guard_equals(left, sympy.Integer(right)) + return int(right) + + def evaluate_static_shapes(self, left: List[Expr]) -> List[int]: + return [self.evaluate_static_shape(x) for x in left] + + def remove_precomputed_replacements(self, expr: Expr) -> Expr: + if any(s.name.startswith("ps") for s in expr.free_symbols): # type: ignore[attr-defined] + return sympy_subs(expr, self.inv_precomputed_replacements) # type: ignore[arg-type] + return expr + + def symbolic_hint(self, expr: Expr) -> Expr: + # Substitute all hints into expr, but leave unbacked symints alone + if not isinstance(expr, Expr): + assert isinstance(expr, int) + return expr + free_symbols = expr.free_symbols + if not free_symbols: + return int(expr) # type: ignore[return-value] + expr = self.remove_precomputed_replacements(expr) + return sympy_subs(expr, self.var_to_val) + + def size_hint(self, expr: Expr, *, fallback: Optional[int] = None) -> int: + out = self.symbolic_hint(expr) + if not isinstance(out, (int, sympy.Integer)) and fallback is not None: + # Use the provided heuristic fallback hint + sym_vrs = { + s: self.shape_env.var_to_range.get(s, None) for s in expr.free_symbols + } + if all(vr is not None for vr in sym_vrs.values()): + expr_vr = bound_sympy(expr, sym_vrs) # type: ignore[arg-type] + lower = self.size_hint(expr_vr.lower) # type: ignore[arg-type] + upper = self.size_hint(expr_vr.upper) # type: ignore[arg-type] + fallback = min(max(fallback, lower), upper) + return fallback + try: + return int(out) + except Exception: + log.debug("failed on: %s", out) + raise + + def size_hints( + self, + exprs: Iterable[Expr], + *, + fallback: Optional[int] = None, + ) -> Tuple[int, ...]: + return tuple(self.size_hint(x, fallback=fallback) for x in exprs) + + def _lru_cache(self, fn, maxsize=None): + """ + Wrapper around functools.lru_cache that clears when replacements + has been invalidated. + """ + fn_cache = functools.lru_cache(maxsize)(fn) + prior_len = len(self.replacements) + + @functools.wraps(fn) + def wrapper(*args, **kwargs): + nonlocal prior_len + if prior_len != len(self.replacements): + prior_len = len(self.replacements) + fn_cache.cache_clear() + return fn_cache(*args, **kwargs) + + return wrapper + + def make_stride_vars_cache(self): + cache = self._lru_cache(self._stride_vars) + + def stride_vars( + index: Expr, + vars: List[sympy.Symbol], + support_vars: Optional[List[sympy.Symbol]] = None, + ) -> List[Expr]: + if not support_vars: + support_vars = vars + return cache(index, tuple(vars), tuple(support_vars)) + + return stride_vars + + def _stride_vars( + self, index: Expr, vars: List[sympy.Symbol], support_vars: List[sympy.Symbol] + ) -> List[Expr]: + """Convert an indexing expression back into strides + + NOTE: This is only valid if the index is a standard strided offset + calculation. e.g. 10 * ModularIndexing(i0 + 1, 1, 2) would give a + stride of -10 because the index wraps around after the first element + + """ + strides = [] + index = self.simplify(index) + # remove any offset + index = index - sympy_subs( + index, {v: sympy.Integer(0) for v in support_vars if v != 0} + ) + for i in range(len(vars)): + # drop all the other dims + index_dim = sympy_subs( + index, + { + support_vars[j]: sympy.Integer(0) + for j in range(len(support_vars)) + if vars[i] != support_vars[j] and support_vars[j] != 0 + }, + ) + v = vars[i] + if v == 0: + strides.append(sympy.Integer(0)) + else: + # TODO(jansel): should we use sympy.diff here? + strides.append( + sympy_subs(index_dim, {v: sympy.Integer(1)}) + - sympy_subs(index_dim, {v: sympy.Integer(0)}) + ) + return strides + + def offset_var(self, index: Expr, vars: List[sympy.Symbol]) -> Expr: + """Extract offset part of an indexing expression""" + index = self.simplify(index) + return sympy_subs(index, {v: sympy.Integer(0) for v in vars if v != 0}) + + def stride_hints( + self, + index: Expr, + vars: List[sympy.Symbol], + support_vars: Optional[List[sympy.Symbol]] = None, + ) -> List[int]: + for v in index.free_symbols: + if v.name.startswith("indirect"): # type: ignore[attr-defined] + index = sympy_subs(index, {v: 0}) # type: ignore[dict-item] + result = [] + for s in self.stride_vars(index, vars, support_vars): + try: + result.append(self.size_hint(s)) + except TypeError: + result.append(0) + return result + + def stride_order(self, index: Expr, vars: List[sympy.Symbol]) -> List[int]: + strides = tuple(map(abs, self.stride_hints(index, vars))) + order = list(range(len(strides))) + order.sort(key=lambda x: (strides[x] == 0, strides[x])) + return order + + def lookup_precomputed_size(self, expr: Expr) -> Expr: + if ( + isinstance(expr, (int, sympy.Symbol, sympy.Number)) + or expr.is_number + or expr.is_symbol + ): + return expr + expr = self.remove_precomputed_replacements(expr) + if expr not in self.precomputed_replacements: + sym = sympy_index_symbol(f"ps{len(self.precomputed_replacements)}") + self.precomputed_replacements[expr] = sym + self.inv_precomputed_replacements[sym] = expr + return self.precomputed_replacements[expr] + + def free_symbols(self) -> Set[sympy.Symbol]: + return set(self.var_to_val.keys()) - set(self.replacements.keys()) + + +def join_dimensions(expr: Expr) -> Expr: + if not isinstance(expr, sympy.Add) or not expr.has(ModularIndexing): + return expr # fast exit path + return _join_dimensions_cached(expr) + + +@functools.lru_cache(256) +def _join_dimensions_cached(expr: Expr) -> Expr: + """ + ModularIndexing(i0, 1, 32) + 32 * ModularIndexing(i0, 32, 4) + becomes + ModularIndexing(i0, 1, 128) + ModularIndexing(i0, 1, 32) + 32 * FloorDiv(i0, 32) + becomes i0 + + + This type of pattern can come from view operations + """ + assert isinstance(expr, sympy.Add) + + scale = sympy.Wild("scale", exclude=[0]) + base = sympy.Wild("base") + divisor = sympy.Wild("divisor") + mod1 = sympy.Wild("modulus") + mod2 = sympy.Wild("modulus2") + for term1 in expr.args: + m1 = term1.match(scale * ModularIndexing(base, divisor, mod1)) + if m1: + for term2 in expr.args: + m2 = term2.match( + m1[scale] + * m1[mod1] + * ModularIndexing(m1[base], m1[divisor] * m1[mod1], mod2) + ) + if m2 and term1 != term2: + expr = join_dimensions( + expr + - term1 + - term2 + + m1[scale] + * ModularIndexing(m1[base], m1[divisor], m1[mod1] * m2[mod2]) + ) + return expr + for term1 in expr.args: + m1 = term1.match(scale * ModularIndexing(base, divisor, mod1)) + if m1: + for term2 in expr.args: + m2 = term2.match( + m1[scale] * m1[mod1] * FloorDiv(m1[base], m1[divisor] * m1[mod1]) + ) + if m2 is not None: # in case of success we get an empty dict here + expr = join_dimensions( + expr + - term1 + - term2 + + m1[scale] * FloorDiv(m1[base], m1[divisor]) + ) + return expr + return expr + + +class SimplifyIndexing(V.WrapperHandler): # type: ignore[name-defined] + """ + A wrapper around .virtualize.ops that uses var range information to + simplify ModularIndexing/FloorDiv. + """ + + def __init__(self, inner, var_ranges: VarRanges): + super().__init__(inner) + self.name = "SimplifyIndexing" + self._simplify: Callable[ + [Expr], Expr + ] = lambda index: V.graph.sizevars.simplify_with_ranges(index, var_ranges) + + def load(self, name: str, index: sympy.Expr): + return self._inner.load(name, self._simplify(index)) + + def store(self, name, index, value, mode=None): + return self._inner.store(name, self._simplify(index), value, mode=mode) + + def store_reduction(self, name, index, value): + return self._inner.store_reduction(name, self._simplify(index), value) + + def index_expr(self, index, dtype): + return self._inner.index_expr(self._simplify(index), dtype) diff --git a/shared/package-files/71/719244755d233fc69f45932a27cf9a2fd31ae4d75749632e8f58556e318c4768/test_convert_pandas.py b/shared/package-files/71/719244755d233fc69f45932a27cf9a2fd31ae4d75749632e8f58556e318c4768/test_convert_pandas.py new file mode 100644 index 0000000000000000000000000000000000000000..ca8d08c705f142bb24232aaf63f9b3397375409e --- /dev/null +++ b/shared/package-files/71/719244755d233fc69f45932a27cf9a2fd31ae4d75749632e8f58556e318c4768/test_convert_pandas.py @@ -0,0 +1,320 @@ +import pytest + +import networkx as nx +from networkx.utils import edges_equal, graphs_equal, nodes_equal + +np = pytest.importorskip("numpy") +pd = pytest.importorskip("pandas") + + +class TestConvertPandas: + def setup_method(self): + self.rng = np.random.RandomState(seed=5) + ints = self.rng.randint(1, 11, size=(3, 2)) + a = ["A", "B", "C"] + b = ["D", "A", "E"] + df = pd.DataFrame(ints, columns=["weight", "cost"]) + df[0] = a # Column label 0 (int) + df["b"] = b # Column label 'b' (str) + self.df = df + + mdf = pd.DataFrame([[4, 16, "A", "D"]], columns=["weight", "cost", 0, "b"]) + self.mdf = pd.concat([df, mdf]) + + def test_exceptions(self): + G = pd.DataFrame(["a"]) # adj + pytest.raises(nx.NetworkXError, nx.to_networkx_graph, G) + G = pd.DataFrame(["a", 0.0]) # elist + pytest.raises(nx.NetworkXError, nx.to_networkx_graph, G) + df = pd.DataFrame([[1, 1], [1, 0]], dtype=int, index=[1, 2], columns=["a", "b"]) + pytest.raises(nx.NetworkXError, nx.from_pandas_adjacency, df) + + def test_from_edgelist_all_attr(self): + Gtrue = nx.Graph( + [ + ("E", "C", {"cost": 9, "weight": 10}), + ("B", "A", {"cost": 1, "weight": 7}), + ("A", "D", {"cost": 7, "weight": 4}), + ] + ) + G = nx.from_pandas_edgelist(self.df, 0, "b", True) + assert graphs_equal(G, Gtrue) + # MultiGraph + MGtrue = nx.MultiGraph(Gtrue) + MGtrue.add_edge("A", "D", cost=16, weight=4) + MG = nx.from_pandas_edgelist(self.mdf, 0, "b", True, nx.MultiGraph()) + assert graphs_equal(MG, MGtrue) + + def test_from_edgelist_multi_attr(self): + Gtrue = nx.Graph( + [ + ("E", "C", {"cost": 9, "weight": 10}), + ("B", "A", {"cost": 1, "weight": 7}), + ("A", "D", {"cost": 7, "weight": 4}), + ] + ) + G = nx.from_pandas_edgelist(self.df, 0, "b", ["weight", "cost"]) + assert graphs_equal(G, Gtrue) + + def test_from_edgelist_multi_attr_incl_target(self): + Gtrue = nx.Graph( + [ + ("E", "C", {0: "C", "b": "E", "weight": 10}), + ("B", "A", {0: "B", "b": "A", "weight": 7}), + ("A", "D", {0: "A", "b": "D", "weight": 4}), + ] + ) + G = nx.from_pandas_edgelist(self.df, 0, "b", [0, "b", "weight"]) + assert graphs_equal(G, Gtrue) + + def test_from_edgelist_multidigraph_and_edge_attr(self): + # example from issue #2374 + edges = [ + ("X1", "X4", {"Co": "zA", "Mi": 0, "St": "X1"}), + ("X1", "X4", {"Co": "zB", "Mi": 54, "St": "X2"}), + ("X1", "X4", {"Co": "zB", "Mi": 49, "St": "X3"}), + ("X1", "X4", {"Co": "zB", "Mi": 44, "St": "X4"}), + ("Y1", "Y3", {"Co": "zC", "Mi": 0, "St": "Y1"}), + ("Y1", "Y3", {"Co": "zC", "Mi": 34, "St": "Y2"}), + ("Y1", "Y3", {"Co": "zC", "Mi": 29, "St": "X2"}), + ("Y1", "Y3", {"Co": "zC", "Mi": 24, "St": "Y3"}), + ("Z1", "Z3", {"Co": "zD", "Mi": 0, "St": "Z1"}), + ("Z1", "Z3", {"Co": "zD", "Mi": 14, "St": "X3"}), + ] + Gtrue = nx.MultiDiGraph(edges) + data = { + "O": ["X1", "X1", "X1", "X1", "Y1", "Y1", "Y1", "Y1", "Z1", "Z1"], + "D": ["X4", "X4", "X4", "X4", "Y3", "Y3", "Y3", "Y3", "Z3", "Z3"], + "St": ["X1", "X2", "X3", "X4", "Y1", "Y2", "X2", "Y3", "Z1", "X3"], + "Co": ["zA", "zB", "zB", "zB", "zC", "zC", "zC", "zC", "zD", "zD"], + "Mi": [0, 54, 49, 44, 0, 34, 29, 24, 0, 14], + } + df = pd.DataFrame.from_dict(data) + G1 = nx.from_pandas_edgelist( + df, source="O", target="D", edge_attr=True, create_using=nx.MultiDiGraph + ) + G2 = nx.from_pandas_edgelist( + df, + source="O", + target="D", + edge_attr=["St", "Co", "Mi"], + create_using=nx.MultiDiGraph, + ) + assert graphs_equal(G1, Gtrue) + assert graphs_equal(G2, Gtrue) + + def test_from_edgelist_one_attr(self): + Gtrue = nx.Graph( + [ + ("E", "C", {"weight": 10}), + ("B", "A", {"weight": 7}), + ("A", "D", {"weight": 4}), + ] + ) + G = nx.from_pandas_edgelist(self.df, 0, "b", "weight") + assert graphs_equal(G, Gtrue) + + def test_from_edgelist_int_attr_name(self): + # note: this also tests that edge_attr can be `source` + Gtrue = nx.Graph( + [("E", "C", {0: "C"}), ("B", "A", {0: "B"}), ("A", "D", {0: "A"})] + ) + G = nx.from_pandas_edgelist(self.df, 0, "b", 0) + assert graphs_equal(G, Gtrue) + + def test_from_edgelist_invalid_attr(self): + pytest.raises( + nx.NetworkXError, nx.from_pandas_edgelist, self.df, 0, "b", "misspell" + ) + pytest.raises(nx.NetworkXError, nx.from_pandas_edgelist, self.df, 0, "b", 1) + # see Issue #3562 + edgeframe = pd.DataFrame([[0, 1], [1, 2], [2, 0]], columns=["s", "t"]) + pytest.raises( + nx.NetworkXError, nx.from_pandas_edgelist, edgeframe, "s", "t", True + ) + pytest.raises( + nx.NetworkXError, nx.from_pandas_edgelist, edgeframe, "s", "t", "weight" + ) + pytest.raises( + nx.NetworkXError, + nx.from_pandas_edgelist, + edgeframe, + "s", + "t", + ["weight", "size"], + ) + + def test_from_edgelist_no_attr(self): + Gtrue = nx.Graph([("E", "C", {}), ("B", "A", {}), ("A", "D", {})]) + G = nx.from_pandas_edgelist(self.df, 0, "b") + assert graphs_equal(G, Gtrue) + + def test_from_edgelist(self): + # Pandas DataFrame + G = nx.cycle_graph(10) + G.add_weighted_edges_from((u, v, u) for u, v in list(G.edges)) + + edgelist = nx.to_edgelist(G) + source = [s for s, t, d in edgelist] + target = [t for s, t, d in edgelist] + weight = [d["weight"] for s, t, d in edgelist] + edges = pd.DataFrame({"source": source, "target": target, "weight": weight}) + + GG = nx.from_pandas_edgelist(edges, edge_attr="weight") + assert nodes_equal(G.nodes(), GG.nodes()) + assert edges_equal(G.edges(), GG.edges()) + GW = nx.to_networkx_graph(edges, create_using=nx.Graph) + assert nodes_equal(G.nodes(), GW.nodes()) + assert edges_equal(G.edges(), GW.edges()) + + def test_to_edgelist_default_source_or_target_col_exists(self): + G = nx.path_graph(10) + G.add_weighted_edges_from((u, v, u) for u, v in list(G.edges)) + nx.set_edge_attributes(G, 0, name="source") + pytest.raises(nx.NetworkXError, nx.to_pandas_edgelist, G) + + # drop source column to test an exception raised for the target column + for u, v, d in G.edges(data=True): + d.pop("source", None) + + nx.set_edge_attributes(G, 0, name="target") + pytest.raises(nx.NetworkXError, nx.to_pandas_edgelist, G) + + def test_to_edgelist_custom_source_or_target_col_exists(self): + G = nx.path_graph(10) + G.add_weighted_edges_from((u, v, u) for u, v in list(G.edges)) + nx.set_edge_attributes(G, 0, name="source_col_name") + pytest.raises( + nx.NetworkXError, nx.to_pandas_edgelist, G, source="source_col_name" + ) + + # drop source column to test an exception raised for the target column + for u, v, d in G.edges(data=True): + d.pop("source_col_name", None) + + nx.set_edge_attributes(G, 0, name="target_col_name") + pytest.raises( + nx.NetworkXError, nx.to_pandas_edgelist, G, target="target_col_name" + ) + + def test_to_edgelist_edge_key_col_exists(self): + G = nx.path_graph(10, create_using=nx.MultiGraph) + G.add_weighted_edges_from((u, v, u) for u, v in list(G.edges())) + nx.set_edge_attributes(G, 0, name="edge_key_name") + pytest.raises( + nx.NetworkXError, nx.to_pandas_edgelist, G, edge_key="edge_key_name" + ) + + def test_from_adjacency(self): + nodelist = [1, 2] + dftrue = pd.DataFrame( + [[1, 1], [1, 0]], dtype=int, index=nodelist, columns=nodelist + ) + G = nx.Graph([(1, 1), (1, 2)]) + df = nx.to_pandas_adjacency(G, dtype=int) + pd.testing.assert_frame_equal(df, dftrue) + + @pytest.mark.parametrize("graph", [nx.Graph, nx.MultiGraph]) + def test_roundtrip(self, graph): + # edgelist + Gtrue = graph([(1, 1), (1, 2)]) + df = nx.to_pandas_edgelist(Gtrue) + G = nx.from_pandas_edgelist(df, create_using=graph) + assert graphs_equal(Gtrue, G) + # adjacency + adj = {1: {1: {"weight": 1}, 2: {"weight": 1}}, 2: {1: {"weight": 1}}} + Gtrue = graph(adj) + df = nx.to_pandas_adjacency(Gtrue, dtype=int) + G = nx.from_pandas_adjacency(df, create_using=graph) + assert graphs_equal(Gtrue, G) + + def test_from_adjacency_named(self): + # example from issue #3105 + data = { + "A": {"A": 0, "B": 0, "C": 0}, + "B": {"A": 1, "B": 0, "C": 0}, + "C": {"A": 0, "B": 1, "C": 0}, + } + dftrue = pd.DataFrame(data, dtype=np.intp) + df = dftrue[["A", "C", "B"]] + G = nx.from_pandas_adjacency(df, create_using=nx.DiGraph()) + df = nx.to_pandas_adjacency(G, dtype=np.intp) + pd.testing.assert_frame_equal(df, dftrue) + + def test_edgekey_with_multigraph(self): + df = pd.DataFrame( + { + "source": {"A": "N1", "B": "N2", "C": "N1", "D": "N1"}, + "target": {"A": "N2", "B": "N3", "C": "N1", "D": "N2"}, + "attr1": {"A": "F1", "B": "F2", "C": "F3", "D": "F4"}, + "attr2": {"A": 1, "B": 0, "C": 0, "D": 0}, + "attr3": {"A": 0, "B": 1, "C": 0, "D": 1}, + } + ) + Gtrue = nx.MultiGraph( + [ + ("N1", "N2", "F1", {"attr2": 1, "attr3": 0}), + ("N2", "N3", "F2", {"attr2": 0, "attr3": 1}), + ("N1", "N1", "F3", {"attr2": 0, "attr3": 0}), + ("N1", "N2", "F4", {"attr2": 0, "attr3": 1}), + ] + ) + # example from issue #4065 + G = nx.from_pandas_edgelist( + df, + source="source", + target="target", + edge_attr=["attr2", "attr3"], + edge_key="attr1", + create_using=nx.MultiGraph(), + ) + assert graphs_equal(G, Gtrue) + + df_roundtrip = nx.to_pandas_edgelist(G, edge_key="attr1") + df_roundtrip = df_roundtrip.sort_values("attr1") + df_roundtrip.index = ["A", "B", "C", "D"] + pd.testing.assert_frame_equal( + df, df_roundtrip[["source", "target", "attr1", "attr2", "attr3"]] + ) + + def test_edgekey_with_normal_graph_no_action(self): + Gtrue = nx.Graph( + [ + ("E", "C", {"cost": 9, "weight": 10}), + ("B", "A", {"cost": 1, "weight": 7}), + ("A", "D", {"cost": 7, "weight": 4}), + ] + ) + G = nx.from_pandas_edgelist(self.df, 0, "b", True, edge_key="weight") + assert graphs_equal(G, Gtrue) + + def test_nonexisting_edgekey_raises(self): + with pytest.raises(nx.exception.NetworkXError): + nx.from_pandas_edgelist( + self.df, + source="source", + target="target", + edge_key="Not_real", + edge_attr=True, + create_using=nx.MultiGraph(), + ) + + +def test_to_pandas_adjacency_with_nodelist(): + G = nx.complete_graph(5) + nodelist = [1, 4] + expected = pd.DataFrame( + [[0, 1], [1, 0]], dtype=int, index=nodelist, columns=nodelist + ) + pd.testing.assert_frame_equal( + expected, nx.to_pandas_adjacency(G, nodelist, dtype=int) + ) + + +def test_to_pandas_edgelist_with_nodelist(): + G = nx.Graph() + G.add_edges_from([(0, 1), (1, 2), (1, 3)], weight=2.0) + G.add_edge(0, 5, weight=100) + df = nx.to_pandas_edgelist(G, nodelist=[1, 2]) + assert 0 not in df["source"].to_numpy() + assert 100 not in df["weight"].to_numpy() diff --git a/shared/package-files/71/7194a527c06bb5e6fd6966bb573bc2ae99f0dbac11929945f4ab45da7aad1fc3/memory.pxi b/shared/package-files/71/7194a527c06bb5e6fd6966bb573bc2ae99f0dbac11929945f4ab45da7aad1fc3/memory.pxi new file mode 100644 index 0000000000000000000000000000000000000000..a526f0fbe31278f28eda0729b4010a16e5eeee4b --- /dev/null +++ b/shared/package-files/71/7194a527c06bb5e6fd6966bb573bc2ae99f0dbac11929945f4ab45da7aad1fc3/memory.pxi @@ -0,0 +1,296 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# cython: profile=False +# distutils: language = c++ +# cython: embedsignature = True + + +cdef class MemoryPool(_Weakrefable): + """ + Base class for memory allocation. + + Besides tracking its number of allocated bytes, a memory pool also + takes care of the required 64-byte alignment for Arrow data. + """ + + def __init__(self): + raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly, " + "use pyarrow.*_memory_pool instead.") + + cdef void init(self, CMemoryPool* pool): + self.pool = pool + + def release_unused(self): + """ + Attempt to return to the OS any memory being held onto by the pool. + + This function should not be called except potentially for + benchmarking or debugging as it could be expensive and detrimental to + performance. + + This is best effort and may not have any effect on some memory pools + or in some situations (e.g. fragmentation). + """ + cdef CMemoryPool* pool = c_get_memory_pool() + with nogil: + pool.ReleaseUnused() + + def bytes_allocated(self): + """ + Return the number of bytes that are currently allocated from this + memory pool. + """ + return self.pool.bytes_allocated() + + def total_bytes_allocated(self): + """ + Return the total number of bytes that have been allocated from this + memory pool. + """ + return self.pool.total_bytes_allocated() + + def max_memory(self): + """ + Return the peak memory allocation in this memory pool. + This can be an approximate number in multi-threaded applications. + + None is returned if the pool implementation doesn't know how to + compute this number. + """ + ret = self.pool.max_memory() + return ret if ret >= 0 else None + + def num_allocations(self): + """ + Return the number of allocations or reallocations that were made + using this memory pool. + """ + return self.pool.num_allocations() + + def print_stats(self): + """ + Print statistics about this memory pool. + + The output format is implementation-specific. Not all memory pools + implement this method. + """ + with nogil: + self.pool.PrintStats() + + @property + def backend_name(self): + """ + The name of the backend used by this MemoryPool (e.g. "jemalloc"). + """ + return frombytes(self.pool.backend_name()) + + def __repr__(self): + name = f"pyarrow.{self.__class__.__name__}" + return (f"<{name} " + f"backend_name={self.backend_name} " + f"bytes_allocated={self.bytes_allocated()} " + f"max_memory={self.max_memory()}>") + + +cdef CMemoryPool* maybe_unbox_memory_pool(MemoryPool memory_pool): + if memory_pool is None: + return c_get_memory_pool() + else: + return memory_pool.pool + + +cdef api object box_memory_pool(CMemoryPool *c_pool): + cdef MemoryPool pool = MemoryPool.__new__(MemoryPool) + pool.init(c_pool) + return pool + + +cdef class LoggingMemoryPool(MemoryPool): + cdef: + unique_ptr[CLoggingMemoryPool] logging_pool + + def __init__(self): + raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly, " + "use pyarrow.logging_memory_pool instead.") + + +cdef class ProxyMemoryPool(MemoryPool): + """ + Memory pool implementation that tracks the number of bytes and + maximum memory allocated through its direct calls, while redirecting + to another memory pool. + """ + cdef: + unique_ptr[CProxyMemoryPool] proxy_pool + + def __init__(self): + raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly, " + "use pyarrow.proxy_memory_pool instead.") + + +def default_memory_pool(): + """ + Return the process-global memory pool. + + Examples + -------- + >>> default_memory_pool() + + """ + cdef: + MemoryPool pool = MemoryPool.__new__(MemoryPool) + pool.init(c_get_memory_pool()) + return pool + + +def proxy_memory_pool(MemoryPool parent): + """ + Create and return a MemoryPool instance that redirects to the + *parent*, but with separate allocation statistics. + + Parameters + ---------- + parent : MemoryPool + The real memory pool that should be used for allocations. + """ + cdef ProxyMemoryPool out = ProxyMemoryPool.__new__(ProxyMemoryPool) + out.proxy_pool.reset(new CProxyMemoryPool(parent.pool)) + out.init(out.proxy_pool.get()) + return out + + +def logging_memory_pool(MemoryPool parent): + """ + Create and return a MemoryPool instance that redirects to the + *parent*, but also dumps allocation logs on stderr. + + Parameters + ---------- + parent : MemoryPool + The real memory pool that should be used for allocations. + """ + cdef LoggingMemoryPool out = LoggingMemoryPool.__new__( + LoggingMemoryPool, parent) + out.logging_pool.reset(new CLoggingMemoryPool(parent.pool)) + out.init(out.logging_pool.get()) + return out + + +def system_memory_pool(): + """ + Return a memory pool based on the C malloc heap. + """ + cdef: + MemoryPool pool = MemoryPool.__new__(MemoryPool) + pool.init(c_system_memory_pool()) + return pool + + +def jemalloc_memory_pool(): + """ + Return a memory pool based on the jemalloc heap. + + NotImplementedError is raised if jemalloc support is not enabled. + """ + cdef: + CMemoryPool* c_pool + MemoryPool pool = MemoryPool.__new__(MemoryPool) + check_status(c_jemalloc_memory_pool(&c_pool)) + pool.init(c_pool) + return pool + + +def mimalloc_memory_pool(): + """ + Return a memory pool based on the mimalloc heap. + + NotImplementedError is raised if mimalloc support is not enabled. + """ + cdef: + CMemoryPool* c_pool + MemoryPool pool = MemoryPool.__new__(MemoryPool) + check_status(c_mimalloc_memory_pool(&c_pool)) + pool.init(c_pool) + return pool + + +def set_memory_pool(MemoryPool pool): + """ + Set the default memory pool. + + Parameters + ---------- + pool : MemoryPool + The memory pool that should be used by default. + """ + c_set_default_memory_pool(pool.pool) + + +cdef MemoryPool _default_memory_pool = default_memory_pool() +cdef LoggingMemoryPool _logging_memory_pool = logging_memory_pool( + _default_memory_pool) + + +def log_memory_allocations(enable=True): + """ + Enable or disable memory allocator logging for debugging purposes + + Parameters + ---------- + enable : bool, default True + Pass False to disable logging + """ + if enable: + set_memory_pool(_logging_memory_pool) + else: + set_memory_pool(_default_memory_pool) + + +def total_allocated_bytes(): + """ + Return the currently allocated bytes from the default memory pool. + Other memory pools may not be accounted for. + """ + cdef CMemoryPool* pool = c_get_memory_pool() + return pool.bytes_allocated() + + +def jemalloc_set_decay_ms(decay_ms): + """ + Set arenas.dirty_decay_ms and arenas.muzzy_decay_ms to indicated number of + milliseconds. A value of 0 (the default) results in dirty / muzzy memory + pages being released right away to the OS, while a higher value will result + in a time-based decay. See the jemalloc docs for more information + + It's best to set this at the start of your application. + + Parameters + ---------- + decay_ms : int + Number of milliseconds to set for jemalloc decay conf parameters. Note + that this change will only affect future memory arenas + """ + check_status(c_jemalloc_set_decay_ms(decay_ms)) + + +def supported_memory_backends(): + """ + Return a list of available memory pool backends + """ + cdef vector[c_string] backends = c_supported_memory_backends() + return [backend.decode() for backend in backends] diff --git a/shared/package-files/71/719a4967ae94166b332c14389b519d3f28b6ed81c5900ea3a36f5c8101e3a334/test_matmul.py b/shared/package-files/71/719a4967ae94166b332c14389b519d3f28b6ed81c5900ea3a36f5c8101e3a334/test_matmul.py new file mode 100644 index 0000000000000000000000000000000000000000..51f1181a3a8ad46c38708eb215dfa26570354ab1 --- /dev/null +++ b/shared/package-files/71/719a4967ae94166b332c14389b519d3f28b6ed81c5900ea3a36f5c8101e3a334/test_matmul.py @@ -0,0 +1,74 @@ +import numpy as np + +from numba import cuda, float32, void +from numba.cuda.testing import unittest, CUDATestCase +from numba.core import config + +# Ensure the test takes a reasonable amount of time in the simulator +if config.ENABLE_CUDASIM: + bpg, tpb = 2, 8 +else: + bpg, tpb = 50, 32 + +n = bpg * tpb +SM_SIZE = (tpb, tpb) + + +class TestCudaMatMul(CUDATestCase): + + def test_func(self): + + @cuda.jit(void(float32[:, ::1], float32[:, ::1], float32[:, ::1])) + def cu_square_matrix_mul(A, B, C): + sA = cuda.shared.array(shape=SM_SIZE, dtype=float32) + sB = cuda.shared.array(shape=(tpb, tpb), dtype=float32) + + tx = cuda.threadIdx.x + ty = cuda.threadIdx.y + bx = cuda.blockIdx.x + by = cuda.blockIdx.y + bw = cuda.blockDim.x + bh = cuda.blockDim.y + + x = tx + bx * bw + y = ty + by * bh + + acc = float32(0) # forces all the math to be f32 + for i in range(bpg): + if x < n and y < n: + sA[ty, tx] = A[y, tx + i * tpb] + sB[ty, tx] = B[ty + i * tpb, x] + + cuda.syncthreads() + + if x < n and y < n: + for j in range(tpb): + acc += sA[ty, j] * sB[j, tx] + + cuda.syncthreads() + + if x < n and y < n: + C[y, x] = acc + + np.random.seed(42) + A = np.array(np.random.random((n, n)), dtype=np.float32) + B = np.array(np.random.random((n, n)), dtype=np.float32) + C = np.empty_like(A) + + stream = cuda.stream() + with stream.auto_synchronize(): + dA = cuda.to_device(A, stream) + dB = cuda.to_device(B, stream) + dC = cuda.to_device(C, stream) + cu_square_matrix_mul[(bpg, bpg), (tpb, tpb), stream](dA, dB, dC) + dC.copy_to_host(C, stream) + + # Host compute + Cans = np.dot(A, B) + + # Check result + np.testing.assert_allclose(C, Cans, rtol=1e-5) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/71/719c0e90fde118b563dd634c5ede0d7be47a991ff0038f7264364c5aec3d33d5/direct_url.json b/shared/package-files/71/719c0e90fde118b563dd634c5ede0d7be47a991ff0038f7264364c5aec3d33d5/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..abf2101e6b2a9cc066a2ad292195ace1199fcc6f --- /dev/null +++ b/shared/package-files/71/719c0e90fde118b563dd634c5ede0d7be47a991ff0038f7264364c5aec3d33d5/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///croot/jsonschema-specifications_1699032386549/work"} \ No newline at end of file diff --git a/shared/package-files/71/719e3996e3d9020e127a124a5d0efa8ea0ff86e08b9ac1401738b9c918033415/sparse_compressed_tensor.h b/shared/package-files/71/719e3996e3d9020e127a124a5d0efa8ea0ff86e08b9ac1401738b9c918033415/sparse_compressed_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..aa42a438061cf782d11511384a0e850d5dc7e4e1 --- /dev/null +++ b/shared/package-files/71/719e3996e3d9020e127a124a5d0efa8ea0ff86e08b9ac1401738b9c918033415/sparse_compressed_tensor.h @@ -0,0 +1,78 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::sparse_compressed_tensor.comp_plain_value_size(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, c10::fromIntArrayRefSlow(size), c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +namespace symint { + template ::value>> + at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, c10::fromIntArrayRefSlow(size), c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); + } +} + +// aten::sparse_compressed_tensor.comp_plain_value_size(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, c10::fromIntArrayRefSlow(size), dtype, layout, device, pin_memory); +} +namespace symint { + template ::value>> + at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, c10::fromIntArrayRefSlow(size), dtype, layout, device, pin_memory); + } +} + +// aten::sparse_compressed_tensor.comp_plain_value_size(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +inline at::Tensor sparse_compressed_tensor_symint(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, at::TensorOptions options) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, size, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +namespace symint { + template ::value>> + at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, at::TensorOptions options) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, size, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); + } +} + +// aten::sparse_compressed_tensor.comp_plain_value_size(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +inline at::Tensor sparse_compressed_tensor_symint(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, size, dtype, layout, device, pin_memory); +} +namespace symint { + template ::value>> + at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, size, dtype, layout, device, pin_memory); + } +} + +// aten::sparse_compressed_tensor.comp_plain_value(Tensor compressed_indices, Tensor plain_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::TensorOptions options) { + return at::_ops::sparse_compressed_tensor_comp_plain_value::call(compressed_indices, plain_indices, values, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::sparse_compressed_tensor.comp_plain_value(Tensor compressed_indices, Tensor plain_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::sparse_compressed_tensor_comp_plain_value::call(compressed_indices, plain_indices, values, dtype, layout, device, pin_memory); +} + +} diff --git a/shared/package-files/71/719f8c5d80684a222127798eda547403c6f9de5322acc1acbe280ef791fccc16/linalg_inv_ex_meta_dispatch.h b/shared/package-files/71/719f8c5d80684a222127798eda547403c6f9de5322acc1acbe280ef791fccc16/linalg_inv_ex_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..c77e5128b6e93f11aed1874a699ded6b6198bfb5 --- /dev/null +++ b/shared/package-files/71/719f8c5d80684a222127798eda547403c6f9de5322acc1acbe280ef791fccc16/linalg_inv_ex_meta_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API ::std::tuple linalg_inv_ex(const at::Tensor & A, bool check_errors=false); +TORCH_API ::std::tuple linalg_inv_ex_out(at::Tensor & inverse, at::Tensor & info, const at::Tensor & A, bool check_errors=false); +TORCH_API ::std::tuple linalg_inv_ex_outf(const at::Tensor & A, bool check_errors, at::Tensor & inverse, at::Tensor & info); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/71/71a1d43457c879dffff18e9971a0b69872e84224c805d83cf80cb95050e72112/fft_fft_native.h b/shared/package-files/71/71a1d43457c879dffff18e9971a0b69872e84224c805d83cf80cb95050e72112/fft_fft_native.h new file mode 100644 index 0000000000000000000000000000000000000000..6a8190caa08b71c64bf8453fd2cecce9f3ce512f --- /dev/null +++ b/shared/package-files/71/71a1d43457c879dffff18e9971a0b69872e84224c805d83cf80cb95050e72112/fft_fft_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor fft_fft_symint(const at::Tensor & self, c10::optional n=c10::nullopt, int64_t dim=-1, c10::optional norm=c10::nullopt); +TORCH_API at::Tensor & fft_fft_symint_out(const at::Tensor & self, c10::optional n, int64_t dim, c10::optional norm, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/71/71a61cfb194422b5fd23f03e28f41dc29e680e9ad52526df70e68a83fa949ec3/test_products.py b/shared/package-files/71/71a61cfb194422b5fd23f03e28f41dc29e680e9ad52526df70e68a83fa949ec3/test_products.py new file mode 100644 index 0000000000000000000000000000000000000000..9be053a7040014c6ed38c1279a609fcb2426258e --- /dev/null +++ b/shared/package-files/71/71a61cfb194422b5fd23f03e28f41dc29e680e9ad52526df70e68a83fa949ec3/test_products.py @@ -0,0 +1,410 @@ +from sympy.concrete.products import (Product, product) +from sympy.concrete.summations import Sum +from sympy.core.function import (Derivative, Function, diff) +from sympy.core.numbers import (Rational, oo, pi) +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, Symbol, symbols) +from sympy.functions.combinatorial.factorials import (rf, factorial) +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.functions.special.tensor_functions import KroneckerDelta +from sympy.simplify.combsimp import combsimp +from sympy.simplify.simplify import simplify +from sympy.testing.pytest import raises + +a, k, n, m, x = symbols('a,k,n,m,x', integer=True) +f = Function('f') + + +def test_karr_convention(): + # Test the Karr product convention that we want to hold. + # See his paper "Summation in Finite Terms" for a detailed + # reasoning why we really want exactly this definition. + # The convention is described for sums on page 309 and + # essentially in section 1.4, definition 3. For products + # we can find in analogy: + # + # \prod_{m <= i < n} f(i) 'has the obvious meaning' for m < n + # \prod_{m <= i < n} f(i) = 0 for m = n + # \prod_{m <= i < n} f(i) = 1 / \prod_{n <= i < m} f(i) for m > n + # + # It is important to note that he defines all products with + # the upper limit being *exclusive*. + # In contrast, SymPy and the usual mathematical notation has: + # + # prod_{i = a}^b f(i) = f(a) * f(a+1) * ... * f(b-1) * f(b) + # + # with the upper limit *inclusive*. So translating between + # the two we find that: + # + # \prod_{m <= i < n} f(i) = \prod_{i = m}^{n-1} f(i) + # + # where we intentionally used two different ways to typeset the + # products and its limits. + + i = Symbol("i", integer=True) + k = Symbol("k", integer=True) + j = Symbol("j", integer=True, positive=True) + + # A simple example with a concrete factors and symbolic limits. + + # The normal product: m = k and n = k + j and therefore m < n: + m = k + n = k + j + + a = m + b = n - 1 + S1 = Product(i**2, (i, a, b)).doit() + + # The reversed product: m = k + j and n = k and therefore m > n: + m = k + j + n = k + + a = m + b = n - 1 + S2 = Product(i**2, (i, a, b)).doit() + + assert S1 * S2 == 1 + + # Test the empty product: m = k and n = k and therefore m = n: + m = k + n = k + + a = m + b = n - 1 + Sz = Product(i**2, (i, a, b)).doit() + + assert Sz == 1 + + # Another example this time with an unspecified factor and + # numeric limits. (We can not do both tests in the same example.) + f = Function("f") + + # The normal product with m < n: + m = 2 + n = 11 + + a = m + b = n - 1 + S1 = Product(f(i), (i, a, b)).doit() + + # The reversed product with m > n: + m = 11 + n = 2 + + a = m + b = n - 1 + S2 = Product(f(i), (i, a, b)).doit() + + assert simplify(S1 * S2) == 1 + + # Test the empty product with m = n: + m = 5 + n = 5 + + a = m + b = n - 1 + Sz = Product(f(i), (i, a, b)).doit() + + assert Sz == 1 + + +def test_karr_proposition_2a(): + # Test Karr, page 309, proposition 2, part a + i, u, v = symbols('i u v', integer=True) + + def test_the_product(m, n): + # g + g = i**3 + 2*i**2 - 3*i + # f = Delta g + f = simplify(g.subs(i, i+1) / g) + # The product + a = m + b = n - 1 + P = Product(f, (i, a, b)).doit() + # Test if Product_{m <= i < n} f(i) = g(n) / g(m) + assert combsimp(P / (g.subs(i, n) / g.subs(i, m))) == 1 + + # m < n + test_the_product(u, u + v) + # m = n + test_the_product(u, u) + # m > n + test_the_product(u + v, u) + + +def test_karr_proposition_2b(): + # Test Karr, page 309, proposition 2, part b + i, u, v, w = symbols('i u v w', integer=True) + + def test_the_product(l, n, m): + # Productmand + s = i**3 + # First product + a = l + b = n - 1 + S1 = Product(s, (i, a, b)).doit() + # Second product + a = l + b = m - 1 + S2 = Product(s, (i, a, b)).doit() + # Third product + a = m + b = n - 1 + S3 = Product(s, (i, a, b)).doit() + # Test if S1 = S2 * S3 as required + assert combsimp(S1 / (S2 * S3)) == 1 + + # l < m < n + test_the_product(u, u + v, u + v + w) + # l < m = n + test_the_product(u, u + v, u + v) + # l < m > n + test_the_product(u, u + v + w, v) + # l = m < n + test_the_product(u, u, u + v) + # l = m = n + test_the_product(u, u, u) + # l = m > n + test_the_product(u + v, u + v, u) + # l > m < n + test_the_product(u + v, u, u + w) + # l > m = n + test_the_product(u + v, u, u) + # l > m > n + test_the_product(u + v + w, u + v, u) + + +def test_simple_products(): + assert product(2, (k, a, n)) == 2**(n - a + 1) + assert product(k, (k, 1, n)) == factorial(n) + assert product(k**3, (k, 1, n)) == factorial(n)**3 + + assert product(k + 1, (k, 0, n - 1)) == factorial(n) + assert product(k + 1, (k, a, n - 1)) == rf(1 + a, n - a) + + assert product(cos(k), (k, 0, 5)) == cos(1)*cos(2)*cos(3)*cos(4)*cos(5) + assert product(cos(k), (k, 3, 5)) == cos(3)*cos(4)*cos(5) + assert product(cos(k), (k, 1, Rational(5, 2))) != cos(1)*cos(2) + + assert isinstance(product(k**k, (k, 1, n)), Product) + + assert Product(x**k, (k, 1, n)).variables == [k] + + raises(ValueError, lambda: Product(n)) + raises(ValueError, lambda: Product(n, k)) + raises(ValueError, lambda: Product(n, k, 1)) + raises(ValueError, lambda: Product(n, k, 1, 10)) + raises(ValueError, lambda: Product(n, (k, 1))) + + assert product(1, (n, 1, oo)) == 1 # issue 8301 + assert product(2, (n, 1, oo)) is oo + assert product(-1, (n, 1, oo)).func is Product + + +def test_multiple_products(): + assert product(x, (n, 1, k), (k, 1, m)) == x**(m**2/2 + m/2) + assert product(f(n), ( + n, 1, m), (m, 1, k)) == Product(f(n), (n, 1, m), (m, 1, k)).doit() + assert Product(f(n), (m, 1, k), (n, 1, k)).doit() == \ + Product(Product(f(n), (m, 1, k)), (n, 1, k)).doit() == \ + product(f(n), (m, 1, k), (n, 1, k)) == \ + product(product(f(n), (m, 1, k)), (n, 1, k)) == \ + Product(f(n)**k, (n, 1, k)) + assert Product( + x, (x, 1, k), (k, 1, n)).doit() == Product(factorial(k), (k, 1, n)) + + assert Product(x**k, (n, 1, k), (k, 1, m)).variables == [n, k] + + +def test_rational_products(): + assert product(1 + 1/k, (k, 1, n)) == rf(2, n)/factorial(n) + + +def test_special_products(): + # Wallis product + assert product((4*k)**2 / (4*k**2 - 1), (k, 1, n)) == \ + 4**n*factorial(n)**2/rf(S.Half, n)/rf(Rational(3, 2), n) + + # Euler's product formula for sin + assert product(1 + a/k**2, (k, 1, n)) == \ + rf(1 - sqrt(-a), n)*rf(1 + sqrt(-a), n)/factorial(n)**2 + + +def test__eval_product(): + from sympy.abc import i, n + # issue 4809 + a = Function('a') + assert product(2*a(i), (i, 1, n)) == 2**n * Product(a(i), (i, 1, n)) + # issue 4810 + assert product(2**i, (i, 1, n)) == 2**(n*(n + 1)/2) + k, m = symbols('k m', integer=True) + assert product(2**i, (i, k, m)) == 2**(-k**2/2 + k/2 + m**2/2 + m/2) + n = Symbol('n', negative=True, integer=True) + p = Symbol('p', positive=True, integer=True) + assert product(2**i, (i, n, p)) == 2**(-n**2/2 + n/2 + p**2/2 + p/2) + assert product(2**i, (i, p, n)) == 2**(n**2/2 + n/2 - p**2/2 + p/2) + + +def test_product_pow(): + # issue 4817 + assert product(2**f(k), (k, 1, n)) == 2**Sum(f(k), (k, 1, n)) + assert product(2**(2*f(k)), (k, 1, n)) == 2**Sum(2*f(k), (k, 1, n)) + + +def test_infinite_product(): + # issue 5737 + assert isinstance(Product(2**(1/factorial(n)), (n, 0, oo)), Product) + + +def test_conjugate_transpose(): + p = Product(x**k, (k, 1, 3)) + assert p.adjoint().doit() == p.doit().adjoint() + assert p.conjugate().doit() == p.doit().conjugate() + assert p.transpose().doit() == p.doit().transpose() + + A, B = symbols("A B", commutative=False) + p = Product(A*B**k, (k, 1, 3)) + assert p.adjoint().doit() == p.doit().adjoint() + assert p.conjugate().doit() == p.doit().conjugate() + assert p.transpose().doit() == p.doit().transpose() + + p = Product(B**k*A, (k, 1, 3)) + assert p.adjoint().doit() == p.doit().adjoint() + assert p.conjugate().doit() == p.doit().conjugate() + assert p.transpose().doit() == p.doit().transpose() + + +def test_simplify_prod(): + y, t, b, c, v, d = symbols('y, t, b, c, v, d', integer = True) + + _simplify = lambda e: simplify(e, doit=False) + assert _simplify(Product(x*y, (x, n, m), (y, a, k)) * \ + Product(y, (x, n, m), (y, a, k))) == \ + Product(x*y**2, (x, n, m), (y, a, k)) + assert _simplify(3 * y* Product(x, (x, n, m)) * Product(x, (x, m + 1, a))) \ + == 3 * y * Product(x, (x, n, a)) + assert _simplify(Product(x, (x, k + 1, a)) * Product(x, (x, n, k))) == \ + Product(x, (x, n, a)) + assert _simplify(Product(x, (x, k + 1, a)) * Product(x + 1, (x, n, k))) == \ + Product(x, (x, k + 1, a)) * Product(x + 1, (x, n, k)) + assert _simplify(Product(x, (t, a, b)) * Product(y, (t, a, b)) * \ + Product(x, (t, b+1, c))) == Product(x*y, (t, a, b)) * \ + Product(x, (t, b+1, c)) + assert _simplify(Product(x, (t, a, b)) * Product(x, (t, b+1, c)) * \ + Product(y, (t, a, b))) == Product(x*y, (t, a, b)) * \ + Product(x, (t, b+1, c)) + assert _simplify(Product(sin(t)**2 + cos(t)**2 + 1, (t, a, b))) == \ + Product(2, (t, a, b)) + assert _simplify(Product(sin(t)**2 + cos(t)**2 - 1, (t, a, b))) == \ + Product(0, (t, a, b)) + assert _simplify(Product(v*Product(sin(t)**2 + cos(t)**2, (t, a, b)), + (v, c, d))) == Product(v*Product(1, (t, a, b)), (v, c, d)) + + +def test_change_index(): + b, y, c, d, z = symbols('b, y, c, d, z', integer = True) + + assert Product(x, (x, a, b)).change_index(x, x + 1, y) == \ + Product(y - 1, (y, a + 1, b + 1)) + assert Product(x**2, (x, a, b)).change_index(x, x - 1) == \ + Product((x + 1)**2, (x, a - 1, b - 1)) + assert Product(x**2, (x, a, b)).change_index(x, -x, y) == \ + Product((-y)**2, (y, -b, -a)) + assert Product(x, (x, a, b)).change_index(x, -x - 1) == \ + Product(-x - 1, (x, - b - 1, -a - 1)) + assert Product(x*y, (x, a, b), (y, c, d)).change_index(x, x - 1, z) == \ + Product((z + 1)*y, (z, a - 1, b - 1), (y, c, d)) + + +def test_reorder(): + b, y, c, d, z = symbols('b, y, c, d, z', integer = True) + + assert Product(x*y, (x, a, b), (y, c, d)).reorder((0, 1)) == \ + Product(x*y, (y, c, d), (x, a, b)) + assert Product(x, (x, a, b), (x, c, d)).reorder((0, 1)) == \ + Product(x, (x, c, d), (x, a, b)) + assert Product(x*y + z, (x, a, b), (z, m, n), (y, c, d)).reorder(\ + (2, 0), (0, 1)) == Product(x*y + z, (z, m, n), (y, c, d), (x, a, b)) + assert Product(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\ + (0, 1), (1, 2), (0, 2)) == \ + Product(x*y*z, (x, a, b), (z, m, n), (y, c, d)) + assert Product(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\ + (x, y), (y, z), (x, z)) == \ + Product(x*y*z, (x, a, b), (z, m, n), (y, c, d)) + assert Product(x*y, (x, a, b), (y, c, d)).reorder((x, 1)) == \ + Product(x*y, (y, c, d), (x, a, b)) + assert Product(x*y, (x, a, b), (y, c, d)).reorder((y, x)) == \ + Product(x*y, (y, c, d), (x, a, b)) + + +def test_Product_is_convergent(): + assert Product(1/n**2, (n, 1, oo)).is_convergent() is S.false + assert Product(exp(1/n**2), (n, 1, oo)).is_convergent() is S.true + assert Product(1/n, (n, 1, oo)).is_convergent() is S.false + assert Product(1 + 1/n, (n, 1, oo)).is_convergent() is S.false + assert Product(1 + 1/n**2, (n, 1, oo)).is_convergent() is S.true + + +def test_reverse_order(): + x, y, a, b, c, d= symbols('x, y, a, b, c, d', integer = True) + + assert Product(x, (x, 0, 3)).reverse_order(0) == Product(1/x, (x, 4, -1)) + assert Product(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(0, 1) == \ + Product(x*y, (x, 6, 0), (y, 7, -1)) + assert Product(x, (x, 1, 2)).reverse_order(0) == Product(1/x, (x, 3, 0)) + assert Product(x, (x, 1, 3)).reverse_order(0) == Product(1/x, (x, 4, 0)) + assert Product(x, (x, 1, a)).reverse_order(0) == Product(1/x, (x, a + 1, 0)) + assert Product(x, (x, a, 5)).reverse_order(0) == Product(1/x, (x, 6, a - 1)) + assert Product(x, (x, a + 1, a + 5)).reverse_order(0) == \ + Product(1/x, (x, a + 6, a)) + assert Product(x, (x, a + 1, a + 2)).reverse_order(0) == \ + Product(1/x, (x, a + 3, a)) + assert Product(x, (x, a + 1, a + 1)).reverse_order(0) == \ + Product(1/x, (x, a + 2, a)) + assert Product(x, (x, a, b)).reverse_order(0) == Product(1/x, (x, b + 1, a - 1)) + assert Product(x, (x, a, b)).reverse_order(x) == Product(1/x, (x, b + 1, a - 1)) + assert Product(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) == \ + Product(x*y, (x, b + 1, a - 1), (y, 6, 1)) + assert Product(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) == \ + Product(x*y, (x, b + 1, a - 1), (y, 6, 1)) + + +def test_issue_9983(): + n = Symbol('n', integer=True, positive=True) + p = Product(1 + 1/n**Rational(2, 3), (n, 1, oo)) + assert p.is_convergent() is S.false + assert product(1 + 1/n**Rational(2, 3), (n, 1, oo)) == p.doit() + + +def test_issue_13546(): + n = Symbol('n') + k = Symbol('k') + p = Product(n + 1 / 2**k, (k, 0, n-1)).doit() + assert p.subs(n, 2).doit() == Rational(15, 2) + + +def test_issue_14036(): + a, n = symbols('a n') + assert product(1 - a**2 / (n*pi)**2, [n, 1, oo]) != 0 + + +def test_rewrite_Sum(): + assert Product(1 - S.Half**2/k**2, (k, 1, oo)).rewrite(Sum) == \ + exp(Sum(log(1 - 1/(4*k**2)), (k, 1, oo))) + + +def test_KroneckerDelta_Product(): + y = Symbol('y') + assert Product(x*KroneckerDelta(x, y), (x, 0, 1)).doit() == 0 + + +def test_issue_20848(): + _i = Dummy('i') + t, y, z = symbols('t y z') + assert diff(Product(x, (y, 1, z)), x).as_dummy() == Sum(Product(x, (y, 1, _i - 1))*Product(x, (y, _i + 1, z)), (_i, 1, z)).as_dummy() + assert diff(Product(x, (y, 1, z)), x).doit() == x**(z - 1)*z + assert diff(Product(x, (y, x, z)), x) == Derivative(Product(x, (y, x, z)), x) + assert diff(Product(t, (x, 1, z)), x) == S(0) + assert Product(sin(n*x), (n, -1, 1)).diff(x).doit() == S(0) diff --git a/shared/package-files/71/71a6da0cb7bf47199829ddc06bddcf791747ed3be528a42c04c6d2a7d91a447e/centrality.py b/shared/package-files/71/71a6da0cb7bf47199829ddc06bddcf791747ed3be528a42c04c6d2a7d91a447e/centrality.py new file mode 100644 index 0000000000000000000000000000000000000000..3eab83422db8b2e1b9dccc59990be5194b0fe4f0 --- /dev/null +++ b/shared/package-files/71/71a6da0cb7bf47199829ddc06bddcf791747ed3be528a42c04c6d2a7d91a447e/centrality.py @@ -0,0 +1,266 @@ +import networkx as nx + +__all__ = ["degree_centrality", "betweenness_centrality", "closeness_centrality"] + + +def degree_centrality(G, nodes): + r"""Compute the degree centrality for nodes in a bipartite network. + + The degree centrality for a node `v` is the fraction of nodes + connected to it. + + Parameters + ---------- + G : graph + A bipartite network + + nodes : list or container + Container with all nodes in one bipartite node set. + + Returns + ------- + centrality : dictionary + Dictionary keyed by node with bipartite degree centrality as the value. + + See Also + -------- + betweenness_centrality + closeness_centrality + :func:`~networkx.algorithms.bipartite.basic.sets` + :func:`~networkx.algorithms.bipartite.basic.is_bipartite` + + Notes + ----- + The nodes input parameter must contain all nodes in one bipartite node set, + but the dictionary returned contains all nodes from both bipartite node + sets. See :mod:`bipartite documentation ` + for further details on how bipartite graphs are handled in NetworkX. + + For unipartite networks, the degree centrality values are + normalized by dividing by the maximum possible degree (which is + `n-1` where `n` is the number of nodes in G). + + In the bipartite case, the maximum possible degree of a node in a + bipartite node set is the number of nodes in the opposite node set + [1]_. The degree centrality for a node `v` in the bipartite + sets `U` with `n` nodes and `V` with `m` nodes is + + .. math:: + + d_{v} = \frac{deg(v)}{m}, \mbox{for} v \in U , + + d_{v} = \frac{deg(v)}{n}, \mbox{for} v \in V , + + + where `deg(v)` is the degree of node `v`. + + References + ---------- + .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation + Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook + of Social Network Analysis. Sage Publications. + https://dx.doi.org/10.4135/9781446294413.n28 + """ + top = set(nodes) + bottom = set(G) - top + s = 1.0 / len(bottom) + centrality = {n: d * s for n, d in G.degree(top)} + s = 1.0 / len(top) + centrality.update({n: d * s for n, d in G.degree(bottom)}) + return centrality + + +def betweenness_centrality(G, nodes): + r"""Compute betweenness centrality for nodes in a bipartite network. + + Betweenness centrality of a node `v` is the sum of the + fraction of all-pairs shortest paths that pass through `v`. + + Values of betweenness are normalized by the maximum possible + value which for bipartite graphs is limited by the relative size + of the two node sets [1]_. + + Let `n` be the number of nodes in the node set `U` and + `m` be the number of nodes in the node set `V`, then + nodes in `U` are normalized by dividing by + + .. math:: + + \frac{1}{2} [m^2 (s + 1)^2 + m (s + 1)(2t - s - 1) - t (2s - t + 3)] , + + where + + .. math:: + + s = (n - 1) \div m , t = (n - 1) \mod m , + + and nodes in `V` are normalized by dividing by + + .. math:: + + \frac{1}{2} [n^2 (p + 1)^2 + n (p + 1)(2r - p - 1) - r (2p - r + 3)] , + + where, + + .. math:: + + p = (m - 1) \div n , r = (m - 1) \mod n . + + Parameters + ---------- + G : graph + A bipartite graph + + nodes : list or container + Container with all nodes in one bipartite node set. + + Returns + ------- + betweenness : dictionary + Dictionary keyed by node with bipartite betweenness centrality + as the value. + + See Also + -------- + degree_centrality + closeness_centrality + :func:`~networkx.algorithms.bipartite.basic.sets` + :func:`~networkx.algorithms.bipartite.basic.is_bipartite` + + Notes + ----- + The nodes input parameter must contain all nodes in one bipartite node set, + but the dictionary returned contains all nodes from both node sets. + See :mod:`bipartite documentation ` + for further details on how bipartite graphs are handled in NetworkX. + + + References + ---------- + .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation + Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook + of Social Network Analysis. Sage Publications. + https://dx.doi.org/10.4135/9781446294413.n28 + """ + top = set(nodes) + bottom = set(G) - top + n = len(top) + m = len(bottom) + s, t = divmod(n - 1, m) + bet_max_top = ( + ((m**2) * ((s + 1) ** 2)) + + (m * (s + 1) * (2 * t - s - 1)) + - (t * ((2 * s) - t + 3)) + ) / 2.0 + p, r = divmod(m - 1, n) + bet_max_bot = ( + ((n**2) * ((p + 1) ** 2)) + + (n * (p + 1) * (2 * r - p - 1)) + - (r * ((2 * p) - r + 3)) + ) / 2.0 + betweenness = nx.betweenness_centrality(G, normalized=False, weight=None) + for node in top: + betweenness[node] /= bet_max_top + for node in bottom: + betweenness[node] /= bet_max_bot + return betweenness + + +def closeness_centrality(G, nodes, normalized=True): + r"""Compute the closeness centrality for nodes in a bipartite network. + + The closeness of a node is the distance to all other nodes in the + graph or in the case that the graph is not connected to all other nodes + in the connected component containing that node. + + Parameters + ---------- + G : graph + A bipartite network + + nodes : list or container + Container with all nodes in one bipartite node set. + + normalized : bool, optional + If True (default) normalize by connected component size. + + Returns + ------- + closeness : dictionary + Dictionary keyed by node with bipartite closeness centrality + as the value. + + See Also + -------- + betweenness_centrality + degree_centrality + :func:`~networkx.algorithms.bipartite.basic.sets` + :func:`~networkx.algorithms.bipartite.basic.is_bipartite` + + Notes + ----- + The nodes input parameter must contain all nodes in one bipartite node set, + but the dictionary returned contains all nodes from both node sets. + See :mod:`bipartite documentation ` + for further details on how bipartite graphs are handled in NetworkX. + + + Closeness centrality is normalized by the minimum distance possible. + In the bipartite case the minimum distance for a node in one bipartite + node set is 1 from all nodes in the other node set and 2 from all + other nodes in its own set [1]_. Thus the closeness centrality + for node `v` in the two bipartite sets `U` with + `n` nodes and `V` with `m` nodes is + + .. math:: + + c_{v} = \frac{m + 2(n - 1)}{d}, \mbox{for} v \in U, + + c_{v} = \frac{n + 2(m - 1)}{d}, \mbox{for} v \in V, + + where `d` is the sum of the distances from `v` to all + other nodes. + + Higher values of closeness indicate higher centrality. + + As in the unipartite case, setting normalized=True causes the + values to normalized further to n-1 / size(G)-1 where n is the + number of nodes in the connected part of graph containing the + node. If the graph is not completely connected, this algorithm + computes the closeness centrality for each connected part + separately. + + References + ---------- + .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation + Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook + of Social Network Analysis. Sage Publications. + https://dx.doi.org/10.4135/9781446294413.n28 + """ + closeness = {} + path_length = nx.single_source_shortest_path_length + top = set(nodes) + bottom = set(G) - top + n = len(top) + m = len(bottom) + for node in top: + sp = dict(path_length(G, node)) + totsp = sum(sp.values()) + if totsp > 0.0 and len(G) > 1: + closeness[node] = (m + 2 * (n - 1)) / totsp + if normalized: + s = (len(sp) - 1) / (len(G) - 1) + closeness[node] *= s + else: + closeness[node] = 0.0 + for node in bottom: + sp = dict(path_length(G, node)) + totsp = sum(sp.values()) + if totsp > 0.0 and len(G) > 1: + closeness[node] = (n + 2 * (m - 1)) / totsp + if normalized: + s = (len(sp) - 1) / (len(G) - 1) + closeness[node] *= s + else: + closeness[node] = 0.0 + return closeness diff --git a/shared/package-files/71/71a7b41c5c536bdbf1eba8d9f08ed8831558ea99c8659a9b193b107b921cbf60/nsterm-acs-c b/shared/package-files/71/71a7b41c5c536bdbf1eba8d9f08ed8831558ea99c8659a9b193b107b921cbf60/nsterm-acs-c new file mode 100644 index 0000000000000000000000000000000000000000..a232413a498dd25d7963aeddd8b8803dac7c4012 Binary files /dev/null and b/shared/package-files/71/71a7b41c5c536bdbf1eba8d9f08ed8831558ea99c8659a9b193b107b921cbf60/nsterm-acs-c differ diff --git a/shared/package-files/71/71a7b41c5c536bdbf1eba8d9f08ed8831558ea99c8659a9b193b107b921cbf60/nsterm-c-acs b/shared/package-files/71/71a7b41c5c536bdbf1eba8d9f08ed8831558ea99c8659a9b193b107b921cbf60/nsterm-c-acs new file mode 100644 index 0000000000000000000000000000000000000000..a232413a498dd25d7963aeddd8b8803dac7c4012 Binary files /dev/null and b/shared/package-files/71/71a7b41c5c536bdbf1eba8d9f08ed8831558ea99c8659a9b193b107b921cbf60/nsterm-c-acs differ diff --git a/shared/package-files/71/71aa159437555157d96dfc68aa73ba6ed902261b13b91df360a395b38e22433d/values_copy.h b/shared/package-files/71/71aa159437555157d96dfc68aa73ba6ed902261b13b91df360a395b38e22433d/values_copy.h new file mode 100644 index 0000000000000000000000000000000000000000..ad661701478f61b4337b0f9163170d06c05269a8 --- /dev/null +++ b/shared/package-files/71/71aa159437555157d96dfc68aa73ba6ed902261b13b91df360a395b38e22433d/values_copy.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::values_copy(Tensor self) -> Tensor +inline at::Tensor values_copy(const at::Tensor & self) { + return at::_ops::values_copy::call(self); +} + +// aten::values_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & values_copy_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::values_copy_out::call(self, out); +} +// aten::values_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & values_copy_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::values_copy_out::call(self, out); +} + +} diff --git a/shared/package-files/71/71aa3a9137fd1740ffc072544fe3078c4cb833086f9712f79763c9815072c624/dynamic_shape_map.py b/shared/package-files/71/71aa3a9137fd1740ffc072544fe3078c4cb833086f9712f79763c9815072c624/dynamic_shape_map.py new file mode 100644 index 0000000000000000000000000000000000000000..5be0003fd170abb49afc80544229177d4b8b8de4 --- /dev/null +++ b/shared/package-files/71/71aa3a9137fd1740ffc072544fe3078c4cb833086f9712f79763c9815072c624/dynamic_shape_map.py @@ -0,0 +1,23 @@ +import torch + +from torch._export.db.case import export_case +from functorch.experimental.control_flow import map + + +@export_case( + example_inputs=(torch.ones(3, 2), torch.ones(2)), + tags={"torch.dynamic-shape", "torch.map"}, +) +class DynamicShapeMap(torch.nn.Module): + """ + functorch map() maps a function over the first tensor dimension. + """ + + def __init__(self): + super().__init__() + + def forward(self, xs, y): + def body(x, y): + return x + y + + return map(body, xs, y) diff --git a/shared/package-files/71/71ade73b74da3f0efceb93cde529462414dcd87deb05740231a14fcb05f6f72e/page.css b/shared/package-files/71/71ade73b74da3f0efceb93cde529462414dcd87deb05740231a14fcb05f6f72e/page.css new file mode 100644 index 0000000000000000000000000000000000000000..ded0d92203790eaaab21feea83930611acec51f0 --- /dev/null +++ b/shared/package-files/71/71ade73b74da3f0efceb93cde529462414dcd87deb05740231a14fcb05f6f72e/page.css @@ -0,0 +1,82 @@ +/** + * Primary styles + * + * Author: IPython Development Team + */ + + +body { + background-color: white; + /* This makes sure that the body covers the entire window and needs to + be in a different element than the display: box in wrapper below */ + position: absolute; + left: 0px; + right: 0px; + top: 0px; + bottom: 0px; + overflow: visible; +} + + +div#header { + /* Initially hidden to prevent FLOUC */ + display: none; + position: relative; + height: 40px; + padding: 5px; + margin: 0px; + width: 100%; +} + +span#ipython_notebook { + position: absolute; + padding: 2px 2px 2px 5px; +} + +span#ipython_notebook img { + font-family: Verdana, "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif; + height: 24px; + text-decoration:none; + display: inline; + color: black; +} + +#site { + width: 100%; + display: none; +} + +/* We set the fonts by hand here to override the values in the theme */ +.ui-widget { + font-family: "Lucinda Grande", "Lucinda Sans Unicode", Helvetica, Arial, Verdana, sans-serif; +} + +.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { + font-family: "Lucinda Grande", "Lucinda Sans Unicode", Helvetica, Arial, Verdana, sans-serif; +} + +/* Smaller buttons */ +.ui-button .ui-button-text { + padding: 0.2em 0.8em; + font-size: 77%; +} + +input.ui-button { + padding: 0.3em 0.9em; +} + +span#login_widget { + float: right; +} + +.border-box-sizing { + box-sizing: border-box; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; +} + +#figure-div { + display: inline-block; + margin: 10px; + vertical-align: top; +} diff --git a/shared/package-files/71/71ae61e950a73811ed787240095224d25f8fb23c7165786c3fac22b7fa718639/_embedding_bag_dense_backward_native.h b/shared/package-files/71/71ae61e950a73811ed787240095224d25f8fb23c7165786c3fac22b7fa718639/_embedding_bag_dense_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..31ffaca726d6fc061def1597b1468746f9afc35b --- /dev/null +++ b/shared/package-files/71/71ae61e950a73811ed787240095224d25f8fb23c7165786c3fac22b7fa718639/_embedding_bag_dense_backward_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & _embedding_bag_dense_backward_out_symint(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, c10::SymInt num_weights, bool scale_grad_by_freq, int64_t mode, const c10::optional & per_sample_weights, int64_t padding_idx, at::Tensor & out); +TORCH_API at::Tensor _embedding_bag_dense_backward_cpu(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, int64_t num_weights, bool scale_grad_by_freq, int64_t mode, const c10::optional & per_sample_weights, int64_t padding_idx=-1); +TORCH_API at::Tensor _embedding_bag_dense_backward_cuda(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, int64_t num_weights, bool scale_grad_by_freq, int64_t mode, const c10::optional & per_sample_weights, int64_t padding_idx=-1); +} // namespace native +} // namespace at diff --git a/shared/package-files/71/71ae80adfb437b7bc88f3c76fd37074449b3526e7aa5776d2b9fd5a43c066fa8/macRomania.enc b/shared/package-files/71/71ae80adfb437b7bc88f3c76fd37074449b3526e7aa5776d2b9fd5a43c066fa8/macRomania.enc new file mode 100644 index 0000000000000000000000000000000000000000..ce41cf427f257dfaa63c6d577c17d28f6563758f --- /dev/null +++ b/shared/package-files/71/71ae80adfb437b7bc88f3c76fd37074449b3526e7aa5776d2b9fd5a43c066fa8/macRomania.enc @@ -0,0 +1,20 @@ +# Encoding file: macRomania, single-byte +S +003F 0 1 +00 +0000000100020003000400050006000700080009000A000B000C000D000E000F +0010001100120013001400150016001700180019001A001B001C001D001E001F +0020002100220023002400250026002700280029002A002B002C002D002E002F +0030003100320033003400350036003700380039003A003B003C003D003E003F +0040004100420043004400450046004700480049004A004B004C004D004E004F +0050005100520053005400550056005700580059005A005B005C005D005E005F +0060006100620063006400650066006700680069006A006B006C006D006E006F +0070007100720073007400750076007700780079007A007B007C007D007E007F +00C400C500C700C900D100D600DC00E100E000E200E400E300E500E700E900E8 +00EA00EB00ED00EC00EE00EF00F100F300F200F400F600F500FA00F900FB00FC +202000B000A200A300A7202200B600DF00AE00A9212200B400A822600102015E +221E00B12264226500A500B522022211220F03C0222B00AA00BA21260103015F +00BF00A100AC221A01922248220600AB00BB202600A000C000C300D501520153 +20132014201C201D2018201900F725CA00FF0178204400A42039203A01620163 +202100B7201A201E203000C200CA00C100CB00C800CD00CE00CF00CC00D300D4 +F8FF00D200DA00DB00D9013102C602DC00AF02D802D902DA00B802DD02DB02C7 diff --git a/shared/package-files/71/71afab2aa1b34db1b3ed7f87b8b17d573919dc27cd122205d8187b4237d943bb/_heap.pyx b/shared/package-files/71/71afab2aa1b34db1b3ed7f87b8b17d573919dc27cd122205d8187b4237d943bb/_heap.pyx new file mode 100644 index 0000000000000000000000000000000000000000..98bc3046a0798bee36e9e5782701788a595e237d --- /dev/null +++ b/shared/package-files/71/71afab2aa1b34db1b3ed7f87b8b17d573919dc27cd122205d8187b4237d943bb/_heap.pyx @@ -0,0 +1,85 @@ +from cython cimport floating + +from ._typedefs cimport intp_t + + +cdef inline int heap_push( + floating* values, + intp_t* indices, + intp_t size, + floating val, + intp_t val_idx, +) noexcept nogil: + """Push a tuple (val, val_idx) onto a fixed-size max-heap. + + The max-heap is represented as a Structure of Arrays where: + - values is the array containing the data to construct the heap with + - indices is the array containing the indices (meta-data) of each value + + Notes + ----- + Arrays are manipulated via a pointer to there first element and their size + as to ease the processing of dynamically allocated buffers. + + For instance, in pseudo-code: + + values = [1.2, 0.4, 0.1], + indices = [42, 1, 5], + heap_push( + values=values, + indices=indices, + size=3, + val=0.2, + val_idx=4, + ) + + will modify values and indices inplace, giving at the end of the call: + + values == [0.4, 0.2, 0.1] + indices == [1, 4, 5] + + """ + cdef: + intp_t current_idx, left_child_idx, right_child_idx, swap_idx + + # Check if val should be in heap + if val >= values[0]: + return 0 + + # Insert val at position zero + values[0] = val + indices[0] = val_idx + + # Descend the heap, swapping values until the max heap criterion is met + current_idx = 0 + while True: + left_child_idx = 2 * current_idx + 1 + right_child_idx = left_child_idx + 1 + + if left_child_idx >= size: + break + elif right_child_idx >= size: + if values[left_child_idx] > val: + swap_idx = left_child_idx + else: + break + elif values[left_child_idx] >= values[right_child_idx]: + if val < values[left_child_idx]: + swap_idx = left_child_idx + else: + break + else: + if val < values[right_child_idx]: + swap_idx = right_child_idx + else: + break + + values[current_idx] = values[swap_idx] + indices[current_idx] = indices[swap_idx] + + current_idx = swap_idx + + values[current_idx] = val + indices[current_idx] = val_idx + + return 0 diff --git a/shared/package-files/71/71b4bcb476fde728300d4fbd80d685b3cdc5a5b563f1aa107f0ee0c0918413aa/parsing.pyi b/shared/package-files/71/71b4bcb476fde728300d4fbd80d685b3cdc5a5b563f1aa107f0ee0c0918413aa/parsing.pyi new file mode 100644 index 0000000000000000000000000000000000000000..40394f915d4b0f12d3631d997c46381757152bfe --- /dev/null +++ b/shared/package-files/71/71b4bcb476fde728300d4fbd80d685b3cdc5a5b563f1aa107f0ee0c0918413aa/parsing.pyi @@ -0,0 +1,33 @@ +from datetime import datetime + +import numpy as np + +from pandas._typing import npt + +class DateParseError(ValueError): ... + +def py_parse_datetime_string( + date_string: str, + dayfirst: bool = ..., + yearfirst: bool = ..., +) -> datetime: ... +def parse_datetime_string_with_reso( + date_string: str, + freq: str | None = ..., + dayfirst: bool | None = ..., + yearfirst: bool | None = ..., +) -> tuple[datetime, str]: ... +def _does_string_look_like_datetime(py_string: str) -> bool: ... +def quarter_to_myear(year: int, quarter: int, freq: str) -> tuple[int, int]: ... +def try_parse_dates( + values: npt.NDArray[np.object_], # object[:] + parser, +) -> npt.NDArray[np.object_]: ... +def guess_datetime_format( + dt_str: str, + dayfirst: bool | None = ..., +) -> str | None: ... +def concat_date_cols( + date_cols: tuple, +) -> npt.NDArray[np.object_]: ... +def get_rule_month(source: str) -> str: ... diff --git a/shared/package-files/71/71b5a52d74455edbc94c748e9bbd644cc9af9582efcd57a327a3c8bb8fd1e4f3/features.pyi b/shared/package-files/71/71b5a52d74455edbc94c748e9bbd644cc9af9582efcd57a327a3c8bb8fd1e4f3/features.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8d24f2a5573f3acfb85f4e86e8bcb66b91667ec0 --- /dev/null +++ b/shared/package-files/71/71b5a52d74455edbc94c748e9bbd644cc9af9582efcd57a327a3c8bb8fd1e4f3/features.pyi @@ -0,0 +1,100 @@ +from typing import Any + +from django.db.backends.base.base import BaseDatabaseWrapper + +class BaseDatabaseFeatures: + gis_enabled: bool = ... + allows_group_by_pk: bool = ... + allows_group_by_selected_pks: bool = ... + empty_fetchmany_value: Any = ... + update_can_self_select: bool = ... + interprets_empty_strings_as_nulls: bool = ... + supports_nullable_unique_constraints: bool = ... + supports_partially_nullable_unique_constraints: bool = ... + can_use_chunked_reads: bool = ... + can_return_id_from_insert: bool = ... + can_return_ids_from_bulk_insert: bool = ... + has_bulk_insert: bool = ... + uses_savepoints: bool = ... + can_release_savepoints: bool = ... + related_fields_match_type: bool = ... + allow_sliced_subqueries_with_in: bool = ... + has_select_for_update: bool = ... + has_select_for_update_nowait: bool = ... + has_select_for_update_skip_locked: bool = ... + has_select_for_update_of: bool = ... + select_for_update_of_column: bool = ... + test_db_allows_multiple_connections: bool = ... + supports_unspecified_pk: bool = ... + supports_forward_references: bool = ... + truncates_names: bool = ... + has_real_datatype: bool = ... + supports_subqueries_in_group_by: bool = ... + has_native_uuid_field: bool = ... + has_native_duration_field: bool = ... + supports_temporal_subtraction: bool = ... + supports_regex_backreferencing: bool = ... + supports_date_lookup_using_string: bool = ... + supports_timezones: bool = ... + has_zoneinfo_database: bool = ... + requires_explicit_null_ordering_when_grouping: bool = ... + nulls_order_largest: bool = ... + max_query_params: Any = ... + allows_auto_pk_0: bool = ... + can_defer_constraint_checks: bool = ... + supports_mixed_date_datetime_comparisons: bool = ... + supports_tablespaces: bool = ... + supports_sequence_reset: bool = ... + can_introspect_default: bool = ... + can_introspect_foreign_keys: bool = ... + can_introspect_autofield: bool = ... + can_introspect_big_integer_field: bool = ... + can_introspect_binary_field: bool = ... + can_introspect_decimal_field: bool = ... + can_introspect_ip_address_field: bool = ... + can_introspect_positive_integer_field: bool = ... + can_introspect_small_integer_field: bool = ... + can_introspect_time_field: bool = ... + introspected_boolean_field_type: str = ... + supports_index_column_ordering: bool = ... + can_distinct_on_fields: bool = ... + autocommits_when_autocommit_is_off: bool = ... + atomic_transactions: bool = ... + can_rollback_ddl: bool = ... + supports_atomic_references_rename: bool = ... + supports_combined_alters: bool = ... + supports_foreign_keys: bool = ... + supports_column_check_constraints: bool = ... + supports_paramstyle_pyformat: bool = ... + requires_literal_defaults: bool = ... + connection_persists_old_columns: bool = ... + closed_cursor_error_class: Any = ... + has_case_insensitive_like: bool = ... + requires_sqlparse_for_splitting: bool = ... + bare_select_suffix: str = ... + implied_column_null: bool = ... + uppercases_column_names: bool = ... + supports_select_for_update_with_limit: bool = ... + greatest_least_ignores_nulls: bool = ... + can_clone_databases: bool = ... + ignores_table_name_case: bool = ... + for_update_after_from: bool = ... + supports_select_union: bool = ... + supports_select_intersection: bool = ... + supports_select_difference: bool = ... + supports_slicing_ordering_in_compound: bool = ... + supports_aggregate_filter_clause: bool = ... + supports_index_on_text_field: bool = ... + supports_over_clause: bool = ... + supports_cast_with_precision: bool = ... + create_test_procedure_without_params_sql: Any = ... + create_test_procedure_with_int_param_sql: Any = ... + supports_callproc_kwargs: bool = ... + db_functions_convert_bytes_to_str: bool = ... + supported_explain_formats: Any = ... + validates_explain_options: bool = ... + connection: Any = ... + def __init__(self, connection: BaseDatabaseWrapper) -> None: ... + def supports_explaining_query_execution(self) -> bool: ... + def supports_transactions(self): ... + def supports_stddev(self): ... diff --git a/shared/package-files/71/71b6a8ff603bf14f47e767dcdd8d6f49bdc41f4b9fd68926db0ea05e1bec7da4/test_errorhandling.py b/shared/package-files/71/71b6a8ff603bf14f47e767dcdd8d6f49bdc41f4b9fd68926db0ea05e1bec7da4/test_errorhandling.py new file mode 100644 index 0000000000000000000000000000000000000000..cc141f4da43c31af2ded7d131e0d575555e16f5c --- /dev/null +++ b/shared/package-files/71/71b6a8ff603bf14f47e767dcdd8d6f49bdc41f4b9fd68926db0ea05e1bec7da4/test_errorhandling.py @@ -0,0 +1,501 @@ +""" +Unspecified error handling tests +""" + +import numpy as np +import os +import warnings + +from numba import jit, njit, types +from numba.core import errors +from numba.experimental import structref +from numba.extending import (overload, intrinsic, overload_method, + overload_attribute) +from numba.core.compiler import CompilerBase +from numba.core.untyped_passes import (TranslateByteCode, FixupArgs, + IRProcessing,) +from numba.core.typed_passes import (NopythonTypeInference, DeadCodeElimination, + NoPythonBackend, NativeLowering) +from numba.core.compiler_machinery import PassManager +from numba.core.types.functions import _err_reasons as error_reasons + +from numba.tests.support import (skip_parfors_unsupported, override_config, + SerialMixin, skip_unless_cffi, + skip_unless_scipy, TestCase) +import unittest + + +class TestErrorHandlingBeforeLowering(unittest.TestCase): + + def test_unsupported_make_function_return_inner_func(self): + def func(x): + """ return the closure """ + z = x + 1 + + def inner(x): + return x + z + return inner + + for pipeline in jit, njit: + with self.assertRaises(errors.TypingError) as raises: + pipeline(func)(1) + + expected = "Cannot capture the non-constant value" + self.assertIn(expected, str(raises.exception)) + + +class TestUnsupportedReporting(unittest.TestCase): + + def test_unsupported_numpy_function(self): + # np.asanyarray(list) currently unsupported + @njit + def func(): + np.asanyarray([1,2,3]) + + with self.assertRaises(errors.TypingError) as raises: + func() + + expected = "Use of unsupported NumPy function 'numpy.asanyarray'" + self.assertIn(expected, str(raises.exception)) + + +class TestMiscErrorHandling(unittest.TestCase): + + def test_use_of_exception_for_flow_control(self): + # constant inference uses exceptions with no Loc specified to determine + # flow control, this asserts that the construction of the lowering + # error context handler works in the case of an exception with no Loc + # specified. See issue #3135. + @njit + def fn(x): + return 10**x + + a = np.array([1.0],dtype=np.float64) + fn(a) # should not raise + + def test_commented_func_definition_is_not_a_definition(self): + # See issue #4056, the commented def should not be found as the + # definition for reporting purposes when creating the synthetic + # traceback because it is commented! Use of def in docstring would also + # cause this issue hence is tested. + + def foo_commented(): + #def commented_definition() + raise Exception('test_string') + + def foo_docstring(): + """ def docstring containing def might match function definition!""" + raise Exception('test_string') + + for func in (foo_commented, foo_docstring): + with self.assertRaises(Exception) as raises: + func() + + self.assertIn("test_string", str(raises.exception)) + + def test_use_of_ir_unknown_loc(self): + # for context see # 3390 + class TestPipeline(CompilerBase): + def define_pipelines(self): + name = 'bad_DCE_pipeline' + pm = PassManager(name) + pm.add_pass(TranslateByteCode, "analyzing bytecode") + pm.add_pass(FixupArgs, "fix up args") + pm.add_pass(IRProcessing, "processing IR") + # remove dead before type inference so that the Arg node is + # removed and the location of the arg cannot be found + pm.add_pass(DeadCodeElimination, "DCE") + # typing + pm.add_pass(NopythonTypeInference, "nopython frontend") + pm.add_pass(NativeLowering, "native lowering") + pm.add_pass(NoPythonBackend, "nopython mode backend") + pm.finalize() + return [pm] + + @njit(pipeline_class=TestPipeline) + def f(a): + return 0 + + with self.assertRaises(errors.TypingError) as raises: + f(iter([1,2])) # use a type that Numba doesn't recognize + + expected = 'File "unknown location", line 0:' + self.assertIn(expected, str(raises.exception)) + + def check_write_to_globals(self, func): + with self.assertRaises(errors.TypingError) as raises: + func() + + expected = ["The use of a", "in globals, is not supported as globals"] + for ex in expected: + self.assertIn(ex, str(raises.exception)) + + def test_handling_of_write_to_reflected_global(self): + from numba.tests.errorhandling_usecases import global_reflected_write + self.check_write_to_globals(njit(global_reflected_write)) + + def test_handling_of_write_to_typed_dict_global(self): + from numba.tests.errorhandling_usecases import global_dict_write + self.check_write_to_globals(njit(global_dict_write)) + + @skip_parfors_unsupported + def test_handling_forgotten_numba_internal_import(self): + @njit(parallel=True) + def foo(): + for i in prange(10): # noqa: F821 prange is not imported + pass + + with self.assertRaises(errors.TypingError) as raises: + foo() + + expected = ("'prange' looks like a Numba internal function, " + "has it been imported") + self.assertIn(expected, str(raises.exception)) + + def test_handling_unsupported_generator_expression(self): + def foo(): + (x for x in range(10)) + + expected = "The use of yield in a closure is unsupported." + + for dec in jit(forceobj=True), njit: + with self.assertRaises(errors.UnsupportedError) as raises: + dec(foo)() + self.assertIn(expected, str(raises.exception)) + + def test_handling_undefined_variable(self): + @njit + def foo(): + return a # noqa: F821 + + expected = "NameError: name 'a' is not defined" + + with self.assertRaises(errors.TypingError) as raises: + foo() + self.assertIn(expected, str(raises.exception)) + + +class TestErrorMessages(unittest.TestCase): + + def test_specific_error(self): + + given_reason = "specific_reason" + + def foo(): + pass + + @overload(foo) + def ol_foo(): + raise errors.NumbaValueError(given_reason) + + @njit + def call_foo(): + foo() + + with self.assertRaises(errors.TypingError) as raises: + call_foo() + + excstr = str(raises.exception) + self.assertIn(error_reasons['specific_error'].splitlines()[0], excstr) + self.assertIn(given_reason, excstr) + + def test_no_match_error(self): + + def foo(): + pass + + @overload(foo) + def ol_foo(): + return None # emulate no impl available for type + + @njit + def call_foo(): + foo() + + with self.assertRaises(errors.TypingError) as raises: + call_foo() + + excstr = str(raises.exception) + self.assertIn("No match", excstr) + + @skip_unless_scipy + def test_error_function_source_is_correct(self): + """ Checks that the reported source location for an overload is the + overload implementation source, not the actual function source from the + target library.""" + + @njit + def foo(): + np.linalg.svd("chars") + + with self.assertRaises(errors.TypingError) as raises: + foo() + + excstr = str(raises.exception) + self.assertIn(error_reasons['specific_error'].splitlines()[0], excstr) + expected_file = os.path.join("numba", "np", "linalg.py") + expected = f"Overload in function 'svd_impl': File: {expected_file}:" + self.assertIn(expected.format(expected_file), excstr) + + def test_concrete_template_source(self): + # hits ConcreteTemplate + @njit + def foo(): + return 'a' + 1 + + with self.assertRaises(errors.TypingError) as raises: + foo() + + excstr = str(raises.exception) + + self.assertIn("Overload of function 'add'", excstr) + # there'll be numerous matched templates that don't work but as they + # are mostly "overload"s they'll just appear as "No match". + self.assertIn("No match.", excstr) + + def test_abstract_template_source(self): + # hits AbstractTemplate + @njit + def foo(): + return len(1) + + with self.assertRaises(errors.TypingError) as raises: + foo() + + excstr = str(raises.exception) + self.assertIn("Overload of function 'len'", excstr) + + def test_callable_template_source(self): + # hits CallableTemplate + @njit + def foo(): + return np.angle(None) + + with self.assertRaises(errors.TypingError) as raises: + foo() + + excstr = str(raises.exception) + self.assertIn("No implementation of function Function(", excstr) + expected_file = os.path.join("numba", "tests", + "test_errorhandling.py") + expected_ol = f"Overload of function 'bar': File: {expected_file}:" + self.assertIn(expected_ol.format(expected_file), excstr) + self.assertIn("No match.", excstr) + + def test_intrinsic_template_source(self): + # hits _IntrinsicTemplate + given_reason1 = "x must be literal" + given_reason2 = "array.ndim must be 1" + + @intrinsic + def myintrin(typingctx, x, arr): + if not isinstance(x, types.IntegerLiteral): + raise errors.RequireLiteralValue(given_reason1) + + if arr.ndim != 1: + raise errors.NumbaValueError(given_reason2) + + sig = types.intp(x, arr) + + def codegen(context, builder, signature, args): + pass + return sig, codegen + + @njit + def call_intrin(): + arr = np.zeros((2, 2)) + myintrin(1, arr) + + with self.assertRaises(errors.TypingError) as raises: + call_intrin() + + excstr = str(raises.exception) + self.assertIn(error_reasons['specific_error'].splitlines()[0], excstr) + self.assertIn(given_reason1, excstr) + self.assertIn(given_reason2, excstr) + self.assertIn("Intrinsic in function", excstr) + + def test_overloadmethod_template_source(self): + # doesn't hit _OverloadMethodTemplate for source as it's a nested + # exception + @overload_method(types.UnicodeType, 'isnonsense') + def ol_unicode_isnonsense(self): + pass + + @njit + def foo(): + "abc".isnonsense() + + with self.assertRaises(errors.TypingError) as raises: + foo() + + excstr = str(raises.exception) + self.assertIn("Overload of function 'ol_unicode_isnonsense'", excstr) + + def test_overloadattribute_template_source(self): + # doesn't hit _OverloadMethodTemplate for source as it's a nested + # exception + @overload_attribute(types.UnicodeType, 'isnonsense') + def ol_unicode_isnonsense(self): + pass + + @njit + def foo(): + "abc".isnonsense + + with self.assertRaises(errors.TypingError) as raises: + foo() + + excstr = str(raises.exception) + self.assertIn("Overload of function 'ol_unicode_isnonsense'", excstr) + + def test_external_function_pointer_template_source(self): + from numba.tests.ctypes_usecases import c_cos + + @njit + def foo(): + c_cos('a') + + with self.assertRaises(errors.TypingError) as raises: + foo() + + excstr = str(raises.exception) + self.assertIn("Type Restricted Function in function 'unknown'", excstr) + + @skip_unless_cffi + def test_cffi_function_pointer_template_source(self): + from numba.tests import cffi_usecases as mod + mod.init() + func = mod.cffi_cos + + @njit + def foo(): + func('a') + + with self.assertRaises(errors.TypingError) as raises: + foo() + + excstr = str(raises.exception) + self.assertIn("Type Restricted Function in function 'unknown'", excstr) + + def test_missing_source(self): + + @structref.register + class ParticleType(types.StructRef): + pass + + class Particle(structref.StructRefProxy): + def __new__(cls, pos, mass): + return structref.StructRefProxy.__new__(cls, pos) + # didn't provide the required mass argument ----^ + + structref.define_proxy(Particle, ParticleType, ["pos", "mass"]) + + with self.assertRaises(errors.TypingError) as raises: + Particle(pos=1, mass=2) + + excstr = str(raises.exception) + self.assertIn("missing a required argument: 'mass'", excstr) + + +class TestDeveloperSpecificErrorMessages(SerialMixin, unittest.TestCase): + + def test_bound_function_error_string(self): + # See PR #5952 + def foo(x): + x.max(-1) + + with override_config('DEVELOPER_MODE', 1): + with self.assertRaises(errors.TypingError) as raises: + njit("void(int64[:,:])")(foo) + + excstr = str(raises.exception) + self.assertIn("too many positional arguments", excstr) + + +class TestCapturedErrorHandling(SerialMixin, TestCase): + """Checks that the way errors are captured. + """ + + def test_error_in_overload(self): + + def bar(x): + pass + + @overload(bar) + def ol_bar(x): + x.some_invalid_attr # doesn't exist! + + def impl(x): + pass + return impl + + with warnings.catch_warnings(): + # Suppress error going into stdout + warnings.simplefilter("ignore", + errors.NumbaPendingDeprecationWarning) + + with self.assertRaises(AttributeError) as raises: + @njit('void(int64)') + def foo(x): + bar(x) + expected = "object has no attribute 'some_invalid_attr'" + self.assertIn(expected, str(raises.exception)) + + +class TestCurlyBracesInPaths(unittest.TestCase): + """ + Test that error messages handle file paths with curly braces (issue #10094) + """ + + def test_placeholders_with_positional_args(self): + + # used on typeinfer: placeholders with positional args + problematic_path = ( + r"C:\\Users\\" + r"{fa977bf3384160bce9243175b380be8}" + r"\\file.py" + ) + fmt = "Error at {0}" + + result = errors._format_msg(fmt, (problematic_path,), {}) + + expected = f"Error at {problematic_path}" + self.assertEqual(result, expected) + + def test_preformatted_string_no_args(self): + + # used on compiler_machinery: preformatted string without args + name_with_braces = "{abc123}" + fmt = f"Pass {name_with_braces}" + + result = errors._format_msg(fmt, (), {}) + + expected = f"Pass {name_with_braces}" + self.assertEqual(result, expected) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/71/71b98a4c1fe95ae19d001bf638c4a4dea2147b7a69c8e67da80659c3e5b12fe9/tab132-rv b/shared/package-files/71/71b98a4c1fe95ae19d001bf638c4a4dea2147b7a69c8e67da80659c3e5b12fe9/tab132-rv new file mode 100644 index 0000000000000000000000000000000000000000..6d6d6c6744aaac4e663a5c11da70cbdb1679ed48 Binary files /dev/null and b/shared/package-files/71/71b98a4c1fe95ae19d001bf638c4a4dea2147b7a69c8e67da80659c3e5b12fe9/tab132-rv differ diff --git a/shared/package-files/71/71bb0ddcb93d1e4c33afd73ec8e3f6c44060d7f9a5d57ee7c003035b11a3cdcf/gfortran_vs2003_hack.c b/shared/package-files/71/71bb0ddcb93d1e4c33afd73ec8e3f6c44060d7f9a5d57ee7c003035b11a3cdcf/gfortran_vs2003_hack.c new file mode 100644 index 0000000000000000000000000000000000000000..485a675d8a1fb80bc4927fe236ba3fe550f5a0c9 --- /dev/null +++ b/shared/package-files/71/71bb0ddcb93d1e4c33afd73ec8e3f6c44060d7f9a5d57ee7c003035b11a3cdcf/gfortran_vs2003_hack.c @@ -0,0 +1,6 @@ +int _get_output_format(void) +{ + return 0; +} + +int _imp____lc_codepage = 0; diff --git a/shared/package-files/71/71be1b3dc629a0eaffda7f421c7c620d3ce9b31d48d190757fd09e4f7a048bbe/test_pretty_print.py b/shared/package-files/71/71be1b3dc629a0eaffda7f421c7c620d3ce9b31d48d190757fd09e4f7a048bbe/test_pretty_print.py new file mode 100644 index 0000000000000000000000000000000000000000..b0be5dbe8e4fcb78e2c1edafc679a4ebe3b1bbee --- /dev/null +++ b/shared/package-files/71/71be1b3dc629a0eaffda7f421c7c620d3ce9b31d48d190757fd09e4f7a048bbe/test_pretty_print.py @@ -0,0 +1,69 @@ +# NOTE: This test is sensitive to line numbers as it checks breakpoints +from numba import njit +import numpy as np +from numba.tests.gdb_support import GdbMIDriver, needs_gdb_py3 +from numba.tests.support import TestCase, needs_subprocess +from numba.misc.numba_gdbinfo import collect_gdbinfo +import unittest +import re + + +@needs_gdb_py3 +@needs_subprocess +class Test(TestCase): + + def test(self): + rdt_a = np.dtype([("x", np.int16), ("y", np.float64)], align=True) + + @njit(debug=True) + def foo(): + a = 1.234 + b = (1, 2, 3) + c = ('a', b, 4) + d = np.arange(5.) + e = np.array([[1, 3j], [2, 4j]]) + f = "Some string" + " L-Padded string".lstrip() + g = 11 + 22j + h = np.arange(24).reshape((4, 6))[::2, ::3] + i = np.zeros(2, dtype=rdt_a) + return a, b, c, d, e, f, g, h, i + + foo() + + extension = collect_gdbinfo().extension_loc + driver = GdbMIDriver(__file__, init_cmds=['-x', extension], debug=False) + driver.set_breakpoint(line=29) + driver.run() + driver.check_hit_breakpoint(1) + + # Ideally the function would be run to get the string repr of locals + # but not everything appears in DWARF e.g. string literals. Further, + # str on NumPy arrays seems to vary a bit in output. Therefore a custom + # match is used. + + driver.stack_list_variables(1) + output = driver._captured.after.decode('UTF-8') + done_str = output.splitlines()[0] + pat = r'^\^done,variables=\[\{(.*)\}\]$' + lcls_strs = re.match(pat, done_str).groups()[0].split('},{') + lcls = {k: v for k, v in [re.match(r'name="(.*)",value="(.*)"', + x).groups() for x in lcls_strs]} + expected = dict() + expected['a'] = r'1\.234' + expected['b'] = r'\(1, 2, 3\)' + expected['c'] = r'\(0x0, \(1, 2, 3\), 4\)' + expected['d'] = r'\\n\[0. 1. 2. 3. 4.\]' + expected['e'] = r'\\n\[\[1.\+0.j 0.\+3.j\]\\n \[2.\+0.j 0.\+4.j\]\]' + expected['f'] = "'Some stringL-Padded string'" + expected['g'] = r"11\+22j" + expected['h'] = r'\\n\[\[ 0 3\]\\n \[12 15\]\]' + expected['i'] = r'\\n\[\(0, 0.\) \(0, 0.\)\]' + + for k, v in expected.items(): + self.assertRegex(lcls[k], v) + + driver.quit() + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/71/71bfa827653be2e4ee300475edf14468e62591e35cf4cad64578eb5cd9c884c7/expr.py b/shared/package-files/71/71bfa827653be2e4ee300475edf14468e62591e35cf4cad64578eb5cd9c884c7/expr.py new file mode 100644 index 0000000000000000000000000000000000000000..9608cc46cef2663df389db586cce25ddeede33ac --- /dev/null +++ b/shared/package-files/71/71bfa827653be2e4ee300475edf14468e62591e35cf4cad64578eb5cd9c884c7/expr.py @@ -0,0 +1,1236 @@ +from __future__ import annotations + +from functools import partial +from itertools import islice +from operator import methodcaller +from typing import TYPE_CHECKING, Any, Generic, Literal, Protocol + +from narwhals._compliant.any_namespace import ( + CatNamespace, + DateTimeNamespace, + ListNamespace, + NameNamespace, + StringNamespace, + StructNamespace, +) +from narwhals._compliant.column import CompliantColumn +from narwhals._compliant.typing import ( + AliasName, + AliasNames, + CompliantExprT_co, + CompliantFrameT, + CompliantLazyFrameT, + CompliantSeriesOrNativeExprT_co, + EagerDataFrameT, + EagerExprT, + EagerSeriesT, + LazyExprT, + NativeExprT, +) +from narwhals._utils import ( + _resolve_sample_size, + _StoresCompliant, + not_implemented, + qualified_type_name, +) +from narwhals.dependencies import is_numpy_array, is_numpy_scalar +from narwhals.exceptions import MultiOutputExpressionError + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from typing_extensions import Self, TypeIs + + from narwhals._compliant.namespace import CompliantNamespace, EagerNamespace + from narwhals._compliant.series import CompliantSeries + from narwhals._compliant.typing import EvalNames, EvalSeries + from narwhals._expression_parsing import ExprMetadata + from narwhals._typing import NoDefault + from narwhals._utils import Implementation, Version, _LimitedContext + from narwhals.typing import ( + ClosedInterval, + FillNullStrategy, + IntoDType, + ModeKeepStrategy, + NonNestedLiteral, + RankMethod, + RollingInterpolationMethod, + TimeUnit, + ) + +__all__ = ["CompliantExpr", "DepthTrackingExpr", "EagerExpr", "LazyExpr", "NativeExpr"] + + +class NativeExpr(Protocol): + """An `Expr`-like object from a package with [Lazy-only support](https://narwhals-dev.github.io/narwhals/extending/#levels-of-support). + + Protocol members are chosen *purely* for matching statically - as they + are common to all currently supported packages. + """ + + def between(self, *args: Any, **kwds: Any) -> Any: ... + + # NOTE: None of these are annotated for `dx.Series`, but are added imperatively + # Probably better to define a sub-protocol for `NativeSQLExpr` + # - match `dx.Series` to `NativeExpr` + # - match the others to `NativeSQLExpr` + def __gt__(self, value: Any, /) -> Self: ... + def __lt__(self, value: Any, /) -> Self: ... + def __ge__(self, value: Any, /) -> Self: ... + def __le__(self, value: Any, /) -> Self: ... + def __eq__(self, value: Any, /) -> Self: ... # type: ignore[override] + def __ne__(self, value: Any, /) -> Self: ... # type: ignore[override] + + +class CompliantExpr( + CompliantColumn, Protocol[CompliantFrameT, CompliantSeriesOrNativeExprT_co] +): + # NOTE: `narwhals` + _implementation: Implementation + _evaluate_output_names: EvalNames[CompliantFrameT] + _alias_output_names: AliasNames | None + # This should be set with extreme care, only in `_expression_parsing.py`, + # and never from within any compliant class. + _opt_metadata: ExprMetadata | None = None + + @property + def _metadata(self) -> ExprMetadata: + if self._opt_metadata is None: # pragma: no cover + msg = ( + "`_opt_metadata` is None. This is usually the result of trying to do " + "some operation (such as `over`) which requires access to the metadata " + "at the compliant level. You may want to consider rewriting your logic " + "so that this operation is not necessary. Ideally you should avoid " + "setting `_opt_metadata` manually." + ) + raise AssertionError(msg) + return self._opt_metadata + + def __call__( + self, df: CompliantFrameT + ) -> Sequence[CompliantSeriesOrNativeExprT_co]: ... + def __narwhals_expr__(self) -> Self: # pragma: no cover + return self + + def __narwhals_namespace__(self) -> CompliantNamespace[CompliantFrameT, Self]: ... + @classmethod + def from_column_indices( + cls, *column_indices: int, context: _LimitedContext + ) -> Self: ... + @classmethod + def from_column_names( + cls, + evaluate_column_names: EvalNames[CompliantFrameT], + /, + *, + context: _LimitedContext, + ) -> Self: ... + def broadcast(self) -> Self: ... + def _is_close_float_promote(self) -> Self: + # Default float promotion for `is_close`: equivalent to `self + 0.0`, letting + # each backend pick its float type (broadcast mirrors the node-evaluation path). + # Polars overrides this to align old versions (see `PolarsExpr`). + plx = self.__narwhals_namespace__() + return self + plx.lit(0.0, None).broadcast() + + # NOTE: `polars` + def alias(self, name: str) -> Self: ... + def all(self) -> Self: ... + def any(self) -> Self: ... + def any_value(self, *, ignore_nulls: bool) -> Self: ... + def count(self) -> Self: ... + def min(self) -> Self: ... + def max(self) -> Self: ... + def mean(self) -> Self: ... + def sum(self) -> Self: ... + def median(self) -> Self: ... + def first(self, order_by: Sequence[str] = ()) -> Self: ... + def last(self, order_by: Sequence[str] = ()) -> Self: ... + def skew(self) -> Self: ... + def kurtosis(self) -> Self: ... + def std(self, *, ddof: int) -> Self: ... + def var(self, *, ddof: int) -> Self: ... + def n_unique(self) -> Self: ... + def null_count(self) -> Self: ... + def len(self) -> Self: ... + def over(self, partition_by: Sequence[str], order_by: Sequence[str]) -> Self: ... + def quantile( + self, quantile: float, interpolation: RollingInterpolationMethod + ) -> Self: ... + def map_batches( + self, + function: Callable[[CompliantSeries[Any]], CompliantExpr[Any, Any]], + return_dtype: IntoDType | None, + *, + returns_scalar: bool, + ) -> Self: ... + def replace_strict( + self, + default: Self | NoDefault, + old: Sequence[Any], + new: Sequence[Any], + *, + return_dtype: IntoDType | None, + ) -> Self: ... + @property + def name(self) -> NameNamespace[Self]: ... + + +class ImplExpr( + CompliantExpr[CompliantFrameT, CompliantSeriesOrNativeExprT_co], + Protocol[CompliantFrameT, CompliantSeriesOrNativeExprT_co], +): + @staticmethod + def _eval_names_indices(indices: Sequence[int], /) -> EvalNames[CompliantFrameT]: + def fn(df: CompliantFrameT) -> Sequence[str]: + column_names = df.columns + return [column_names[i] for i in indices] + + return fn + + def _evaluate_aliases(self, frame: CompliantFrameT, /) -> Sequence[str]: + # NOTE: Ignore intermittent [False Negative] + # Argument of type "CompliantFrameT@ImplExpr" cannot be assigned to parameter of type "CompliantFrameT@ImplExpr" + # Type "CompliantFrameT@ImplExpr" is not assignable to type "CompliantFrameT@ImplExpr" + names = self._evaluate_output_names(frame) # pyright: ignore[reportArgumentType] + return alias(names) if (alias := self._alias_output_names) else names + + +class DepthTrackingExpr( + ImplExpr[CompliantFrameT, CompliantSeriesOrNativeExprT_co], + Protocol[CompliantFrameT, CompliantSeriesOrNativeExprT_co], +): + # NOTE: pyright bug? + # Method "from_column_names" overrides class "CompliantExpr" in an incompatible manner + # Parameter 2 type mismatch: base parameter is type "EvalNames[CompliantFrameT@DepthTrackingExpr]", override parameter is type "EvalNames[CompliantFrameT@DepthTrackingExpr]" + # Type "EvalNames[CompliantFrameT@DepthTrackingExpr]" is not assignable to type "EvalNames[CompliantFrameT@DepthTrackingExpr]" + # Parameter 1: type "CompliantFrameT@DepthTrackingExpr" is incompatible with type "CompliantFrameT@DepthTrackingExpr" + # Type "CompliantFrameT@DepthTrackingExpr" is not assignable to type "CompliantFrameT@DepthTrackingExpr" + @classmethod + def from_column_names( # pyright: ignore[reportIncompatibleMethodOverride] + cls: type[Self], + evaluate_column_names: EvalNames[CompliantFrameT], + /, + *, + context: _LimitedContext, + ) -> Self: ... + + def _is_elementary(self) -> bool: + """Check if expr is elementary. + + Examples: + - nw.col('a').mean() # depth 1 + - nw.mean('a') # depth 1 + - nw.len() # depth 0 + + as opposed to, say + + - nw.col('a').filter(nw.col('b')>nw.col('c')).max() + + Elementary expressions are the only ones supported properly in + pandas, PyArrow, and Dask. + """ + return len(list(islice(self._metadata.op_nodes_reversed(), 3))) <= 2 + + +class EagerExpr( + DepthTrackingExpr[EagerDataFrameT, EagerSeriesT], + Protocol[EagerDataFrameT, EagerSeriesT], +): + _call: EvalSeries[EagerDataFrameT, EagerSeriesT] + + def __init__( + self, + call: EvalSeries[EagerDataFrameT, EagerSeriesT], + *, + evaluate_output_names: EvalNames[EagerDataFrameT], + alias_output_names: AliasNames | None, + implementation: Implementation, + version: Version, + ) -> None: ... + + def __call__(self, df: EagerDataFrameT) -> Sequence[EagerSeriesT]: + return self._call(df) + + def __narwhals_namespace__( + self, + ) -> EagerNamespace[EagerDataFrameT, EagerSeriesT, Self, Any, Any]: ... + @classmethod + def _from_callable( + cls, + func: EvalSeries[EagerDataFrameT, EagerSeriesT], + *, + evaluate_output_names: EvalNames[EagerDataFrameT], + alias_output_names: AliasNames | None, + context: _LimitedContext, + ) -> Self: + return cls( + func, + evaluate_output_names=evaluate_output_names, + alias_output_names=alias_output_names, + implementation=context._implementation, + version=context._version, + ) + + @classmethod + def _from_series(cls, series: EagerSeriesT) -> Self: + return cls( + lambda _df: [series], + evaluate_output_names=lambda _df: [series.name], + alias_output_names=None, + implementation=series._implementation, + version=series._version, + ) + + def _with_alias_output_names(self, alias_name: AliasName | None, /) -> Self: + current_alias_output_names = self._alias_output_names + alias_output_names: AliasNames | None = ( + None + if alias_name is None + else ( + lambda output_names: [ + alias_name(x) for x in current_alias_output_names(output_names) + ] + ) + if current_alias_output_names is not None + else (lambda output_names: [alias_name(x) for x in output_names]) + ) + + def func(df: EagerDataFrameT) -> list[EagerSeriesT]: + if alias_output_names: + return [ + series.alias(name) + for series, name in zip( + self(df), + alias_output_names(self._evaluate_output_names(df)), + strict=True, + ) + ] + return [ + series.alias(name) + for series, name in zip( + self(df), self._evaluate_output_names(df), strict=True + ) + ] + + return self.__class__( + func, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=alias_output_names, + implementation=self._implementation, + version=self._version, + ) + + def _reuse_series( + self, method_name: str, *, returns_scalar: bool = False, **kwargs: Any + ) -> Self: + """Reuse Series implementation for expression. + + If Series.foo is already defined, and we'd like Expr.foo to be the same, we can + leverage this method to do that for us. + + Arguments: + method_name: name of method. + returns_scalar: whether the Series version returns a scalar. In this case, + the expression version should return a 1-row Series. + kwargs: keyword arguments to pass to function. + """ + func = partial( + self._reuse_series_inner, + method_name=method_name, + returns_scalar=returns_scalar, + **kwargs, + ) + return self._from_callable( + func, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=self._alias_output_names, + context=self, + ) + + # For PyArrow.Series, we return Python Scalars (like Polars does) instead of PyArrow Scalars. + # However, when working with expressions, we keep everything PyArrow-native. + def _reuse_series_extra_kwargs( + self, *, returns_scalar: bool = False + ) -> dict[str, Any]: + return {} + + @classmethod + def _is_expr(cls, obj: Self | Any) -> TypeIs[Self]: + return hasattr(obj, "__narwhals_expr__") + + def _reuse_series_inner( + self, + df: EagerDataFrameT, + *, + method_name: str, + returns_scalar: bool, + **kwargs: Any, + ) -> Sequence[EagerSeriesT]: + kwargs = { + name: df._evaluate_single_output_expr(value) + if self._is_expr(value) + else value + for name, value in kwargs.items() + } + method = methodcaller( + method_name, + **self._reuse_series_extra_kwargs(returns_scalar=returns_scalar), + **kwargs, + ) + out: Sequence[EagerSeriesT] = [ + series._from_scalar(method(series)) if returns_scalar else method(series) + for series in self(df) + ] + aliases, names = self._evaluate_aliases(df), (s.name for s in out) + if any( + alias != name for alias, name in zip(aliases, names, strict=True) + ): # pragma: no cover + msg = ( + f"Safety assertion failed, please report a bug to https://github.com/narwhals-dev/narwhals/issues\n" + f"Expression aliases: {aliases}\n" + ) + raise AssertionError(msg) + return out + + def _reuse_series_namespace( + self, + series_namespace: Literal["cat", "dt", "list", "name", "str", "struct"], + method_name: str, + **expressifiable_args: Any, + ) -> Self: + """Reuse Series implementation for expression. + + Just like `_reuse_series`, but for e.g. `Expr.dt.foo` instead + of `Expr.foo`. + + Arguments: + series_namespace: The Series namespace. + method_name: name of method, within `series_namespace`. + expressifiable_args: keyword arguments to pass to function, which may + be expressifiable (e.g. `nw.col('a').str.replace('abc', nw.col('b')))`). + """ + + def inner(df: EagerDataFrameT) -> list[EagerSeriesT]: + kwargs = { + name: df._evaluate_single_output_expr(value) + if self._is_expr(value) + else value + for name, value in expressifiable_args.items() + } + return [ + getattr(getattr(series, series_namespace), method_name)(**kwargs) + for series in self(df) + ] + + return self._from_callable( + inner, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=self._alias_output_names, + context=self, + ) + + def broadcast(self) -> Self: + # Mark the resulting Series with `_broadcast = True`. + # Then, when extracting native objects, `extract_native` will + # know what to do. + def func(df: EagerDataFrameT) -> list[EagerSeriesT]: + results = [] + for result in self(df): + result._broadcast = True + results.append(result) + return results + + return type(self)( + func, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=self._alias_output_names, + implementation=self._implementation, + version=self._version, + ) + + def cast(self, dtype: IntoDType) -> Self: + return self._reuse_series("cast", dtype=dtype) + + def _with_binary(self, operator: str, other: Self, /) -> Self: + return self._reuse_series(operator, other=other) + + def _with_binary_right(self, operator: str, other: Self, /) -> Self: + return self.alias("literal")._reuse_series(operator, other=other) + + def __eq__(self, other: Self) -> Self: # type: ignore[override] + return self._with_binary("__eq__", other) + + def __ne__(self, other: Self) -> Self: # type: ignore[override] + return self._with_binary("__ne__", other) + + def __ge__(self, other: Self) -> Self: + return self._with_binary("__ge__", other) + + def __gt__(self, other: Self) -> Self: + return self._with_binary("__gt__", other) + + def __le__(self, other: Self) -> Self: + return self._with_binary("__le__", other) + + def __lt__(self, other: Self) -> Self: + return self._with_binary("__lt__", other) + + def __and__(self, other: Self) -> Self: + return self._with_binary("__and__", other) + + def __or__(self, other: Self) -> Self: + return self._with_binary("__or__", other) + + def __add__(self, other: Self) -> Self: + return self._with_binary("__add__", other) + + def __sub__(self, other: Self) -> Self: + return self._with_binary("__sub__", other) + + def __rsub__(self, other: Self) -> Self: + return self._with_binary_right("__rsub__", other) + + def __mul__(self, other: Self) -> Self: + return self._with_binary("__mul__", other) + + def __truediv__(self, other: Self) -> Self: + return self._with_binary("__truediv__", other) + + def __rtruediv__(self, other: Self) -> Self: + return self._with_binary_right("__rtruediv__", other) + + def __floordiv__(self, other: Self) -> Self: + return self._with_binary("__floordiv__", other) + + def __rfloordiv__(self, other: Self) -> Self: + return self._with_binary_right("__rfloordiv__", other) + + def __pow__(self, other: Self) -> Self: + return self._with_binary("__pow__", other) + + def __rpow__(self, other: Self) -> Self: + return self._with_binary_right("__rpow__", other) + + def __mod__(self, other: Self) -> Self: + return self._with_binary("__mod__", other) + + def __rmod__(self, other: Self) -> Self: + return self._with_binary_right("__rmod__", other) + + # Unary + def __invert__(self) -> Self: + return self._reuse_series("__invert__") + + def __neg__(self) -> Self: + return self._reuse_series("__neg__") + + # Reductions + def null_count(self) -> Self: + return self._reuse_series("null_count", returns_scalar=True) + + def n_unique(self) -> Self: + return self._reuse_series("n_unique", returns_scalar=True) + + def sum(self) -> Self: + return self._reuse_series("sum", returns_scalar=True) + + def count(self) -> Self: + return self._reuse_series("count", returns_scalar=True) + + def mean(self) -> Self: + return self._reuse_series("mean", returns_scalar=True) + + def median(self) -> Self: + return self._reuse_series("median", returns_scalar=True) + + def std(self, *, ddof: int) -> Self: + return self._reuse_series("std", returns_scalar=True, ddof=ddof) + + def var(self, *, ddof: int) -> Self: + return self._reuse_series("var", returns_scalar=True, ddof=ddof) + + def skew(self) -> Self: + return self._reuse_series("skew", returns_scalar=True) + + def kurtosis(self) -> Self: + return self._reuse_series("kurtosis", returns_scalar=True) + + def any(self) -> Self: + return self._reuse_series("any", returns_scalar=True) + + def all(self) -> Self: + return self._reuse_series("all", returns_scalar=True) + + def max(self) -> Self: + return self._reuse_series("max", returns_scalar=True) + + def min(self) -> Self: + return self._reuse_series("min", returns_scalar=True) + + def arg_min(self) -> Self: + return self._reuse_series("arg_min", returns_scalar=True) + + def arg_max(self) -> Self: + return self._reuse_series("arg_max", returns_scalar=True) + + # Other + + def clip(self, lower_bound: Self, upper_bound: Self) -> Self: + return self._reuse_series( + "clip", lower_bound=lower_bound, upper_bound=upper_bound + ) + + def clip_lower(self, lower_bound: Self) -> Self: + return self._reuse_series("clip_lower", lower_bound=lower_bound) + + def clip_upper(self, upper_bound: Self) -> Self: + return self._reuse_series("clip_upper", upper_bound=upper_bound) + + def is_null(self) -> Self: + return self._reuse_series("is_null") + + def is_nan(self) -> Self: + return self._reuse_series("is_nan") + + def fill_nan(self, value: float | None) -> Self: + return self._reuse_series("fill_nan", value=value) + + def fill_null( + self, value: Self | None, strategy: FillNullStrategy | None, limit: int | None + ) -> Self: + return self._reuse_series( + "fill_null", value=value, strategy=strategy, limit=limit + ) + + def is_in(self, other: Any) -> Self: + return self._reuse_series("is_in", other=other) + + def arg_true(self) -> Self: + return self._reuse_series("arg_true") + + def filter(self, *predicates: Self) -> Self: + plx = self.__narwhals_namespace__() + predicate = plx.all_horizontal(*predicates, ignore_nulls=False) + return self._reuse_series("filter", predicate=predicate) + + def drop_nulls(self) -> Self: + return self._reuse_series("drop_nulls") + + def replace_strict( + self, + default: Self | NoDefault, + old: Sequence[Any], + new: Sequence[Any], + *, + return_dtype: IntoDType | None, + ) -> Self: + return self._reuse_series( + "replace_strict", old=old, new=new, default=default, return_dtype=return_dtype + ) + + def sort(self, *, descending: bool, nulls_last: bool) -> Self: + return self._reuse_series("sort", descending=descending, nulls_last=nulls_last) + + def abs(self) -> Self: + return self._reuse_series("abs") + + def unique(self) -> Self: + return self._reuse_series("unique", maintain_order=False) + + def diff(self) -> Self: + return self._reuse_series("diff") + + def sample( + self, + n: int | None, + *, + fraction: float | None, + with_replacement: bool, + seed: int | None, + ) -> Self: + # `n`/`fraction` are resolved per output series here, rather than in the public + # layer, because height is only known at evaluation time. + _resolve_sample_size_from_height = partial( + _resolve_sample_size, + n=n, + fraction=fraction, + with_replacement=with_replacement, + ) + + def func(df: EagerDataFrameT) -> Sequence[EagerSeriesT]: + return [ + series.sample( + n=_resolve_sample_size_from_height(height=series.len()), + with_replacement=with_replacement, + seed=seed, + ) + for series in self(df) + ] + + return self._from_callable( + func, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=self._alias_output_names, + context=self, + ) + + def alias(self, name: str) -> Self: + def alias_output_names(names: Sequence[str]) -> Sequence[str]: + if len(names) != 1: + msg = f"Expected function with single output, found output names: {names}" + raise MultiOutputExpressionError(msg) + return [name] + + return type(self)( + lambda df: [series.alias(name) for series in self(df)], + evaluate_output_names=self._evaluate_output_names, + alias_output_names=alias_output_names, + implementation=self._implementation, + version=self._version, + ) + + def is_unique(self) -> Self: + return self._reuse_series("is_unique") + + def is_first_distinct(self) -> Self: + return self._reuse_series("is_first_distinct") + + def is_last_distinct(self) -> Self: + return self._reuse_series("is_last_distinct") + + def quantile( + self, quantile: float, interpolation: RollingInterpolationMethod + ) -> Self: + return self._reuse_series( + "quantile", + returns_scalar=True, + quantile=quantile, + interpolation=interpolation, + ) + + def head(self, n: int) -> Self: + return self._reuse_series("head", n=n) + + def tail(self, n: int) -> Self: + return self._reuse_series("tail", n=n) + + def round(self, decimals: int) -> Self: + return self._reuse_series("round", decimals=decimals) + + def floor(self) -> Self: + return self._reuse_series("floor") + + def ceil(self) -> Self: + return self._reuse_series("ceil") + + def len(self) -> Self: + return self._reuse_series("len", returns_scalar=True) + + def gather_every(self, n: int, offset: int) -> Self: + return self._reuse_series("gather_every", n=n, offset=offset) + + def mode(self, *, keep: ModeKeepStrategy) -> Self: + return self._reuse_series("mode", keep=keep) + + def is_finite(self) -> Self: + return self._reuse_series("is_finite") + + def rolling_mean(self, window_size: int, *, min_samples: int, center: bool) -> Self: + return self._reuse_series( + "rolling_mean", + window_size=window_size, + min_samples=min_samples, + center=center, + ) + + def rolling_std( + self, window_size: int, *, min_samples: int, center: bool, ddof: int + ) -> Self: + return self._reuse_series( + "rolling_std", + window_size=window_size, + min_samples=min_samples, + center=center, + ddof=ddof, + ) + + def rolling_sum(self, window_size: int, *, min_samples: int, center: bool) -> Self: + return self._reuse_series( + "rolling_sum", window_size=window_size, min_samples=min_samples, center=center + ) + + def rolling_var( + self, window_size: int, *, min_samples: int, center: bool, ddof: int + ) -> Self: + return self._reuse_series( + "rolling_var", + window_size=window_size, + min_samples=min_samples, + center=center, + ddof=ddof, + ) + + def map_batches( + self, + function: Callable[[Any], Any], + return_dtype: IntoDType | None, + *, + returns_scalar: bool, + ) -> Self: + def func(df: EagerDataFrameT) -> Sequence[EagerSeriesT]: + udf_series_in = self(df) + output_names = (input_series.name for input_series in udf_series_in) + udf_series_out = tuple(function(series) for series in udf_series_in) + _first_in, _first_out = udf_series_in[0], udf_series_out[0] + + result: Sequence[EagerSeriesT] + it = zip(udf_series_out, output_names, strict=True) + if is_numpy_array(_first_out) or is_numpy_scalar(_first_out): + from_numpy = partial(_first_in.from_numpy, context=self) + result = tuple(from_numpy(arr).alias(out_name) for arr, out_name in it) + elif isinstance(_first_out, _first_in.__class__): # compliant series + result = tuple(series.alias(out_name) for series, out_name in it) + else: # If everything else fails, assume scalar case + from_scalar = _first_in._from_scalar + result = tuple(from_scalar(val).alias(out_name) for val, out_name in it) + + if return_dtype is not None: + result = tuple(series.cast(return_dtype) for series in result) + + is_scalar_result = tuple(len(r) == 1 for r in result) + if (not returns_scalar) and any(is_scalar_result) and (len(df) > 1): + _idx = is_scalar_result.index(True) # Index of first result with length 1 + _type = type(udf_series_out[_idx]) + msg = ( + "`map_batches` with `returns_scalar=False` must return a Series; " + f"found '{qualified_type_name(_type)}'.\n\nIf `returns_scalar` " + "is set to `True`, a returned value can be a scalar value." + ) + raise TypeError(msg) + return result + + return self._from_callable( + func, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=self._alias_output_names, + context=self, + ) + + def shift(self, n: int) -> Self: + return self._reuse_series("shift", n=n) + + def cum_sum(self, *, reverse: bool) -> Self: + return self._reuse_series("cum_sum", reverse=reverse) + + def cum_count(self, *, reverse: bool) -> Self: + return self._reuse_series("cum_count", reverse=reverse) + + def cum_min(self, *, reverse: bool) -> Self: + return self._reuse_series("cum_min", reverse=reverse) + + def cum_max(self, *, reverse: bool) -> Self: + return self._reuse_series("cum_max", reverse=reverse) + + def cum_prod(self, *, reverse: bool) -> Self: + return self._reuse_series("cum_prod", reverse=reverse) + + def rank(self, method: RankMethod, *, descending: bool) -> Self: + return self._reuse_series("rank", method=method, descending=descending) + + def log(self, base: float) -> Self: + return self._reuse_series("log", base=base) + + def exp(self) -> Self: + return self._reuse_series("exp") + + def sin(self) -> Self: + return self._reuse_series("sin") + + def cos(self) -> Self: + return self._reuse_series("cos") + + def sqrt(self) -> Self: + return self._reuse_series("sqrt") + + def is_between( + self, lower_bound: Self, upper_bound: Self, closed: ClosedInterval + ) -> Self: + return self._reuse_series( + "is_between", lower_bound=lower_bound, upper_bound=upper_bound, closed=closed + ) + + def first(self, order_by: Sequence[str] = ()) -> Self: + if not order_by: + return self._reuse_series("first", returns_scalar=True) + + def func(df: EagerDataFrameT) -> Sequence[Any]: + df = df.sort(*order_by, descending=False, nulls_last=False) + return self.first()(df) + + return self._from_callable( + func, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=self._alias_output_names, + context=self, + ) + + def last(self, order_by: Sequence[str] = ()) -> Self: + if not order_by: + return self._reuse_series("last", returns_scalar=True) + + def func(df: EagerDataFrameT) -> Sequence[Any]: + df = df.sort(*order_by, descending=False, nulls_last=False) + return self.last()(df) + + return self._from_callable( + func, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=self._alias_output_names, + context=self, + ) + + def any_value(self, *, ignore_nulls: bool) -> Self: + return self._reuse_series( + "any_value", returns_scalar=True, ignore_nulls=ignore_nulls + ) + + @property + def cat(self) -> EagerExprCatNamespace[Self]: + return EagerExprCatNamespace(self) + + @property + def dt(self) -> EagerExprDateTimeNamespace[Self]: + return EagerExprDateTimeNamespace(self) + + @property + def list(self) -> EagerExprListNamespace[Self]: + return EagerExprListNamespace(self) + + @property + def name(self) -> EagerExprNameNamespace[Self]: + return EagerExprNameNamespace(self) + + @property + def str(self) -> EagerExprStringNamespace[Self]: + return EagerExprStringNamespace(self) + + @property + def struct(self) -> EagerExprStructNamespace[Self]: + return EagerExprStructNamespace(self) + + +# mypy thinks `NativeExprT` should be covariant, pyright thinks it should be invariant +class LazyExpr( # type: ignore[misc] + ImplExpr[CompliantLazyFrameT, NativeExprT], Protocol[CompliantLazyFrameT, NativeExprT] +): + def _with_alias_output_names(self, func: AliasNames | None, /) -> Self: ... + def alias(self, name: str) -> Self: + def fn(names: Sequence[str]) -> Sequence[str]: + if len(names) != 1: + msg = f"Expected function with single output, found output names: {names}" + raise ValueError(msg) + return [name] + + return self._with_alias_output_names(fn) + + @property + def name(self) -> LazyExprNameNamespace[Self]: + return LazyExprNameNamespace(self) + + ewm_mean = not_implemented() # type: ignore[misc] + map_batches = not_implemented() # type: ignore[misc] + cat: not_implemented = not_implemented() # type: ignore[assignment] + + +class _ExprNamespace( # type: ignore[misc] + _StoresCompliant[CompliantExprT_co], Protocol[CompliantExprT_co] +): + _compliant_expr: CompliantExprT_co + + @property + def compliant(self) -> CompliantExprT_co: + return self._compliant_expr + + +class EagerExprNamespace(_ExprNamespace[EagerExprT], Generic[EagerExprT]): + def __init__(self, expr: EagerExprT, /) -> None: + self._compliant_expr = expr + + +class LazyExprNamespace(_ExprNamespace[LazyExprT], Generic[LazyExprT]): + def __init__(self, expr: LazyExprT, /) -> None: + self._compliant_expr = expr + + +class EagerExprCatNamespace( + EagerExprNamespace[EagerExprT], CatNamespace[EagerExprT], Generic[EagerExprT] +): + def get_categories(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("cat", "get_categories") + + +class EagerExprDateTimeNamespace( + EagerExprNamespace[EagerExprT], DateTimeNamespace[EagerExprT], Generic[EagerExprT] +): + def to_string(self, format: str) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "to_string", format=format) + + def replace_time_zone(self, time_zone: str | None) -> EagerExprT: + return self.compliant._reuse_series_namespace( + "dt", "replace_time_zone", time_zone=time_zone + ) + + def convert_time_zone(self, time_zone: str) -> EagerExprT: + return self.compliant._reuse_series_namespace( + "dt", "convert_time_zone", time_zone=time_zone + ) + + def timestamp(self, time_unit: TimeUnit) -> EagerExprT: + return self.compliant._reuse_series_namespace( + "dt", "timestamp", time_unit=time_unit + ) + + def date(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "date") + + def year(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "year") + + def month(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "month") + + def day(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "day") + + def hour(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "hour") + + def minute(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "minute") + + def second(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "second") + + def millisecond(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "millisecond") + + def microsecond(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "microsecond") + + def nanosecond(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "nanosecond") + + def ordinal_day(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "ordinal_day") + + def weekday(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "weekday") + + def total_minutes(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "total_minutes") + + def total_seconds(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "total_seconds") + + def total_milliseconds(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "total_milliseconds") + + def total_microseconds(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "total_microseconds") + + def total_nanoseconds(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "total_nanoseconds") + + def truncate(self, every: str) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "truncate", every=every) + + def offset_by(self, by: str) -> EagerExprT: + return self.compliant._reuse_series_namespace("dt", "offset_by", by=by) + + +class EagerExprListNamespace( + EagerExprNamespace[EagerExprT], ListNamespace[EagerExprT], Generic[EagerExprT] +): + def len(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("list", "len") + + def unique(self, *, maintain_order: bool) -> EagerExprT: + return self.compliant._reuse_series_namespace( + "list", "unique", maintain_order=maintain_order + ) + + def contains(self, item: NonNestedLiteral) -> EagerExprT: + return self.compliant._reuse_series_namespace("list", "contains", item=item) + + def get(self, index: int) -> EagerExprT: + return self.compliant._reuse_series_namespace("list", "get", index=index) + + def min(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("list", "min") + + def max(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("list", "max") + + def mean(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("list", "mean") + + def median(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("list", "median") + + def sum(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("list", "sum") + + def sort(self, *, descending: bool, nulls_last: bool) -> EagerExprT: + return self.compliant._reuse_series_namespace( + "list", "sort", descending=descending, nulls_last=nulls_last + ) + + +class CompliantExprNameNamespace( # type: ignore[misc] + _ExprNamespace[CompliantExprT_co], + NameNamespace[CompliantExprT_co], + Protocol[CompliantExprT_co], +): + def keep(self) -> CompliantExprT_co: + return self._from_callable(None) + + def map(self, function: AliasName) -> CompliantExprT_co: + return self._from_callable(function) + + def prefix(self, prefix: str) -> CompliantExprT_co: + return self._from_callable(lambda name: f"{prefix}{name}") + + def suffix(self, suffix: str) -> CompliantExprT_co: + return self._from_callable(lambda name: f"{name}{suffix}") + + def to_lowercase(self) -> CompliantExprT_co: + return self._from_callable(str.lower) + + def to_uppercase(self) -> CompliantExprT_co: + return self._from_callable(str.upper) + + @staticmethod + def _alias_output_names(func: AliasName, /) -> AliasNames: + def fn(output_names: Sequence[str], /) -> Sequence[str]: + return [func(name) for name in output_names] + + return fn + + def _from_callable(self, func: AliasName | None, /) -> CompliantExprT_co: ... + + +class EagerExprNameNamespace( + EagerExprNamespace[EagerExprT], + CompliantExprNameNamespace[EagerExprT], + Generic[EagerExprT], +): + def _from_callable(self, func: AliasName | None) -> EagerExprT: + expr = self.compliant + return expr._with_alias_output_names(func) + + +class LazyExprNameNamespace( + LazyExprNamespace[LazyExprT], + CompliantExprNameNamespace[LazyExprT], + Generic[LazyExprT], +): + def _from_callable(self, func: AliasName | None) -> LazyExprT: + expr = self.compliant + output_names = self._alias_output_names(func) if func else None + return expr._with_alias_output_names(output_names) + + +class EagerExprStringNamespace( + EagerExprNamespace[EagerExprT], StringNamespace[EagerExprT], Generic[EagerExprT] +): + def len_chars(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("str", "len_chars") + + def replace( + self, value: EagerExprT, pattern: str, *, literal: bool, n: int + ) -> EagerExprT: + return self.compliant._reuse_series_namespace( + "str", "replace", pattern=pattern, value=value, literal=literal, n=n + ) + + def replace_all( + self, value: EagerExprT, pattern: str, *, literal: bool + ) -> EagerExprT: + return self.compliant._reuse_series_namespace( + "str", "replace_all", pattern=pattern, value=value, literal=literal + ) + + def strip_chars(self, characters: str | None) -> EagerExprT: + return self.compliant._reuse_series_namespace( + "str", "strip_chars", characters=characters + ) + + def strip_chars_start(self, characters: str) -> EagerExprT: + return self.compliant._reuse_series_namespace( + "str", "strip_chars_start", characters=characters + ) + + def strip_chars_end(self, characters: str) -> EagerExprT: + return self.compliant._reuse_series_namespace( + "str", "strip_chars_end", characters=characters + ) + + def starts_with(self, prefix: EagerExprT) -> EagerExprT: + return self.compliant._reuse_series_namespace("str", "starts_with", prefix=prefix) + + def ends_with(self, suffix: EagerExprT) -> EagerExprT: + return self.compliant._reuse_series_namespace("str", "ends_with", suffix=suffix) + + def contains(self, pattern: EagerExprT, *, literal: bool) -> EagerExprT: + return self.compliant._reuse_series_namespace( + "str", "contains", pattern=pattern, literal=literal + ) + + def slice(self, offset: int, length: int | None) -> EagerExprT: + return self.compliant._reuse_series_namespace( + "str", "slice", offset=offset, length=length + ) + + def split(self, by: str) -> EagerExprT: + return self.compliant._reuse_series_namespace("str", "split", by=by) + + def to_datetime(self, format: str | None) -> EagerExprT: + return self.compliant._reuse_series_namespace("str", "to_datetime", format=format) + + def to_date(self, format: str | None) -> EagerExprT: + return self.compliant._reuse_series_namespace("str", "to_date", format=format) + + def to_time(self, format: str | None) -> EagerExprT: + return self.compliant._reuse_series_namespace("str", "to_time", format=format) + + def to_lowercase(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("str", "to_lowercase") + + def to_uppercase(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("str", "to_uppercase") + + def zfill(self, width: int) -> EagerExprT: + return self.compliant._reuse_series_namespace("str", "zfill", width=width) + + def to_titlecase(self) -> EagerExprT: + return self.compliant._reuse_series_namespace("str", "to_titlecase") + + def pad_start(self, length: int, fill_char: str = " ") -> EagerExprT: + return self.compliant._reuse_series_namespace( + "str", "pad_start", length=length, fill_char=fill_char + ) + + def pad_end(self, length: int, fill_char: str = " ") -> EagerExprT: + return self.compliant._reuse_series_namespace( + "str", "pad_end", length=length, fill_char=fill_char + ) + + +class EagerExprStructNamespace( + EagerExprNamespace[EagerExprT], StructNamespace[EagerExprT], Generic[EagerExprT] +): + def field(self, name: str) -> EagerExprT: + return self.compliant._reuse_series_namespace("struct", "field", name=name).alias( + name + ) diff --git a/shared/package-files/71/71c12c8a2e068ec062059d0eca9f608d3498719e6086a6ede37cfc8579dc3d62/dynamic_arrays.py b/shared/package-files/71/71c12c8a2e068ec062059d0eca9f608d3498719e6086a6ede37cfc8579dc3d62/dynamic_arrays.py new file mode 100644 index 0000000000000000000000000000000000000000..4353a48878a6902382496d0dd663c72cab5738b1 --- /dev/null +++ b/shared/package-files/71/71c12c8a2e068ec062059d0eca9f608d3498719e6086a6ede37cfc8579dc3d62/dynamic_arrays.py @@ -0,0 +1,200 @@ +""" +A module to deal with stuff like `list.append` and `set.add`. + +Array modifications +******************* + +If the content of an array (``set``/``list``) is requested somewhere, the +current module will be checked for appearances of ``arr.append``, +``arr.insert``, etc. If the ``arr`` name points to an actual array, the +content will be added + +This can be really cpu intensive, as you can imagine. Because |jedi| has to +follow **every** ``append`` and check whether it's the right array. However this +works pretty good, because in *slow* cases, the recursion detector and other +settings will stop this process. + +It is important to note that: + +1. Array modfications work only in the current module. +2. Jedi only checks Array additions; ``list.pop``, etc are ignored. +""" +from jedi import debug +from jedi import settings +from jedi.inference import recursion +from jedi.inference.base_value import ValueSet, NO_VALUES, HelperValueMixin, \ + ValueWrapper +from jedi.inference.lazy_value import LazyKnownValues +from jedi.inference.helpers import infer_call_of_leaf +from jedi.inference.cache import inference_state_method_cache + +_sentinel = object() + + +def check_array_additions(context, sequence): + """ Just a mapper function for the internal _internal_check_array_additions """ + if sequence.array_type not in ('list', 'set'): + # TODO also check for dict updates + return NO_VALUES + + return _internal_check_array_additions(context, sequence) + + +@inference_state_method_cache(default=NO_VALUES) +@debug.increase_indent +def _internal_check_array_additions(context, sequence): + """ + Checks if a `Array` has "add" (append, insert, extend) statements: + + >>> a = [""] + >>> a.append(1) + """ + from jedi.inference import arguments + + debug.dbg('Dynamic array search for %s' % sequence, color='MAGENTA') + module_context = context.get_root_context() + if not settings.dynamic_array_additions or module_context.is_compiled(): + debug.dbg('Dynamic array search aborted.', color='MAGENTA') + return NO_VALUES + + def find_additions(context, arglist, add_name): + params = list(arguments.TreeArguments(context.inference_state, context, arglist).unpack()) + result = set() + if add_name in ['insert']: + params = params[1:] + if add_name in ['append', 'add', 'insert']: + for key, lazy_value in params: + result.add(lazy_value) + elif add_name in ['extend', 'update']: + for key, lazy_value in params: + result |= set(lazy_value.infer().iterate()) + return result + + temp_param_add, settings.dynamic_params_for_other_modules = \ + settings.dynamic_params_for_other_modules, False + + is_list = sequence.name.string_name == 'list' + search_names = (['append', 'extend', 'insert'] if is_list else ['add', 'update']) + + added_types = set() + for add_name in search_names: + try: + possible_names = module_context.tree_node.get_used_names()[add_name] + except KeyError: + continue + else: + for name in possible_names: + value_node = context.tree_node + if not (value_node.start_pos < name.start_pos < value_node.end_pos): + continue + trailer = name.parent + power = trailer.parent + trailer_pos = power.children.index(trailer) + try: + execution_trailer = power.children[trailer_pos + 1] + except IndexError: + continue + else: + if execution_trailer.type != 'trailer' \ + or execution_trailer.children[0] != '(' \ + or execution_trailer.children[1] == ')': + continue + + random_context = context.create_context(name) + + with recursion.execution_allowed(context.inference_state, power) as allowed: + if allowed: + found = infer_call_of_leaf( + random_context, + name, + cut_own_trailer=True + ) + if sequence in found: + # The arrays match. Now add the results + added_types |= find_additions( + random_context, + execution_trailer.children[1], + add_name + ) + + # reset settings + settings.dynamic_params_for_other_modules = temp_param_add + debug.dbg('Dynamic array result %s', added_types, color='MAGENTA') + return added_types + + +def get_dynamic_array_instance(instance, arguments): + """Used for set() and list() instances.""" + ai = _DynamicArrayAdditions(instance, arguments) + from jedi.inference import arguments + return arguments.ValuesArguments([ValueSet([ai])]) + + +class _DynamicArrayAdditions(HelperValueMixin): + """ + Used for the usage of set() and list(). + This is definitely a hack, but a good one :-) + It makes it possible to use set/list conversions. + + This is not a proper context, because it doesn't have to be. It's not used + in the wild, it's just used within typeshed as an argument to `__init__` + for set/list and never used in any other place. + """ + def __init__(self, instance, arguments): + self._instance = instance + self._arguments = arguments + + def py__class__(self): + tuple_, = self._instance.inference_state.builtins_module.py__getattribute__('tuple') + return tuple_ + + def py__iter__(self, contextualized_node=None): + arguments = self._arguments + try: + _, lazy_value = next(arguments.unpack()) + except StopIteration: + pass + else: + yield from lazy_value.infer().iterate() + + from jedi.inference.arguments import TreeArguments + if isinstance(arguments, TreeArguments): + additions = _internal_check_array_additions(arguments.context, self._instance) + yield from additions + + def iterate(self, contextualized_node=None, is_async=False): + return self.py__iter__(contextualized_node) + + +class _Modification(ValueWrapper): + def __init__(self, wrapped_value, assigned_values, contextualized_key): + super().__init__(wrapped_value) + self._assigned_values = assigned_values + self._contextualized_key = contextualized_key + + def py__getitem__(self, *args, **kwargs): + return self._wrapped_value.py__getitem__(*args, **kwargs) | self._assigned_values + + def py__simple_getitem__(self, index): + actual = [ + v.get_safe_value(_sentinel) + for v in self._contextualized_key.infer() + ] + if index in actual: + return self._assigned_values + return self._wrapped_value.py__simple_getitem__(index) + + +class DictModification(_Modification): + def py__iter__(self, contextualized_node=None): + yield from self._wrapped_value.py__iter__(contextualized_node) + yield self._contextualized_key + + def get_key_values(self): + return self._wrapped_value.get_key_values() | self._contextualized_key.infer() + + +class ListModification(_Modification): + def py__iter__(self, contextualized_node=None): + yield from self._wrapped_value.py__iter__(contextualized_node) + yield LazyKnownValues(self._assigned_values) diff --git a/shared/package-files/71/71c5772fbf5ae7fdfbd44e09277b276f9d4a8deef306aa7d25b09f7e8a9bf584/conj_native.h b/shared/package-files/71/71c5772fbf5ae7fdfbd44e09277b276f9d4a8deef306aa7d25b09f7e8a9bf584/conj_native.h new file mode 100644 index 0000000000000000000000000000000000000000..bb4ef5b51bcca28a7a9e6024368bd96999bcbc0a --- /dev/null +++ b/shared/package-files/71/71c5772fbf5ae7fdfbd44e09277b276f9d4a8deef306aa7d25b09f7e8a9bf584/conj_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor conj(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/71/71c5c33f8a0635b3ad4c0d7a665f67b6e87947926a9c196f6504fa9b7538e13c/darwin-bigsur-m1 b/shared/package-files/71/71c5c33f8a0635b3ad4c0d7a665f67b6e87947926a9c196f6504fa9b7538e13c/darwin-bigsur-m1 new file mode 100644 index 0000000000000000000000000000000000000000..b033bcb90d939d207f6c1bec351843c4ef488634 --- /dev/null +++ b/shared/package-files/71/71c5c33f8a0635b3ad4c0d7a665f67b6e87947926a9c196f6504fa9b7538e13c/darwin-bigsur-m1 @@ -0,0 +1,19 @@ +machdep.cpu.cores_per_package: 8 +machdep.cpu.core_count: 8 +machdep.cpu.logical_per_package: 8 +machdep.cpu.thread_count: 8 +machdep.cpu.brand_string: Apple processor +hw.optional.floatingpoint: 1 +hw.optional.watchpoint: 4 +hw.optional.breakpoint: 6 +hw.optional.neon: 1 +hw.optional.neon_hpfp: 1 +hw.optional.neon_fp16: 1 +hw.optional.armv8_1_atomics: 1 +hw.optional.armv8_crc32: 1 +hw.optional.armv8_2_fhm: 1 +hw.optional.armv8_2_sha512: 1 +hw.optional.armv8_2_sha3: 1 +hw.optional.amx_version: 2 +hw.optional.ucnormal_mem: 1 +hw.optional.arm64: 1 diff --git a/shared/package-files/71/71ca4af5998f09990c5e875d350fc3c8e34f280bae6fe14f36d4692face7a563/Helsinki b/shared/package-files/71/71ca4af5998f09990c5e875d350fc3c8e34f280bae6fe14f36d4692face7a563/Helsinki new file mode 100644 index 0000000000000000000000000000000000000000..ff5e56530570974516d249927952c69da601b664 Binary files /dev/null and b/shared/package-files/71/71ca4af5998f09990c5e875d350fc3c8e34f280bae6fe14f36d4692face7a563/Helsinki differ diff --git a/shared/package-files/71/71ca4af5998f09990c5e875d350fc3c8e34f280bae6fe14f36d4692face7a563/Mariehamn b/shared/package-files/71/71ca4af5998f09990c5e875d350fc3c8e34f280bae6fe14f36d4692face7a563/Mariehamn new file mode 100644 index 0000000000000000000000000000000000000000..ff5e56530570974516d249927952c69da601b664 Binary files /dev/null and b/shared/package-files/71/71ca4af5998f09990c5e875d350fc3c8e34f280bae6fe14f36d4692face7a563/Mariehamn differ diff --git a/shared/package-files/71/71d2130bdac9c68a9af09e241b48e7d594bdd188c8303d6928eaac5be43aad1c/direct_url.json b/shared/package-files/71/71d2130bdac9c68a9af09e241b48e7d594bdd188c8303d6928eaac5be43aad1c/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..60e343a60c6bb29b2a26d0ae200cb3e26d97f9cf --- /dev/null +++ b/shared/package-files/71/71d2130bdac9c68a9af09e241b48e7d594bdd188c8303d6928eaac5be43aad1c/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///croot/soupsieve_1696347547217/work"} \ No newline at end of file diff --git a/shared/package-files/71/71d370a6912295a32754defb001b774c169d8d46b032d30581241bd4f0aac109/hashing.pyi b/shared/package-files/71/71d370a6912295a32754defb001b774c169d8d46b032d30581241bd4f0aac109/hashing.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8361026e4a87d462e04c53f7f1f8aee8a7f6ffe0 --- /dev/null +++ b/shared/package-files/71/71d370a6912295a32754defb001b774c169d8d46b032d30581241bd4f0aac109/hashing.pyi @@ -0,0 +1,9 @@ +import numpy as np + +from pandas._typing import npt + +def hash_object_array( + arr: npt.NDArray[np.object_], + key: str, + encoding: str = ..., +) -> npt.NDArray[np.uint64]: ... diff --git a/shared/package-files/71/71d7afd4940a67426f960b95f62a478339d3767be52335050c16f422dd8fce32/_palettes.py b/shared/package-files/71/71d7afd4940a67426f960b95f62a478339d3767be52335050c16f422dd8fce32/_palettes.py new file mode 100644 index 0000000000000000000000000000000000000000..3c748d33e45bfcdc690ceee490cbb50b516cd2b3 --- /dev/null +++ b/shared/package-files/71/71d7afd4940a67426f960b95f62a478339d3767be52335050c16f422dd8fce32/_palettes.py @@ -0,0 +1,309 @@ +from .palette import Palette + + +# Taken from https://en.wikipedia.org/wiki/ANSI_escape_code (Windows 10 column) +WINDOWS_PALETTE = Palette( + [ + (12, 12, 12), + (197, 15, 31), + (19, 161, 14), + (193, 156, 0), + (0, 55, 218), + (136, 23, 152), + (58, 150, 221), + (204, 204, 204), + (118, 118, 118), + (231, 72, 86), + (22, 198, 12), + (249, 241, 165), + (59, 120, 255), + (180, 0, 158), + (97, 214, 214), + (242, 242, 242), + ] +) + +# # The standard ansi colors (including bright variants) +STANDARD_PALETTE = Palette( + [ + (0, 0, 0), + (170, 0, 0), + (0, 170, 0), + (170, 85, 0), + (0, 0, 170), + (170, 0, 170), + (0, 170, 170), + (170, 170, 170), + (85, 85, 85), + (255, 85, 85), + (85, 255, 85), + (255, 255, 85), + (85, 85, 255), + (255, 85, 255), + (85, 255, 255), + (255, 255, 255), + ] +) + + +# The 256 color palette +EIGHT_BIT_PALETTE = Palette( + [ + (0, 0, 0), + (128, 0, 0), + (0, 128, 0), + (128, 128, 0), + (0, 0, 128), + (128, 0, 128), + (0, 128, 128), + (192, 192, 192), + (128, 128, 128), + (255, 0, 0), + (0, 255, 0), + (255, 255, 0), + (0, 0, 255), + (255, 0, 255), + (0, 255, 255), + (255, 255, 255), + (0, 0, 0), + (0, 0, 95), + (0, 0, 135), + (0, 0, 175), + (0, 0, 215), + (0, 0, 255), + (0, 95, 0), + (0, 95, 95), + (0, 95, 135), + (0, 95, 175), + (0, 95, 215), + (0, 95, 255), + (0, 135, 0), + (0, 135, 95), + (0, 135, 135), + (0, 135, 175), + (0, 135, 215), + (0, 135, 255), + (0, 175, 0), + (0, 175, 95), + (0, 175, 135), + (0, 175, 175), + (0, 175, 215), + (0, 175, 255), + (0, 215, 0), + (0, 215, 95), + (0, 215, 135), + (0, 215, 175), + (0, 215, 215), + (0, 215, 255), + (0, 255, 0), + (0, 255, 95), + (0, 255, 135), + (0, 255, 175), + (0, 255, 215), + (0, 255, 255), + (95, 0, 0), + (95, 0, 95), + (95, 0, 135), + (95, 0, 175), + (95, 0, 215), + (95, 0, 255), + (95, 95, 0), + (95, 95, 95), + (95, 95, 135), + (95, 95, 175), + (95, 95, 215), + (95, 95, 255), + (95, 135, 0), + (95, 135, 95), + (95, 135, 135), + (95, 135, 175), + (95, 135, 215), + (95, 135, 255), + (95, 175, 0), + (95, 175, 95), + (95, 175, 135), + (95, 175, 175), + (95, 175, 215), + (95, 175, 255), + (95, 215, 0), + (95, 215, 95), + (95, 215, 135), + (95, 215, 175), + (95, 215, 215), + (95, 215, 255), + (95, 255, 0), + (95, 255, 95), + (95, 255, 135), + (95, 255, 175), + (95, 255, 215), + (95, 255, 255), + (135, 0, 0), + (135, 0, 95), + (135, 0, 135), + (135, 0, 175), + (135, 0, 215), + (135, 0, 255), + (135, 95, 0), + (135, 95, 95), + (135, 95, 135), + (135, 95, 175), + (135, 95, 215), + (135, 95, 255), + (135, 135, 0), + (135, 135, 95), + (135, 135, 135), + (135, 135, 175), + (135, 135, 215), + (135, 135, 255), + (135, 175, 0), + (135, 175, 95), + (135, 175, 135), + (135, 175, 175), + (135, 175, 215), + (135, 175, 255), + (135, 215, 0), + (135, 215, 95), + (135, 215, 135), + (135, 215, 175), + (135, 215, 215), + (135, 215, 255), + (135, 255, 0), + (135, 255, 95), + (135, 255, 135), + (135, 255, 175), + (135, 255, 215), + (135, 255, 255), + (175, 0, 0), + (175, 0, 95), + (175, 0, 135), + (175, 0, 175), + (175, 0, 215), + (175, 0, 255), + (175, 95, 0), + (175, 95, 95), + (175, 95, 135), + (175, 95, 175), + (175, 95, 215), + (175, 95, 255), + (175, 135, 0), + (175, 135, 95), + (175, 135, 135), + (175, 135, 175), + (175, 135, 215), + (175, 135, 255), + (175, 175, 0), + (175, 175, 95), + (175, 175, 135), + (175, 175, 175), + (175, 175, 215), + (175, 175, 255), + (175, 215, 0), + (175, 215, 95), + (175, 215, 135), + (175, 215, 175), + (175, 215, 215), + (175, 215, 255), + (175, 255, 0), + (175, 255, 95), + (175, 255, 135), + (175, 255, 175), + (175, 255, 215), + (175, 255, 255), + (215, 0, 0), + (215, 0, 95), + (215, 0, 135), + (215, 0, 175), + (215, 0, 215), + (215, 0, 255), + (215, 95, 0), + (215, 95, 95), + (215, 95, 135), + (215, 95, 175), + (215, 95, 215), + (215, 95, 255), + (215, 135, 0), + (215, 135, 95), + (215, 135, 135), + (215, 135, 175), + (215, 135, 215), + (215, 135, 255), + (215, 175, 0), + (215, 175, 95), + (215, 175, 135), + (215, 175, 175), + (215, 175, 215), + (215, 175, 255), + (215, 215, 0), + (215, 215, 95), + (215, 215, 135), + (215, 215, 175), + (215, 215, 215), + (215, 215, 255), + (215, 255, 0), + (215, 255, 95), + (215, 255, 135), + (215, 255, 175), + (215, 255, 215), + (215, 255, 255), + (255, 0, 0), + (255, 0, 95), + (255, 0, 135), + (255, 0, 175), + (255, 0, 215), + (255, 0, 255), + (255, 95, 0), + (255, 95, 95), + (255, 95, 135), + (255, 95, 175), + (255, 95, 215), + (255, 95, 255), + (255, 135, 0), + (255, 135, 95), + (255, 135, 135), + (255, 135, 175), + (255, 135, 215), + (255, 135, 255), + (255, 175, 0), + (255, 175, 95), + (255, 175, 135), + (255, 175, 175), + (255, 175, 215), + (255, 175, 255), + (255, 215, 0), + (255, 215, 95), + (255, 215, 135), + (255, 215, 175), + (255, 215, 215), + (255, 215, 255), + (255, 255, 0), + (255, 255, 95), + (255, 255, 135), + (255, 255, 175), + (255, 255, 215), + (255, 255, 255), + (8, 8, 8), + (18, 18, 18), + (28, 28, 28), + (38, 38, 38), + (48, 48, 48), + (58, 58, 58), + (68, 68, 68), + (78, 78, 78), + (88, 88, 88), + (98, 98, 98), + (108, 108, 108), + (118, 118, 118), + (128, 128, 128), + (138, 138, 138), + (148, 148, 148), + (158, 158, 158), + (168, 168, 168), + (178, 178, 178), + (188, 188, 188), + (198, 198, 198), + (208, 208, 208), + (218, 218, 218), + (228, 228, 228), + (238, 238, 238), + ] +) diff --git a/shared/package-files/71/71d8195c31e94d52a4ba1b863f538d738c28fd151abdcad8d214a9e15eb54fd5/test_compute.py b/shared/package-files/71/71d8195c31e94d52a4ba1b863f538d738c28fd151abdcad8d214a9e15eb54fd5/test_compute.py new file mode 100644 index 0000000000000000000000000000000000000000..d8a1c4d093eb2abf7e792d5c099de6b45ba0559e --- /dev/null +++ b/shared/package-files/71/71d8195c31e94d52a4ba1b863f538d738c28fd151abdcad8d214a9e15eb54fd5/test_compute.py @@ -0,0 +1,4101 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from collections import namedtuple +import datetime +import decimal +from functools import lru_cache, partial +import inspect +import itertools +import math +import os +import pytest +import random +import sys +import textwrap + +try: + import numpy as np +except ImportError: + np = None + +try: + import pandas as pd +except ImportError: + pd = None + +import pyarrow as pa +import pyarrow.compute as pc +from pyarrow.lib import ArrowNotImplementedError, ArrowIndexError + +try: + import pyarrow.substrait as pas +except ImportError: + pas = None + +exported_functions = [ + func for (name, func) in sorted(pc.__dict__.items()) + if hasattr(func, '__arrow_compute_function__')] + +exported_option_classes = [ + cls for (name, cls) in sorted(pc.__dict__.items()) + if (isinstance(cls, type) and + cls is not pc.FunctionOptions and + issubclass(cls, pc.FunctionOptions))] + +numerical_arrow_types = [ + pa.int8(), + pa.int16(), + pa.int64(), + pa.uint8(), + pa.uint16(), + pa.uint64(), + pa.float32(), + pa.float64() +] + + +all_array_types = [ + ('bool', [True, False, False, True, True]), + ('uint8', range(5)), + ('int8', range(5)), + ('uint16', range(5)), + ('int16', range(5)), + ('uint32', range(5)), + ('int32', range(5)), + ('uint64', range(5, 10)), + ('int64', range(5, 10)), + ('float', [0, 0.1, 0.2, 0.3, 0.4]), + ('double', [0, 0.1, 0.2, 0.3, 0.4]), + ('string', ['a', 'b', None, 'ddd', 'ee']), + ('binary', [b'a', b'b', b'c', b'ddd', b'ee']), + (pa.binary(3), [b'abc', b'bcd', b'cde', b'def', b'efg']), + (pa.list_(pa.int8()), [[1, 2], [3, 4], [5, 6], None, [9, 16]]), + (pa.large_list(pa.int16()), [[1], [2, 3, 4], [5, 6], None, [9, 16]]), + (pa.struct([('a', pa.int8()), ('b', pa.int8())]), [ + {'a': 1, 'b': 2}, None, {'a': 3, 'b': 4}, None, {'a': 5, 'b': 6}]), +] + + +def test_exported_functions(): + # Check that all exported concrete functions can be called with + # the right number of arguments. + # Note that unregistered functions (e.g. with a mismatching name) + # will raise KeyError. + functions = exported_functions + assert len(functions) >= 10 + for func in functions: + desc = func.__arrow_compute_function__ + if desc['options_required']: + # Skip this function as it will fail with a different error + # message if we don't pass an options instance. + continue + arity = desc['arity'] + if arity == 0: + continue + if arity is Ellipsis: + args = [object()] * 3 + else: + args = [object()] * arity + with pytest.raises(TypeError, + match="Got unexpected argument type " + " for compute function"): + func(*args) + + +def test_hash_aggregate_not_exported(): + # Ensure we are not leaking hash aggregate functions + # which are not callable by themselves. + for func in exported_functions: + arrow_f = pc.get_function(func.__arrow_compute_function__["name"]) + assert arrow_f.kind != "hash_aggregate" + + +def test_exported_option_classes(): + classes = exported_option_classes + assert len(classes) >= 10 + for cls in classes: + # Option classes must have an introspectable constructor signature, + # and that signature should not have any *args or **kwargs. + sig = inspect.signature(cls) + for param in sig.parameters.values(): + assert param.kind not in (param.VAR_POSITIONAL, + param.VAR_KEYWORD) + + +@pytest.mark.filterwarnings( + "ignore:pyarrow.CumulativeSumOptions is deprecated as of 14.0" +) +def test_option_class_equality(request): + options = [ + pc.ArraySortOptions(), + pc.AssumeTimezoneOptions("UTC"), + pc.CastOptions.safe(pa.int8()), + pc.CumulativeOptions(start=None, skip_nulls=False), + pc.CountOptions(), + pc.DayOfWeekOptions(count_from_zero=False, week_start=0), + pc.DictionaryEncodeOptions(), + pc.RunEndEncodeOptions(), + pc.ElementWiseAggregateOptions(skip_nulls=True), + pc.ExtractRegexOptions("pattern"), + pc.ExtractRegexSpanOptions("pattern"), + pc.FilterOptions(), + pc.IndexOptions(pa.scalar(1)), + pc.JoinOptions(), + pc.ListSliceOptions(0, -1, 1, True), + pc.ListFlattenOptions(recursive=False), + pc.MakeStructOptions(["field", "names"], + field_nullability=[True, True], + field_metadata=[pa.KeyValueMetadata({"a": "1"}), + pa.KeyValueMetadata({"b": "2"})]), + pc.MapLookupOptions(pa.scalar(1), "first"), + pc.MatchSubstringOptions("pattern"), + pc.ModeOptions(), + pc.NullOptions(), + pc.PadOptions(5), + pc.PairwiseOptions(period=1), + pc.PartitionNthOptions(1, null_placement="at_start"), + pc.PivotWiderOptions(["height"], unexpected_key_behavior="raise"), + pc.QuantileOptions(), + pc.RandomOptions(), + pc.RankOptions(sort_keys="ascending", + null_placement="at_start", tiebreaker="max"), + pc.RankQuantileOptions(sort_keys="ascending", + null_placement="at_start"), + pc.ReplaceSliceOptions(0, 1, "a"), + pc.ReplaceSubstringOptions("a", "b"), + pc.RoundOptions(2, "towards_infinity"), + pc.RoundBinaryOptions("towards_infinity"), + pc.RoundTemporalOptions(1, "second", week_starts_monday=True), + pc.RoundToMultipleOptions(100, "towards_infinity"), + pc.ScalarAggregateOptions(), + pc.SelectKOptions(0, sort_keys=[("b", "ascending")]), + pc.SetLookupOptions(pa.array([1])), + pc.SkewOptions(min_count=2), + pc.SliceOptions(0, 1, 1), + pc.SortOptions([("dummy", "descending")], null_placement="at_start"), + pc.SplitOptions(), + pc.SplitPatternOptions("pattern"), + pc.StrftimeOptions(), + pc.StrptimeOptions("%Y", "s", True), + pc.StructFieldOptions(indices=[]), + pc.TakeOptions(), + pc.TDigestOptions(), + pc.TrimOptions(" "), + pc.Utf8NormalizeOptions("NFKC"), + pc.VarianceOptions(), + pc.WinsorizeOptions(0.05, 0.9), + pc.WeekOptions(week_starts_monday=True, count_from_zero=False, + first_week_is_fully_in_year=False), + pc.ZeroFillOptions(4, "0"), + ] + # Timezone database might not be installed on Windows or Emscripten + if request.config.pyarrow.is_enabled["timezone_data"]: + options.append(pc.AssumeTimezoneOptions("Europe/Ljubljana")) + + classes = {type(option) for option in options} + + for cls in exported_option_classes: + # Timezone database might not be installed on Windows or Emscripten + if ( + cls not in classes + and (request.config.pyarrow.is_enabled["timezone_data"]) + and cls != pc.AssumeTimezoneOptions + ): + try: + options.append(cls()) + except TypeError: + pytest.fail(f"Options class is not tested: {cls}") + + for option in options: + assert option == option + assert repr(option).startswith(option.__class__.__name__) + buf = option.serialize() + deserialized = pc.FunctionOptions.deserialize(buf) + assert option == deserialized + # TODO remove the check under the if statement and the filterwarnings + # mark when the deprecated class CumulativeSumOptions is removed. + if repr(option).startswith("CumulativeSumOptions"): + assert repr(deserialized).startswith("CumulativeOptions") + else: + assert repr(option) == repr(deserialized) + for option1, option2 in zip(options, options[1:]): + assert option1 != option2 + + assert repr(pc.IndexOptions(pa.scalar(1))) == "IndexOptions(value=int64:1)" + assert repr(pc.ArraySortOptions()) == \ + "ArraySortOptions(order=Ascending, null_placement=AtEnd)" + + +def test_list_functions(): + assert len(pc.list_functions()) > 10 + assert "add" in pc.list_functions() + + +def _check_get_function(name, expected_func_cls, expected_ker_cls, + min_num_kernels=1): + func = pc.get_function(name) + assert isinstance(func, expected_func_cls) + n = func.num_kernels + assert n >= min_num_kernels + assert n == len(func.kernels) + assert all(isinstance(ker, expected_ker_cls) for ker in func.kernels) + + +def test_get_function_scalar(): + _check_get_function("add", pc.ScalarFunction, pc.ScalarKernel, 8) + + +def test_get_function_vector(): + _check_get_function("unique", pc.VectorFunction, pc.VectorKernel, 8) + + +def test_get_function_scalar_aggregate(): + _check_get_function("mean", pc.ScalarAggregateFunction, + pc.ScalarAggregateKernel, 8) + + +def test_get_function_hash_aggregate(): + _check_get_function("hash_sum", pc.HashAggregateFunction, + pc.HashAggregateKernel, 1) + + +@pytest.mark.numpy +def test_call_function_with_memory_pool(): + arr = pa.array(["foo", "bar", "baz"]) + indices = np.array([2, 2, 1]) + result1 = arr.take(indices) + result2 = pc.call_function('take', [arr, indices], + memory_pool=pa.default_memory_pool()) + expected = pa.array(["baz", "baz", "bar"]) + assert result1.equals(expected) + assert result2.equals(expected) + + result3 = pc.take(arr, indices, memory_pool=pa.default_memory_pool()) + assert result3.equals(expected) + + +def test_pickle_functions(pickle_module): + # Pickle registered functions + for name in pc.list_functions(): + func = pc.get_function(name) + reconstructed = pickle_module.loads(pickle_module.dumps(func)) + assert type(reconstructed) is type(func) + assert reconstructed.name == func.name + assert reconstructed.arity == func.arity + assert reconstructed.num_kernels == func.num_kernels + + +def test_pickle_global_functions(pickle_module): + # Pickle global wrappers (manual or automatic) of registered functions + for name in pc.list_functions(): + try: + func = getattr(pc, name) + except AttributeError: + # hash_aggregate functions are not exported as callables. + continue + reconstructed = pickle_module.loads(pickle_module.dumps(func)) + assert reconstructed is func + + +def test_function_attributes(): + # Sanity check attributes of registered functions + for name in pc.list_functions(): + func = pc.get_function(name) + assert isinstance(func, pc.Function) + assert func.name == name + kernels = func.kernels + assert func.num_kernels == len(kernels) + assert all(isinstance(ker, pc.Kernel) for ker in kernels) + repr(func) + for ker in kernels: + repr(ker) + + +def test_input_type_conversion(): + # Automatic array conversion from Python + arr = pc.add([1, 2], [4, None]) + assert arr.to_pylist() == [5, None] + # Automatic scalar conversion from Python + arr = pc.add([1, 2], 4) + assert arr.to_pylist() == [5, 6] + # Other scalar type + assert pc.equal(["foo", "bar", None], + "foo").to_pylist() == [True, False, None] + + +@pytest.mark.parametrize('arrow_type', numerical_arrow_types) +def test_sum_array(arrow_type): + arr = pa.array([1, 2, 3, 4], type=arrow_type) + assert arr.sum().as_py() == 10 + assert pc.sum(arr).as_py() == 10 + + arr = pa.array([1, 2, 3, 4, None], type=arrow_type) + assert arr.sum().as_py() == 10 + assert pc.sum(arr).as_py() == 10 + + arr = pa.array([None], type=arrow_type) + assert arr.sum().as_py() is None # noqa: E711 + assert pc.sum(arr).as_py() is None # noqa: E711 + assert arr.sum(min_count=0).as_py() == 0 + assert pc.sum(arr, min_count=0).as_py() == 0 + + arr = pa.array([], type=arrow_type) + assert arr.sum().as_py() is None # noqa: E711 + assert arr.sum(min_count=0).as_py() == 0 + assert pc.sum(arr, min_count=0).as_py() == 0 + + +@pytest.mark.parametrize("arrow_type", [pa.decimal128(3, 2), pa.decimal256(3, 2)]) +def test_sum_decimal_array(arrow_type): + from decimal import Decimal + max_precision_type = ( + pa.decimal128(38, arrow_type.scale) + if pa.types.is_decimal128(arrow_type) + else pa.decimal256(76, arrow_type.scale) + ) + expected_sum = Decimal("5.79") + expected_sum_overflow = Decimal("10.00") + zero = Decimal("0.00") + + # No overflow + arr = pa.array([Decimal("1.23"), Decimal("4.56")], type=arrow_type) + assert arr.sum().as_py() == expected_sum + assert arr.sum().type == max_precision_type + + arr = pa.array([Decimal("1.23"), Decimal("4.56"), None], type=arrow_type) + assert arr.sum().as_py() == expected_sum + assert arr.sum().type == max_precision_type + + # With overflow + arr = pa.array([Decimal("1.23"), Decimal("8.77")], type=arrow_type) + assert arr.sum().as_py() == expected_sum_overflow + assert arr.sum().type == max_precision_type + + arr = pa.array([Decimal("1.23"), Decimal("8.77"), None], type=arrow_type) + assert arr.sum().as_py() == expected_sum_overflow + assert arr.sum().type == max_precision_type + + arr = pa.array([None], type=arrow_type) + assert arr.sum().as_py() is None # noqa: E711 + assert arr.sum().type == max_precision_type # noqa: E711 + assert arr.sum(min_count=0).as_py() == zero + assert arr.sum(min_count=0).type == max_precision_type + + arr = pa.array([], type=arrow_type) + assert arr.sum().as_py() is None # noqa: E711 + assert arr.sum().type == max_precision_type # noqa: E711 + assert arr.sum(min_count=0).as_py() == zero + assert arr.sum(min_count=0).type == max_precision_type + + +@pytest.mark.parametrize('arrow_type', numerical_arrow_types) +def test_sum_chunked_array(arrow_type): + arr = pa.chunked_array([pa.array([1, 2, 3, 4], type=arrow_type)]) + assert pc.sum(arr).as_py() == 10 + + arr = pa.chunked_array([ + pa.array([1, 2], type=arrow_type), pa.array([3, 4], type=arrow_type) + ]) + assert pc.sum(arr).as_py() == 10 + + arr = pa.chunked_array([ + pa.array([1, 2], type=arrow_type), + pa.array([], type=arrow_type), + pa.array([3, 4], type=arrow_type) + ]) + assert pc.sum(arr).as_py() == 10 + + arr = pa.chunked_array((), type=arrow_type) + assert arr.num_chunks == 0 + assert pc.sum(arr).as_py() is None # noqa: E711 + assert pc.sum(arr, min_count=0).as_py() == 0 + + +@pytest.mark.parametrize('arrow_type', [pa.decimal128(3, 2), pa.decimal256(3, 2)]) +def test_sum_chunked_array_decimal_type(arrow_type): + from decimal import Decimal + max_precision_type = ( + pa.decimal128(38, arrow_type.scale) + if pa.types.is_decimal128(arrow_type) + else pa.decimal256(76, arrow_type.scale) + ) + expected_sum = Decimal("5.79") + zero = Decimal("0.00") + + arr = pa.chunked_array( + [ + pa.array([Decimal("1.23"), Decimal("4.56")], type=arrow_type) + ] + ) + assert pc.sum(arr).as_py() == expected_sum + assert pc.sum(arr).type == max_precision_type + + arr = pa.chunked_array([ + pa.array([Decimal("1.23")], type=arrow_type), + pa.array([Decimal("4.56")], type=arrow_type) + ]) + assert pc.sum(arr).as_py() == expected_sum + assert pc.sum(arr).type == max_precision_type + + arr = pa.chunked_array([ + pa.array([Decimal("1.23")], type=arrow_type), + pa.array([], type=arrow_type), + pa.array([Decimal("4.56")], type=arrow_type) + ]) + assert pc.sum(arr).as_py() == expected_sum + assert pc.sum(arr).type == max_precision_type + + arr = pa.chunked_array((), type=arrow_type) + assert arr.num_chunks == 0 + assert pc.sum(arr).as_py() is None # noqa: E711 + assert pc.sum(arr).type == max_precision_type + assert pc.sum(arr, min_count=0).as_py() == zero + assert pc.sum(arr, min_count=0).type == max_precision_type + + +def test_mode_array(): + # ARROW-9917 + arr = pa.array([1, 1, 3, 4, 3, 5], type='int64') + mode = pc.mode(arr) + assert len(mode) == 1 + assert mode[0].as_py() == {"mode": 1, "count": 2} + + mode = pc.mode(arr, n=2) + assert len(mode) == 2 + assert mode[0].as_py() == {"mode": 1, "count": 2} + assert mode[1].as_py() == {"mode": 3, "count": 2} + + arr = pa.array([], type='int64') + assert len(pc.mode(arr)) == 0 + + arr = pa.array([1, 1, 3, 4, 3, None], type='int64') + mode = pc.mode(arr, skip_nulls=False) + assert len(mode) == 0 + mode = pc.mode(arr, min_count=6) + assert len(mode) == 0 + mode = pc.mode(arr, skip_nulls=False, min_count=5) + assert len(mode) == 0 + + arr = pa.array([True, False]) + mode = pc.mode(arr, n=2) + assert len(mode) == 2 + assert mode[0].as_py() == {"mode": False, "count": 1} + assert mode[1].as_py() == {"mode": True, "count": 1} + + +def test_mode_chunked_array(): + # ARROW-9917 + arr = pa.chunked_array([pa.array([1, 1, 3, 4, 3, 5], type='int64')]) + mode = pc.mode(arr) + assert len(mode) == 1 + assert mode[0].as_py() == {"mode": 1, "count": 2} + + mode = pc.mode(arr, n=2) + assert len(mode) == 2 + assert mode[0].as_py() == {"mode": 1, "count": 2} + assert mode[1].as_py() == {"mode": 3, "count": 2} + + arr = pa.chunked_array((), type='int64') + assert arr.num_chunks == 0 + assert len(pc.mode(arr)) == 0 + + +def test_empty_chunked_array(): + msg = "cannot construct ChunkedArray from empty vector and omitted type" + with pytest.raises(pa.ArrowInvalid, match=msg): + pa.chunked_array([]) + + pa.chunked_array([], type=pa.int8()) + + +def test_variance(): + data = [1, 2, 3, 4, 5, 6, 7, 8] + assert pc.variance(data).as_py() == 5.25 + assert pc.variance(data, ddof=0).as_py() == 5.25 + assert pc.variance(data, ddof=1).as_py() == 6.0 + + +def test_skew(): + data = [1, 1, None, 2] + assert pc.skew(data).as_py() == pytest.approx(0.707106781186548, rel=1e-10) + assert pc.skew(data, skip_nulls=False).as_py() is None + assert pc.skew(data, min_count=4).as_py() is None + + +def test_kurtosis(): + data = [1, 1, None, 2] + assert pc.kurtosis(data).as_py() == pytest.approx(-1.5, rel=1e-10) + assert pc.kurtosis(data, skip_nulls=False).as_py() is None + assert pc.kurtosis(data, min_count=4).as_py() is None + + +@pytest.mark.parametrize("input, expected", ( + ( + [1.0, 2.0, 3.0, 40.0, None], + {'skew': pytest.approx(1.988947740397821), + 'kurtosis': pytest.approx(3.9631931024230695)} + ), + ([1, 2, 40], {'skew': pytest.approx(1.7281098503730385), 'kurtosis': None}), + ([1, 40], {'skew': None, 'kurtosis': None}), +)) +def test_unbiased_skew_and_kurtosis(input, expected): + arrow_skew = pc.skew(input, skip_nulls=True, biased=False) + arrow_kurtosis = pc.kurtosis(input, skip_nulls=True, biased=False) + assert arrow_skew.as_py() == expected['skew'] + assert arrow_kurtosis.as_py() == expected['kurtosis'] + + +def test_count_substring(): + for (ty, offset) in [(pa.string(), pa.int32()), + (pa.large_string(), pa.int64())]: + arr = pa.array(["ab", "cab", "abcab", "ba", "AB", None], type=ty) + + result = pc.count_substring(arr, "ab") + expected = pa.array([1, 1, 2, 0, 0, None], type=offset) + assert expected == result + + result = pc.count_substring(arr, "ab", ignore_case=True) + expected = pa.array([1, 1, 2, 0, 1, None], type=offset) + assert expected == result + + +def test_count_substring_regex(): + for (ty, offset) in [(pa.string(), pa.int32()), + (pa.large_string(), pa.int64())]: + arr = pa.array(["ab", "cab", "baAacaa", "ba", "AB", None], type=ty) + + result = pc.count_substring_regex(arr, "a+") + expected = pa.array([1, 1, 3, 1, 0, None], type=offset) + assert expected.equals(result) + + result = pc.count_substring_regex(arr, "a+", ignore_case=True) + expected = pa.array([1, 1, 2, 1, 1, None], type=offset) + assert expected.equals(result) + + +def test_find_substring(): + for ty in [pa.string(), pa.binary(), pa.large_string(), pa.large_binary()]: + arr = pa.array(["ab", "cab", "ba", None], type=ty) + result = pc.find_substring(arr, "ab") + assert result.to_pylist() == [0, 1, -1, None] + + result = pc.find_substring_regex(arr, "a?b") + assert result.to_pylist() == [0, 1, 0, None] + + arr = pa.array(["ab*", "cAB*", "ba", "aB?"], type=ty) + result = pc.find_substring(arr, "aB*", ignore_case=True) + assert result.to_pylist() == [0, 1, -1, -1] + + result = pc.find_substring_regex(arr, "a?b", ignore_case=True) + assert result.to_pylist() == [0, 1, 0, 0] + + +def test_match_like(): + arr = pa.array(["ab", "ba%", "ba", "ca%d", None]) + result = pc.match_like(arr, r"_a\%%") + expected = pa.array([False, True, False, True, None]) + assert expected.equals(result) + + arr = pa.array(["aB", "bA%", "ba", "ca%d", None]) + result = pc.match_like(arr, r"_a\%%", ignore_case=True) + expected = pa.array([False, True, False, True, None]) + assert expected.equals(result) + result = pc.match_like(arr, r"_a\%%", ignore_case=False) + expected = pa.array([False, False, False, True, None]) + assert expected.equals(result) + + +def test_match_substring(): + arr = pa.array(["ab", "abc", "ba", None]) + result = pc.match_substring(arr, "ab") + expected = pa.array([True, True, False, None]) + assert expected.equals(result) + + arr = pa.array(["áB", "Ábc", "ba", None]) + result = pc.match_substring(arr, "áb", ignore_case=True) + expected = pa.array([True, True, False, None]) + assert expected.equals(result) + result = pc.match_substring(arr, "áb", ignore_case=False) + expected = pa.array([False, False, False, None]) + assert expected.equals(result) + + +def test_match_substring_regex(): + arr = pa.array(["ab", "abc", "ba", "c", None]) + result = pc.match_substring_regex(arr, "^a?b") + expected = pa.array([True, True, True, False, None]) + assert expected.equals(result) + + arr = pa.array(["aB", "Abc", "BA", "c", None]) + result = pc.match_substring_regex(arr, "^a?b", ignore_case=True) + expected = pa.array([True, True, True, False, None]) + assert expected.equals(result) + result = pc.match_substring_regex(arr, "^a?b", ignore_case=False) + expected = pa.array([False, False, False, False, None]) + assert expected.equals(result) + + +def test_trim(): + # \u3000 is unicode whitespace + arr = pa.array([" foo", None, " \u3000foo bar \t"]) + result = pc.utf8_trim_whitespace(arr) + expected = pa.array(["foo", None, "foo bar"]) + assert expected.equals(result) + + arr = pa.array([" foo", None, " \u3000foo bar \t"]) + result = pc.ascii_trim_whitespace(arr) + expected = pa.array(["foo", None, "\u3000foo bar"]) + assert expected.equals(result) + + arr = pa.array([" foo", None, " \u3000foo bar \t"]) + result = pc.utf8_trim(arr, characters=' f\u3000') + expected = pa.array(["oo", None, "oo bar \t"]) + assert expected.equals(result) + # Positional option + result = pc.utf8_trim(arr, ' f\u3000') + expected = pa.array(["oo", None, "oo bar \t"]) + assert expected.equals(result) + + +def test_slice_compatibility(): + arr = pa.array(["", "𝑓", "𝑓ö", "𝑓öõ", "𝑓öõḍ", "𝑓öõḍš"]) + for start in range(-6, 6): + for stop in itertools.chain(range(-6, 6), [None]): + for step in [-3, -2, -1, 1, 2, 3]: + expected = pa.array([k.as_py()[start:stop:step] + for k in arr]) + result = pc.utf8_slice_codeunits( + arr, start=start, stop=stop, step=step) + assert expected.equals(result) + # Positional options + assert pc.utf8_slice_codeunits(arr, + start, stop, step) == result + + +def test_binary_slice_compatibility(): + data = [b"", b"a", b"a\xff", b"ab\x00", b"abc\xfb", b"ab\xf2de"] + arr = pa.array(data) + for start, stop, step in itertools.product(range(-6, 6), + range(-6, 6), + range(-3, 4)): + if step == 0: + continue + expected = pa.array([k.as_py()[start:stop:step] + for k in arr]) + result = pc.binary_slice( + arr, start=start, stop=stop, step=step) + assert expected.equals(result) + # Positional options + assert pc.binary_slice(arr, start, stop, step) == result + # Fixed size binary input / output + for item in data: + fsb_scalar = pa.scalar(item, type=pa.binary(len(item))) + expected = item[start:stop:step] + actual = pc.binary_slice(fsb_scalar, start, stop, step) + assert actual.type == pa.binary(len(expected)) + assert actual.as_py() == expected + + +def test_split_pattern(): + arr = pa.array(["-foo---bar--", "---foo---b"]) + result = pc.split_pattern(arr, pattern="---") + expected = pa.array([["-foo", "bar--"], ["", "foo", "b"]]) + assert expected.equals(result) + + result = pc.split_pattern(arr, "---", max_splits=1) + expected = pa.array([["-foo", "bar--"], ["", "foo---b"]]) + assert expected.equals(result) + + result = pc.split_pattern(arr, "---", max_splits=1, reverse=True) + expected = pa.array([["-foo", "bar--"], ["---foo", "b"]]) + assert expected.equals(result) + + +def test_split_whitespace_utf8(): + arr = pa.array(["foo bar", " foo \u3000\tb"]) + result = pc.utf8_split_whitespace(arr) + expected = pa.array([["foo", "bar"], ["", "foo", "b"]]) + assert expected.equals(result) + + result = pc.utf8_split_whitespace(arr, max_splits=1) + expected = pa.array([["foo", "bar"], ["", "foo \u3000\tb"]]) + assert expected.equals(result) + + result = pc.utf8_split_whitespace(arr, max_splits=1, reverse=True) + expected = pa.array([["foo", "bar"], [" foo", "b"]]) + assert expected.equals(result) + + +def test_split_whitespace_ascii(): + arr = pa.array(["foo bar", " foo \u3000\tb"]) + result = pc.ascii_split_whitespace(arr) + expected = pa.array([["foo", "bar"], ["", "foo", "\u3000", "b"]]) + assert expected.equals(result) + + result = pc.ascii_split_whitespace(arr, max_splits=1) + expected = pa.array([["foo", "bar"], ["", "foo \u3000\tb"]]) + assert expected.equals(result) + + result = pc.ascii_split_whitespace(arr, max_splits=1, reverse=True) + expected = pa.array([["foo", "bar"], [" foo \u3000", "b"]]) + assert expected.equals(result) + + +def test_split_pattern_regex(): + arr = pa.array(["-foo---bar--", "---foo---b"]) + result = pc.split_pattern_regex(arr, pattern="-+") + expected = pa.array([["", "foo", "bar", ""], ["", "foo", "b"]]) + assert expected.equals(result) + + result = pc.split_pattern_regex(arr, "-+", max_splits=1) + expected = pa.array([["", "foo---bar--"], ["", "foo---b"]]) + assert expected.equals(result) + + with pytest.raises(NotImplementedError, + match="Cannot split in reverse with regex"): + result = pc.split_pattern_regex( + arr, pattern="---", max_splits=1, reverse=True) + + +def test_min_max(): + # An example generated function wrapper with possible options + data = [4, 5, 6, None, 1] + s = pc.min_max(data) + assert s.as_py() == {'min': 1, 'max': 6} + s = pc.min_max(data, options=pc.ScalarAggregateOptions()) + assert s.as_py() == {'min': 1, 'max': 6} + s = pc.min_max(data, options=pc.ScalarAggregateOptions(skip_nulls=True)) + assert s.as_py() == {'min': 1, 'max': 6} + s = pc.min_max(data, options=pc.ScalarAggregateOptions(skip_nulls=False)) + assert s.as_py() == {'min': None, 'max': None} + + # Options as dict of kwargs + s = pc.min_max(data, options={'skip_nulls': False}) + assert s.as_py() == {'min': None, 'max': None} + # Options as named functions arguments + s = pc.min_max(data, skip_nulls=False) + assert s.as_py() == {'min': None, 'max': None} + + # Both options and named arguments + with pytest.raises(TypeError): + s = pc.min_max( + data, options=pc.ScalarAggregateOptions(), skip_nulls=False) + + # Wrong options type + options = pc.TakeOptions() + with pytest.raises(TypeError): + s = pc.min_max(data, options=options) + + # Missing argument + with pytest.raises(TypeError, match="min_max takes 1 positional"): + s = pc.min_max() + + +def test_any(): + # ARROW-1846 + + options = pc.ScalarAggregateOptions(skip_nulls=False, min_count=0) + + a = pa.array([], type='bool') + assert pc.any(a).as_py() is None + assert pc.any(a, min_count=0).as_py() is False + assert pc.any(a, options=options).as_py() is False + + a = pa.array([False, None, True]) + assert pc.any(a).as_py() is True + assert pc.any(a, options=options).as_py() is True + + a = pa.array([False, None, False]) + assert pc.any(a).as_py() is False + assert pc.any(a, options=options).as_py() is None + + +def test_all(): + # ARROW-10301 + + options = pc.ScalarAggregateOptions(skip_nulls=False, min_count=0) + + a = pa.array([], type='bool') + assert pc.all(a).as_py() is None + assert pc.all(a, min_count=0).as_py() is True + assert pc.all(a, options=options).as_py() is True + + a = pa.array([False, True]) + assert pc.all(a).as_py() is False + assert pc.all(a, options=options).as_py() is False + + a = pa.array([True, None]) + assert pc.all(a).as_py() is True + assert pc.all(a, options=options).as_py() is None + + a = pa.chunked_array([[True], [True, None]]) + assert pc.all(a).as_py() is True + assert pc.all(a, options=options).as_py() is None + + a = pa.chunked_array([[True], [False]]) + assert pc.all(a).as_py() is False + assert pc.all(a, options=options).as_py() is False + + +def test_is_valid(): + # An example generated function wrapper without options + data = [4, 5, None] + assert pc.is_valid(data).to_pylist() == [True, True, False] + + with pytest.raises(TypeError): + pc.is_valid(data, options=None) + + +def test_generated_docstrings(): + # With options + assert pc.min_max.__doc__ == textwrap.dedent("""\ + Compute the minimum and maximum values of a numeric array. + + Null values are ignored by default. + This can be changed through ScalarAggregateOptions. + + Parameters + ---------- + array : Array-like + Argument to compute function. + skip_nulls : bool, default True + Whether to skip (ignore) nulls in the input. + If False, any null in the input forces the output to null. + min_count : int, default 1 + Minimum number of non-null values in the input. If the number + of non-null values is below `min_count`, the output is null. + options : pyarrow.compute.ScalarAggregateOptions, optional + Alternative way of passing options. + memory_pool : pyarrow.MemoryPool, optional + If not passed, will allocate memory from the default memory pool. + + Examples + -------- + >>> import pyarrow as pa + >>> import pyarrow.compute as pc + >>> arr1 = pa.array([1, 1, 2, 2, 3, 2, 2, 2]) + >>> pc.min_max(arr1) + + + Using ``skip_nulls`` to handle null values. + + >>> arr2 = pa.array([1.0, None, 2.0, 3.0]) + >>> pc.min_max(arr2) + + >>> pc.min_max(arr2, skip_nulls=False) + + + Using ``ScalarAggregateOptions`` to control minimum number of non-null values. + + >>> arr3 = pa.array([1.0, None, float("nan"), 3.0]) + >>> pc.min_max(arr3) + + >>> pc.min_max(arr3, options=pc.ScalarAggregateOptions(min_count=3)) + + >>> pc.min_max(arr3, options=pc.ScalarAggregateOptions(min_count=4)) + + + This function also works with string values. + + >>> arr4 = pa.array(["z", None, "y", "x"]) + >>> pc.min_max(arr4) + + """) + # Without options + assert pc.add.__doc__ == textwrap.dedent("""\ + Add the arguments element-wise. + + Results will wrap around on integer overflow. + Use function "add_checked" if you want overflow + to return an error. + + Parameters + ---------- + x : Array-like or scalar-like + Argument to compute function. + y : Array-like or scalar-like + Argument to compute function. + memory_pool : pyarrow.MemoryPool, optional + If not passed, will allocate memory from the default memory pool. + """) + # Varargs with options + assert pc.min_element_wise.__doc__ == textwrap.dedent("""\ + Find the element-wise minimum value. + + Nulls are ignored (by default) or propagated. + NaN is preferred over null, but not over any valid value. + + Parameters + ---------- + *args : Array-like or scalar-like + Argument to compute function. + skip_nulls : bool, default True + Whether to skip (ignore) nulls in the input. + If False, any null in the input forces the output to null. + options : pyarrow.compute.ElementWiseAggregateOptions, optional + Alternative way of passing options. + memory_pool : pyarrow.MemoryPool, optional + If not passed, will allocate memory from the default memory pool. + """) + assert pc.filter.__doc__ == textwrap.dedent("""\ + Filter with a boolean selection filter. + + The output is populated with values from the input at positions + where the selection filter is non-zero. Nulls in the selection filter + are handled based on FilterOptions. + + Parameters + ---------- + input : Array-like or scalar-like + Argument to compute function. + selection_filter : Array-like or scalar-like + Argument to compute function. + null_selection_behavior : str, default "drop" + How to handle nulls in the selection filter. + Accepted values are "drop", "emit_null". + options : pyarrow.compute.FilterOptions, optional + Alternative way of passing options. + memory_pool : pyarrow.MemoryPool, optional + If not passed, will allocate memory from the default memory pool. + + Examples + -------- + >>> import pyarrow as pa + >>> arr = pa.array(["a", "b", "c", None, "e"]) + >>> mask = pa.array([True, False, None, False, True]) + >>> arr.filter(mask) + + [ + "a", + "e" + ] + >>> arr.filter(mask, null_selection_behavior='emit_null') + + [ + "a", + null, + "e" + ] + """) + + +def test_generated_signatures(): + # The self-documentation provided by signatures should show acceptable + # options and their default values. + + # Without options + sig = inspect.signature(pc.add) + assert str(sig) == "(x, y, /, *, memory_pool=None)" + # With options + sig = inspect.signature(pc.min_max) + assert str(sig) == ("(array, /, *, skip_nulls=True, min_count=1, " + "options=None, memory_pool=None)") + # With positional options + sig = inspect.signature(pc.quantile) + assert str(sig) == ("(array, /, q=0.5, *, interpolation='linear', " + "skip_nulls=True, min_count=0, " + "options=None, memory_pool=None)") + # Varargs with options + sig = inspect.signature(pc.binary_join_element_wise) + assert str(sig) == ("(*strings, null_handling='emit_null', " + "null_replacement='', options=None, " + "memory_pool=None)") + # Varargs without options + sig = inspect.signature(pc.choose) + assert str(sig) == "(indices, /, *values, memory_pool=None)" + # Nullary with options + sig = inspect.signature(pc.random) + assert str(sig) == ("(n, *, initializer='system', " + "options=None, memory_pool=None)") + + +# We use isprintable to find about codepoints that Python doesn't know, but +# utf8proc does (or in a future version of Python the other way around). +# These codepoints cannot be compared between Arrow and the Python +# implementation. +@lru_cache() +def find_new_unicode_codepoints(): + new = set() + characters = [chr(c) for c in range(0x80, 0x11000) + if not (0xD800 <= c < 0xE000)] + is_printable = pc.utf8_is_printable(pa.array(characters)).to_pylist() + for i, c in enumerate(characters): + if is_printable[i] != c.isprintable(): + new.add(ord(c)) + return new + + +# Python claims there are not alpha, not sure why, they are in +# gc='Other Letter': https://graphemica.com/%E1%B3%B2 +unknown_issue_is_alpha = {0x1cf2, 0x1cf3} +# utf8proc does not know if codepoints are lower case +utf8proc_issue_is_lower = { + 0xaa, 0xba, 0x2b0, 0x2b1, 0x2b2, 0x2b3, 0x2b4, + 0x2b5, 0x2b6, 0x2b7, 0x2b8, 0x2c0, 0x2c1, 0x2e0, + 0x2e1, 0x2e2, 0x2e3, 0x2e4, 0x37a, 0x1d2c, 0x1d2d, + 0x1d2e, 0x1d2f, 0x1d30, 0x1d31, 0x1d32, 0x1d33, + 0x1d34, 0x1d35, 0x1d36, 0x1d37, 0x1d38, 0x1d39, + 0x1d3a, 0x1d3b, 0x1d3c, 0x1d3d, 0x1d3e, 0x1d3f, + 0x1d40, 0x1d41, 0x1d42, 0x1d43, 0x1d44, 0x1d45, + 0x1d46, 0x1d47, 0x1d48, 0x1d49, 0x1d4a, 0x1d4b, + 0x1d4c, 0x1d4d, 0x1d4e, 0x1d4f, 0x1d50, 0x1d51, + 0x1d52, 0x1d53, 0x1d54, 0x1d55, 0x1d56, 0x1d57, + 0x1d58, 0x1d59, 0x1d5a, 0x1d5b, 0x1d5c, 0x1d5d, + 0x1d5e, 0x1d5f, 0x1d60, 0x1d61, 0x1d62, 0x1d63, + 0x1d64, 0x1d65, 0x1d66, 0x1d67, 0x1d68, 0x1d69, + 0x1d6a, 0x1d78, 0x1d9b, 0x1d9c, 0x1d9d, 0x1d9e, + 0x1d9f, 0x1da0, 0x1da1, 0x1da2, 0x1da3, 0x1da4, + 0x1da5, 0x1da6, 0x1da7, 0x1da8, 0x1da9, 0x1daa, + 0x1dab, 0x1dac, 0x1dad, 0x1dae, 0x1daf, 0x1db0, + 0x1db1, 0x1db2, 0x1db3, 0x1db4, 0x1db5, 0x1db6, + 0x1db7, 0x1db8, 0x1db9, 0x1dba, 0x1dbb, 0x1dbc, + 0x1dbd, 0x1dbe, 0x1dbf, 0x2071, 0x207f, 0x2090, + 0x2091, 0x2092, 0x2093, 0x2094, 0x2095, 0x2096, + 0x2097, 0x2098, 0x2099, 0x209a, 0x209b, 0x209c, + 0x2c7c, 0x2c7d, 0xa69c, 0xa69d, 0xa770, 0xa7f8, + 0xa7f9, 0xab5c, 0xab5d, 0xab5e, 0xab5f, } +# utf8proc does not store if a codepoint is numeric +numeric_info_missing = { + 0x3405, 0x3483, 0x382a, 0x3b4d, 0x4e00, 0x4e03, + 0x4e07, 0x4e09, 0x4e5d, 0x4e8c, 0x4e94, 0x4e96, + 0x4ebf, 0x4ec0, 0x4edf, 0x4ee8, 0x4f0d, 0x4f70, + 0x5104, 0x5146, 0x5169, 0x516b, 0x516d, 0x5341, + 0x5343, 0x5344, 0x5345, 0x534c, 0x53c1, 0x53c2, + 0x53c3, 0x53c4, 0x56db, 0x58f1, 0x58f9, 0x5e7a, + 0x5efe, 0x5eff, 0x5f0c, 0x5f0d, 0x5f0e, 0x5f10, + 0x62fe, 0x634c, 0x67d2, 0x6f06, 0x7396, 0x767e, + 0x8086, 0x842c, 0x8cae, 0x8cb3, 0x8d30, 0x9621, + 0x9646, 0x964c, 0x9678, 0x96f6, 0xf96b, 0xf973, + 0xf978, 0xf9b2, 0xf9d1, 0xf9d3, 0xf9fd, 0x10fc5, + 0x10fc6, 0x10fc7, 0x10fc8, 0x10fc9, 0x10fca, + 0x10fcb, } +# utf8proc has no no digit/numeric information +digit_info_missing = { + 0xb2, 0xb3, 0xb9, 0x1369, 0x136a, 0x136b, 0x136c, + 0x136d, 0x136e, 0x136f, 0x1370, 0x1371, 0x19da, 0x2070, + 0x2074, 0x2075, 0x2076, 0x2077, 0x2078, 0x2079, 0x2080, + 0x2081, 0x2082, 0x2083, 0x2084, 0x2085, 0x2086, 0x2087, + 0x2088, 0x2089, 0x2460, 0x2461, 0x2462, 0x2463, 0x2464, + 0x2465, 0x2466, 0x2467, 0x2468, 0x2474, 0x2475, 0x2476, + 0x2477, 0x2478, 0x2479, 0x247a, 0x247b, 0x247c, 0x2488, + 0x2489, 0x248a, 0x248b, 0x248c, 0x248d, 0x248e, 0x248f, + 0x2490, 0x24ea, 0x24f5, 0x24f6, 0x24f7, 0x24f8, 0x24f9, + 0x24fa, 0x24fb, 0x24fc, 0x24fd, 0x24ff, 0x2776, 0x2777, + 0x2778, 0x2779, 0x277a, 0x277b, 0x277c, 0x277d, 0x277e, + 0x2780, 0x2781, 0x2782, 0x2783, 0x2784, 0x2785, 0x2786, + 0x2787, 0x2788, 0x278a, 0x278b, 0x278c, 0x278d, 0x278e, + 0x278f, 0x2790, 0x2791, 0x2792, 0x10a40, 0x10a41, + 0x10a42, 0x10a43, 0x10e60, 0x10e61, 0x10e62, 0x10e63, + 0x10e64, 0x10e65, 0x10e66, 0x10e67, 0x10e68, } +numeric_info_missing = { + 0x3405, 0x3483, 0x382a, 0x3b4d, 0x4e00, 0x4e03, + 0x4e07, 0x4e09, 0x4e5d, 0x4e8c, 0x4e94, 0x4e96, + 0x4ebf, 0x4ec0, 0x4edf, 0x4ee8, 0x4f0d, 0x4f70, + 0x5104, 0x5146, 0x5169, 0x516b, 0x516d, 0x5341, + 0x5343, 0x5344, 0x5345, 0x534c, 0x53c1, 0x53c2, + 0x53c3, 0x53c4, 0x56db, 0x58f1, 0x58f9, 0x5e7a, + 0x5efe, 0x5eff, 0x5f0c, 0x5f0d, 0x5f0e, 0x5f10, + 0x62fe, 0x634c, 0x67d2, 0x6f06, 0x7396, 0x767e, + 0x8086, 0x842c, 0x8cae, 0x8cb3, 0x8d30, 0x9621, + 0x9646, 0x964c, 0x9678, 0x96f6, 0xf96b, 0xf973, + 0xf978, 0xf9b2, 0xf9d1, 0xf9d3, 0xf9fd, } + +codepoints_ignore = { + 'is_alnum': numeric_info_missing | digit_info_missing | + unknown_issue_is_alpha, + 'is_alpha': unknown_issue_is_alpha, + 'is_digit': digit_info_missing, + 'is_numeric': numeric_info_missing, + 'is_lower': utf8proc_issue_is_lower +} + + +@pytest.mark.parametrize('function_name', ['is_alnum', 'is_alpha', + 'is_ascii', 'is_decimal', + 'is_digit', 'is_lower', + 'is_numeric', 'is_printable', + 'is_space', 'is_upper', ]) +@pytest.mark.parametrize('variant', ['ascii', 'utf8']) +def test_string_py_compat_boolean(function_name, variant): + arrow_name = variant + "_" + function_name + py_name = function_name.replace('_', '') + ignore = codepoints_ignore.get(function_name, set()) | \ + find_new_unicode_codepoints() + for i in range(128 if ascii else 0x11000): + if i in range(0xD800, 0xE000): + continue # bug? pyarrow doesn't allow utf16 surrogates + # the issues we know of, we skip + if i in ignore: + continue + # Compare results with the equivalent Python predicate + # (except "is_space" where functions are known to be incompatible) + c = chr(i) + if hasattr(pc, arrow_name) and function_name != 'is_space': + ar = pa.array([c]) + arrow_func = getattr(pc, arrow_name) + assert arrow_func(ar)[0].as_py() == getattr(c, py_name)() + + +def test_pad(): + arr = pa.array([None, 'a', 'abcd']) + assert pc.ascii_center(arr, width=3).tolist() == [None, ' a ', 'abcd'] + assert pc.ascii_lpad(arr, width=3).tolist() == [None, ' a', 'abcd'] + assert pc.ascii_rpad(arr, width=3).tolist() == [None, 'a ', 'abcd'] + assert pc.ascii_center(arr, 3).tolist() == [None, ' a ', 'abcd'] + assert pc.ascii_lpad(arr, 3).tolist() == [None, ' a', 'abcd'] + assert pc.ascii_rpad(arr, 3).tolist() == [None, 'a ', 'abcd'] + + arr = pa.array([None, 'á', 'abcd']) + assert pc.utf8_center(arr, width=3).tolist() == [None, ' á ', 'abcd'] + assert pc.utf8_lpad(arr, width=3).tolist() == [None, ' á', 'abcd'] + assert pc.utf8_rpad(arr, width=3).tolist() == [None, 'á ', 'abcd'] + assert pc.utf8_center(arr, 3).tolist() == [None, ' á ', 'abcd'] + assert pc.utf8_lpad(arr, 3).tolist() == [None, ' á', 'abcd'] + assert pc.utf8_rpad(arr, 3).tolist() == [None, 'á ', 'abcd'] + + +def test_utf8_zfill(): + assert pc.utf8_zfill is pc.utf8_zero_fill + + # match str.zfill behavior + examples = ['A', 'AB', 'ABC', '', '-1', '+1', '1', None] + for width in range(0, 6): + arr = pa.array(examples) + result = pc.utf8_zero_fill(arr, width=width).to_pylist() + expected = [x.zfill(width) if x is not None else None for x in examples] + assert result == expected, f"Mismatch at width={width}: {result} vs {expected}" + + # unicode padding character + arr = pa.array(["1", "-2", "+3"]) + result = pc.utf8_zero_fill(arr, options=pc.ZeroFillOptions( + width=5, padding="💠")).to_pylist() + assert result == ["💠💠💠💠1", "-💠💠💠2", "+💠💠💠3"] + + # custom ASCII padding character + arr = pa.array(["1", "-2", "+3"]) + result = pc.utf8_zero_fill(arr, options=pc.ZeroFillOptions( + width=4, padding="x")).to_pylist() + assert result == ["xxx1", "-xx2", "+xx3"] + + # multi-codepoint padding — should raise + arr = pa.array(["foo"]) + with pytest.raises(pa.ArrowInvalid, match="Padding must be one codepoint"): + pc.utf8_zero_fill(arr, options=pc.ZeroFillOptions(width=4, padding="spam")) + with pytest.raises(pa.ArrowInvalid, match="Padding must be one codepoint"): + pc.utf8_zero_fill(arr, options=pc.ZeroFillOptions(width=4, padding="")) + + +@pytest.mark.pandas +def test_replace_slice(): + offsets = range(-3, 4) + + arr = pa.array([None, '', 'a', 'ab', 'abc', 'abcd', 'abcde']) + series = arr.to_pandas().astype(object).replace({np.nan: None}) + for start in offsets: + for stop in offsets: + expected = series.str.slice_replace(start, stop, 'XX') + actual = pc.binary_replace_slice( + arr, start=start, stop=stop, replacement='XX') + assert actual.tolist() == expected.tolist() + # Positional options + assert pc.binary_replace_slice(arr, start, stop, 'XX') == actual + + arr = pa.array([None, '', 'π', 'πb', 'πbθ', 'πbθd', 'πbθde']) + series = arr.to_pandas().astype(object).replace({np.nan: None}) + for start in offsets: + for stop in offsets: + expected = series.str.slice_replace(start, stop, 'XX') + actual = pc.utf8_replace_slice( + arr, start=start, stop=stop, replacement='XX') + assert actual.tolist() == expected.tolist() + + +def test_replace_plain(): + data = pa.array(['foozfoo', 'food', None]) + ar = pc.replace_substring(data, pattern='foo', replacement='bar') + assert ar.tolist() == ['barzbar', 'bard', None] + ar = pc.replace_substring(data, 'foo', 'bar') + assert ar.tolist() == ['barzbar', 'bard', None] + + ar = pc.replace_substring(data, pattern='foo', replacement='bar', + max_replacements=1) + assert ar.tolist() == ['barzfoo', 'bard', None] + ar = pc.replace_substring(data, 'foo', 'bar', max_replacements=1) + assert ar.tolist() == ['barzfoo', 'bard', None] + + +def test_replace_regex(): + data = pa.array(['foo', 'mood', None]) + expected = ['f00', 'm00d', None] + ar = pc.replace_substring_regex(data, pattern='(.)oo', replacement=r'\100') + assert ar.tolist() == expected + ar = pc.replace_substring_regex(data, '(.)oo', replacement=r'\100') + assert ar.tolist() == expected + ar = pc.replace_substring_regex(data, '(.)oo', r'\100') + assert ar.tolist() == expected + + +def test_extract_regex(): + ar = pa.array(['a1', 'zb2z']) + expected = [{'letter': 'a', 'digit': '1'}, {'letter': 'b', 'digit': '2'}] + struct = pc.extract_regex(ar, pattern=r'(?P[ab])(?P\d)') + assert struct.tolist() == expected + struct = pc.extract_regex(ar, r'(?P[ab])(?P\d)') + assert struct.tolist() == expected + + +def test_extract_regex_span(): + ar = pa.array(['a1', 'zb234z']) + expected = [{'letter': [0, 1], 'digit': [1, 1]}, + {'letter': [1, 1], 'digit': [2, 3]}] + struct = pc.extract_regex_span(ar, pattern=r'(?P[ab])(?P\d+)') + assert struct.tolist() == expected + struct = pc.extract_regex_span(ar, r'(?P[ab])(?P\d+)') + assert struct.tolist() == expected + + +def test_binary_join(): + ar_list = pa.array([['foo', 'bar'], None, []]) + expected = pa.array(['foo-bar', None, '']) + assert pc.binary_join(ar_list, '-').equals(expected) + + separator_array = pa.array(['1', '2'], type=pa.binary()) + expected = pa.array(['a1b', 'c2d'], type=pa.binary()) + ar_list = pa.array([['a', 'b'], ['c', 'd']], type=pa.list_(pa.binary())) + assert pc.binary_join(ar_list, separator_array).equals(expected) + + +def test_binary_join_element_wise(): + null = pa.scalar(None, type=pa.string()) + arrs = [[None, 'a', 'b'], ['c', None, 'd'], [None, '-', '--']] + assert pc.binary_join_element_wise(*arrs).to_pylist() == \ + [None, None, 'b--d'] + assert pc.binary_join_element_wise('a', 'b', '-').as_py() == 'a-b' + assert pc.binary_join_element_wise('a', null, '-').as_py() is None + assert pc.binary_join_element_wise('a', 'b', null).as_py() is None + + skip = pc.JoinOptions(null_handling='skip') + assert pc.binary_join_element_wise(*arrs, options=skip).to_pylist() == \ + [None, 'a', 'b--d'] + assert pc.binary_join_element_wise( + 'a', 'b', '-', options=skip).as_py() == 'a-b' + assert pc.binary_join_element_wise( + 'a', null, '-', options=skip).as_py() == 'a' + assert pc.binary_join_element_wise( + 'a', 'b', null, options=skip).as_py() is None + + replace = pc.JoinOptions(null_handling='replace', null_replacement='spam') + assert pc.binary_join_element_wise(*arrs, options=replace).to_pylist() == \ + [None, 'a-spam', 'b--d'] + assert pc.binary_join_element_wise( + 'a', 'b', '-', options=replace).as_py() == 'a-b' + assert pc.binary_join_element_wise( + 'a', null, '-', options=replace).as_py() == 'a-spam' + assert pc.binary_join_element_wise( + 'a', 'b', null, options=replace).as_py() is None + + +@pytest.mark.parametrize(('ty', 'values'), all_array_types) +def test_take(ty, values): + arr = pa.array(values, type=ty) + for indices_type in [pa.int8(), pa.int64()]: + indices = pa.array([0, 4, 2, None], type=indices_type) + result = arr.take(indices) + result.validate() + expected = pa.array([values[0], values[4], values[2], None], type=ty) + assert result.equals(expected) + + # empty indices + indices = pa.array([], type=indices_type) + result = arr.take(indices) + result.validate() + expected = pa.array([], type=ty) + assert result.equals(expected) + + indices = pa.array([2, 5]) + with pytest.raises(IndexError): + arr.take(indices) + + indices = pa.array([2, -1]) + with pytest.raises(IndexError): + arr.take(indices) + + +def test_take_indices_types(): + arr = pa.array(range(5)) + + for indices_type in ['uint8', 'int8', 'uint16', 'int16', + 'uint32', 'int32', 'uint64', 'int64']: + indices = pa.array([0, 4, 2, None], type=indices_type) + result = arr.take(indices) + result.validate() + expected = pa.array([0, 4, 2, None]) + assert result.equals(expected) + + for indices_type in [pa.float32(), pa.float64()]: + indices = pa.array([0, 4, 2], type=indices_type) + with pytest.raises(NotImplementedError): + arr.take(indices) + + +def test_take_on_chunked_array(): + # ARROW-9504 + arr = pa.chunked_array([ + [ + "a", + "b", + "c", + "d", + "e" + ], + [ + "f", + "g", + "h", + "i", + "j" + ] + ]) + + indices = pa.array([0, 5, 1, 6, 9, 2]) + result = arr.take(indices) + expected = pa.chunked_array([["a", "f", "b", "g", "j", "c"]]) + assert result.equals(expected) + + indices = pa.chunked_array([[1], [9, 2]]) + result = arr.take(indices) + expected = pa.chunked_array([ + [ + "b" + ], + [ + "j", + "c" + ] + ]) + assert result.equals(expected) + + +@pytest.mark.parametrize('ordered', [False, True]) +def test_take_dictionary(ordered): + arr = pa.DictionaryArray.from_arrays([0, 1, 2, 0, 1, 2], ['a', 'b', 'c'], + ordered=ordered) + result = arr.take(pa.array([0, 1, 3])) + result.validate() + assert result.to_pylist() == ['a', 'b', 'a'] + assert result.dictionary.to_pylist() == ['a', 'b', 'c'] + assert result.type.ordered is ordered + + +def test_take_null_type(): + # ARROW-10027 + arr = pa.array([None] * 10) + chunked_arr = pa.chunked_array([[None] * 5] * 2) + batch = pa.record_batch([arr], names=['a']) + table = pa.table({'a': arr}) + + indices = pa.array([1, 3, 7, None]) + assert len(arr.take(indices)) == 4 + assert len(chunked_arr.take(indices)) == 4 + assert len(batch.take(indices).column(0)) == 4 + assert len(table.take(indices).column(0)) == 4 + + +@pytest.mark.parametrize(('ty', 'values'), all_array_types) +def test_drop_null(ty, values): + arr = pa.array(values, type=ty) + result = arr.drop_null() + result.validate(full=True) + indices = [i for i in range(len(arr)) if arr[i].is_valid] + expected = arr.take(pa.array(indices)) + assert result.equals(expected) + + +def test_drop_null_chunked_array(): + arr = pa.chunked_array([["a", None], ["c", "d", None], [None], []]) + expected_drop = pa.chunked_array([["a"], ["c", "d"], [], []]) + + result = arr.drop_null() + assert result.equals(expected_drop) + + +def test_drop_null_record_batch(): + batch = pa.record_batch( + [pa.array(["a", None, "c", "d", None])], names=["a'"]) + result = batch.drop_null() + expected = pa.record_batch([pa.array(["a", "c", "d"])], names=["a'"]) + assert result.equals(expected) + + batch = pa.record_batch( + [pa.array(["a", None, "c", "d", None]), + pa.array([None, None, "c", None, "e"])], names=["a'", "b'"]) + + result = batch.drop_null() + expected = pa.record_batch( + [pa.array(["c"]), pa.array(["c"])], names=["a'", "b'"]) + assert result.equals(expected) + + +def test_drop_null_table(): + table = pa.table([pa.array(["a", None, "c", "d", None])], names=["a"]) + expected = pa.table([pa.array(["a", "c", "d"])], names=["a"]) + result = table.drop_null() + assert result.equals(expected) + + table = pa.table([pa.chunked_array([["a", None], ["c", "d", None]]), + pa.chunked_array([["a", None], [None, "d", None]]), + pa.chunked_array([["a"], ["b"], [None], ["d", None]])], + names=["a", "b", "c"]) + expected = pa.table([pa.array(["a", "d"]), + pa.array(["a", "d"]), + pa.array(["a", "d"])], + names=["a", "b", "c"]) + result = table.drop_null() + assert result.equals(expected) + + table = pa.table([pa.chunked_array([["a", "b"], ["c", "d", "e"]]), + pa.chunked_array([["A"], ["B"], [None], ["D", None]]), + pa.chunked_array([["a`", None], ["c`", "d`", None]])], + names=["a", "b", "c"]) + expected = pa.table([pa.array(["a", "d"]), + pa.array(["A", "D"]), + pa.array(["a`", "d`"])], + names=["a", "b", "c"]) + result = table.drop_null() + assert result.equals(expected) + + +def test_drop_null_null_type(): + arr = pa.array([None] * 10) + chunked_arr = pa.chunked_array([[None] * 5] * 2) + batch = pa.record_batch([arr], names=['a']) + table = pa.table({'a': arr}) + + assert len(arr.drop_null()) == 0 + assert len(chunked_arr.drop_null()) == 0 + assert len(batch.drop_null().column(0)) == 0 + assert len(table.drop_null().column(0)) == 0 + + +@pytest.mark.parametrize(('ty', 'values'), all_array_types) +def test_filter(ty, values): + arr = pa.array(values, type=ty) + + mask = pa.array([True, False, False, True, None]) + result = arr.filter(mask, null_selection_behavior='drop') + result.validate() + assert result.equals(pa.array([values[0], values[3]], type=ty)) + result = arr.filter(mask, null_selection_behavior='emit_null') + result.validate() + assert result.equals(pa.array([values[0], values[3], None], type=ty)) + + # non-boolean dtype + mask = pa.array([0, 1, 0, 1, 0]) + with pytest.raises(NotImplementedError): + arr.filter(mask) + + # wrong length + mask = pa.array([True, False, True]) + with pytest.raises(ValueError, match="must all be the same length"): + arr.filter(mask) + + +@pytest.mark.numpy +@pytest.mark.parametrize(('ty', 'values'), all_array_types) +def test_filter_numpy_array_mask(ty, values): + arr = pa.array(values, type=ty) + # same test as test_filter with different array type + mask = np.array([True, False, False, True, None]) + result = arr.filter(mask, null_selection_behavior='drop') + result.validate() + assert result.equals(pa.array([values[0], values[3]], type=ty)) + + +def test_filter_chunked_array(): + arr = pa.chunked_array([["a", None], ["c", "d", "e"]]) + expected_drop = pa.chunked_array([["a"], ["e"]]) + expected_null = pa.chunked_array([["a"], [None, "e"]]) + + for mask in [ + # mask is array + pa.array([True, False, None, False, True]), + # mask is chunked array + pa.chunked_array([[True, False, None], [False, True]]), + # mask is python object + [True, False, None, False, True] + ]: + result = arr.filter(mask) + assert result.equals(expected_drop) + result = arr.filter(mask, null_selection_behavior="emit_null") + assert result.equals(expected_null) + + +def test_filter_record_batch(): + batch = pa.record_batch( + [pa.array(["a", None, "c", "d", "e"])], names=["a'"]) + + # mask is array + mask = pa.array([True, False, None, False, True]) + result = batch.filter(mask) + expected = pa.record_batch([pa.array(["a", "e"])], names=["a'"]) + assert result.equals(expected) + + # GH-38770: mask is chunked array + chunked_mask = pa.chunked_array([[True, False], [None], [False, True]]) + result = batch.filter(chunked_mask) + assert result.equals(expected) + + result = batch.filter(mask, null_selection_behavior="emit_null") + expected = pa.record_batch([pa.array(["a", None, "e"])], names=["a'"]) + assert result.equals(expected) + + +def test_filter_table(): + table = pa.table([pa.array(["a", None, "c", "d", "e"])], names=["a"]) + expected_drop = pa.table([pa.array(["a", "e"])], names=["a"]) + expected_null = pa.table([pa.array(["a", None, "e"])], names=["a"]) + + for mask in [ + # mask is array + pa.array([True, False, None, False, True]), + # mask is chunked array + pa.chunked_array([[True, False], [None, False, True]]), + # mask is python object + [True, False, None, False, True] + ]: + result = table.filter(mask) + assert result.equals(expected_drop) + result = table.filter(mask, null_selection_behavior="emit_null") + assert result.equals(expected_null) + + +def test_filter_errors(): + arr = pa.chunked_array([["a", None], ["c", "d", "e"]]) + batch = pa.record_batch( + [pa.array(["a", None, "c", "d", "e"])], names=["a'"]) + table = pa.table([pa.array(["a", None, "c", "d", "e"])], names=["a"]) + + for obj in [arr, batch, table]: + # non-boolean dtype + mask = pa.array([0, 1, 0, 1, 0]) + with pytest.raises(NotImplementedError): + obj.filter(mask) + + # wrong length + mask = pa.array([True, False, True]) + with pytest.raises(pa.ArrowInvalid, + match="must all be the same length"): + obj.filter(mask) + + scalar = pa.scalar(True) + for filt in [batch, table, scalar]: + with pytest.raises(TypeError): + table.filter(filt) + + +def test_filter_null_type(): + # ARROW-10027 + arr = pa.array([None] * 10) + chunked_arr = pa.chunked_array([[None] * 5] * 2) + batch = pa.record_batch([arr], names=['a']) + table = pa.table({'a': arr}) + + mask = pa.array([True, False] * 5) + assert len(arr.filter(mask)) == 5 + assert len(chunked_arr.filter(mask)) == 5 + assert len(batch.filter(mask).column(0)) == 5 + assert len(table.filter(mask).column(0)) == 5 + + +def test_inverse_permutation(): + arr0 = pa.array([], type=pa.int32()) + arr = pa.chunked_array([ + arr0, [9, 7, 5, 3, 1], [0], [2, 4, 6], [8], arr0, + ]) + expected = pa.chunked_array([[5, 4, 6, 3, 7, 2, 8, 1, 9, 0]], type=pa.int32()) + assert pc.inverse_permutation(arr).equals(expected) + + options = pc.InversePermutationOptions(max_index=9, output_type=pa.int32()) + assert pc.inverse_permutation(arr, options=options).equals(expected) + assert pc.inverse_permutation(arr, max_index=-1).equals(expected) + + with pytest.raises(ArrowIndexError, match="Index out of bounds: 9"): + pc.inverse_permutation(arr, max_index=4) + + +def test_scatter(): + values = pa.array([True, False, True, True, False, False, True, True, True, False]) + indices = pa.array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) + expected = pa.array([False, True, True, True, False, + False, True, True, False, True]) + result = pc.scatter(values, indices) + assert result.equals(expected) + + options = pc.ScatterOptions(max_index=-1) + assert pc.scatter(values, indices, options=options).equals(expected) + assert pc.scatter(values, indices, max_index=9).equals(expected) + + with pytest.raises(ArrowIndexError, match="Index out of bounds: 9"): + pc.scatter(values, indices, max_index=4) + + +@pytest.mark.parametrize("typ", ["array", "chunked_array"]) +def test_compare_array(typ): + if typ == "array": + def con(values): + return pa.array(values) + else: + def con(values): + return pa.chunked_array([values]) + + arr1 = con([1, 2, 3, 4, None]) + arr2 = con([1, 1, 4, None, 4]) + + result = pc.equal(arr1, arr2) + assert result.equals(con([True, False, False, None, None])) + + result = pc.not_equal(arr1, arr2) + assert result.equals(con([False, True, True, None, None])) + + result = pc.less(arr1, arr2) + assert result.equals(con([False, False, True, None, None])) + + result = pc.less_equal(arr1, arr2) + assert result.equals(con([True, False, True, None, None])) + + result = pc.greater(arr1, arr2) + assert result.equals(con([False, True, False, None, None])) + + result = pc.greater_equal(arr1, arr2) + assert result.equals(con([True, True, False, None, None])) + + +@pytest.mark.parametrize("typ", ["array", "chunked_array"]) +def test_compare_string_scalar(typ): + if typ == "array": + def con(values): + return pa.array(values) + else: + def con(values): + return pa.chunked_array([values]) + + arr = con(['a', 'b', 'c', None]) + scalar = pa.scalar('b') + + result = pc.equal(arr, scalar) + assert result.equals(con([False, True, False, None])) + + if typ == "array": + nascalar = pa.scalar(None, type="string") + result = pc.equal(arr, nascalar) + isnull = pc.is_null(result) + assert isnull.equals(con([True, True, True, True])) + + result = pc.not_equal(arr, scalar) + assert result.equals(con([True, False, True, None])) + + result = pc.less(arr, scalar) + assert result.equals(con([True, False, False, None])) + + result = pc.less_equal(arr, scalar) + assert result.equals(con([True, True, False, None])) + + result = pc.greater(arr, scalar) + assert result.equals(con([False, False, True, None])) + + result = pc.greater_equal(arr, scalar) + assert result.equals(con([False, True, True, None])) + + +@pytest.mark.parametrize("typ", ["array", "chunked_array"]) +def test_compare_scalar(typ): + if typ == "array": + def con(values): + return pa.array(values) + else: + def con(values): + return pa.chunked_array([values]) + + arr = con([1, 2, 3, None]) + scalar = pa.scalar(2) + + result = pc.equal(arr, scalar) + assert result.equals(con([False, True, False, None])) + + if typ == "array": + nascalar = pa.scalar(None, type="int64") + result = pc.equal(arr, nascalar) + assert result.to_pylist() == [None, None, None, None] + + result = pc.not_equal(arr, scalar) + assert result.equals(con([True, False, True, None])) + + result = pc.less(arr, scalar) + assert result.equals(con([True, False, False, None])) + + result = pc.less_equal(arr, scalar) + assert result.equals(con([True, True, False, None])) + + result = pc.greater(arr, scalar) + assert result.equals(con([False, False, True, None])) + + result = pc.greater_equal(arr, scalar) + assert result.equals(con([False, True, True, None])) + + +def test_compare_chunked_array_mixed(): + arr = pa.array([1, 2, 3, 4, None]) + arr_chunked = pa.chunked_array([[1, 2, 3], [4, None]]) + arr_chunked2 = pa.chunked_array([[1, 2], [3, 4, None]]) + + expected = pa.chunked_array([[True, True, True, True, None]]) + + for left, right in [ + (arr, arr_chunked), + (arr_chunked, arr), + (arr_chunked, arr_chunked2), + ]: + result = pc.equal(left, right) + assert result.equals(expected) + + +def test_arithmetic_add(): + left = pa.array([1, 2, 3, 4, 5]) + right = pa.array([0, -1, 1, 2, 3]) + result = pc.add(left, right) + expected = pa.array([1, 1, 4, 6, 8]) + assert result.equals(expected) + + +def test_arithmetic_subtract(): + left = pa.array([1, 2, 3, 4, 5]) + right = pa.array([0, -1, 1, 2, 3]) + result = pc.subtract(left, right) + expected = pa.array([1, 3, 2, 2, 2]) + assert result.equals(expected) + + +def test_arithmetic_multiply(): + left = pa.array([1, 2, 3, 4, 5]) + right = pa.array([0, -1, 1, 2, 3]) + result = pc.multiply(left, right) + expected = pa.array([0, -2, 3, 8, 15]) + assert result.equals(expected) + + +@pytest.mark.parametrize("ty", ["round", "round_to_multiple"]) +def test_round_to_integer(ty): + if ty == "round": + round = pc.round + RoundOptions = partial(pc.RoundOptions, ndigits=0) + elif ty == "round_to_multiple": + round = pc.round_to_multiple + RoundOptions = partial(pc.RoundToMultipleOptions, multiple=1) + + values = [3.2, 3.5, 3.7, 4.5, -3.2, -3.5, -3.7, None] + rmode_and_expected = { + "down": [3, 3, 3, 4, -4, -4, -4, None], + "up": [4, 4, 4, 5, -3, -3, -3, None], + "towards_zero": [3, 3, 3, 4, -3, -3, -3, None], + "towards_infinity": [4, 4, 4, 5, -4, -4, -4, None], + "half_down": [3, 3, 4, 4, -3, -4, -4, None], + "half_up": [3, 4, 4, 5, -3, -3, -4, None], + "half_towards_zero": [3, 3, 4, 4, -3, -3, -4, None], + "half_towards_infinity": [3, 4, 4, 5, -3, -4, -4, None], + "half_to_even": [3, 4, 4, 4, -3, -4, -4, None], + "half_to_odd": [3, 3, 4, 5, -3, -3, -4, None], + } + for round_mode, expected in rmode_and_expected.items(): + options = RoundOptions(round_mode=round_mode) + result = round(values, options=options) + expected_array = pa.array(expected, type=pa.float64()) + assert expected_array.equals(result) + + +@pytest.mark.numpy +def test_round(): + values = [320, 3.5, 3.075, 4.5, -3.212, -35.1234, -3.045, None] + ndigits_and_expected = { + -2: [300, 0, 0, 0, -0, -0, -0, None], + -1: [320, 0, 0, 0, -0, -40, -0, None], + 0: [320, 4, 3, 5, -3, -35, -3, None], + 1: [320, 3.5, 3.1, 4.5, -3.2, -35.1, -3, None], + 2: [320, 3.5, 3.08, 4.5, -3.21, -35.12, -3.05, None], + } + for ndigits, expected in ndigits_and_expected.items(): + options = pc.RoundOptions(ndigits, "half_towards_infinity") + result = pc.round(values, options=options) + np.testing.assert_allclose(result, pa.array(expected), equal_nan=True) + assert pc.round(values, ndigits, + round_mode="half_towards_infinity") == result + assert pc.round(values, ndigits, "half_towards_infinity") == result + + +@pytest.mark.numpy +def test_round_to_multiple(): + values = [320, 3.5, 3.075, 4.5, -3.212, -35.1234, -3.045, None] + multiple_and_expected = { + 0.05: [320, 3.5, 3.1, 4.5, -3.2, -35.1, -3.05, None], + pa.scalar(0.1): [320, 3.5, 3.1, 4.5, -3.2, -35.1, -3, None], + 2: [320, 4, 4, 4, -4, -36, -4, None], + 10: [320, 0, 0, 0, -0, -40, -0, None], + pa.scalar(100, type=pa.decimal256(10, 4)): + [300, 0, 0, 0, -0, -0, -0, None], + } + for multiple, expected in multiple_and_expected.items(): + options = pc.RoundToMultipleOptions(multiple, "half_towards_infinity") + result = pc.round_to_multiple(values, options=options) + np.testing.assert_allclose(result, pa.array(expected), equal_nan=True) + assert pc.round_to_multiple(values, multiple, + "half_towards_infinity") == result + + for multiple in [0, -2, pa.scalar(-10.4)]: + with pytest.raises(pa.ArrowInvalid, + match="Rounding multiple must be positive"): + pc.round_to_multiple(values, multiple=multiple) + + for multiple in [object, 99999999999999999999999]: + with pytest.raises(TypeError, match="is not a valid multiple type"): + pc.round_to_multiple(values, multiple=multiple) + + +def test_round_binary(): + values = [123.456, 234.567, 345.678, 456.789, 123.456, 234.567, 345.678] + scales = pa.array([-3, -2, -1, 0, 1, 2, 3], pa.int32()) + expected = pa.array( + [0, 200, 350, 457, 123.5, 234.57, 345.678], pa.float64()) + assert pc.round_binary(values, scales) == expected + + expect_zero = pa.scalar(0, pa.float64()) + expect_inf = pa.scalar(10, pa.float64()) + scale = pa.scalar(-1, pa.int32()) + + assert pc.round_binary( + 5.0, scale, round_mode="half_towards_zero") == expect_zero + assert pc.round_binary( + 5.0, scale, round_mode="half_towards_infinity") == expect_inf + + +def test_is_null(): + arr = pa.array([1, 2, 3, None]) + result = arr.is_null() + expected = pa.array([False, False, False, True]) + assert result.equals(expected) + assert result.equals(pc.is_null(arr)) + result = arr.is_valid() + expected = pa.array([True, True, True, False]) + assert result.equals(expected) + assert result.equals(pc.is_valid(arr)) + + arr = pa.chunked_array([[1, 2], [3, None]]) + result = arr.is_null() + expected = pa.chunked_array([[False, False], [False, True]]) + assert result.equals(expected) + result = arr.is_valid() + expected = pa.chunked_array([[True, True], [True, False]]) + assert result.equals(expected) + + arr = pa.array([1, 2, 3, None, float("nan")]) + result = arr.is_null() + expected = pa.array([False, False, False, True, False]) + assert result.equals(expected) + + result = arr.is_null(nan_is_null=True) + expected = pa.array([False, False, False, True, True]) + assert result.equals(expected) + + +def test_is_nan(): + arr = pa.array([1, 2, 3, None, float("nan")]) + result = arr.is_nan() + expected = pa.array([False, False, False, None, True]) + assert result.equals(expected) + + arr = pa.array(["1", "2", None], type=pa.string()) + with pytest.raises( + ArrowNotImplementedError, match="has no kernel matching input types"): + _ = arr.is_nan() + + with pytest.raises( + ArrowNotImplementedError, match="has no kernel matching input types"): + arr = pa.array([b'a', b'bb', None], type=pa.large_binary()) + _ = arr.is_nan() + + +def test_fill_null(): + arr = pa.array([1, 2, None, 4], type=pa.int8()) + fill_value = pa.array([5], type=pa.int8()) + with pytest.raises(pa.ArrowInvalid, + match="Array arguments must all be the same length"): + arr.fill_null(fill_value) + + arr = pa.array([None, None, None, None], type=pa.null()) + fill_value = pa.scalar(None, type=pa.null()) + result = arr.fill_null(fill_value) + expected = pa.array([None, None, None, None]) + assert result.equals(expected) + + arr = pa.array(['a', 'bb', None]) + result = arr.fill_null('ccc') + expected = pa.array(['a', 'bb', 'ccc']) + assert result.equals(expected) + + arr = pa.array([b'a', b'bb', None], type=pa.large_binary()) + result = arr.fill_null('ccc') + expected = pa.array([b'a', b'bb', b'ccc'], type=pa.large_binary()) + assert result.equals(expected) + + arr = pa.array(['a', 'bb', None]) + result = arr.fill_null(None) + expected = pa.array(['a', 'bb', None]) + assert result.equals(expected) + + +@pytest.mark.parametrize('arrow_type', numerical_arrow_types) +def test_fill_null_array(arrow_type): + arr = pa.array([1, 2, None, 4], type=arrow_type) + fill_value = pa.scalar(5, type=arrow_type) + result = arr.fill_null(fill_value) + expected = pa.array([1, 2, 5, 4], type=arrow_type) + assert result.equals(expected) + + # Implicit conversions + result = arr.fill_null(5) + assert result.equals(expected) + + # ARROW-9451: Unsigned integers allow this for some reason + if not pa.types.is_unsigned_integer(arr.type): + with pytest.raises((ValueError, TypeError)): + arr.fill_null('5') + + result = arr.fill_null(pa.scalar(5, type='int8')) + assert result.equals(expected) + + +@pytest.mark.parametrize('arrow_type', numerical_arrow_types) +def test_fill_null_chunked_array(arrow_type): + fill_value = pa.scalar(5, type=arrow_type) + arr = pa.chunked_array([pa.array([None, 2, 3, 4], type=arrow_type)]) + result = arr.fill_null(fill_value) + expected = pa.chunked_array([pa.array([5, 2, 3, 4], type=arrow_type)]) + assert result.equals(expected) + + arr = pa.chunked_array([ + pa.array([1, 2], type=arrow_type), + pa.array([], type=arrow_type), + pa.array([None, 4], type=arrow_type) + ]) + expected = pa.chunked_array([ + pa.array([1, 2], type=arrow_type), + pa.array([], type=arrow_type), + pa.array([5, 4], type=arrow_type) + ]) + result = arr.fill_null(fill_value) + assert result.equals(expected) + + # Implicit conversions + result = arr.fill_null(5) + assert result.equals(expected) + + result = arr.fill_null(pa.scalar(5, type='int8')) + assert result.equals(expected) + + +def test_fill_null_windows_regression(): + # Regression test for GH-47234, which was failing due to a MSVC compiler bug + # (possibly https://developercommunity.visualstudio.com/t/10912292 + # or https://developercommunity.visualstudio.com/t/10945478) + arr = pa.array([True, False, False, False, False, None]) + s = pa.scalar(True, type=pa.bool_()) + + result = pa.compute.call_function("coalesce", [arr, s]) + result.validate(full=True) + expected = pa.array([True, False, False, False, False, True]) + assert result.equals(expected) + + for ty in [pa.int8(), pa.int16(), pa.int32(), pa.int64()]: + arr = pa.array([1, 2, 3, 4, 5, None], type=ty) + s = pa.scalar(42, type=ty) + + result = pa.compute.call_function("coalesce", [arr, s]) + result.validate(full=True) + expected = pa.array([1, 2, 3, 4, 5, 42], type=ty) + assert result.equals(expected) + + +def test_logical(): + a = pa.array([True, False, False, None]) + b = pa.array([True, True, False, True]) + + assert pc.and_(a, b) == pa.array([True, False, False, None]) + assert pc.and_kleene(a, b) == pa.array([True, False, False, None]) + + assert pc.or_(a, b) == pa.array([True, True, False, None]) + assert pc.or_kleene(a, b) == pa.array([True, True, False, True]) + + assert pc.xor(a, b) == pa.array([False, True, False, None]) + + assert pc.invert(a) == pa.array([False, True, True, None]) + + +def test_dictionary_decode(): + array = pa.array(["a", "a", "b", "c", "b"]) + dictionary_array = array.dictionary_encode() + dictionary_array_decode = pc.dictionary_decode(dictionary_array) + + assert array != dictionary_array + + assert array == dictionary_array_decode + assert array == pc.dictionary_decode(array) + assert pc.dictionary_encode(dictionary_array) == dictionary_array + + +def test_cast(): + arr = pa.array([1, 2, 3, 4], type='int64') + options = pc.CastOptions(pa.int8()) + + with pytest.raises(TypeError): + pc.cast(arr, target_type=None) + + with pytest.raises(ValueError): + pc.cast(arr, 'int32', options=options) + + with pytest.raises(ValueError): + pc.cast(arr, safe=True, options=options) + + assert pc.cast(arr, options=options) == pa.array( + [1, 2, 3, 4], type='int8') + + arr = pa.array([2 ** 63 - 1], type='int64') + allow_overflow_options = pc.CastOptions( + pa.int32(), allow_int_overflow=True) + + with pytest.raises(pa.ArrowInvalid): + pc.cast(arr, 'int32') + + assert pc.cast(arr, 'int32', safe=False) == pa.array([-1], type='int32') + + assert pc.cast(arr, options=allow_overflow_options) == pa.array( + [-1], type='int32') + + arr = pa.array( + [datetime.datetime(2010, 1, 1), datetime.datetime(2015, 1, 1)]) + expected = pa.array([1262304000000, 1420070400000], type='timestamp[ms]') + assert pc.cast(arr, 'timestamp[ms]') == expected + + arr = pa.array([[1, 2], [3, 4, 5]], type=pa.large_list(pa.int8())) + expected = pa.array([["1", "2"], ["3", "4", "5"]], + type=pa.list_(pa.utf8())) + assert pc.cast(arr, expected.type) == expected + + +@pytest.mark.parametrize('value_type', [pa.date32(), pa.date64()]) +def test_identity_cast_dates(value_type): + dt = datetime.date(1990, 3, 1) + + arr = pa.array([dt], type=value_type) + assert pc.cast(arr, value_type) == arr + + +@pytest.mark.parametrize('value_type', numerical_arrow_types) +def test_fsl_to_fsl_cast(value_type): + # Different field name and different type. + cast_type = pa.list_(pa.field("element", value_type), 2) + + dtype = pa.int32() + type = pa.list_(pa.field("values", dtype), 2) + + fsl = pa.FixedSizeListArray.from_arrays( + pa.array([1, 2, 3, 4, 5, 6], type=dtype), type=type) + assert cast_type == fsl.cast(cast_type).type + + # Different field name and different type (with null values). + fsl = pa.FixedSizeListArray.from_arrays( + pa.array([1, None, None, 4, 5, 6], type=dtype), type=type) + assert cast_type == fsl.cast(cast_type).type + + # Null FSL type. + dtype = pa.null() + type = pa.list_(pa.field("values", dtype), 2) + fsl = pa.FixedSizeListArray.from_arrays( + pa.array([None, None, None, None, None, None], type=dtype), type=type) + assert cast_type == fsl.cast(cast_type).type + + # Different sized FSL + cast_type = pa.list_(pa.field("element", value_type), 3) + err_msg = 'Size of FixedSizeList is not the same.' + with pytest.raises(pa.lib.ArrowTypeError, match=err_msg): + fsl.cast(cast_type) + + +DecimalTypeTraits = namedtuple('DecimalTypeTraits', + ('name', 'factory', 'max_precision')) + +FloatToDecimalCase = namedtuple('FloatToDecimalCase', + ('precision', 'scale', 'float_val')) + +decimal_type_traits = [DecimalTypeTraits('decimal32', pa.decimal32, 9), + DecimalTypeTraits('decimal64', pa.decimal64, 18), + DecimalTypeTraits('decimal128', pa.decimal128, 38), + DecimalTypeTraits('decimal256', pa.decimal256, 76)] + + +def largest_scaled_float_not_above(val, scale): + """ + Find the largest float f such as `f * 10**scale <= val` + """ + assert val >= 0 + assert scale >= 0 + float_val = float(val) / 10**scale + if float_val * 10**scale > val: + # Take the float just below... it *should* satisfy + float_val = np.nextafter(float_val, 0.0) + if float_val * 10**scale > val: + float_val = np.nextafter(float_val, 0.0) + assert float_val * 10**scale <= val + return float_val + + +def scaled_float(int_val, scale): + """ + Return a float representation (possibly approximate) of `int_val**-scale` + """ + assert isinstance(int_val, int) + unscaled = decimal.Decimal(int_val) + scaled = unscaled.scaleb(-scale) + float_val = float(scaled) + return float_val + + +def integral_float_to_decimal_cast_cases(float_ty, max_precision): + """ + Return FloatToDecimalCase instances with integral values. + """ + mantissa_digits = 16 + for precision in range(1, max_precision, 3): + for scale in range(0, precision, 2): + yield FloatToDecimalCase(precision, scale, 0.0) + yield FloatToDecimalCase(precision, scale, 1.0) + epsilon = 10**max(precision - mantissa_digits, scale) + abs_maxval = largest_scaled_float_not_above( + 10**precision - epsilon, scale) + yield FloatToDecimalCase(precision, scale, abs_maxval) + + +def real_float_to_decimal_cast_cases(float_ty, max_precision): + """ + Return FloatToDecimalCase instances with real values. + """ + mantissa_digits = 16 + for precision in range(1, max_precision, 3): + for scale in range(0, precision, 2): + epsilon = 2 * 10**max(precision - mantissa_digits, 0) + abs_minval = largest_scaled_float_not_above(epsilon, scale) + abs_maxval = largest_scaled_float_not_above( + 10**precision - epsilon, scale) + yield FloatToDecimalCase(precision, scale, abs_minval) + yield FloatToDecimalCase(precision, scale, abs_maxval) + + +def random_float_to_decimal_cast_cases(float_ty, max_precision): + """ + Return random-generated FloatToDecimalCase instances. + """ + r = random.Random(42) + for precision in range(1, max_precision, 6): + for scale in range(0, precision, 4): + for i in range(20): + unscaled = r.randrange(0, 10**precision) + float_val = scaled_float(unscaled, scale) + assert float_val * 10**scale < 10**precision + yield FloatToDecimalCase(precision, scale, float_val) + + +def check_cast_float_to_decimal(float_ty, float_val, decimal_ty, decimal_ctx, + max_precision): + # Use the Python decimal module to build the expected result + # using the right precision + decimal_ctx.prec = decimal_ty.precision + decimal_ctx.rounding = decimal.ROUND_HALF_EVEN + expected = decimal_ctx.create_decimal_from_float(float_val) + # Round `expected` to `scale` digits after the decimal point + expected = expected.quantize(decimal.Decimal(1).scaleb(-decimal_ty.scale)) + s = pa.scalar(float_val, type=float_ty) + actual = pc.cast(s, decimal_ty).as_py() + if actual != expected: + # Allow the last digit to vary. The tolerance is higher for + # very high precisions as rounding errors can accumulate in + # the iterative algorithm (GH-35576). + diff_digits = abs(actual - expected) * 10**decimal_ty.scale + limit = 2 if decimal_ty.precision < max_precision - 2 else 4 + assert diff_digits <= limit, ( + f"float_val = {float_val!r}, precision={decimal_ty.precision}, " + f"expected = {expected!r}, actual = {actual!r}, " + f"diff_digits = {diff_digits!r}") + + +# Cannot test float32 as case generators above assume float64 +@pytest.mark.numpy +@pytest.mark.parametrize('float_ty', [pa.float64()], ids=str) +@pytest.mark.parametrize('decimal_ty', decimal_type_traits, + ids=lambda v: v.name) +@pytest.mark.parametrize('case_generator', + [integral_float_to_decimal_cast_cases, + real_float_to_decimal_cast_cases, + random_float_to_decimal_cast_cases], + ids=['integrals', 'reals', 'random']) +def test_cast_float_to_decimal(float_ty, decimal_ty, case_generator): + with decimal.localcontext() as ctx: + for case in case_generator(float_ty, decimal_ty.max_precision): + check_cast_float_to_decimal( + float_ty, case.float_val, + decimal_ty.factory(case.precision, case.scale), + ctx, decimal_ty.max_precision) + + +@pytest.mark.numpy +@pytest.mark.parametrize('float_ty', [pa.float32(), pa.float64()], ids=str) +@pytest.mark.parametrize('decimal_traits', decimal_type_traits, + ids=lambda v: v.name) +def test_cast_float_to_decimal_random(float_ty, decimal_traits): + """ + Test float-to-decimal conversion against exactly generated values. + """ + r = random.Random(43) + np_float_ty = { + pa.float32(): np.float32, + pa.float64(): np.float64, + }[float_ty] + mantissa_bits = { + pa.float32(): 24, + pa.float64(): 53, + }[float_ty] + float_exp_min, float_exp_max = { + pa.float32(): (-126, 127), + pa.float64(): (-1022, 1023), + }[float_ty] + mantissa_digits = math.floor(math.log10(2**mantissa_bits)) + max_precision = decimal_traits.max_precision + + # For example, decimal32 <-> float64 + if max_precision < mantissa_digits: + mantissa_bits = math.floor(math.log2(10**max_precision)) + mantissa_digits = math.floor(math.log10(2**mantissa_bits)) + + with decimal.localcontext() as ctx: + precision = mantissa_digits + ctx.prec = precision + # The scale must be chosen so as + # 1) it's within bounds for the decimal type + # 2) the floating point exponent is within bounds + min_scale = max(-max_precision, + precision + math.ceil(math.log10(2**float_exp_min))) + max_scale = min(max_precision, + math.floor(math.log10(2**float_exp_max))) + for scale in range(min_scale, max_scale): + decimal_ty = decimal_traits.factory(precision, scale) + # We want to random-generate a float from its mantissa bits + # and exponent, and compute the expected value in the + # decimal domain. The float exponent has to ensure the + # expected value doesn't overflow and doesn't lose precision. + float_exp = (-mantissa_bits + + math.floor(math.log2(10**(precision - scale)))) + assert float_exp_min <= float_exp <= float_exp_max + for i in range(5): + mantissa = r.randrange(0, 2**mantissa_bits) + float_val = np.ldexp(np_float_ty(mantissa), float_exp) + assert isinstance(float_val, np_float_ty) + # Make sure we compute the exact expected value and + # round by half-to-even when converting to the expected precision. + if float_exp >= 0: + expected = decimal.Decimal(mantissa) * 2**float_exp + else: + expected = decimal.Decimal(mantissa) / 2**-float_exp + expected_as_int = round(expected.scaleb(scale)) + actual = pc.cast( + pa.scalar(float_val, type=float_ty), decimal_ty).as_py() + actual_as_int = round(actual.scaleb(scale)) + # We allow for a minor rounding error between expected and actual + assert abs(actual_as_int - expected_as_int) <= 1 + + +def test_strptime(): + arr = pa.array(["5/1/2020", None, "12/13/1900"]) + + got = pc.strptime(arr, format='%m/%d/%Y', unit='s') + expected = pa.array( + [datetime.datetime(2020, 5, 1), None, datetime.datetime(1900, 12, 13)], + type=pa.timestamp('s')) + assert got == expected + # Positional format + assert pc.strptime(arr, '%m/%d/%Y', unit='s') == got + + expected = pa.array([datetime.datetime(2020, 1, 5), None, None], + type=pa.timestamp('s')) + got = pc.strptime(arr, format='%d/%m/%Y', unit='s', error_is_null=True) + assert got == expected + + with pytest.raises(pa.ArrowInvalid, + match="Failed to parse string: '5/1/2020'"): + pc.strptime(arr, format='%Y-%m-%d', unit='s', error_is_null=False) + + with pytest.raises(pa.ArrowInvalid, + match="Failed to parse string: '5/1/2020'"): + pc.strptime(arr, format='%Y-%m-%d', unit='s') + + got = pc.strptime(arr, format='%Y-%m-%d', unit='s', error_is_null=True) + assert got == pa.array([None, None, None], type=pa.timestamp('s')) + + +@pytest.mark.pandas +@pytest.mark.timezone_data +def test_strftime(): + times = ["2018-03-10 09:00", "2038-01-31 12:23", None] + timezones = ["CET", "UTC", "Europe/Ljubljana"] + + formats = ["%a", "%A", "%w", "%d", "%b", "%B", "%m", "%y", "%Y", "%H", "%I", + "%p", "%M", "%z", "%Z", "%j", "%U", "%W", "%%", "%G", "%V", "%u"] + if sys.platform != "win32": + # Locale-dependent formats don't match on Windows + formats.extend(["%c", "%x", "%X"]) + + for timezone in timezones: + ts = pd.to_datetime(times).tz_localize(timezone) + for unit in ["s", "ms", "us", "ns"]: + tsa = pa.array(ts, type=pa.timestamp(unit, timezone)) + for fmt in formats: + options = pc.StrftimeOptions(fmt) + result = pc.strftime(tsa, options=options) + # cast to the same type as result to ignore string vs large_string + expected = pa.array(ts.strftime(fmt)).cast(result.type) + assert result.equals(expected) + + fmt = "%Y-%m-%dT%H:%M:%S" + + # Default format + tsa = pa.array(ts, type=pa.timestamp("s", timezone)) + result = pc.strftime(tsa, options=pc.StrftimeOptions()) + expected = pa.array(ts.strftime(fmt)).cast(result.type) + assert result.equals(expected) + + # Default format plus timezone + tsa = pa.array(ts, type=pa.timestamp("s", timezone)) + result = pc.strftime(tsa, options=pc.StrftimeOptions(fmt + "%Z")) + expected = pa.array(ts.strftime(fmt + "%Z")).cast(result.type) + assert result.equals(expected) + + # Pandas %S is equivalent to %S in arrow for unit="s" + tsa = pa.array(ts, type=pa.timestamp("s", timezone)) + options = pc.StrftimeOptions("%S") + result = pc.strftime(tsa, options=options) + expected = pa.array(ts.strftime("%S")).cast(result.type) + assert result.equals(expected) + + # Pandas %S.%f is equivalent to %S in arrow for unit="us" + tsa = pa.array(ts, type=pa.timestamp("us", timezone)) + options = pc.StrftimeOptions("%S") + result = pc.strftime(tsa, options=options) + expected = pa.array(ts.strftime("%S.%f")).cast(result.type) + assert result.equals(expected) + + # Test setting locale + tsa = pa.array(ts, type=pa.timestamp("s", timezone)) + options = pc.StrftimeOptions(fmt, locale="C") + result = pc.strftime(tsa, options=options) + expected = pa.array(ts.strftime(fmt)).cast(result.type) + assert result.equals(expected) + + # Test timestamps without timezone + fmt = "%Y-%m-%dT%H:%M:%S" + ts = pd.to_datetime(times) + tsa = pa.array(ts, type=pa.timestamp("s")) + result = pc.strftime(tsa, options=pc.StrftimeOptions(fmt)) + expected = pa.array(ts.strftime(fmt)).cast(result.type) + + # Positional format + assert pc.strftime(tsa, fmt) == result + + assert result.equals(expected) + with pytest.raises(pa.ArrowInvalid, + match="Timezone not present, cannot convert to string"): + pc.strftime(tsa, options=pc.StrftimeOptions(fmt + "%Z")) + with pytest.raises(pa.ArrowInvalid, + match="Timezone not present, cannot convert to string"): + pc.strftime(tsa, options=pc.StrftimeOptions(fmt + "%z")) + + +def _check_datetime_components(timestamps, timezone=None): + from pyarrow.vendored.version import Version + + ts = pd.to_datetime(timestamps).tz_localize( + "UTC").tz_convert(timezone).to_series() + tsa = pa.array(ts, pa.timestamp("ns", tz=timezone)) + + subseconds = ((ts.dt.microsecond * 10 ** 3 + + ts.dt.nanosecond) * 10 ** -9).round(9) + iso_calendar_fields = [ + pa.field('iso_year', pa.int64()), + pa.field('iso_week', pa.int64()), + pa.field('iso_day_of_week', pa.int64()) + ] + + if Version(pd.__version__) < Version("1.1.0"): + # https://github.com/pandas-dev/pandas/issues/33206 + iso_year = ts.map(lambda x: x.isocalendar()[0]).astype("int64") + iso_week = ts.map(lambda x: x.isocalendar()[1]).astype("int64") + iso_day = ts.map(lambda x: x.isocalendar()[2]).astype("int64") + else: + # Casting is required because pandas isocalendar returns int32 + # while arrow isocalendar returns int64. + iso_year = ts.dt.isocalendar()["year"].astype("int64") + iso_week = ts.dt.isocalendar()["week"].astype("int64") + iso_day = ts.dt.isocalendar()["day"].astype("int64") + + iso_calendar = pa.StructArray.from_arrays( + [iso_year, iso_week, iso_day], + fields=iso_calendar_fields) + + # Casting is required because pandas with 2.0.0 various numeric + # date/time attributes have dtype int32 (previously int64) + year = ts.dt.year.astype("int64") + month = ts.dt.month.astype("int64") + day = ts.dt.day.astype("int64") + dayofweek = ts.dt.dayofweek.astype("int64") + dayofyear = ts.dt.dayofyear.astype("int64") + quarter = ts.dt.quarter.astype("int64") + hour = ts.dt.hour.astype("int64") + minute = ts.dt.minute.astype("int64") + second = ts.dt.second.values.astype("int64") + microsecond = ts.dt.microsecond.astype("int64") + nanosecond = ts.dt.nanosecond.astype("int64") + + assert pc.year(tsa).equals(pa.array(year)) + assert pc.is_leap_year(tsa).equals(pa.array(ts.dt.is_leap_year)) + assert pc.month(tsa).equals(pa.array(month)) + assert pc.day(tsa).equals(pa.array(day)) + assert pc.day_of_week(tsa).equals(pa.array(dayofweek)) + assert pc.day_of_year(tsa).equals(pa.array(dayofyear)) + assert pc.iso_year(tsa).equals(pa.array(iso_year)) + assert pc.iso_week(tsa).equals(pa.array(iso_week)) + assert pc.iso_calendar(tsa).equals(iso_calendar) + assert pc.quarter(tsa).equals(pa.array(quarter)) + assert pc.hour(tsa).equals(pa.array(hour)) + assert pc.minute(tsa).equals(pa.array(minute)) + assert pc.second(tsa).equals(pa.array(second)) + assert pc.millisecond(tsa).equals(pa.array(microsecond // 10 ** 3)) + assert pc.microsecond(tsa).equals(pa.array(microsecond % 10 ** 3)) + assert pc.nanosecond(tsa).equals(pa.array(nanosecond)) + assert pc.subsecond(tsa).equals(pa.array(subseconds)) + assert pc.local_timestamp(tsa).equals(pa.array(ts.dt.tz_localize(None))) + + if ts.dt.tz: + if ts.dt.tz is datetime.timezone.utc: + # datetime with utc returns None for dst() + is_dst = [False] * len(ts) + else: + is_dst = ts.apply(lambda x: x.dst().seconds > 0) + assert pc.is_dst(tsa).equals(pa.array(is_dst)) + + day_of_week_options = pc.DayOfWeekOptions( + count_from_zero=False, week_start=1) + assert pc.day_of_week(tsa, options=day_of_week_options).equals( + pa.array(dayofweek + 1)) + + week_options = pc.WeekOptions( + week_starts_monday=True, count_from_zero=False, + first_week_is_fully_in_year=False) + assert pc.week(tsa, options=week_options).equals(pa.array(iso_week)) + + +@pytest.mark.pandas +def test_extract_datetime_components(request): + timestamps = ["1970-01-01T00:00:59.123456789", + "2000-02-29T23:23:23.999999999", + "2033-05-18T03:33:20.000000000", + "2020-01-01T01:05:05.001", + "2019-12-31T02:10:10.002", + "2019-12-30T03:15:15.003", + "2009-12-31T04:20:20.004132", + "2010-01-01T05:25:25.005321", + "2010-01-03T06:30:30.006163", + "2010-01-04T07:35:35.0", + "2006-01-01T08:40:40.0", + "2005-12-31T09:45:45.0", + "2008-12-28T00:00:00.0", + "2008-12-29T00:00:00.0", + "2012-01-01T01:02:03.0"] + timezones = ["UTC", "America/Chicago", "Asia/Kolkata", + "Etc/GMT-4", "Etc/GMT+4", "Australia/Broken_Hill"] + + # Test timezone naive timestamp array + _check_datetime_components(timestamps) + + # Test timezone aware timestamp array + if not request.config.pyarrow.is_enabled["timezone_data"]: + pytest.skip('Timezone database is not installed on Windows') + else: + for timezone in timezones: + _check_datetime_components(timestamps, timezone) + + +def test_offset_timezone(): + arr = pc.strptime(["2012-12-12T12:12:12"], format="%Y-%m-%dT%H:%M:%S", unit="s") + zoned_arr = arr.cast(pa.timestamp("s", tz="+05:30")) + assert pc.hour(zoned_arr)[0].as_py() == 17 + assert pc.minute(zoned_arr)[0].as_py() == 42 + + +@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"]) +def test_iso_calendar_longer_array(unit): + # https://github.com/apache/arrow/issues/38655 + # ensure correct result for array length > 32 + arr = pa.array([datetime.datetime(2022, 1, 2, 9)]*50, pa.timestamp(unit)) + result = pc.iso_calendar(arr) + expected = pa.StructArray.from_arrays( + [[2021]*50, [52]*50, [7]*50], + names=['iso_year', 'iso_week', 'iso_day_of_week'] + ) + assert result.equals(expected) + + +@pytest.mark.pandas +@pytest.mark.timezone_data +def test_assume_timezone(): + ts_type = pa.timestamp("ns") + timestamps = pd.to_datetime(["1970-01-01T00:00:59.123456789", + "2000-02-29T23:23:23.999999999", + "2033-05-18T03:33:20.000000000", + "2020-01-01T01:05:05.001", + "2019-12-31T02:10:10.002", + "2019-12-30T03:15:15.003", + "2009-12-31T04:20:20.004132", + "2010-01-01T05:25:25.005321", + "2010-01-03T06:30:30.006163", + "2010-01-04T07:35:35.0", + "2006-01-01T08:40:40.0", + "2005-12-31T09:45:45.0", + "2008-12-28T00:00:00.0", + "2008-12-29T00:00:00.0", + "2012-01-01T01:02:03.0"]) + nonexistent = pd.to_datetime(["2015-03-29 02:30:00", + "2015-03-29 03:30:00"]) + ambiguous = pd.to_datetime(["2018-10-28 01:20:00", + "2018-10-28 02:36:00", + "2018-10-28 03:46:00"]) + ambiguous_array = pa.array(ambiguous, type=ts_type) + nonexistent_array = pa.array(nonexistent, type=ts_type) + + for timezone in ["UTC", "America/Chicago", "Asia/Kolkata"]: + options = pc.AssumeTimezoneOptions(timezone) + ta = pa.array(timestamps, type=ts_type) + expected = timestamps.tz_localize(timezone) + result = pc.assume_timezone(ta, options=options) + assert result.equals(pa.array(expected)) + result = pc.assume_timezone(ta, timezone) # Positional option + assert result.equals(pa.array(expected)) + + ta_zoned = pa.array(timestamps, type=pa.timestamp("ns", timezone)) + with pytest.raises(pa.ArrowInvalid, match="already have a timezone:"): + pc.assume_timezone(ta_zoned, options=options) + + invalid_options = pc.AssumeTimezoneOptions("Europe/Brusselsss") + with pytest.raises(ValueError, match="not found in timezone database"): + pc.assume_timezone(ta, options=invalid_options) + + timezone = "Europe/Brussels" + + options_nonexistent_raise = pc.AssumeTimezoneOptions(timezone) + options_nonexistent_earliest = pc.AssumeTimezoneOptions( + timezone, ambiguous="raise", nonexistent="earliest") + options_nonexistent_latest = pc.AssumeTimezoneOptions( + timezone, ambiguous="raise", nonexistent="latest") + + with pytest.raises(ValueError, + match="Timestamp doesn't exist in " + f"timezone '{timezone}'"): + pc.assume_timezone(nonexistent_array, + options=options_nonexistent_raise) + + expected = pa.array(nonexistent.tz_localize( + timezone, nonexistent="shift_forward")) + result = pc.assume_timezone( + nonexistent_array, options=options_nonexistent_latest) + expected.equals(result) + + expected = pa.array(nonexistent.tz_localize( + timezone, nonexistent="shift_backward")) + result = pc.assume_timezone( + nonexistent_array, options=options_nonexistent_earliest) + expected.equals(result) + + options_ambiguous_raise = pc.AssumeTimezoneOptions(timezone) + options_ambiguous_latest = pc.AssumeTimezoneOptions( + timezone, ambiguous="latest", nonexistent="raise") + options_ambiguous_earliest = pc.AssumeTimezoneOptions( + timezone, ambiguous="earliest", nonexistent="raise") + + with pytest.raises(ValueError, + match="Timestamp is ambiguous in " + f"timezone '{timezone}'"): + pc.assume_timezone(ambiguous_array, options=options_ambiguous_raise) + + expected = ambiguous.tz_localize(timezone, ambiguous=[True, True, True]) + result = pc.assume_timezone( + ambiguous_array, options=options_ambiguous_earliest) + result.equals(pa.array(expected)) + + expected = ambiguous.tz_localize(timezone, ambiguous=[False, False, False]) + result = pc.assume_timezone( + ambiguous_array, options=options_ambiguous_latest) + result.equals(pa.array(expected)) + + +def _check_temporal_rounding(ts, values, unit): + unit_shorthand = { + "nanosecond": "ns", + "microsecond": "us", + "millisecond": "ms", + "second": "s", + "minute": "min", + "hour": "h", + "day": "D" + } + greater_unit = { + "nanosecond": "us", + "microsecond": "ms", + "millisecond": "s", + "second": "min", + "minute": "h", + "hour": "D", + } + ta = pa.array(ts) + + for value in values: + frequency = str(value) + unit_shorthand[unit] + options = pc.RoundTemporalOptions(value, unit) + + result = pc.ceil_temporal(ta, options=options).to_pandas() + expected = ts.dt.ceil(frequency) + np.testing.assert_array_equal(result, expected) + + result = pc.floor_temporal(ta, options=options).to_pandas() + expected = ts.dt.floor(frequency) + np.testing.assert_array_equal(result, expected) + + result = pc.round_temporal(ta, options=options).to_pandas() + expected = ts.dt.round(frequency) + np.testing.assert_array_equal(result, expected) + + # Check rounding with calendar_based_origin=True. + # Note: rounding to month is not supported in Pandas so we can't + # approximate this functionality and exclude unit == "day". + if unit != "day": + options = pc.RoundTemporalOptions( + value, unit, calendar_based_origin=True) + origin = ts.dt.floor(greater_unit[unit]) + + if ta.type.tz is None: + result = pc.ceil_temporal(ta, options=options).to_pandas() + expected = (ts - origin).dt.ceil(frequency) + origin + np.testing.assert_array_equal(result, expected) + + result = pc.floor_temporal(ta, options=options).to_pandas() + expected = (ts - origin).dt.floor(frequency) + origin + np.testing.assert_array_equal(result, expected) + + result = pc.round_temporal(ta, options=options).to_pandas() + expected = (ts - origin).dt.round(frequency) + origin + np.testing.assert_array_equal(result, expected) + + # Check RoundTemporalOptions partial defaults + if unit == "day": + result = pc.ceil_temporal(ta, multiple=value).to_pandas() + expected = ts.dt.ceil(frequency) + np.testing.assert_array_equal(result, expected) + + result = pc.floor_temporal(ta, multiple=value).to_pandas() + expected = ts.dt.floor(frequency) + np.testing.assert_array_equal(result, expected) + + result = pc.round_temporal(ta, multiple=value).to_pandas() + expected = ts.dt.round(frequency) + np.testing.assert_array_equal(result, expected) + + # We naively test ceil_is_strictly_greater by adding time unit multiple + # to regular ceiled timestamp if it is equal to the original timestamp. + # This does not work if timestamp is zoned since our logic will not + # account for DST jumps. + if ta.type.tz is None: + options = pc.RoundTemporalOptions( + value, unit, ceil_is_strictly_greater=True) + result = pc.ceil_temporal(ta, options=options) + expected = ts.dt.ceil(frequency) + + expected = np.where( + expected == ts, + expected + pd.Timedelta(value, unit_shorthand[unit]), + expected) + np.testing.assert_array_equal(result, expected) + + # Check RoundTemporalOptions defaults + if unit == "day": + frequency = "1D" + + result = pc.ceil_temporal(ta).to_pandas() + expected = ts.dt.ceil(frequency) + np.testing.assert_array_equal(result, expected) + + result = pc.floor_temporal(ta).to_pandas() + expected = ts.dt.floor(frequency) + np.testing.assert_array_equal(result, expected) + + result = pc.round_temporal(ta).to_pandas() + expected = ts.dt.round(frequency) + np.testing.assert_array_equal(result, expected) + + +@pytest.mark.timezone_data +@pytest.mark.parametrize('unit', ("nanosecond", "microsecond", "millisecond", + "second", "minute", "hour", "day")) +@pytest.mark.pandas +def test_round_temporal(unit): + values = (1, 2, 3, 4, 5, 6, 7, 10, 15, 24, 60, 250, 500, 750) + timestamps = [ + "1923-07-07 08:52:35.203790336", + "1931-03-17 10:45:00.641559040", + "1932-06-16 01:16:42.911994368", + "1941-05-27 11:46:43.822831872", + "1943-12-14 07:32:05.424766464", + "1954-04-12 04:31:50.699881472", + "1966-02-12 17:41:28.693282560", + "1967-02-26 05:56:46.922376960", + "1975-11-01 10:55:37.016146432", + "1982-01-21 18:43:44.517366784", + "1992-01-01 00:00:00.100000000", + "1999-12-04 05:55:34.794991104", + "2026-10-26 08:39:00.316686848"] + ts = pd.Series([pd.Timestamp(x, unit="ns") for x in timestamps]) + _check_temporal_rounding(ts, values, unit) + + timezones = ["Asia/Kolkata", "America/New_York", "Etc/GMT-4", "Etc/GMT+4", + "Europe/Brussels", "Pacific/Marquesas", "America/Chicago", "UTC"] + + for timezone in timezones: + ts_zoned = ts.dt.tz_localize("UTC").dt.tz_convert(timezone) + _check_temporal_rounding(ts_zoned, values, unit) + + +def test_count(): + arr = pa.array([1, 2, 3, None, None]) + assert pc.count(arr).as_py() == 3 + assert pc.count(arr, mode='only_valid').as_py() == 3 + assert pc.count(arr, mode='only_null').as_py() == 2 + assert pc.count(arr, mode='all').as_py() == 5 + assert pc.count(arr, 'all').as_py() == 5 + + with pytest.raises(ValueError, + match='"something else" is not a valid count mode'): + pc.count(arr, 'something else') + + +def test_index(): + arr = pa.array([0, 1, None, 3, 4], type=pa.int64()) + assert pc.index(arr, pa.scalar(0)).as_py() == 0 + assert pc.index(arr, pa.scalar(2, type=pa.int8())).as_py() == -1 + assert pc.index(arr, 4).as_py() == 4 + assert arr.index(3, start=2).as_py() == 3 + assert arr.index(None).as_py() == -1 + + arr = pa.chunked_array([[1, 2], [1, 3]], type=pa.int64()) + assert arr.index(1).as_py() == 0 + assert arr.index(1, start=2).as_py() == 2 + assert arr.index(1, start=1, end=2).as_py() == -1 + + +def check_partition_nth(data, indices, pivot, null_placement): + indices = indices.to_pylist() + assert len(indices) == len(data) + assert sorted(indices) == list(range(len(data))) + until_pivot = [data[indices[i]] for i in range(pivot)] + after_pivot = [data[indices[i]] for i in range(pivot, len(data))] + p = data[indices[pivot]] + if p is None: + if null_placement == "at_start": + assert all(v is None for v in until_pivot) + else: + assert all(v is None for v in after_pivot) + else: + if null_placement == "at_start": + assert all(v is None or v <= p for v in until_pivot) + assert all(v >= p for v in after_pivot) + else: + assert all(v <= p for v in until_pivot) + assert all(v is None or v >= p for v in after_pivot) + + +def test_partition_nth(): + data = list(range(100, 140)) + random.shuffle(data) + pivot = 10 + indices = pc.partition_nth_indices(data, pivot=pivot) + check_partition_nth(data, indices, pivot, "at_end") + # Positional pivot argument + assert pc.partition_nth_indices(data, pivot) == indices + + with pytest.raises( + ValueError, + match="'partition_nth_indices' cannot be called without options"): + pc.partition_nth_indices(data) + + +def test_partition_nth_null_placement(): + data = list(range(10)) + [None] * 10 + random.shuffle(data) + + for pivot in (0, 7, 13, 19): + for null_placement in ("at_start", "at_end"): + indices = pc.partition_nth_indices(data, pivot=pivot, + null_placement=null_placement) + check_partition_nth(data, indices, pivot, null_placement) + + +def test_select_k_array(): + def validate_select_k(select_k_indices, arr, order, stable_sort=False): + sorted_indices = pc.sort_indices(arr, sort_keys=[("dummy", order)]) + head_k_indices = sorted_indices.slice(0, len(select_k_indices)) + if stable_sort: + assert select_k_indices == head_k_indices + else: + expected = pc.take(arr, head_k_indices) + actual = pc.take(arr, select_k_indices) + assert actual == expected + + arr = pa.array([1, 2, None, 0]) + for k in [0, 2, 4]: + for order in ["descending", "ascending"]: + result = pc.select_k_unstable( + arr, k=k, sort_keys=[("dummy", order)]) + validate_select_k(result, arr, order) + + result = pc.top_k_unstable(arr, k=k) + validate_select_k(result, arr, "descending") + + result = pc.bottom_k_unstable(arr, k=k) + validate_select_k(result, arr, "ascending") + + result = pc.select_k_unstable( + arr, options=pc.SelectKOptions( + k=2, sort_keys=[("dummy", "descending")]) + ) + validate_select_k(result, arr, "descending") + + result = pc.select_k_unstable( + arr, options=pc.SelectKOptions(k=2, sort_keys=[("dummy", "ascending")]) + ) + validate_select_k(result, arr, "ascending") + + # Position options + assert pc.select_k_unstable(arr, 2, + sort_keys=[("dummy", "ascending")]) == result + assert pc.select_k_unstable(arr, 2, [("dummy", "ascending")]) == result + + +def test_select_k_table(): + def validate_select_k(select_k_indices, tbl, sort_keys, stable_sort=False): + sorted_indices = pc.sort_indices(tbl, sort_keys=sort_keys) + head_k_indices = sorted_indices.slice(0, len(select_k_indices)) + if stable_sort: + assert select_k_indices == head_k_indices + else: + expected = pc.take(tbl, head_k_indices) + actual = pc.take(tbl, select_k_indices) + assert actual == expected + + table = pa.table({"a": [1, 2, 0], "b": [1, 0, 1]}) + for k in [0, 2, 4]: + result = pc.select_k_unstable( + table, k=k, sort_keys=[("a", "ascending")]) + validate_select_k(result, table, sort_keys=[("a", "ascending")]) + + result = pc.select_k_unstable( + table, k=k, sort_keys=[(pc.field("a"), "ascending"), ("b", "ascending")]) + validate_select_k( + result, table, sort_keys=[("a", "ascending"), ("b", "ascending")]) + + result = pc.top_k_unstable(table, k=k, sort_keys=["a"]) + validate_select_k(result, table, sort_keys=[("a", "descending")]) + + result = pc.bottom_k_unstable(table, k=k, sort_keys=["a", "b"]) + validate_select_k( + result, table, sort_keys=[("a", "ascending"), ("b", "ascending")]) + + with pytest.raises( + ValueError, + match="'select_k_unstable' cannot be called without options"): + pc.select_k_unstable(table) + + with pytest.raises(ValueError, + match="select_k_unstable requires a nonnegative `k`"): + pc.select_k_unstable(table, k=-1, sort_keys=[("a", "ascending")]) + + with pytest.raises(ValueError, + match="select_k_unstable requires a " + "non-empty `sort_keys`"): + pc.select_k_unstable(table, k=2, sort_keys=[]) + + with pytest.raises(ValueError, match="not a valid sort order"): + pc.select_k_unstable(table, k=k, sort_keys=[("a", "nonscending")]) + + with pytest.raises(ValueError, + match="Invalid sort key column: No match for.*unknown"): + pc.select_k_unstable(table, k=k, sort_keys=[("unknown", "ascending")]) + + +def test_array_sort_indices(): + arr = pa.array([1, 2, None, 0]) + result = pc.array_sort_indices(arr) + assert result.to_pylist() == [3, 0, 1, 2] + result = pc.array_sort_indices(arr, order="ascending") + assert result.to_pylist() == [3, 0, 1, 2] + result = pc.array_sort_indices(arr, order="descending") + assert result.to_pylist() == [1, 0, 3, 2] + result = pc.array_sort_indices(arr, order="descending", + null_placement="at_start") + assert result.to_pylist() == [2, 1, 0, 3] + result = pc.array_sort_indices(arr, "descending", + null_placement="at_start") + assert result.to_pylist() == [2, 1, 0, 3] + + with pytest.raises(ValueError, match="not a valid sort order"): + pc.array_sort_indices(arr, order="nonscending") + + +def test_sort_indices_array(): + arr = pa.array([1, 2, None, 0]) + result = pc.sort_indices(arr) + assert result.to_pylist() == [3, 0, 1, 2] + result = pc.sort_indices(arr, sort_keys=[("dummy", "ascending")]) + assert result.to_pylist() == [3, 0, 1, 2] + result = pc.sort_indices(arr, sort_keys=[("dummy", "descending")]) + assert result.to_pylist() == [1, 0, 3, 2] + result = pc.sort_indices(arr, sort_keys=[("dummy", "descending")], + null_placement="at_start") + assert result.to_pylist() == [2, 1, 0, 3] + # Positional `sort_keys` + result = pc.sort_indices(arr, [("dummy", "descending")], + null_placement="at_start") + assert result.to_pylist() == [2, 1, 0, 3] + # Using SortOptions + result = pc.sort_indices( + arr, options=pc.SortOptions(sort_keys=[("dummy", "descending")]) + ) + assert result.to_pylist() == [1, 0, 3, 2] + result = pc.sort_indices( + arr, options=pc.SortOptions(sort_keys=[("dummy", "descending")], + null_placement="at_start") + ) + assert result.to_pylist() == [2, 1, 0, 3] + + +def test_sort_indices_table(): + table = pa.table({"a": [1, 1, None, 0], "b": [1, 0, 0, 1]}) + + result = pc.sort_indices(table, sort_keys=[("a", "ascending")]) + assert result.to_pylist() == [3, 0, 1, 2] + result = pc.sort_indices(table, sort_keys=[(pc.field("a"), "ascending")], + null_placement="at_start") + assert result.to_pylist() == [2, 3, 0, 1] + + result = pc.sort_indices( + table, sort_keys=[("a", "descending"), ("b", "ascending")] + ) + assert result.to_pylist() == [1, 0, 3, 2] + result = pc.sort_indices( + table, sort_keys=[("a", "descending"), ("b", "ascending")], + null_placement="at_start" + ) + assert result.to_pylist() == [2, 1, 0, 3] + # Positional `sort_keys` + result = pc.sort_indices( + table, [("a", "descending"), ("b", "ascending")], + null_placement="at_start" + ) + assert result.to_pylist() == [2, 1, 0, 3] + + with pytest.raises(ValueError, match="Must specify one or more sort keys"): + pc.sort_indices(table) + + with pytest.raises(ValueError, + match="Invalid sort key column: No match for.*unknown"): + pc.sort_indices(table, sort_keys=[("unknown", "ascending")]) + + with pytest.raises(ValueError, match="not a valid sort order"): + pc.sort_indices(table, sort_keys=[("a", "nonscending")]) + + +def test_is_in(): + arr = pa.array([1, 2, None, 1, 2, 3]) + + result = pc.is_in(arr, value_set=pa.array([1, 3, None])) + assert result.to_pylist() == [True, False, True, True, False, True] + + result = pc.is_in(arr, value_set=pa.array([1, 3, None]), skip_nulls=True) + assert result.to_pylist() == [True, False, False, True, False, True] + + result = pc.is_in(arr, value_set=pa.array([1, 3])) + assert result.to_pylist() == [True, False, False, True, False, True] + + result = pc.is_in(arr, value_set=pa.array([1, 3]), skip_nulls=True) + assert result.to_pylist() == [True, False, False, True, False, True] + + +def test_index_in(): + arr = pa.array([1, 2, None, 1, 2, 3]) + + result = pc.index_in(arr, value_set=pa.array([1, 3, None])) + assert result.to_pylist() == [0, None, 2, 0, None, 1] + + result = pc.index_in(arr, value_set=pa.array([1, 3, None]), + skip_nulls=True) + assert result.to_pylist() == [0, None, None, 0, None, 1] + + result = pc.index_in(arr, value_set=pa.array([1, 3])) + assert result.to_pylist() == [0, None, None, 0, None, 1] + + result = pc.index_in(arr, value_set=pa.array([1, 3]), skip_nulls=True) + assert result.to_pylist() == [0, None, None, 0, None, 1] + + # Positional value_set + result = pc.index_in(arr, pa.array([1, 3]), skip_nulls=True) + assert result.to_pylist() == [0, None, None, 0, None, 1] + + +def test_quantile(): + arr = pa.array([1, 2, 3, 4]) + + result = pc.quantile(arr) + assert result.to_pylist() == [2.5] + + result = pc.quantile(arr, interpolation='lower') + assert result.to_pylist() == [2] + result = pc.quantile(arr, interpolation='higher') + assert result.to_pylist() == [3] + result = pc.quantile(arr, interpolation='nearest') + assert result.to_pylist() == [3] + result = pc.quantile(arr, interpolation='midpoint') + assert result.to_pylist() == [2.5] + result = pc.quantile(arr, interpolation='linear') + assert result.to_pylist() == [2.5] + + arr = pa.array([1, 2]) + + result = pc.quantile(arr, q=[0.25, 0.5, 0.75]) + assert result.to_pylist() == [1.25, 1.5, 1.75] + + result = pc.quantile(arr, q=[0.25, 0.5, 0.75], interpolation='lower') + assert result.to_pylist() == [1, 1, 1] + result = pc.quantile(arr, q=[0.25, 0.5, 0.75], interpolation='higher') + assert result.to_pylist() == [2, 2, 2] + result = pc.quantile(arr, q=[0.25, 0.5, 0.75], interpolation='midpoint') + assert result.to_pylist() == [1.5, 1.5, 1.5] + result = pc.quantile(arr, q=[0.25, 0.5, 0.75], interpolation='nearest') + assert result.to_pylist() == [1, 1, 2] + result = pc.quantile(arr, q=[0.25, 0.5, 0.75], interpolation='linear') + assert result.to_pylist() == [1.25, 1.5, 1.75] + + # Positional `q` + result = pc.quantile(arr, [0.25, 0.5, 0.75], interpolation='linear') + assert result.to_pylist() == [1.25, 1.5, 1.75] + + with pytest.raises(ValueError, match="Quantile must be between 0 and 1"): + pc.quantile(arr, q=1.1) + with pytest.raises(ValueError, match="not a valid quantile interpolation"): + pc.quantile(arr, interpolation='zzz') + + +def test_tdigest(): + arr = pa.array([1, 2, 3, 4]) + result = pc.tdigest(arr) + assert result.to_pylist() == [2.5] + + arr = pa.chunked_array([pa.array([1, 2]), pa.array([3, 4])]) + result = pc.tdigest(arr) + assert result.to_pylist() == [2.5] + + arr = pa.array([1, 2, 3, 4]) + result = pc.tdigest(arr, q=[0, 0.5, 1]) + assert result.to_pylist() == [1, 2.5, 4] + + arr = pa.chunked_array([pa.array([1, 2]), pa.array([3, 4])]) + result = pc.tdigest(arr, [0, 0.5, 1]) # positional `q` + assert result.to_pylist() == [1, 2.5, 4] + + +def test_fill_null_segfault(): + # ARROW-12672 + arr = pa.array([None], pa.bool_()).fill_null(False) + result = arr.cast(pa.int8()) + assert result == pa.array([0], pa.int8()) + + +def test_min_max_element_wise(): + arr1 = pa.array([1, 2, 3]) + arr2 = pa.array([3, 1, 2]) + arr3 = pa.array([2, 3, None]) + + result = pc.max_element_wise(arr1, arr2) + assert result == pa.array([3, 2, 3]) + result = pc.min_element_wise(arr1, arr2) + assert result == pa.array([1, 1, 2]) + + result = pc.max_element_wise(arr1, arr2, arr3) + assert result == pa.array([3, 3, 3]) + result = pc.min_element_wise(arr1, arr2, arr3) + assert result == pa.array([1, 1, 2]) + + # with specifying the option + result = pc.max_element_wise(arr1, arr3, skip_nulls=True) + assert result == pa.array([2, 3, 3]) + result = pc.min_element_wise(arr1, arr3, skip_nulls=True) + assert result == pa.array([1, 2, 3]) + result = pc.max_element_wise( + arr1, arr3, options=pc.ElementWiseAggregateOptions()) + assert result == pa.array([2, 3, 3]) + result = pc.min_element_wise( + arr1, arr3, options=pc.ElementWiseAggregateOptions()) + assert result == pa.array([1, 2, 3]) + + # not skipping nulls + result = pc.max_element_wise(arr1, arr3, skip_nulls=False) + assert result == pa.array([2, 3, None]) + result = pc.min_element_wise(arr1, arr3, skip_nulls=False) + assert result == pa.array([1, 2, None]) + + +@pytest.mark.numpy +@pytest.mark.parametrize('start', (1.25, 10.5, -10.5)) +@pytest.mark.parametrize('skip_nulls', (True, False)) +def test_cumulative_sum(start, skip_nulls): + # Exact tests (e.g., integral types) + start_int = int(start) + starts = [None, start_int, pa.scalar(start_int, type=pa.int8()), + pa.scalar(start_int, type=pa.int64())] + for strt in starts: + arrays = [ + pa.array([1, 2, 3]), + pa.array([0, None, 20, 30]), + pa.chunked_array([[0, None], [20, 30]]) + ] + expected_arrays = [ + pa.array([1, 3, 6]), + pa.array([0, None, 20, 50]) + if skip_nulls else pa.array([0, None, None, None]), + pa.chunked_array([[0, None, 20, 50]]) + if skip_nulls else pa.chunked_array([[0, None, None, None]]) + ] + for i, arr in enumerate(arrays): + result = pc.cumulative_sum(arr, start=strt, skip_nulls=skip_nulls) + # Add `start` offset to expected array before comparing + expected = pc.add(expected_arrays[i], strt if strt is not None + else 0) + assert result.equals(expected) + + starts = [None, start, pa.scalar(start, type=pa.float32()), + pa.scalar(start, type=pa.float64())] + for strt in starts: + arrays = [ + pa.array([1.125, 2.25, 3.03125]), + pa.array([1, np.nan, 2, -3, 4, 5]), + pa.array([1, np.nan, None, 3, None, 5]) + ] + expected_arrays = [ + np.array([1.125, 3.375, 6.40625]), + np.array([1, np.nan, np.nan, np.nan, np.nan, np.nan]), + np.array([1, np.nan, None, np.nan, None, np.nan]) + if skip_nulls else np.array([1, np.nan, None, None, None, None]) + ] + for i, arr in enumerate(arrays): + result = pc.cumulative_sum(arr, start=strt, skip_nulls=skip_nulls) + # Add `start` offset to expected array before comparing + expected = pc.add(expected_arrays[i], strt if strt is not None + else 0) + np.testing.assert_array_almost_equal(result.to_numpy( + zero_copy_only=False), expected.to_numpy(zero_copy_only=False)) + + for strt in ['a', pa.scalar('arrow'), 1.1]: + with pytest.raises(pa.ArrowInvalid): + pc.cumulative_sum([1, 2, 3], start=strt) + + +@pytest.mark.numpy +@pytest.mark.parametrize('start', (1.25, 10.5, -10.5)) +@pytest.mark.parametrize('skip_nulls', (True, False)) +def test_cumulative_prod(start, skip_nulls): + # Exact tests (e.g., integral types) + start_int = int(start) + starts = [None, start_int, pa.scalar(start_int, type=pa.int8()), + pa.scalar(start_int, type=pa.int64())] + for strt in starts: + arrays = [ + pa.array([1, 2, 3]), + pa.array([1, None, 20, 5]), + pa.chunked_array([[1, None], [20, 5]]) + ] + expected_arrays = [ + pa.array([1, 2, 6]), + pa.array([1, None, 20, 100]) + if skip_nulls else pa.array([1, None, None, None]), + pa.chunked_array([[1, None, 20, 100]]) + if skip_nulls else pa.chunked_array([[1, None, None, None]]) + ] + for i, arr in enumerate(arrays): + result = pc.cumulative_prod(arr, start=strt, skip_nulls=skip_nulls) + # Multiply `start` offset to expected array before comparing + expected = pc.multiply(expected_arrays[i], strt if strt is not None + else 1) + assert result.equals(expected) + + starts = [None, start, pa.scalar(start, type=pa.float32()), + pa.scalar(start, type=pa.float64())] + for strt in starts: + arrays = [ + pa.array([1.5, 2.5, 3.5]), + pa.array([1, np.nan, 2, -3, 4, 5]), + pa.array([1, np.nan, None, 3, None, 5]) + ] + expected_arrays = [ + np.array([1.5, 3.75, 13.125]), + np.array([1, np.nan, np.nan, np.nan, np.nan, np.nan]), + np.array([1, np.nan, None, np.nan, None, np.nan]) + if skip_nulls else np.array([1, np.nan, None, None, None, None]) + ] + for i, arr in enumerate(arrays): + result = pc.cumulative_prod(arr, start=strt, skip_nulls=skip_nulls) + # Multiply `start` offset to expected array before comparing + expected = pc.multiply(expected_arrays[i], strt if strt is not None + else 1) + np.testing.assert_array_almost_equal(result.to_numpy( + zero_copy_only=False), expected.to_numpy(zero_copy_only=False)) + + for strt in ['a', pa.scalar('arrow'), 1.1]: + with pytest.raises(pa.ArrowInvalid): + pc.cumulative_prod([1, 2, 3], start=strt) + + +@pytest.mark.numpy +@pytest.mark.parametrize('start', (0.5, 3.5, 6.5)) +@pytest.mark.parametrize('skip_nulls', (True, False)) +def test_cumulative_max(start, skip_nulls): + # Exact tests (e.g., integral types) + start_int = int(start) + starts = [None, start_int, pa.scalar(start_int, type=pa.int8()), + pa.scalar(start_int, type=pa.int64())] + for strt in starts: + arrays = [ + pa.array([2, 1, 3, 5, 4, 6]), + pa.array([2, 1, None, 5, 4, None]), + pa.chunked_array([[2, 1, None], [5, 4, None]]) + ] + expected_arrays = [ + pa.array([2, 2, 3, 5, 5, 6]), + pa.array([2, 2, None, 5, 5, None]) + if skip_nulls else pa.array([2, 2, None, None, None, None]), + pa.chunked_array([[2, 2, None, 5, 5, None]]) + if skip_nulls else + pa.chunked_array([[2, 2, None, None, None, None]]) + ] + for i, arr in enumerate(arrays): + result = pc.cumulative_max(arr, start=strt, skip_nulls=skip_nulls) + # Max `start` offset with expected array before comparing + expected = pc.max_element_wise( + expected_arrays[i], strt if strt is not None else int(-1e9), + skip_nulls=False) + assert result.equals(expected) + + starts = [None, start, pa.scalar(start, type=pa.float32()), + pa.scalar(start, type=pa.float64())] + for strt in starts: + arrays = [ + pa.array([2.5, 1.3, 3.7, 5.1, 4.9, 6.2]), + pa.array([2.5, 1.3, 3.7, np.nan, 4.9, 6.2]), + pa.array([2.5, 1.3, None, np.nan, 4.9, None]) + ] + expected_arrays = [ + np.array([2.5, 2.5, 3.7, 5.1, 5.1, 6.2]), + np.array([2.5, 2.5, 3.7, 3.7, 4.9, 6.2]), + np.array([2.5, 2.5, None, 2.5, 4.9, None]) + if skip_nulls else np.array([2.5, 2.5, None, None, None, None]) + ] + for i, arr in enumerate(arrays): + result = pc.cumulative_max(arr, start=strt, skip_nulls=skip_nulls) + # Max `start` offset with expected array before comparing + expected = pc.max_element_wise( + expected_arrays[i], strt if strt is not None else -1e9, + skip_nulls=False) + np.testing.assert_array_almost_equal(result.to_numpy( + zero_copy_only=False), expected.to_numpy(zero_copy_only=False)) + + for strt in ['a', pa.scalar('arrow'), 1.1]: + with pytest.raises(pa.ArrowInvalid): + pc.cumulative_max([1, 2, 3], start=strt) + + +@pytest.mark.numpy +@pytest.mark.parametrize('start', (0.5, 3.5, 6.5)) +@pytest.mark.parametrize('skip_nulls', (True, False)) +def test_cumulative_min(start, skip_nulls): + # Exact tests (e.g., integral types) + start_int = int(start) + starts = [None, start_int, pa.scalar(start_int, type=pa.int8()), + pa.scalar(start_int, type=pa.int64())] + for strt in starts: + arrays = [ + pa.array([5, 6, 4, 2, 3, 1]), + pa.array([5, 6, None, 2, 3, None]), + pa.chunked_array([[5, 6, None], [2, 3, None]]) + ] + expected_arrays = [ + pa.array([5, 5, 4, 2, 2, 1]), + pa.array([5, 5, None, 2, 2, None]) + if skip_nulls else pa.array([5, 5, None, None, None, None]), + pa.chunked_array([[5, 5, None, 2, 2, None]]) + if skip_nulls else + pa.chunked_array([[5, 5, None, None, None, None]]) + ] + for i, arr in enumerate(arrays): + result = pc.cumulative_min(arr, start=strt, skip_nulls=skip_nulls) + # Min `start` offset with expected array before comparing + expected = pc.min_element_wise( + expected_arrays[i], strt if strt is not None else int(1e9), + skip_nulls=False) + assert result.equals(expected) + + starts = [None, start, pa.scalar(start, type=pa.float32()), + pa.scalar(start, type=pa.float64())] + for strt in starts: + arrays = [ + pa.array([5.5, 6.3, 4.7, 2.1, 3.9, 1.2]), + pa.array([5.5, 6.3, 4.7, np.nan, 3.9, 1.2]), + pa.array([5.5, 6.3, None, np.nan, 3.9, None]) + ] + expected_arrays = [ + np.array([5.5, 5.5, 4.7, 2.1, 2.1, 1.2]), + np.array([5.5, 5.5, 4.7, 4.7, 3.9, 1.2]), + np.array([5.5, 5.5, None, 5.5, 3.9, None]) + if skip_nulls else np.array([5.5, 5.5, None, None, None, None]) + ] + for i, arr in enumerate(arrays): + result = pc.cumulative_min(arr, start=strt, skip_nulls=skip_nulls) + # Min `start` offset with expected array before comparing + expected = pc.min_element_wise( + expected_arrays[i], strt if strt is not None else 1e9, + skip_nulls=False) + np.testing.assert_array_almost_equal(result.to_numpy( + zero_copy_only=False), expected.to_numpy(zero_copy_only=False)) + + for strt in ['a', pa.scalar('arrow'), 1.1]: + with pytest.raises(pa.ArrowInvalid): + pc.cumulative_max([1, 2, 3], start=strt) + + +def test_make_struct(): + assert pc.make_struct(1, 'a').as_py() == {'0': 1, '1': 'a'} + + assert pc.make_struct(1, 'a', field_names=['i', 's']).as_py() == { + 'i': 1, 's': 'a'} + + assert pc.make_struct([1, 2, 3], + "a b c".split()) == pa.StructArray.from_arrays([ + [1, 2, 3], + "a b c".split()], names='0 1'.split()) + + with pytest.raises(ValueError, + match="Array arguments must all be the same length"): + pc.make_struct([1, 2, 3, 4], "a b c".split()) + + with pytest.raises(ValueError, match="0 arguments but 2 field names"): + pc.make_struct(field_names=['one', 'two']) + + +def test_map_lookup(): + ty = pa.map_(pa.utf8(), pa.int32()) + arr = pa.array([[('one', 1), ('two', 2)], [('none', 3)], + [], [('one', 5), ('one', 7)], None], type=ty) + result_first = pa.array([1, None, None, 5, None], type=pa.int32()) + result_last = pa.array([1, None, None, 7, None], type=pa.int32()) + result_all = pa.array([[1], None, None, [5, 7], None], + type=pa.list_(pa.int32())) + + assert pc.map_lookup(arr, 'one', 'first') == result_first + assert pc.map_lookup(arr, pa.scalar( + 'one', type=pa.utf8()), 'first') == result_first + assert pc.map_lookup(arr, pa.scalar( + 'one', type=pa.utf8()), 'last') == result_last + assert pc.map_lookup(arr, pa.scalar( + 'one', type=pa.utf8()), 'all') == result_all + + +def test_struct_fields_options(): + a = pa.array([4, 5, 6], type=pa.int64()) + b = pa.array(["bar", None, ""]) + c = pa.StructArray.from_arrays([a, b], ["a", "b"]) + arr = pa.StructArray.from_arrays([a, c], ["a", "c"]) + + assert pc.struct_field(arr, '.c.b') == b + assert pc.struct_field(arr, b'.c.b') == b + assert pc.struct_field(arr, ['c', 'b']) == b + assert pc.struct_field(arr, [1, 'b']) == b + assert pc.struct_field(arr, (b'c', 'b')) == b + assert pc.struct_field(arr, pc.field(('c', 'b'))) == b + + assert pc.struct_field(arr, '.a') == a + assert pc.struct_field(arr, ['a']) == a + assert pc.struct_field(arr, 'a') == a + assert pc.struct_field(arr, pc.field(('a',))) == a + + assert pc.struct_field(arr, indices=[1, 1]) == b + assert pc.struct_field(arr, (1, 1)) == b + assert pc.struct_field(arr, [0]) == a + assert pc.struct_field(arr, []) == arr + + with pytest.raises(pa.ArrowInvalid, match="No match for FieldRef"): + pc.struct_field(arr, 'foo') + + with pytest.raises(pa.ArrowInvalid, match="No match for FieldRef"): + pc.struct_field(arr, '.c.foo') + + # drill into a non-struct array and continue to ask for a field + with pytest.raises(pa.ArrowInvalid, match="No match for FieldRef"): + pc.struct_field(arr, '.a.foo') + + with pytest.raises(pa.ArrowInvalid, match="cannot be called without options"): + pc.struct_field(arr) + + +def test_case_when(): + assert pc.case_when(pc.make_struct([True, False, None], + [False, True, None]), + [1, 2, 3], + [11, 12, 13]) == pa.array([1, 12, None]) + + +def test_list_element(): + element_type = pa.struct([('a', pa.float64()), ('b', pa.int8())]) + list_type = pa.list_(element_type) + l1 = [{'a': .4, 'b': 2}, None, {'a': .2, 'b': 4}, None, {'a': 5.6, 'b': 6}] + l2 = [None, {'a': .52, 'b': 3}, {'a': .7, 'b': 4}, None, {'a': .6, 'b': 8}] + lists = pa.array([l1, l2], list_type) + + index = 1 + result = pa.compute.list_element(lists, index) + expected = pa.array([None, {'a': 0.52, 'b': 3}], element_type) + assert result.equals(expected) + + index = 4 + result = pa.compute.list_element(lists, index) + expected = pa.array([{'a': 5.6, 'b': 6}, {'a': .6, 'b': 8}], element_type) + assert result.equals(expected) + + +def test_count_distinct(): + samples = [datetime.datetime(year=y, month=1, day=1) for y in range(1992, 2092)] + arr = pa.array(samples, pa.timestamp("ns")) + assert pc.count_distinct(arr) == pa.scalar(len(samples), type=pa.int64()) + + +def test_count_distinct_options(): + arr = pa.array([1, 2, 3, None, None]) + assert pc.count_distinct(arr).as_py() == 3 + assert pc.count_distinct(arr, mode='only_valid').as_py() == 3 + assert pc.count_distinct(arr, mode='only_null').as_py() == 1 + assert pc.count_distinct(arr, mode='all').as_py() == 4 + assert pc.count_distinct(arr, 'all').as_py() == 4 + + +def test_utf8_normalize(): + arr = pa.array(["01²3"]) + assert pc.utf8_normalize(arr, form="NFC") == arr + assert pc.utf8_normalize(arr, form="NFKC") == pa.array(["0123"]) + assert pc.utf8_normalize(arr, "NFD") == arr + assert pc.utf8_normalize(arr, "NFKD") == pa.array(["0123"]) + with pytest.raises( + ValueError, + match='"NFZ" is not a valid Unicode normalization form'): + pc.utf8_normalize(arr, form="NFZ") + + +def test_random(): + # (note negative integer initializers are accepted) + for initializer in ['system', 42, -42, b"abcdef"]: + assert pc.random(0, initializer=initializer) == \ + pa.array([], type=pa.float64()) + + # System random initialization => outputs all distinct + arrays = [tuple(pc.random(100).to_pylist()) for i in range(10)] + assert len(set(arrays)) == len(arrays) + + arrays = [tuple(pc.random(100, initializer=i % 7).to_pylist()) + for i in range(0, 100)] + assert len(set(arrays)) == 7 + + # Arbitrary hashable objects can be given as initializer + initializers = [object(), (4, 5, 6), "foo"] + initializers.extend(os.urandom(10) for i in range(10)) + arrays = [tuple(pc.random(100, initializer=i).to_pylist()) + for i in initializers] + assert len(set(arrays)) == len(arrays) + + with pytest.raises(TypeError, + match=r"initializer should be 'system', an integer, " + r"or a hashable object; got \[\]"): + pc.random(100, initializer=[]) + + +@pytest.mark.parametrize( + "tiebreaker,expected_values", + [("min", [3, 1, 4, 6, 4, 6, 1]), + ("max", [3, 2, 5, 7, 5, 7, 2]), + ("first", [3, 1, 4, 6, 5, 7, 2]), + ("dense", [2, 1, 3, 4, 3, 4, 1])] +) +def test_rank_options_tiebreaker(tiebreaker, expected_values): + arr = pa.array([1.2, 0.0, 5.3, None, 5.3, None, 0.0]) + rank_options = pc.RankOptions(sort_keys="ascending", + null_placement="at_end", + tiebreaker=tiebreaker) + result = pc.rank(arr, options=rank_options) + expected = pa.array(expected_values, type=pa.uint64()) + assert result.equals(expected) + + +def test_rank_options(): + arr = pa.array([1.2, 0.0, 5.3, None, 5.3, None, 0.0]) + expected = pa.array([3, 1, 4, 6, 5, 7, 2], type=pa.uint64()) + + # Ensure rank can be called without specifying options + result = pc.rank(arr) + assert result.equals(expected) + + # Ensure default RankOptions + result = pc.rank(arr, options=pc.RankOptions()) + assert result.equals(expected) + + # Ensure sort_keys tuple usage + result = pc.rank(arr, options=pc.RankOptions( + sort_keys=[("b", "ascending")]) + ) + assert result.equals(expected) + + result = pc.rank(arr, null_placement="at_start") + expected_at_start = pa.array([5, 3, 6, 1, 7, 2, 4], type=pa.uint64()) + assert result.equals(expected_at_start) + + result = pc.rank(arr, sort_keys="descending") + expected_descending = pa.array([3, 4, 1, 6, 2, 7, 5], type=pa.uint64()) + assert result.equals(expected_descending) + + with pytest.raises(ValueError, + match=r'"NonExisting" is not a valid tiebreaker'): + pc.RankOptions(sort_keys="descending", + null_placement="at_end", + tiebreaker="NonExisting") + + +def test_rank_quantile_options(): + arr = pa.array([None, 1, None, 2, None]) + expected = pa.array([0.7, 0.1, 0.7, 0.3, 0.7], type=pa.float64()) + + # Ensure rank_quantile can be called without specifying options + result = pc.rank_quantile(arr) + assert result.equals(expected) + + # Ensure default RankOptions + result = pc.rank_quantile(arr, options=pc.RankQuantileOptions()) + assert result.equals(expected) + + # Ensure sort_keys tuple usage + result = pc.rank_quantile(arr, options=pc.RankQuantileOptions( + sort_keys=[("b", "ascending")]) + ) + assert result.equals(expected) + + result = pc.rank_quantile(arr, null_placement="at_start") + expected_at_start = pa.array([0.3, 0.7, 0.3, 0.9, 0.3], type=pa.float64()) + assert result.equals(expected_at_start) + + result = pc.rank_quantile(arr, sort_keys="descending") + expected_descending = pa.array([0.7, 0.3, 0.7, 0.1, 0.7], type=pa.float64()) + assert result.equals(expected_descending) + + with pytest.raises(ValueError, match="not a valid sort order"): + pc.rank_quantile(arr, sort_keys="XXX") + + +def test_rank_normal_options(): + arr = pa.array([None, 1, None, 2, None]) + + expected = pytest.approx( + [0.5244005127080407, -1.2815515655446004, 0.5244005127080407, + -0.5244005127080409, 0.5244005127080407]) + result = pc.rank_normal(arr) + assert result.to_pylist() == expected + result = pc.rank_normal(arr, null_placement="at_end", sort_keys="ascending") + assert result.to_pylist() == expected + result = pc.rank_normal(arr, options=pc.RankQuantileOptions()) + assert result.to_pylist() == expected + + expected = pytest.approx( + [-0.5244005127080409, 1.2815515655446004, -0.5244005127080409, + 0.5244005127080407, -0.5244005127080409]) + result = pc.rank_normal(arr, null_placement="at_start", sort_keys="descending") + assert result.to_pylist() == expected + result = pc.rank_normal(arr, + options=pc.RankQuantileOptions(null_placement="at_start", + sort_keys="descending")) + assert result.to_pylist() == expected + + +def create_sample_expressions(): + # We need a schema for substrait conversion + schema = pa.schema([pa.field("i64", pa.int64()), pa.field( + "foo", pa.struct([pa.field("bar", pa.string())]))]) + + # Creates a bunch of sample expressions for testing + # serialization and deserialization. The expressions are categorized + # to reflect certain nuances in Substrait conversion. + a = pc.scalar(1) + b = pc.scalar(1.1) + c = pc.scalar(True) + d = pc.scalar("string") + e = pc.scalar(None) + f = pc.scalar({'a': 1}) + g = pc.scalar(pa.scalar(1)) + h = pc.scalar(np.int64(2)) + j = pc.scalar(False) + k = pc.scalar(0) + + # These expression consist entirely of literals + literal_exprs = [a, b, c, d, e, g, h, j, k] + + # These expressions include at least one function call + exprs_with_call = [a == b, a != b, a > b, c & j, c | j, ~c, d.is_valid(), + a + b, a - b, a * b, a / b, pc.negate(a), + pc.add(a, b), pc.subtract(a, b), pc.divide(a, b), + pc.multiply(a, b), pc.power(a, a), pc.sqrt(a), + pc.exp(b), pc.cos(b), pc.sin(b), pc.tan(b), + pc.acos(b), pc.atan(b), pc.asin(b), pc.atan2(b, b), + pc.sinh(a), pc.cosh(a), pc.tanh(a), + pc.asinh(a), pc.acosh(b), pc.atanh(k), + pc.abs(b), pc.sign(a), pc.bit_wise_not(a), + pc.bit_wise_and(a, a), pc.bit_wise_or(a, a), + pc.bit_wise_xor(a, a), pc.is_nan(b), pc.is_finite(b), + pc.coalesce(a, b), + a.cast(pa.int32(), safe=False)] + + # These expressions test out various reference styles and may include function + # calls. Named references are used here. + exprs_with_ref = [pc.field('i64') > 5, pc.field('i64') == 5, + pc.field('i64') == 7, + pc.field(('foo', 'bar')) == 'value', + pc.field('foo', 'bar') == 'value'] + + # Similar to above but these use numeric references instead of string refs + exprs_with_numeric_refs = [pc.field(0) > 5, pc.field(0) == 5, + pc.field(0) == 7, + pc.field((1, 0)) == 'value', + pc.field(1, 0) == 'value'] + + # Expressions that behave uniquely when converting to/from substrait + special_cases = [ + f, # Struct literals lose their field names + a.isin([1, 2, 3]), # isin converts to an or list + pc.field('i64').is_null() # pyarrow always specifies a FunctionOptions + # for is_null which, being the default, is + # dropped on serialization + ] + + all_exprs = literal_exprs.copy() + all_exprs += exprs_with_call + all_exprs += exprs_with_ref + all_exprs += special_cases + + return { + "all": all_exprs, + "literals": literal_exprs, + "calls": exprs_with_call, + "refs": exprs_with_ref, + "numeric_refs": exprs_with_numeric_refs, + "special": special_cases, + "schema": schema + } + +# Tests the Arrow-specific serialization mechanism + + +@pytest.mark.numpy +def test_expression_serialization_arrow(pickle_module): + for expr in create_sample_expressions()["all"]: + assert isinstance(expr, pc.Expression) + restored = pickle_module.loads(pickle_module.dumps(expr)) + assert expr.equals(restored) + + +@pytest.mark.numpy +@pytest.mark.substrait +def test_expression_serialization_substrait(): + + exprs = create_sample_expressions() + schema = exprs["schema"] + + # Basic literals don't change on binding and so they will round + # trip without any change + for expr in exprs["literals"]: + serialized = expr.to_substrait(schema) + deserialized = pc.Expression.from_substrait(serialized) + assert expr.equals(deserialized) + + # Expressions are bound when they get serialized. Since bound + # expressions are not equal to their unbound variants we cannot + # compare the round tripped with the original + for expr in exprs["calls"]: + serialized = expr.to_substrait(schema) + deserialized = pc.Expression.from_substrait(serialized) + # We can't compare the expressions themselves because of the bound + # unbound difference. But we can compare the string representation + assert str(deserialized) == str(expr) + serialized_again = deserialized.to_substrait(schema) + deserialized_again = pc.Expression.from_substrait(serialized_again) + assert deserialized.equals(deserialized_again) + + for expr, expr_norm in zip(exprs["refs"], exprs["numeric_refs"]): + serialized = expr.to_substrait(schema) + deserialized = pc.Expression.from_substrait(serialized) + assert str(deserialized) == str(expr_norm) + serialized_again = deserialized.to_substrait(schema) + deserialized_again = pc.Expression.from_substrait(serialized_again) + assert deserialized.equals(deserialized_again) + + # For the special cases we get various wrinkles in serialization but we + # should always get the same thing from round tripping twice + for expr in exprs["special"]: + serialized = expr.to_substrait(schema) + deserialized = pc.Expression.from_substrait(serialized) + serialized_again = deserialized.to_substrait(schema) + deserialized_again = pc.Expression.from_substrait(serialized_again) + assert deserialized.equals(deserialized_again) + + # Special case, we lose the field names of struct literals + f = exprs["special"][0] + serialized = f.to_substrait(schema) + deserialized = pc.Expression.from_substrait(serialized) + assert deserialized.equals(pc.scalar({'': 1})) + + # Special case, is_in converts to a == opt[0] || a == opt[1] ... + a = pc.scalar(1) + expr = a.isin([1, 2, 3]) + target = (a == 1) | (a == 2) | (a == 3) + serialized = expr.to_substrait(schema) + deserialized = pc.Expression.from_substrait(serialized) + # Compare str's here to bypass the bound/unbound difference + assert str(target) == str(deserialized) + serialized_again = deserialized.to_substrait(schema) + deserialized_again = pc.Expression.from_substrait(serialized_again) + assert deserialized.equals(deserialized_again) + + +def test_expression_construction(): + zero = pc.scalar(0) + one = pc.scalar(1) + true = pc.scalar(True) + false = pc.scalar(False) + string = pc.scalar("string") + field = pc.field("field") + nested_mixed_types = pc.field(b"a", 1, "b") + nested_field = pc.field(("nested", "field")) + nested_field2 = pc.field("nested", "field") + + zero | one == string + ~true == false + for typ in ("bool", pa.bool_()): + field.cast(typ) == true + + field.isin([1, 2]) + nested_mixed_types.isin(["foo", "bar"]) + nested_field.isin(["foo", "bar"]) + nested_field2.isin(["foo", "bar"]) + + with pytest.raises(TypeError): + field.isin(1) + + with pytest.raises(pa.ArrowInvalid): + field != object() + + +def test_expression_boolean_operators(): + # https://issues.apache.org/jira/browse/ARROW-11412 + true = pc.scalar(True) + false = pc.scalar(False) + + with pytest.raises(ValueError, match="cannot be evaluated to python True"): + true and false + + with pytest.raises(ValueError, match="cannot be evaluated to python True"): + true or false + + with pytest.raises(ValueError, match="cannot be evaluated to python True"): + bool(true) + + with pytest.raises(ValueError, match="cannot be evaluated to python True"): + not true + + +def test_expression_call_function(): + field = pc.field("field") + + # no options + assert str(pc.hour(field)) == "hour(field)" + + # default options + assert str(pc.round(field)) == "round(field)" + # specified options + assert str(pc.round(field, ndigits=1)) == \ + "round(field, {ndigits=1, round_mode=HALF_TO_EVEN})" + + # Will convert non-expression arguments if possible + assert str(pc.add(field, 1)) == "add(field, 1)" + assert str(pc.add(field, pa.scalar(1))) == "add(field, 1)" + + # Invalid pc.scalar input gives original error message + msg = "only other expressions allowed as arguments" + with pytest.raises(TypeError, match=msg): + pc.add(field, object) + + +def test_cast_table_raises(): + table = pa.table({'a': [1, 2]}) + + with pytest.raises(pa.lib.ArrowTypeError): + pc.cast(table, pa.int64()) + + +@pytest.mark.parametrize("start,stop,expected", ( + (0, None, [[1, 2, 3], [4, 5, None], [6, None, None], None]), + (0, 1, [[1], [4], [6], None]), + (0, 2, [[1, 2], [4, 5], [6, None], None]), + (1, 2, [[2], [5], [None], None]), + (2, 4, [[3, None], [None, None], [None, None], None]) +)) +@pytest.mark.parametrize("step", (1, 2)) +@pytest.mark.parametrize("value_type", (pa.string, pa.int16, pa.float64)) +@pytest.mark.parametrize("list_type", (pa.list_, pa.large_list, "fixed")) +def test_list_slice_output_fixed(start, stop, step, expected, value_type, + list_type): + if list_type == "fixed": + arr = pa.array([[1, 2, 3], [4, 5, None], [6, None, None], None], + pa.list_(pa.int8(), 3)).cast(pa.list_(value_type(), 3)) + else: + arr = pa.array([[1, 2, 3], [4, 5], [6], None], + pa.list_(pa.int8())).cast(list_type(value_type())) + + args = arr, start, stop, step, True + if stop is None and list_type != "fixed": + msg = ("Unable to produce FixedSizeListArray from " + "non-FixedSizeListArray without `stop` being set.") + with pytest.raises(pa.ArrowInvalid, match=msg): + pc.list_slice(*args) + else: + result = pc.list_slice(*args) + pylist = result.cast(pa.list_(pa.int8(), + result.type.list_size)).to_pylist() + assert pylist == [e[::step] if e else e for e in expected] + + +@pytest.mark.parametrize("start,stop", ( + (0, None,), + (0, 1,), + (0, 2,), + (1, 2,), + (2, 4,) +)) +@pytest.mark.parametrize("step", (1, 2)) +@pytest.mark.parametrize("value_type", (pa.string, pa.int16, pa.float64)) +@pytest.mark.parametrize("list_type", (pa.list_, pa.large_list, "fixed")) +def test_list_slice_output_variable(start, stop, step, value_type, list_type): + if list_type == "fixed": + data = [[1, 2, 3], [4, 5, None], [6, None, None], None] + arr = pa.array( + data, + pa.list_(pa.int8(), 3)).cast(pa.list_(value_type(), 3)) + else: + data = [[1, 2, 3], [4, 5], [6], None] + arr = pa.array(data, + pa.list_(pa.int8())).cast(list_type(value_type())) + + # Gets same list type (ListArray vs LargeList) + if list_type == "fixed": + list_type = pa.list_ # non fixed output type + + result = pc.list_slice(arr, start, stop, step, + return_fixed_size_list=False) + assert result.type == list_type(value_type()) + + pylist = result.cast(pa.list_(pa.int8())).to_pylist() + + # Variable output slicing follows Python's slice semantics + expected = [d[start:stop:step] if d is not None else None for d in data] + assert pylist == expected + + +@pytest.mark.parametrize("return_fixed_size", (True, False, None)) +@pytest.mark.parametrize("type", ( + lambda: pa.list_(pa.field('col', pa.int8())), + lambda: pa.list_(pa.field('col', pa.int8()), 1), + lambda: pa.large_list(pa.field('col', pa.int8())))) +def test_list_slice_field_names_retained(return_fixed_size, type): + arr = pa.array([[1]], type()) + out = pc.list_slice(arr, 0, 1, return_fixed_size_list=return_fixed_size) + assert arr.type.field(0).name == out.type.field(0).name + + # Verify out type matches in type if return_fixed_size_list==None + if return_fixed_size is None: + assert arr.type == out.type + + +def test_list_slice_bad_parameters(): + arr = pa.array([[1]], pa.list_(pa.int8(), 1)) + msg = r"`start`(.*) should be greater than 0 and smaller than `stop`(.*)" + with pytest.raises(pa.ArrowInvalid, match=msg): + pc.list_slice(arr, -1, 1) # negative start? + with pytest.raises(pa.ArrowInvalid, match=msg): + pc.list_slice(arr, 2, 1) # start > stop? + + # TODO(ARROW-18281): start==stop -> empty lists + with pytest.raises(pa.ArrowInvalid, match=msg): + pc.list_slice(arr, 0, 0) # start == stop? + + # Step not >= 1 + msg = "`step` must be >= 1, got: " + with pytest.raises(pa.ArrowInvalid, match=msg + "0"): + pc.list_slice(arr, 0, 1, step=0) + with pytest.raises(pa.ArrowInvalid, match=msg + "-1"): + pc.list_slice(arr, 0, 1, step=-1) + + +def check_run_end_encode_decode(value_type, run_end_encode_opts=None): + values = [1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3] + arr = pa.array(values, type=value_type) + encoded = pc.run_end_encode(arr, options=run_end_encode_opts) + decoded = pc.run_end_decode(encoded) + assert decoded.type == arr.type + assert decoded.equals(arr) + + +@pytest.mark.parametrize( + "value_type", + ( + pa.int8(), + pa.int16(), + pa.int32(), + pa.int64(), + pa.float16(), + pa.float32(), + pa.float64(), + pa.decimal32(4, 0), + pa.decimal64(4, 0), + pa.decimal128(4, 0), + pa.decimal256(4, 0), + ), +) +@pytest.mark.parametrize( + "option", + ( + None, + pc.RunEndEncodeOptions(pa.int16()), + pc.RunEndEncodeOptions("int32"), + pc.RunEndEncodeOptions(pa.int64()), + ), +) +def test_run_end_encode(value_type, option): + check_run_end_encode_decode(value_type, option) + + +def test_pairwise_diff(): + arr = pa.array([1, 2, 3, None, 4, 5]) + expected = pa.array([None, 1, 1, None, None, 1]) + result = pa.compute.pairwise_diff(arr, period=1) + assert result.equals(expected) + + arr = pa.array([1, 2, 3, None, 4, 5]) + expected = pa.array([None, None, 2, None, 1, None]) + result = pa.compute.pairwise_diff(arr, period=2) + assert result.equals(expected) + + # negative period + arr = pa.array([1, 2, 3, None, 4, 5], type=pa.int8()) + expected = pa.array([-1, -1, None, None, -1, None], type=pa.int8()) + result = pa.compute.pairwise_diff(arr, period=-1) + assert result.equals(expected) + + # wrap around overflow + arr = pa.array([1, 2, 3, None, 4, 5], type=pa.uint8()) + expected = pa.array([255, 255, None, None, 255, None], type=pa.uint8()) + result = pa.compute.pairwise_diff(arr, period=-1) + assert result.equals(expected) + + # fail on overflow + arr = pa.array([1, 2, 3, None, 4, 5], type=pa.uint8()) + with pytest.raises(pa.ArrowInvalid, + match="overflow"): + pa.compute.pairwise_diff_checked(arr, period=-1) + + +def test_pivot_wider(): + key_names = ["width", "height"] + + result = pc.pivot_wider(["height", "width", "depth"], [10, None, 11]) + assert result.as_py() == {} + + result = pc.pivot_wider(["height", "width", "depth"], [10, None, 11], + key_names) + assert result.as_py() == {"width": None, "height": 10} + # check key order + assert list(result.as_py()) == ["width", "height"] + + result = pc.pivot_wider(["height", "width", "depth"], [10, None, 11], + key_names=key_names) + assert result.as_py() == {"width": None, "height": 10} + + with pytest.raises(KeyError, match="Unexpected pivot key: depth"): + result = pc.pivot_wider(["height", "width", "depth"], [10, None, 11], + key_names=key_names, + unexpected_key_behavior="raise") + + with pytest.raises(ValueError, match="Encountered more than one non-null value"): + result = pc.pivot_wider(["height", "width", "height"], [10, None, 11], + key_names=key_names) + + +def test_winsorize(): + arr = pa.array([10, 4, 9, 8, 5, 3, 7, 2, 1, 6]) + + result = pc.winsorize(arr, 0.1, 0.8) + assert result.to_pylist() == [8, 4, 8, 8, 5, 3, 7, 2, 2, 6] + + result = pc.winsorize( + arr, options=pc.WinsorizeOptions(lower_limit=0.1, upper_limit=0.8)) + assert result.to_pylist() == [8, 4, 8, 8, 5, 3, 7, 2, 2, 6] diff --git a/shared/package-files/71/71dd50409c1c1cb4a47cf8fb148908e714286ed7ec545a27ce47151f67173b62/to_sparse_bsr_ops.h b/shared/package-files/71/71dd50409c1c1cb4a47cf8fb148908e714286ed7ec545a27ce47151f67173b62/to_sparse_bsr_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..13ded2354cb79a0566a694216bd41cdc000f9259 --- /dev/null +++ b/shared/package-files/71/71dd50409c1c1cb4a47cf8fb148908e714286ed7ec545a27ce47151f67173b62/to_sparse_bsr_ops.h @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API to_sparse_bsr { + using schema = at::Tensor (const at::Tensor &, at::IntArrayRef, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::to_sparse_bsr") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "to_sparse_bsr(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, at::IntArrayRef blocksize, c10::optional dense_dim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef blocksize, c10::optional dense_dim); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/71/71de669e0c8c23b96d3444a3f67098241472b25ca0fc76fa10b08d225856ea04/_unary_ufuncs_impl.py b/shared/package-files/71/71de669e0c8c23b96d3444a3f67098241472b25ca0fc76fa10b08d225856ea04/_unary_ufuncs_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..ce4a30cc40e7132e24812041d438c60b8f07ca8e --- /dev/null +++ b/shared/package-files/71/71de669e0c8c23b96d3444a3f67098241472b25ca0fc76fa10b08d225856ea04/_unary_ufuncs_impl.py @@ -0,0 +1,73 @@ +# mypy: ignore-errors + +"""Export torch work functions for unary ufuncs, rename/tweak to match numpy. +This listing is further exported to public symbols in the `_numpy/_ufuncs.py` module. +""" + +import torch + +from torch import ( # noqa: F401 + absolute as fabs, # noqa: F401 + arccos, # noqa: F401 + arccosh, # noqa: F401 + arcsin, # noqa: F401 + arcsinh, # noqa: F401 + arctan, # noqa: F401 + arctanh, # noqa: F401 + bitwise_not, # noqa: F401 + bitwise_not as invert, # noqa: F401 + ceil, # noqa: F401 + conj_physical as conjugate, # noqa: F401 + cos, # noqa: F401 + cosh, # noqa: F401 + deg2rad, # noqa: F401 + deg2rad as radians, # noqa: F401 + exp, # noqa: F401 + exp2, # noqa: F401 + expm1, # noqa: F401 + floor, # noqa: F401 + isfinite, # noqa: F401 + isinf, # noqa: F401 + isnan, # noqa: F401 + log, # noqa: F401 + log10, # noqa: F401 + log1p, # noqa: F401 + log2, # noqa: F401 + logical_not, # noqa: F401 + negative, # noqa: F401 + rad2deg, # noqa: F401 + rad2deg as degrees, # noqa: F401 + reciprocal, # noqa: F401 + round as fix, # noqa: F401 + round as rint, # noqa: F401 + sign, # noqa: F401 + signbit, # noqa: F401 + sin, # noqa: F401 + sinh, # noqa: F401 + sqrt, # noqa: F401 + square, # noqa: F401 + tan, # noqa: F401 + tanh, # noqa: F401 + trunc, # noqa: F401 +) + + +# special cases: torch does not export these names +def cbrt(x): + return torch.pow(x, 1 / 3) + + +def positive(x): + return +x + + +def absolute(x): + # work around torch.absolute not impl for bools + if x.dtype == torch.bool: + return x + return torch.absolute(x) + + +# TODO set __name__ and __qualname__ +abs = absolute +conj = conjugate diff --git a/shared/package-files/71/71df42918330781675fb39c7a66c669968dc114c082c0d49b46e180a148c07b8/__init__.py b/shared/package-files/71/71df42918330781675fb39c7a66c669968dc114c082c0d49b46e180a148c07b8/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5e7af5e2946a5fbe35edc0bfbcdd1555100a120c --- /dev/null +++ b/shared/package-files/71/71df42918330781675fb39c7a66c669968dc114c082c0d49b46e180a148c07b8/__init__.py @@ -0,0 +1,6 @@ +# IANA versions like 2020a are not valid PEP 440 identifiers; the recommended +# way to translate the version is to use YYYY.n where `n` is a 0-based index. +__version__ = "2026.5" + +# This exposes the original IANA version number. +IANA_VERSION = "2026e" diff --git a/shared/package-files/71/71dfbedda0db9c59285389a42a97d8b83c9368acbe72c1f921ce1393eef8d471/model_matrix.py b/shared/package-files/71/71dfbedda0db9c59285389a42a97d8b83c9368acbe72c1f921ce1393eef8d471/model_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..b203375df1e10275485fb11a5bdc7f7f1b3123b5 --- /dev/null +++ b/shared/package-files/71/71dfbedda0db9c59285389a42a97d8b83c9368acbe72c1f921ce1393eef8d471/model_matrix.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +import copy +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Generic, + Optional, + SupportsIndex, + TypeVar, + cast, +) + +import wrapt + +from formulaic.utils.structured import Structured + +if TYPE_CHECKING: # pragma: no cover + from .model_spec import ModelSpec, ModelSpecs + + +MatrixType = TypeVar("MatrixType") + + +class ModelMatrix(Generic[MatrixType], wrapt.ObjectProxy): + """ + A wrapper around arbitrary model matrix output representations. + + This wrapper allows for `isinstance(..., ModelMatrix)` checks, and allows + one to access the `ModelSpec` instance associated with its creation using + `.model_spec`. All other instance attributes and methods of + the wrapped object are directly accessible as if the object were unwrapped. + """ + + def __init__(self, matrix: Any, spec: Optional[ModelSpec] = None): + wrapt.ObjectProxy.__init__(self, matrix) + self._self_model_spec = spec + + @property + def model_spec(self) -> Optional[ModelSpec]: + """ + The `ModelSpec` instance associated with the creation of this + `ModelMatrix` instance. + + This `ModelSpec` instance can be used to create other `ModelMatrix`s + that respect all the choices (including feature selection and encoding) + that were made in the construction of this `ModelMatrix` instance. + + """ + return self._self_model_spec + + def __repr__(self) -> str: + return self.__wrapped__.__repr__() # pragma: no cover + + # Handle copying behaviour + + def __copy__(self) -> ModelMatrix[MatrixType]: + return type(self)(copy.copy(self.__wrapped__), spec=self._self_model_spec) + + def __deepcopy__(self, memo: Any = None) -> ModelMatrix[MatrixType]: + return type(self)( + copy.deepcopy(self.__wrapped__, memo), + spec=copy.deepcopy(self._self_model_spec), + ) + + # Handle pickling behaviour + + def __reduce_ex__( + self, protocol: SupportsIndex + ) -> tuple[ + Callable[[Any, ModelSpec], ModelMatrix], tuple[Any, Optional[ModelSpec]] + ]: + return ModelMatrix, (self.__wrapped__, self._self_model_spec) + + +class ModelMatrices(Structured[ModelMatrix]): + """ + A `Structured[ModelMatrix]` subclass that adds a `.model_spec` attribute + (mirrorin `ModelMatrix.model_spec`) that returns a structured container for + all the `ModelSpec` instances associated with the `ModelSpec` objects + referenced by this container. + """ + + def _prepare_item( + self, key: str, item: Any + ) -> Any: # Verify that all included items are `ModelSpec` instances. + # Verify that all included items are `ModelMatrix` instances. + if not isinstance(item, ModelMatrix): + raise TypeError( + "`ModelMatrices` instances expect all items to be instances " + f"of `ModelMatrix`. [Got: {repr(item)} of type " + f"{repr(type(item))} for key {repr(key)}." + ) + return item + + @property + def model_spec(self) -> ModelSpecs: + """ + The `ModelSpecs` instance representing the structured set of `ModelSpec` + instances associated with the `ModelMatrix` instances stored in this + `Structured` instance. + """ + from .model_spec import ModelSpecs + + return cast( + ModelSpecs, + self._map(lambda model_matrix: model_matrix.model_spec, as_type=ModelSpecs), + ) diff --git a/shared/package-files/71/71e197725956c97ba3dd9325c76e74a9cc8ab561101426731efd94d33c466c69/configobjwalker.py b/shared/package-files/71/71e197725956c97ba3dd9325c76e74a9cc8ab561101426731efd94d33c466c69/configobjwalker.py new file mode 100644 index 0000000000000000000000000000000000000000..cbc6148038ea7480fc4ac6896696d993f01555d5 --- /dev/null +++ b/shared/package-files/71/71e197725956c97ba3dd9325c76e74a9cc8ab561101426731efd94d33c466c69/configobjwalker.py @@ -0,0 +1,14 @@ +# coding: utf-8 + +import warnings + +from ruamel.yaml.util import configobj_walker as new_configobj_walker + +if False: # MYPY + from typing import Any # NOQA + + +def configobj_walker(cfg): + # type: (Any) -> Any + warnings.warn('configobj_walker has moved to ruamel.yaml.util, please update your code') + return new_configobj_walker(cfg) diff --git a/shared/package-files/71/71e5367fe839afc4338c50d450f111728e097538ecaccc1b17b10238001b0bb1/en_in.msg b/shared/package-files/71/71e5367fe839afc4338c50d450f111728e097538ecaccc1b17b10238001b0bb1/en_in.msg new file mode 100644 index 0000000000000000000000000000000000000000..a1f155d2c58101bc3f4551e8c14cc7ab6931a62f --- /dev/null +++ b/shared/package-files/71/71e5367fe839afc4338c50d450f111728e097538ecaccc1b17b10238001b0bb1/en_in.msg @@ -0,0 +1,8 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset en_IN AM "AM" + ::msgcat::mcset en_IN PM "PM" + ::msgcat::mcset en_IN DATE_FORMAT "%d %B %Y" + ::msgcat::mcset en_IN TIME_FORMAT "%H:%M:%S" + ::msgcat::mcset en_IN DATE_TIME_FORMAT "%d %B %Y %H:%M:%S %z" +} diff --git a/shared/package-files/71/71e5fbf5f6e31b273954d926cf6f50d4ded61972e3e3406f4eecf93df340c382/test_constructors.py b/shared/package-files/71/71e5fbf5f6e31b273954d926cf6f50d4ded61972e3e3406f4eecf93df340c382/test_constructors.py new file mode 100644 index 0000000000000000000000000000000000000000..5e6f16075ae636a3aa14e7443097f426bd6f998a --- /dev/null +++ b/shared/package-files/71/71e5fbf5f6e31b273954d926cf6f50d4ded61972e3e3406f4eecf93df340c382/test_constructors.py @@ -0,0 +1,164 @@ +from datetime import datetime + +import numpy as np +import pytest + +from pandas import ( + Index, + RangeIndex, + Series, +) +import pandas._testing as tm + + +class TestRangeIndexConstructors: + @pytest.mark.parametrize("name", [None, "foo"]) + @pytest.mark.parametrize( + "args, kwargs, start, stop, step", + [ + ((5,), {}, 0, 5, 1), + ((1, 5), {}, 1, 5, 1), + ((1, 5, 2), {}, 1, 5, 2), + ((0,), {}, 0, 0, 1), + ((0, 0), {}, 0, 0, 1), + ((), {"start": 0}, 0, 0, 1), + ((), {"stop": 0}, 0, 0, 1), + ], + ) + def test_constructor(self, args, kwargs, start, stop, step, name): + result = RangeIndex(*args, name=name, **kwargs) + expected = Index(np.arange(start, stop, step, dtype=np.int64), name=name) + assert isinstance(result, RangeIndex) + assert result.name is name + assert result._range == range(start, stop, step) + tm.assert_index_equal(result, expected, exact="equiv") + + def test_constructor_invalid_args(self): + msg = "RangeIndex\\(\\.\\.\\.\\) must be called with integers" + with pytest.raises(TypeError, match=msg): + RangeIndex() + + with pytest.raises(TypeError, match=msg): + RangeIndex(name="Foo") + + # we don't allow on a bare Index + msg = ( + r"Index\(\.\.\.\) must be called with a collection of some " + r"kind, 0 was passed" + ) + with pytest.raises(TypeError, match=msg): + Index(0) + + @pytest.mark.parametrize( + "args", + [ + Index(["a", "b"]), + Series(["a", "b"]), + np.array(["a", "b"]), + [], + np.arange(0, 10), + np.array([1]), + [1], + ], + ) + def test_constructor_additional_invalid_args(self, args): + msg = f"Value needs to be a scalar value, was type {type(args).__name__}" + with pytest.raises(TypeError, match=msg): + RangeIndex(args) + + @pytest.mark.parametrize("args", ["foo", datetime(2000, 1, 1, 0, 0)]) + def test_constructor_invalid_args_wrong_type(self, args): + msg = f"Wrong type {type(args)} for value {args}" + with pytest.raises(TypeError, match=msg): + RangeIndex(args) + + def test_constructor_same(self): + # pass thru w and w/o copy + index = RangeIndex(1, 5, 2) + result = RangeIndex(index, copy=False) + assert result.identical(index) + + result = RangeIndex(index, copy=True) + tm.assert_index_equal(result, index, exact=True) + + result = RangeIndex(index) + tm.assert_index_equal(result, index, exact=True) + + with pytest.raises( + ValueError, + match="Incorrect `dtype` passed: expected signed integer, received float64", + ): + RangeIndex(index, dtype="float64") + + def test_constructor_range_object(self): + result = RangeIndex(range(1, 5, 2)) + expected = RangeIndex(1, 5, 2) + tm.assert_index_equal(result, expected, exact=True) + + def test_constructor_range(self): + result = RangeIndex.from_range(range(1, 5, 2)) + expected = RangeIndex(1, 5, 2) + tm.assert_index_equal(result, expected, exact=True) + + result = RangeIndex.from_range(range(5, 6)) + expected = RangeIndex(5, 6, 1) + tm.assert_index_equal(result, expected, exact=True) + + # an invalid range + result = RangeIndex.from_range(range(5, 1)) + expected = RangeIndex(0, 0, 1) + tm.assert_index_equal(result, expected, exact=True) + + result = RangeIndex.from_range(range(5)) + expected = RangeIndex(0, 5, 1) + tm.assert_index_equal(result, expected, exact=True) + + result = Index(range(1, 5, 2)) + expected = RangeIndex(1, 5, 2) + tm.assert_index_equal(result, expected, exact=True) + + msg = ( + r"(RangeIndex.)?from_range\(\) got an unexpected keyword argument( 'copy')?" + ) + with pytest.raises(TypeError, match=msg): + RangeIndex.from_range(range(10), copy=True) + + def test_constructor_name(self): + # GH#12288 + orig = RangeIndex(10) + orig.name = "original" + + copy = RangeIndex(orig) + copy.name = "copy" + + assert orig.name == "original" + assert copy.name == "copy" + + new = Index(copy) + assert new.name == "copy" + + new.name = "new" + assert orig.name == "original" + assert copy.name == "copy" + assert new.name == "new" + + def test_constructor_corner(self): + arr = np.array([1, 2, 3, 4], dtype=object) + index = RangeIndex(1, 5) + assert index.values.dtype == np.int64 + expected = Index(arr).astype("int64") + + tm.assert_index_equal(index, expected, exact="equiv") + + # non-int raise Exception + with pytest.raises(TypeError, match=r"Wrong type \"): + RangeIndex("1", "10", "1") + with pytest.raises(TypeError, match=r"Wrong type \"): + RangeIndex(1.1, 10.2, 1.3) + + # invalid passed type + with pytest.raises( + ValueError, + match="Incorrect `dtype` passed: expected signed integer, received float64", + ): + RangeIndex(1, 5, dtype="float64") diff --git a/shared/package-files/71/71e78a76c67a5351f8d040fe2a6b551a46c00f1796313546d3b25af0fecdfcf8/__init__.py b/shared/package-files/71/71e78a76c67a5351f8d040fe2a6b551a46c00f1796313546d3b25af0fecdfcf8/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cf15ddb592541a959149842a4d581cf9f0a3e5e1 --- /dev/null +++ b/shared/package-files/71/71e78a76c67a5351f8d040fe2a6b551a46c00f1796313546d3b25af0fecdfcf8/__init__.py @@ -0,0 +1,27 @@ +""" +Subpackages related to graph-minor problems. + +In graph theory, an undirected graph H is called a minor of the graph G if H +can be formed from G by deleting edges and vertices and by contracting edges +[1]_. + +References +---------- +.. [1] https://en.wikipedia.org/wiki/Graph_minor +""" + +from networkx.algorithms.minors.contraction import ( + contracted_edge, + contracted_nodes, + equivalence_classes, + identified_nodes, + quotient_graph, +) + +__all__ = [ + "contracted_edge", + "contracted_nodes", + "equivalence_classes", + "identified_nodes", + "quotient_graph", +] diff --git a/shared/package-files/71/71e7cd5fc57d5ec6829a0b8eddedf6b5835d7d49df307678f06bbcb265140aec/stringold.pyi b/shared/package-files/71/71e7cd5fc57d5ec6829a0b8eddedf6b5835d7d49df307678f06bbcb265140aec/stringold.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ea11da72575dd252278248bc2531cbf6008cf78f --- /dev/null +++ b/shared/package-files/71/71e7cd5fc57d5ec6829a0b8eddedf6b5835d7d49df307678f06bbcb265140aec/stringold.pyi @@ -0,0 +1,44 @@ +from typing import AnyStr, Iterable, List, Optional, Type + +whitespace: str +lowercase: str +uppercase: str +letters: str +digits: str +hexdigits: str +octdigits: str +_idmap: str +_idmapL: Optional[List[str]] +index_error = ValueError +atoi_error = ValueError +atof_error = ValueError +atol_error = ValueError + +def lower(s: AnyStr) -> AnyStr: ... +def upper(s: AnyStr) -> AnyStr: ... +def swapcase(s: AnyStr) -> AnyStr: ... +def strip(s: AnyStr) -> AnyStr: ... +def lstrip(s: AnyStr) -> AnyStr: ... +def rstrip(s: AnyStr) -> AnyStr: ... +def split(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def splitfields(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def join(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... +def joinfields(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... +def index(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def rindex(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def count(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def find(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def rfind(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def atof(s: unicode) -> float: ... +def atoi(s: unicode, base: int = ...) -> int: ... +def atol(s: unicode, base: int = ...) -> long: ... +def ljust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def rjust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def center(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def zfill(s: AnyStr, width: int) -> AnyStr: ... +def expandtabs(s: AnyStr, tabsize: int = ...) -> AnyStr: ... +def translate(s: str, table: str, deletions: str = ...) -> str: ... +def capitalize(s: AnyStr) -> AnyStr: ... +def capwords(s: AnyStr, sep: AnyStr = ...) -> AnyStr: ... +def maketrans(fromstr: str, tostr: str) -> str: ... +def replace(s: AnyStr, old: AnyStr, new: AnyStr, maxreplace: int = ...) -> AnyStr: ... diff --git a/shared/package-files/71/71ea4a132597be2891b931d7f1ccb5ff7811aa6353bc13bd9490df7ef18feabc/test_dist.py b/shared/package-files/71/71ea4a132597be2891b931d7f1ccb5ff7811aa6353bc13bd9490df7ef18feabc/test_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..f8a9e86b16f0b579fbc241ac8bc843f5a5f18244 --- /dev/null +++ b/shared/package-files/71/71ea4a132597be2891b931d7f1ccb5ff7811aa6353bc13bd9490df7ef18feabc/test_dist.py @@ -0,0 +1,529 @@ +"""Tests for distutils.dist.""" +import os +import io +import sys +import unittest +import warnings +import textwrap + +from unittest import mock + +from distutils.dist import Distribution, fix_help_options +from distutils.cmd import Command + +from test.support import ( + captured_stdout, captured_stderr, run_unittest +) +from test.support.os_helper import TESTFN +from distutils.tests import support +from distutils import log + + +class test_dist(Command): + """Sample distutils extension command.""" + + user_options = [ + ("sample-option=", "S", "help text"), + ] + + def initialize_options(self): + self.sample_option = None + + +class TestDistribution(Distribution): + """Distribution subclasses that avoids the default search for + configuration files. + + The ._config_files attribute must be set before + .parse_config_files() is called. + """ + + def find_config_files(self): + return self._config_files + + +class DistributionTestCase(support.LoggingSilencer, + support.TempdirManager, + support.EnvironGuard, + unittest.TestCase): + + def setUp(self): + super(DistributionTestCase, self).setUp() + self.argv = sys.argv, sys.argv[:] + del sys.argv[1:] + + def tearDown(self): + sys.argv = self.argv[0] + sys.argv[:] = self.argv[1] + super(DistributionTestCase, self).tearDown() + + def create_distribution(self, configfiles=()): + d = TestDistribution() + d._config_files = configfiles + d.parse_config_files() + d.parse_command_line() + return d + + def test_command_packages_unspecified(self): + sys.argv.append("build") + d = self.create_distribution() + self.assertEqual(d.get_command_packages(), ["distutils.command"]) + + def test_command_packages_cmdline(self): + from distutils.tests.test_dist import test_dist + sys.argv.extend(["--command-packages", + "foo.bar,distutils.tests", + "test_dist", + "-Ssometext", + ]) + d = self.create_distribution() + # let's actually try to load our test command: + self.assertEqual(d.get_command_packages(), + ["distutils.command", "foo.bar", "distutils.tests"]) + cmd = d.get_command_obj("test_dist") + self.assertIsInstance(cmd, test_dist) + self.assertEqual(cmd.sample_option, "sometext") + + def test_venv_install_options(self): + sys.argv.append("install") + self.addCleanup(os.unlink, TESTFN) + + fakepath = '/somedir' + + with open(TESTFN, "w") as f: + print(("[install]\n" + "install-base = {0}\n" + "install-platbase = {0}\n" + "install-lib = {0}\n" + "install-platlib = {0}\n" + "install-purelib = {0}\n" + "install-headers = {0}\n" + "install-scripts = {0}\n" + "install-data = {0}\n" + "prefix = {0}\n" + "exec-prefix = {0}\n" + "home = {0}\n" + "user = {0}\n" + "root = {0}").format(fakepath), file=f) + + # Base case: Not in a Virtual Environment + with mock.patch.multiple(sys, prefix='/a', base_prefix='/a') as values: + d = self.create_distribution([TESTFN]) + + option_tuple = (TESTFN, fakepath) + + result_dict = { + 'install_base': option_tuple, + 'install_platbase': option_tuple, + 'install_lib': option_tuple, + 'install_platlib': option_tuple, + 'install_purelib': option_tuple, + 'install_headers': option_tuple, + 'install_scripts': option_tuple, + 'install_data': option_tuple, + 'prefix': option_tuple, + 'exec_prefix': option_tuple, + 'home': option_tuple, + 'user': option_tuple, + 'root': option_tuple, + } + + self.assertEqual( + sorted(d.command_options.get('install').keys()), + sorted(result_dict.keys())) + + for (key, value) in d.command_options.get('install').items(): + self.assertEqual(value, result_dict[key]) + + # Test case: In a Virtual Environment + with mock.patch.multiple(sys, prefix='/a', base_prefix='/b') as values: + d = self.create_distribution([TESTFN]) + + for key in result_dict.keys(): + self.assertNotIn(key, d.command_options.get('install', {})) + + def test_command_packages_configfile(self): + sys.argv.append("build") + self.addCleanup(os.unlink, TESTFN) + f = open(TESTFN, "w") + try: + print("[global]", file=f) + print("command_packages = foo.bar, splat", file=f) + finally: + f.close() + + d = self.create_distribution([TESTFN]) + self.assertEqual(d.get_command_packages(), + ["distutils.command", "foo.bar", "splat"]) + + # ensure command line overrides config: + sys.argv[1:] = ["--command-packages", "spork", "build"] + d = self.create_distribution([TESTFN]) + self.assertEqual(d.get_command_packages(), + ["distutils.command", "spork"]) + + # Setting --command-packages to '' should cause the default to + # be used even if a config file specified something else: + sys.argv[1:] = ["--command-packages", "", "build"] + d = self.create_distribution([TESTFN]) + self.assertEqual(d.get_command_packages(), ["distutils.command"]) + + def test_empty_options(self): + # an empty options dictionary should not stay in the + # list of attributes + + # catching warnings + warns = [] + + def _warn(msg): + warns.append(msg) + + self.addCleanup(setattr, warnings, 'warn', warnings.warn) + warnings.warn = _warn + dist = Distribution(attrs={'author': 'xxx', 'name': 'xxx', + 'version': 'xxx', 'url': 'xxxx', + 'options': {}}) + + self.assertEqual(len(warns), 0) + self.assertNotIn('options', dir(dist)) + + def test_finalize_options(self): + attrs = {'keywords': 'one,two', + 'platforms': 'one,two'} + + dist = Distribution(attrs=attrs) + dist.finalize_options() + + # finalize_option splits platforms and keywords + self.assertEqual(dist.metadata.platforms, ['one', 'two']) + self.assertEqual(dist.metadata.keywords, ['one', 'two']) + + attrs = {'keywords': 'foo bar', + 'platforms': 'foo bar'} + dist = Distribution(attrs=attrs) + dist.finalize_options() + self.assertEqual(dist.metadata.platforms, ['foo bar']) + self.assertEqual(dist.metadata.keywords, ['foo bar']) + + def test_get_command_packages(self): + dist = Distribution() + self.assertEqual(dist.command_packages, None) + cmds = dist.get_command_packages() + self.assertEqual(cmds, ['distutils.command']) + self.assertEqual(dist.command_packages, + ['distutils.command']) + + dist.command_packages = 'one,two' + cmds = dist.get_command_packages() + self.assertEqual(cmds, ['distutils.command', 'one', 'two']) + + def test_announce(self): + # make sure the level is known + dist = Distribution() + args = ('ok',) + kwargs = {'level': 'ok2'} + self.assertRaises(ValueError, dist.announce, args, kwargs) + + + def test_find_config_files_disable(self): + # Ticket #1180: Allow user to disable their home config file. + temp_home = self.mkdtemp() + if os.name == 'posix': + user_filename = os.path.join(temp_home, ".pydistutils.cfg") + else: + user_filename = os.path.join(temp_home, "pydistutils.cfg") + + with open(user_filename, 'w') as f: + f.write('[distutils]\n') + + def _expander(path): + return temp_home + + old_expander = os.path.expanduser + os.path.expanduser = _expander + try: + d = Distribution() + all_files = d.find_config_files() + + d = Distribution(attrs={'script_args': ['--no-user-cfg']}) + files = d.find_config_files() + finally: + os.path.expanduser = old_expander + + # make sure --no-user-cfg disables the user cfg file + self.assertEqual(len(all_files)-1, len(files)) + +class MetadataTestCase(support.TempdirManager, support.EnvironGuard, + unittest.TestCase): + + def setUp(self): + super(MetadataTestCase, self).setUp() + self.argv = sys.argv, sys.argv[:] + + def tearDown(self): + sys.argv = self.argv[0] + sys.argv[:] = self.argv[1] + super(MetadataTestCase, self).tearDown() + + def format_metadata(self, dist): + sio = io.StringIO() + dist.metadata.write_pkg_file(sio) + return sio.getvalue() + + def test_simple_metadata(self): + attrs = {"name": "package", + "version": "1.0"} + dist = Distribution(attrs) + meta = self.format_metadata(dist) + self.assertIn("Metadata-Version: 1.0", meta) + self.assertNotIn("provides:", meta.lower()) + self.assertNotIn("requires:", meta.lower()) + self.assertNotIn("obsoletes:", meta.lower()) + + def test_provides(self): + attrs = {"name": "package", + "version": "1.0", + "provides": ["package", "package.sub"]} + dist = Distribution(attrs) + self.assertEqual(dist.metadata.get_provides(), + ["package", "package.sub"]) + self.assertEqual(dist.get_provides(), + ["package", "package.sub"]) + meta = self.format_metadata(dist) + self.assertIn("Metadata-Version: 1.1", meta) + self.assertNotIn("requires:", meta.lower()) + self.assertNotIn("obsoletes:", meta.lower()) + + def test_provides_illegal(self): + self.assertRaises(ValueError, Distribution, + {"name": "package", + "version": "1.0", + "provides": ["my.pkg (splat)"]}) + + def test_requires(self): + attrs = {"name": "package", + "version": "1.0", + "requires": ["other", "another (==1.0)"]} + dist = Distribution(attrs) + self.assertEqual(dist.metadata.get_requires(), + ["other", "another (==1.0)"]) + self.assertEqual(dist.get_requires(), + ["other", "another (==1.0)"]) + meta = self.format_metadata(dist) + self.assertIn("Metadata-Version: 1.1", meta) + self.assertNotIn("provides:", meta.lower()) + self.assertIn("Requires: other", meta) + self.assertIn("Requires: another (==1.0)", meta) + self.assertNotIn("obsoletes:", meta.lower()) + + def test_requires_illegal(self): + self.assertRaises(ValueError, Distribution, + {"name": "package", + "version": "1.0", + "requires": ["my.pkg (splat)"]}) + + def test_requires_to_list(self): + attrs = {"name": "package", + "requires": iter(["other"])} + dist = Distribution(attrs) + self.assertIsInstance(dist.metadata.requires, list) + + + def test_obsoletes(self): + attrs = {"name": "package", + "version": "1.0", + "obsoletes": ["other", "another (<1.0)"]} + dist = Distribution(attrs) + self.assertEqual(dist.metadata.get_obsoletes(), + ["other", "another (<1.0)"]) + self.assertEqual(dist.get_obsoletes(), + ["other", "another (<1.0)"]) + meta = self.format_metadata(dist) + self.assertIn("Metadata-Version: 1.1", meta) + self.assertNotIn("provides:", meta.lower()) + self.assertNotIn("requires:", meta.lower()) + self.assertIn("Obsoletes: other", meta) + self.assertIn("Obsoletes: another (<1.0)", meta) + + def test_obsoletes_illegal(self): + self.assertRaises(ValueError, Distribution, + {"name": "package", + "version": "1.0", + "obsoletes": ["my.pkg (splat)"]}) + + def test_obsoletes_to_list(self): + attrs = {"name": "package", + "obsoletes": iter(["other"])} + dist = Distribution(attrs) + self.assertIsInstance(dist.metadata.obsoletes, list) + + def test_classifier(self): + attrs = {'name': 'Boa', 'version': '3.0', + 'classifiers': ['Programming Language :: Python :: 3']} + dist = Distribution(attrs) + self.assertEqual(dist.get_classifiers(), + ['Programming Language :: Python :: 3']) + meta = self.format_metadata(dist) + self.assertIn('Metadata-Version: 1.1', meta) + + def test_classifier_invalid_type(self): + attrs = {'name': 'Boa', 'version': '3.0', + 'classifiers': ('Programming Language :: Python :: 3',)} + with captured_stderr() as error: + d = Distribution(attrs) + # should have warning about passing a non-list + self.assertIn('should be a list', error.getvalue()) + # should be converted to a list + self.assertIsInstance(d.metadata.classifiers, list) + self.assertEqual(d.metadata.classifiers, + list(attrs['classifiers'])) + + def test_keywords(self): + attrs = {'name': 'Monty', 'version': '1.0', + 'keywords': ['spam', 'eggs', 'life of brian']} + dist = Distribution(attrs) + self.assertEqual(dist.get_keywords(), + ['spam', 'eggs', 'life of brian']) + + def test_keywords_invalid_type(self): + attrs = {'name': 'Monty', 'version': '1.0', + 'keywords': ('spam', 'eggs', 'life of brian')} + with captured_stderr() as error: + d = Distribution(attrs) + # should have warning about passing a non-list + self.assertIn('should be a list', error.getvalue()) + # should be converted to a list + self.assertIsInstance(d.metadata.keywords, list) + self.assertEqual(d.metadata.keywords, list(attrs['keywords'])) + + def test_platforms(self): + attrs = {'name': 'Monty', 'version': '1.0', + 'platforms': ['GNU/Linux', 'Some Evil Platform']} + dist = Distribution(attrs) + self.assertEqual(dist.get_platforms(), + ['GNU/Linux', 'Some Evil Platform']) + + def test_platforms_invalid_types(self): + attrs = {'name': 'Monty', 'version': '1.0', + 'platforms': ('GNU/Linux', 'Some Evil Platform')} + with captured_stderr() as error: + d = Distribution(attrs) + # should have warning about passing a non-list + self.assertIn('should be a list', error.getvalue()) + # should be converted to a list + self.assertIsInstance(d.metadata.platforms, list) + self.assertEqual(d.metadata.platforms, list(attrs['platforms'])) + + def test_download_url(self): + attrs = {'name': 'Boa', 'version': '3.0', + 'download_url': 'http://example.org/boa'} + dist = Distribution(attrs) + meta = self.format_metadata(dist) + self.assertIn('Metadata-Version: 1.1', meta) + + def test_long_description(self): + long_desc = textwrap.dedent("""\ + example:: + We start here + and continue here + and end here.""") + attrs = {"name": "package", + "version": "1.0", + "long_description": long_desc} + + dist = Distribution(attrs) + meta = self.format_metadata(dist) + meta = meta.replace('\n' + 8 * ' ', '\n') + self.assertIn(long_desc, meta) + + def test_custom_pydistutils(self): + # fixes #2166 + # make sure pydistutils.cfg is found + if os.name == 'posix': + user_filename = ".pydistutils.cfg" + else: + user_filename = "pydistutils.cfg" + + temp_dir = self.mkdtemp() + user_filename = os.path.join(temp_dir, user_filename) + f = open(user_filename, 'w') + try: + f.write('.') + finally: + f.close() + + try: + dist = Distribution() + + # linux-style + if sys.platform in ('linux', 'darwin'): + os.environ['HOME'] = temp_dir + files = dist.find_config_files() + self.assertIn(user_filename, files) + + # win32-style + if sys.platform == 'win32': + # home drive should be found + os.environ['USERPROFILE'] = temp_dir + files = dist.find_config_files() + self.assertIn(user_filename, files, + '%r not found in %r' % (user_filename, files)) + finally: + os.remove(user_filename) + + def test_fix_help_options(self): + help_tuples = [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] + fancy_options = fix_help_options(help_tuples) + self.assertEqual(fancy_options[0], ('a', 'b', 'c')) + self.assertEqual(fancy_options[1], (1, 2, 3)) + + def test_show_help(self): + # smoke test, just makes sure some help is displayed + self.addCleanup(log.set_threshold, log._global_log.threshold) + dist = Distribution() + sys.argv = [] + dist.help = 1 + dist.script_name = 'setup.py' + with captured_stdout() as s: + dist.parse_command_line() + + output = [line for line in s.getvalue().split('\n') + if line.strip() != ''] + self.assertTrue(output) + + + def test_read_metadata(self): + attrs = {"name": "package", + "version": "1.0", + "long_description": "desc", + "description": "xxx", + "download_url": "http://example.com", + "keywords": ['one', 'two'], + "requires": ['foo']} + + dist = Distribution(attrs) + metadata = dist.metadata + + # write it then reloads it + PKG_INFO = io.StringIO() + metadata.write_pkg_file(PKG_INFO) + PKG_INFO.seek(0) + metadata.read_pkg_file(PKG_INFO) + + self.assertEqual(metadata.name, "package") + self.assertEqual(metadata.version, "1.0") + self.assertEqual(metadata.description, "xxx") + self.assertEqual(metadata.download_url, 'http://example.com') + self.assertEqual(metadata.keywords, ['one', 'two']) + self.assertEqual(metadata.platforms, ['UNKNOWN']) + self.assertEqual(metadata.obsoletes, None) + self.assertEqual(metadata.requires, ['foo']) + +def test_suite(): + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(DistributionTestCase)) + suite.addTest(unittest.makeSuite(MetadataTestCase)) + return suite + +if __name__ == "__main__": + run_unittest(test_suite()) diff --git a/shared/package-files/71/71ec2aab2b6b42204c72e9a8e1d212d7d3f3f827034cbbb044c3ca7754990c8c/tanh_backward_compositeexplicitautogradnonfunctional_dispatch.h b/shared/package-files/71/71ec2aab2b6b42204c72e9a8e1d212d7d3f3f827034cbbb044c3ca7754990c8c/tanh_backward_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..e6753baba53931e77faee19f7a7f197229656b1c --- /dev/null +++ b/shared/package-files/71/71ec2aab2b6b42204c72e9a8e1d212d7d3f3f827034cbbb044c3ca7754990c8c/tanh_backward_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor tanh_backward(const at::Tensor & grad_output, const at::Tensor & output); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/71/71edca765774aab238169c781fc01e487bb96d91a6b17346b162667c603566c0/lark.py b/shared/package-files/71/71edca765774aab238169c781fc01e487bb96d91a6b17346b162667c603566c0/lark.py new file mode 100644 index 0000000000000000000000000000000000000000..37b5f5d40133d2c4708a79e790c6f96712192f98 --- /dev/null +++ b/shared/package-files/71/71edca765774aab238169c781fc01e487bb96d91a6b17346b162667c603566c0/lark.py @@ -0,0 +1,239 @@ +# This file is part of Hypothesis, which may be found at +# https://github.com/HypothesisWorks/hypothesis/ +# +# Copyright the Hypothesis Authors. +# Individual contributors are listed in AUTHORS.rst and the git log. +# +# This Source Code Form is subject to the terms of the Mozilla Public License, +# v. 2.0. If a copy of the MPL was not distributed with this file, You can +# obtain one at https://mozilla.org/MPL/2.0/. + +""" +---------------- +hypothesis[lark] +---------------- + +This extra can be used to generate strings matching any context-free grammar, +using the `Lark parser library `_. + +It currently only supports Lark's native EBNF syntax, but we plan to extend +this to support other common syntaxes such as ANTLR and :rfc:`5234` ABNF. +Lark already `supports loading grammars +`_ +from `nearley.js `_, so you may not have to write +your own at all. +""" + +from inspect import signature +from typing import Dict, Optional + +import lark +from lark.grammar import NonTerminal, Terminal + +from hypothesis import strategies as st +from hypothesis.errors import InvalidArgument +from hypothesis.internal.conjecture.utils import calc_label_from_name +from hypothesis.internal.validation import check_type +from hypothesis.strategies._internal.regex import IncompatibleWithAlphabet +from hypothesis.strategies._internal.utils import cacheable, defines_strategy + +__all__ = ["from_lark"] + + +def get_terminal_names(terminals, rules, ignore_names): + """Get names of all terminals in the grammar. + + The arguments are the results of calling ``Lark.grammar.compile()``, + so you would think that the ``terminals`` and ``ignore_names`` would + have it all... but they omit terminals created with ``@declare``, + which appear only in the expansion(s) of nonterminals. + """ + names = {t.name for t in terminals} | set(ignore_names) + for rule in rules: + names |= {t.name for t in rule.expansion if isinstance(t, Terminal)} + return names + + +class LarkStrategy(st.SearchStrategy): + """Low-level strategy implementation wrapping a Lark grammar. + + See ``from_lark`` for details. + """ + + def __init__(self, grammar, start, explicit, alphabet): + assert isinstance(grammar, lark.lark.Lark) + if start is None: + start = grammar.options.start + if not isinstance(start, list): + start = [start] + self.grammar = grammar + + # This is a total hack, but working around the changes is a nicer user + # experience than breaking for anyone who doesn't instantly update their + # installation of Lark alongside Hypothesis. + compile_args = signature(grammar.grammar.compile).parameters + if "terminals_to_keep" in compile_args: + terminals, rules, ignore_names = grammar.grammar.compile(start, ()) + elif "start" in compile_args: # pragma: no cover + # Support lark <= 0.10.0, without the terminals_to_keep argument. + terminals, rules, ignore_names = grammar.grammar.compile(start) + else: # pragma: no cover + # This branch is to support lark <= 0.7.1, without the start argument. + terminals, rules, ignore_names = grammar.grammar.compile() + + self.names_to_symbols = {} + + for r in rules: + t = r.origin + self.names_to_symbols[t.name] = t + + disallowed = set() + self.terminal_strategies = {} + for t in terminals: + self.names_to_symbols[t.name] = Terminal(t.name) + s = st.from_regex(t.pattern.to_regexp(), fullmatch=True, alphabet=alphabet) + try: + s.validate() + except IncompatibleWithAlphabet: + disallowed.add(t.name) + else: + self.terminal_strategies[t.name] = s + + self.ignored_symbols = tuple(self.names_to_symbols[n] for n in ignore_names) + + all_terminals = get_terminal_names(terminals, rules, ignore_names) + if unknown_explicit := sorted(set(explicit) - all_terminals): + raise InvalidArgument( + "The following arguments were passed as explicit_strategies, but " + f"there is no {unknown_explicit} terminal production in this grammar." + ) + if missing_declared := sorted( + all_terminals - {t.name for t in terminals} - set(explicit) + ): + raise InvalidArgument( + f"Undefined terminal{'s' * (len(missing_declared) > 1)} " + f"{sorted(missing_declared)!r}. Generation does not currently " + "support use of %declare unless you pass `explicit`, a dict of " + f"names-to-strategies, such as `{{{missing_declared[0]!r}: " + 'st.just("")}}`' + ) + self.terminal_strategies.update(explicit) + + nonterminals = {} + + for rule in rules: + if disallowed.isdisjoint(r.name for r in rule.expansion): + nonterminals.setdefault(rule.origin.name, []).append( + tuple(rule.expansion) + ) + + allowed_rules = {*self.terminal_strategies, *nonterminals} + while dict(nonterminals) != ( + nonterminals := { + k: clean + for k, v in nonterminals.items() + if (clean := [x for x in v if all(r.name in allowed_rules for r in x)]) + } + ): + allowed_rules = {*self.terminal_strategies, *nonterminals} + + if set(start).isdisjoint(allowed_rules): + raise InvalidArgument( + f"No start rule {tuple(start)} is allowed by {alphabet=}" + ) + self.start = st.sampled_from( + [self.names_to_symbols[s] for s in start if s in allowed_rules] + ) + + self.nonterminal_strategies = { + k: st.sampled_from(sorted(v, key=len)) for k, v in nonterminals.items() + } + + self.__rule_labels = {} + + def do_draw(self, data): + state = [] + start = data.draw(self.start) + self.draw_symbol(data, start, state) + return "".join(state) + + def rule_label(self, name): + try: + return self.__rule_labels[name] + except KeyError: + return self.__rule_labels.setdefault( + name, calc_label_from_name(f"LARK:{name}") + ) + + def draw_symbol(self, data, symbol, draw_state): + if isinstance(symbol, Terminal): + strategy = self.terminal_strategies[symbol.name] + draw_state.append(data.draw(strategy)) + else: + assert isinstance(symbol, NonTerminal) + data.start_example(self.rule_label(symbol.name)) + expansion = data.draw(self.nonterminal_strategies[symbol.name]) + for e in expansion: + self.draw_symbol(data, e, draw_state) + self.gen_ignore(data, draw_state) + data.stop_example() + + def gen_ignore(self, data, draw_state): + if self.ignored_symbols and data.draw_boolean(1 / 4): + emit = data.draw(st.sampled_from(self.ignored_symbols)) + self.draw_symbol(data, emit, draw_state) + + def calc_has_reusable_values(self, recur): + return True + + +def check_explicit(name): + def inner(value): + check_type(str, value, "value drawn from " + name) + return value + + return inner + + +@cacheable +@defines_strategy(force_reusable_values=True) +def from_lark( + grammar: lark.lark.Lark, + *, + start: Optional[str] = None, + explicit: Optional[Dict[str, st.SearchStrategy[str]]] = None, + alphabet: st.SearchStrategy[str] = st.characters(codec="utf-8"), +) -> st.SearchStrategy[str]: + """A strategy for strings accepted by the given context-free grammar. + + ``grammar`` must be a ``Lark`` object, which wraps an EBNF specification. + The Lark EBNF grammar reference can be found + `here `_. + + ``from_lark`` will automatically generate strings matching the + nonterminal ``start`` symbol in the grammar, which was supplied as an + argument to the Lark class. To generate strings matching a different + symbol, including terminals, you can override this by passing the + ``start`` argument to ``from_lark``. Note that Lark may remove unreachable + productions when the grammar is compiled, so you should probably pass the + same value for ``start`` to both. + + Currently ``from_lark`` does not support grammars that need custom lexing. + Any lexers will be ignored, and any undefined terminals from the use of + ``%declare`` will result in generation errors. To define strategies for + such terminals, pass a dictionary mapping their name to a corresponding + strategy as the ``explicit`` argument. + + The :pypi:`hypothesmith` project includes a strategy for Python source, + based on a grammar and careful post-processing. + """ + check_type(lark.lark.Lark, grammar, "grammar") + if explicit is None: + explicit = {} + else: + check_type(dict, explicit, "explicit") + explicit = { + k: v.map(check_explicit(f"explicit[{k!r}]={v!r}")) + for k, v in explicit.items() + } + return LarkStrategy(grammar, start, explicit, alphabet) diff --git a/shared/package-files/71/71efbf4f9770abf4c9200ecb7e746be40ca810f029b2ec2f87d9048665a82617/zeros_compositeexplicitautograd_dispatch.h b/shared/package-files/71/71efbf4f9770abf4c9200ecb7e746be40ca810f029b2ec2f87d9048665a82617/zeros_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..cccf22d5e96f0851d0ca80f821f3e56abea0b7b2 --- /dev/null +++ b/shared/package-files/71/71efbf4f9770abf4c9200ecb7e746be40ca810f029b2ec2f87d9048665a82617/zeros_compositeexplicitautograd_dispatch.h @@ -0,0 +1,34 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor zeros(at::IntArrayRef size, c10::optional names, at::TensorOptions options={}); +TORCH_API at::Tensor zeros(at::IntArrayRef size, c10::optional names, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +TORCH_API at::Tensor & zeros_out(at::Tensor & out, at::IntArrayRef size, c10::optional names); +TORCH_API at::Tensor & zeros_outf(at::IntArrayRef size, c10::optional names, at::Tensor & out); +TORCH_API at::Tensor zeros(at::IntArrayRef size, at::TensorOptions options={}); +TORCH_API at::Tensor zeros(at::IntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +TORCH_API at::Tensor zeros_symint(c10::SymIntArrayRef size, at::TensorOptions options={}); +TORCH_API at::Tensor zeros_symint(c10::SymIntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +TORCH_API at::Tensor & zeros_out(at::Tensor & out, at::IntArrayRef size); +TORCH_API at::Tensor & zeros_outf(at::IntArrayRef size, at::Tensor & out); +TORCH_API at::Tensor & zeros_symint_out(at::Tensor & out, c10::SymIntArrayRef size); +TORCH_API at::Tensor & zeros_symint_outf(c10::SymIntArrayRef size, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/71/71efc856e6c177b27a1644a92660fba8c9512eec268a27613aa8587d96f5e96a/array_like.py b/shared/package-files/71/71efc856e6c177b27a1644a92660fba8c9512eec268a27613aa8587d96f5e96a/array_like.py new file mode 100644 index 0000000000000000000000000000000000000000..da2520e961e7a3b2d38e0e04183378851c17b479 --- /dev/null +++ b/shared/package-files/71/71efc856e6c177b27a1644a92660fba8c9512eec268a27613aa8587d96f5e96a/array_like.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from typing import Any + +import numpy as np +from numpy._typing import ArrayLike, _SupportsArray + +x1: ArrayLike = True +x2: ArrayLike = 5 +x3: ArrayLike = 1.0 +x4: ArrayLike = 1 + 1j +x5: ArrayLike = np.int8(1) +x6: ArrayLike = np.float64(1) +x7: ArrayLike = np.complex128(1) +x8: ArrayLike = np.array([1, 2, 3]) +x9: ArrayLike = [1, 2, 3] +x10: ArrayLike = (1, 2, 3) +x11: ArrayLike = "foo" +x12: ArrayLike = memoryview(b'foo') + + +class A: + def __array__(self, dtype: None | np.dtype[Any] = None) -> np.ndarray: + return np.array([1, 2, 3]) + + +x13: ArrayLike = A() + +scalar: _SupportsArray = np.int64(1) +scalar.__array__() +array: _SupportsArray = np.array(1) +array.__array__() + +a: _SupportsArray = A() +a.__array__() +a.__array__() + +# Escape hatch for when you mean to make something like an object +# array. +object_array_scalar: Any = (i for i in range(10)) +np.array(object_array_scalar) diff --git a/shared/package-files/71/71f2cc221f72c366f2986ecb7561f722dc1fa8abe77de8f6eecd60895b672b31/ncr160vt300wpp b/shared/package-files/71/71f2cc221f72c366f2986ecb7561f722dc1fa8abe77de8f6eecd60895b672b31/ncr160vt300wpp new file mode 100644 index 0000000000000000000000000000000000000000..96cf1b90c46a6f9157c52dba4056ddf08a1f6a12 Binary files /dev/null and b/shared/package-files/71/71f2cc221f72c366f2986ecb7561f722dc1fa8abe77de8f6eecd60895b672b31/ncr160vt300wpp differ diff --git a/shared/package-files/71/71f38d9c5697858311f683576918926f9d3174a3c1ad6b12e137032102010e70/profiler.py b/shared/package-files/71/71f38d9c5697858311f683576918926f9d3174a3c1ad6b12e137032102010e70/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..b52551c67137519ce65b49c4416fd08c814545ed --- /dev/null +++ b/shared/package-files/71/71f38d9c5697858311f683576918926f9d3174a3c1ad6b12e137032102010e70/profiler.py @@ -0,0 +1,155 @@ +import dataclasses +import os +from typing import Any, List + +import torch + +from .utils import print_once + + +@dataclasses.dataclass +class ProfileMetrics: + microseconds: float = 0.0 + operators: int = 0 + fusions: int = 0 + graphs: int = 0 + + def __iadd__(self, other: "ProfileMetrics"): + self.microseconds += other.microseconds + self.operators += other.operators + self.fusions += other.fusions + return self + + def __add__(self, other: "ProfileMetrics"): + assert isinstance(other, ProfileMetrics) + return ProfileMetrics( + self.microseconds + other.microseconds, + self.operators + other.operators, + self.fusions + other.fusions, + ) + + def __truediv__(self, other): + if isinstance(other, int): + other = ProfileMetrics(other, other, other) + return ProfileMetrics( + self.microseconds / max(1, other.microseconds), + self.operators / max(1, other.operators), + self.fusions / max(1, other.fusions), + ) + + def __str__(self): + return f"{self.operators:4.0%} ops {self.microseconds:4.0%} time" + + def tocsv(self): + return [self.operators, self.microseconds] + + +class ProfileResult: + def __init__(self, captured, total, unique_graphs): + self.captured: ProfileMetrics = captured or ProfileMetrics() + self.total: ProfileMetrics = total or ProfileMetrics() + self.unique_graphs: int = unique_graphs + + def __iadd__(self, other: "ProfileResult"): + self.captured += other.captured + self.total += other.total + self.unique_graphs += other.unique_graphs + return self + + def percent(self): + return self.captured / self.total + + def __str__(self): + return ( + f"{self.unique_graphs:2} graphs {self.captured.graphs:2} graph calls " + f"{self.captured.operators:4}/{self.total.operators:4} = " + + str(self.percent()) + ) + + def tocsv(self): + return [ + self.unique_graphs, + self.captured.graphs, + self.captured.operators, + self.total.operators, + ] + self.percent().tocsv() + + +def should_print_missing(): + return os.environ.get("TORCHDYNAMO_PRINT_MISSING") == "1" + + +def print_missing(stack): + if any("/torch/autograd/profiler.py" in x for x in stack): + return + stack = [ + x for x in stack if ("> ".join(stack[-3:])) + + +class Profiler: + unique_graphs = 0 + + def __init__(self): + self.prof = torch.profiler.profile( + activities=[torch.profiler.ProfilerActivity.CPU], + with_stack=should_print_missing(), + ) + + def results(self): + captured_regions = 0 + captured_ops = 0 + captured_microseconds = 0 + total_ops = 0 + total_microseconds = 0 + + last_op_end_time = -1 + captured_region_end_time = -1 + events = sorted(self.prof.events(), key=lambda x: x.time_range.start) + for e in events: + if e.name == "TORCHDYNAMO": + captured_region_end_time = e.time_range.end + captured_regions += 1 + # ignore `handle = torch.zeros(1)` in record_function.__init__() + total_ops -= 1 + elif e.time_range.start >= last_op_end_time: + last_op_end_time = e.time_range.end + if e.time_range.end <= captured_region_end_time: + captured_ops += 1 + captured_microseconds += e.time_range.elapsed_us() + elif should_print_missing(): + print_missing(e.stack) + total_ops += 1 + total_microseconds += e.time_range.elapsed_us() + else: + pass # ops recursively called from other ops (ignored) + + unique_graphs = Profiler.unique_graphs + Profiler.unique_graphs = 0 + # we counted one extra op that is part of the profiler setup code + total_ops -= 1 + + return ProfileResult( + captured=ProfileMetrics( + microseconds=captured_microseconds, + operators=captured_ops, + fusions=captured_ops - captured_regions, + graphs=captured_regions, + ), + total=ProfileMetrics( + microseconds=total_microseconds, + operators=total_ops, + fusions=total_ops - 1, + ), + unique_graphs=unique_graphs, + ) + + +def fx_insert_profiling(gm: torch.fx.GraphModule, example_inputs: List[Any]): + def _wrapped(*args): + with torch.profiler.record_function("TORCHDYNAMO"): + return gm.forward(*args) + + Profiler.unique_graphs += 1 + return _wrapped diff --git a/shared/package-files/71/71f657cba27902d52ac1de476389bd9714f2bb49b4c6c65b0fd16570179bba2a/test_interval.py b/shared/package-files/71/71f657cba27902d52ac1de476389bd9714f2bb49b4c6c65b0fd16570179bba2a/test_interval.py new file mode 100644 index 0000000000000000000000000000000000000000..be4b2c3e7e74cddfaf8b2efa08879d3a6d8f1757 --- /dev/null +++ b/shared/package-files/71/71f657cba27902d52ac1de476389bd9714f2bb49b4c6c65b0fd16570179bba2a/test_interval.py @@ -0,0 +1,231 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + Index, + Interval, + IntervalIndex, + Timedelta, + Timestamp, + date_range, + timedelta_range, +) +import pandas._testing as tm +from pandas.core.arrays import IntervalArray + + +@pytest.fixture( + params=[ + (Index([0, 2, 4]), Index([1, 3, 5])), + (Index([0.0, 1.0, 2.0]), Index([1.0, 2.0, 3.0])), + (timedelta_range("0 days", periods=3), timedelta_range("1 day", periods=3)), + (date_range("20170101", periods=3), date_range("20170102", periods=3)), + ( + date_range("20170101", periods=3, tz="US/Eastern"), + date_range("20170102", periods=3, tz="US/Eastern"), + ), + ], + ids=lambda x: str(x[0].dtype), +) +def left_right_dtypes(request): + """ + Fixture for building an IntervalArray from various dtypes + """ + return request.param + + +class TestAttributes: + @pytest.mark.parametrize( + "left, right", + [ + (0, 1), + (Timedelta("0 days"), Timedelta("1 day")), + (Timestamp("2018-01-01"), Timestamp("2018-01-02")), + ( + Timestamp("2018-01-01", tz="US/Eastern"), + Timestamp("2018-01-02", tz="US/Eastern"), + ), + ], + ) + @pytest.mark.parametrize("constructor", [IntervalArray, IntervalIndex]) + def test_is_empty(self, constructor, left, right, closed): + # GH27219 + tuples = [(left, left), (left, right), np.nan] + expected = np.array([closed != "both", False, False]) + result = constructor.from_tuples(tuples, closed=closed).is_empty + tm.assert_numpy_array_equal(result, expected) + + +class TestMethods: + @pytest.mark.parametrize("new_closed", ["left", "right", "both", "neither"]) + def test_set_closed(self, closed, new_closed): + # GH 21670 + array = IntervalArray.from_breaks(range(10), closed=closed) + result = array.set_closed(new_closed) + expected = IntervalArray.from_breaks(range(10), closed=new_closed) + tm.assert_extension_array_equal(result, expected) + + @pytest.mark.parametrize( + "other", + [ + Interval(0, 1, closed="right"), + IntervalArray.from_breaks([1, 2, 3, 4], closed="right"), + ], + ) + def test_where_raises(self, other): + # GH#45768 The IntervalArray methods raises; the Series method coerces + ser = pd.Series(IntervalArray.from_breaks([1, 2, 3, 4], closed="left")) + mask = np.array([True, False, True]) + match = "'value.closed' is 'right', expected 'left'." + with pytest.raises(ValueError, match=match): + ser.array._where(mask, other) + + res = ser.where(mask, other=other) + expected = ser.astype(object).where(mask, other) + tm.assert_series_equal(res, expected) + + def test_shift(self): + # https://github.com/pandas-dev/pandas/issues/31495, GH#22428, GH#31502 + a = IntervalArray.from_breaks([1, 2, 3]) + result = a.shift() + # int -> float + expected = IntervalArray.from_tuples([(np.nan, np.nan), (1.0, 2.0)]) + tm.assert_interval_array_equal(result, expected) + + msg = "can only insert Interval objects and NA into an IntervalArray" + with pytest.raises(TypeError, match=msg): + a.shift(1, fill_value=pd.NaT) + + def test_shift_datetime(self): + # GH#31502, GH#31504 + a = IntervalArray.from_breaks(date_range("2000", periods=4)) + result = a.shift(2) + expected = a.take([-1, -1, 0], allow_fill=True) + tm.assert_interval_array_equal(result, expected) + + result = a.shift(-1) + expected = a.take([1, 2, -1], allow_fill=True) + tm.assert_interval_array_equal(result, expected) + + msg = "can only insert Interval objects and NA into an IntervalArray" + with pytest.raises(TypeError, match=msg): + a.shift(1, fill_value=np.timedelta64("NaT", "ns")) + + +class TestSetitem: + def test_set_na(self, left_right_dtypes): + left, right = left_right_dtypes + left = left.copy(deep=True) + right = right.copy(deep=True) + result = IntervalArray.from_arrays(left, right) + + if result.dtype.subtype.kind not in ["m", "M"]: + msg = "'value' should be an interval type, got <.*NaTType'> instead." + with pytest.raises(TypeError, match=msg): + result[0] = pd.NaT + if result.dtype.subtype.kind in ["i", "u"]: + msg = "Cannot set float NaN to integer-backed IntervalArray" + # GH#45484 TypeError, not ValueError, matches what we get with + # non-NA un-holdable value. + with pytest.raises(TypeError, match=msg): + result[0] = np.nan + return + + result[0] = np.nan + + expected_left = Index([left._na_value] + list(left[1:])) + expected_right = Index([right._na_value] + list(right[1:])) + expected = IntervalArray.from_arrays(expected_left, expected_right) + + tm.assert_extension_array_equal(result, expected) + + def test_setitem_mismatched_closed(self): + arr = IntervalArray.from_breaks(range(4)) + orig = arr.copy() + other = arr.set_closed("both") + + msg = "'value.closed' is 'both', expected 'right'" + with pytest.raises(ValueError, match=msg): + arr[0] = other[0] + with pytest.raises(ValueError, match=msg): + arr[:1] = other[:1] + with pytest.raises(ValueError, match=msg): + arr[:0] = other[:0] + with pytest.raises(ValueError, match=msg): + arr[:] = other[::-1] + with pytest.raises(ValueError, match=msg): + arr[:] = list(other[::-1]) + with pytest.raises(ValueError, match=msg): + arr[:] = other[::-1].astype(object) + with pytest.raises(ValueError, match=msg): + arr[:] = other[::-1].astype("category") + + # empty list should be no-op + arr[:0] = [] + tm.assert_interval_array_equal(arr, orig) + + +class TestReductions: + def test_min_max_invalid_axis(self, left_right_dtypes): + left, right = left_right_dtypes + left = left.copy(deep=True) + right = right.copy(deep=True) + arr = IntervalArray.from_arrays(left, right) + + msg = "`axis` must be fewer than the number of dimensions" + for axis in [-2, 1]: + with pytest.raises(ValueError, match=msg): + arr.min(axis=axis) + with pytest.raises(ValueError, match=msg): + arr.max(axis=axis) + + msg = "'>=' not supported between" + with pytest.raises(TypeError, match=msg): + arr.min(axis="foo") + with pytest.raises(TypeError, match=msg): + arr.max(axis="foo") + + def test_min_max(self, left_right_dtypes, index_or_series_or_array): + # GH#44746 + left, right = left_right_dtypes + left = left.copy(deep=True) + right = right.copy(deep=True) + arr = IntervalArray.from_arrays(left, right) + + # The expected results below are only valid if monotonic + assert left.is_monotonic_increasing + assert Index(arr).is_monotonic_increasing + + MIN = arr[0] + MAX = arr[-1] + + indexer = np.arange(len(arr)) + np.random.default_rng(2).shuffle(indexer) + arr = arr.take(indexer) + + arr_na = arr.insert(2, np.nan) + + arr = index_or_series_or_array(arr) + arr_na = index_or_series_or_array(arr_na) + + for skipna in [True, False]: + res = arr.min(skipna=skipna) + assert res == MIN + assert type(res) == type(MIN) + + res = arr.max(skipna=skipna) + assert res == MAX + assert type(res) == type(MAX) + + res = arr_na.min(skipna=False) + assert np.isnan(res) + res = arr_na.max(skipna=False) + assert np.isnan(res) + + res = arr_na.min(skipna=True) + assert res == MIN + assert type(res) == type(MIN) + res = arr_na.max(skipna=True) + assert res == MAX + assert type(res) == type(MAX) diff --git a/shared/package-files/71/71f748978d2ed0b42d57c30e3775c9eb7403dca7a91b85003e231bcb0c58f7d5/_coalesce_ops.h b/shared/package-files/71/71f748978d2ed0b42d57c30e3775c9eb7403dca7a91b85003e231bcb0c58f7d5/_coalesce_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..26c3d1b66de0495df5eb2b63dff8901a0a9b8e29 --- /dev/null +++ b/shared/package-files/71/71f748978d2ed0b42d57c30e3775c9eb7403dca7a91b85003e231bcb0c58f7d5/_coalesce_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _coalesce { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_coalesce") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_coalesce(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API _coalesce_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_coalesce") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_coalesce.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/71/71f86749a8bc528d21b7db0f95332e3230d13231a05c2720e537b2c5aa8ef5e9/iris.rst b/shared/package-files/71/71f86749a8bc528d21b7db0f95332e3230d13231a05c2720e537b2c5aa8ef5e9/iris.rst new file mode 100644 index 0000000000000000000000000000000000000000..98651543620e6160e911c48306c8e805be0bff93 --- /dev/null +++ b/shared/package-files/71/71f86749a8bc528d21b7db0f95332e3230d13231a05c2720e537b2c5aa8ef5e9/iris.rst @@ -0,0 +1,63 @@ +.. _iris_dataset: + +Iris plants dataset +-------------------- + +**Data Set Characteristics:** + +:Number of Instances: 150 (50 in each of three classes) +:Number of Attributes: 4 numeric, predictive attributes and the class +:Attribute Information: + - sepal length in cm + - sepal width in cm + - petal length in cm + - petal width in cm + - class: + - Iris-Setosa + - Iris-Versicolour + - Iris-Virginica + +:Summary Statistics: + +============== ==== ==== ======= ===== ==================== + Min Max Mean SD Class Correlation +============== ==== ==== ======= ===== ==================== +sepal length: 4.3 7.9 5.84 0.83 0.7826 +sepal width: 2.0 4.4 3.05 0.43 -0.4194 +petal length: 1.0 6.9 3.76 1.76 0.9490 (high!) +petal width: 0.1 2.5 1.20 0.76 0.9565 (high!) +============== ==== ==== ======= ===== ==================== + +:Missing Attribute Values: None +:Class Distribution: 33.3% for each of 3 classes. +:Creator: R.A. Fisher +:Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov) +:Date: July, 1988 + +The famous Iris database, first used by Sir R.A. Fisher. The dataset is taken +from Fisher's paper. Note that it's the same as in R, but not as in the UCI +Machine Learning Repository, which has two wrong data points. + +This is perhaps the best known database to be found in the +pattern recognition literature. Fisher's paper is a classic in the field and +is referenced frequently to this day. (See Duda & Hart, for example.) The +data set contains 3 classes of 50 instances each, where each class refers to a +type of iris plant. One class is linearly separable from the other 2; the +latter are NOT linearly separable from each other. + +.. dropdown:: References + + - Fisher, R.A. "The use of multiple measurements in taxonomic problems" + Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to + Mathematical Statistics" (John Wiley, NY, 1950). + - Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis. + (Q327.D83) John Wiley & Sons. ISBN 0-471-22361-1. See page 218. + - Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System + Structure and Classification Rule for Recognition in Partially Exposed + Environments". IEEE Transactions on Pattern Analysis and Machine + Intelligence, Vol. PAMI-2, No. 1, 67-71. + - Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule". IEEE Transactions + on Information Theory, May 1972, 431-433. + - See also: 1988 MLC Proceedings, 54-64. Cheeseman et al"s AUTOCLASS II + conceptual clustering system finds 3 classes in the data. + - Many, many more ... diff --git a/shared/package-files/71/71f96fda706c7b1997bec067601fa5a56f97536d6ab454036ae8e81aafc8a54e/native_dropout_native.h b/shared/package-files/71/71f96fda706c7b1997bec067601fa5a56f97536d6ab454036ae8e81aafc8a54e/native_dropout_native.h new file mode 100644 index 0000000000000000000000000000000000000000..1472bb53d5feb2f892813ed9530dc1a4e105ec32 --- /dev/null +++ b/shared/package-files/71/71f96fda706c7b1997bec067601fa5a56f97536d6ab454036ae8e81aafc8a54e/native_dropout_native.h @@ -0,0 +1,24 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple native_dropout_out(const at::Tensor & input, double p, c10::optional train, at::Tensor & out0, at::Tensor & out1); +TORCH_API ::std::tuple native_dropout_cpu(const at::Tensor & input, double p, c10::optional train); +TORCH_API ::std::tuple native_dropout_cuda(const at::Tensor & input, double p, c10::optional train); +TORCH_API ::std::tuple native_dropout_nested(const at::Tensor & input, double p, c10::optional train); +} // namespace native +} // namespace at diff --git a/shared/package-files/71/71fa20f5fa7f10e166fe9889c2a51c4af00827bf1b4709058de730af7a1c09a9/test_glsl.py b/shared/package-files/71/71fa20f5fa7f10e166fe9889c2a51c4af00827bf1b4709058de730af7a1c09a9/test_glsl.py new file mode 100644 index 0000000000000000000000000000000000000000..86ec1dfe4a37d141e8435c369cb692d3a9a3b7bc --- /dev/null +++ b/shared/package-files/71/71fa20f5fa7f10e166fe9889c2a51c4af00827bf1b4709058de730af7a1c09a9/test_glsl.py @@ -0,0 +1,998 @@ +from sympy.core import (pi, symbols, Rational, Integer, GoldenRatio, EulerGamma, + Catalan, Lambda, Dummy, Eq, Ne, Le, Lt, Gt, Ge) +from sympy.functions import Piecewise, sin, cos, Abs, exp, ceiling, sqrt +from sympy.testing.pytest import raises, warns_deprecated_sympy +from sympy.printing.glsl import GLSLPrinter +from sympy.printing.str import StrPrinter +from sympy.utilities.lambdify import implemented_function +from sympy.tensor import IndexedBase, Idx +from sympy.matrices import Matrix, MatrixSymbol +from sympy.core import Tuple +from sympy.printing.glsl import glsl_code +import textwrap + +x, y, z = symbols('x,y,z') + + +def test_printmethod(): + assert glsl_code(Abs(x)) == "abs(x)" + +def test_print_without_operators(): + assert glsl_code(x*y,use_operators = False) == 'mul(x, y)' + assert glsl_code(x**y+z,use_operators = False) == 'add(pow(x, y), z)' + assert glsl_code(x*(y+z),use_operators = False) == 'mul(x, add(y, z))' + assert glsl_code(x*(y+z),use_operators = False) == 'mul(x, add(y, z))' + assert glsl_code(x*(y+z**y**0.5),use_operators = False) == 'mul(x, add(y, pow(z, sqrt(y))))' + assert glsl_code(-x-y, use_operators=False, zero='zero()') == 'sub(zero(), add(x, y))' + assert glsl_code(-x-y, use_operators=False) == 'sub(0.0, add(x, y))' + +def test_glsl_code_sqrt(): + assert glsl_code(sqrt(x)) == "sqrt(x)" + assert glsl_code(x**0.5) == "sqrt(x)" + assert glsl_code(sqrt(x)) == "sqrt(x)" + + +def test_glsl_code_Pow(): + g = implemented_function('g', Lambda(x, 2*x)) + assert glsl_code(x**3) == "pow(x, 3.0)" + assert glsl_code(x**(y**3)) == "pow(x, pow(y, 3.0))" + assert glsl_code(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \ + "pow(3.5*2*x, -x + pow(y, x))/(pow(x, 2.0) + y)" + assert glsl_code(x**-1.0) == '1.0/x' + + +def test_glsl_code_Relational(): + assert glsl_code(Eq(x, y)) == "x == y" + assert glsl_code(Ne(x, y)) == "x != y" + assert glsl_code(Le(x, y)) == "x <= y" + assert glsl_code(Lt(x, y)) == "x < y" + assert glsl_code(Gt(x, y)) == "x > y" + assert glsl_code(Ge(x, y)) == "x >= y" + + +def test_glsl_code_constants_mathh(): + assert glsl_code(exp(1)) == "float E = 2.71828183;\nE" + assert glsl_code(pi) == "float pi = 3.14159265;\npi" + # assert glsl_code(oo) == "Number.POSITIVE_INFINITY" + # assert glsl_code(-oo) == "Number.NEGATIVE_INFINITY" + + +def test_glsl_code_constants_other(): + assert glsl_code(2*GoldenRatio) == "float GoldenRatio = 1.61803399;\n2*GoldenRatio" + assert glsl_code(2*Catalan) == "float Catalan = 0.915965594;\n2*Catalan" + assert glsl_code(2*EulerGamma) == "float EulerGamma = 0.577215665;\n2*EulerGamma" + + +def test_glsl_code_Rational(): + assert glsl_code(Rational(3, 7)) == "3.0/7.0" + assert glsl_code(Rational(18, 9)) == "2" + assert glsl_code(Rational(3, -7)) == "-3.0/7.0" + assert glsl_code(Rational(-3, -7)) == "3.0/7.0" + + +def test_glsl_code_Integer(): + assert glsl_code(Integer(67)) == "67" + assert glsl_code(Integer(-1)) == "-1" + + +def test_glsl_code_functions(): + assert glsl_code(sin(x) ** cos(x)) == "pow(sin(x), cos(x))" + + +def test_glsl_code_inline_function(): + x = symbols('x') + g = implemented_function('g', Lambda(x, 2*x)) + assert glsl_code(g(x)) == "2*x" + g = implemented_function('g', Lambda(x, 2*x/Catalan)) + assert glsl_code(g(x)) == "float Catalan = 0.915965594;\n2*x/Catalan" + A = IndexedBase('A') + i = Idx('i', symbols('n', integer=True)) + g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x))) + assert glsl_code(g(A[i]), assign_to=A[i]) == ( + "for (int i=0; i 1), (sin(x), x > 0)) + raises(ValueError, lambda: glsl_code(expr)) + + +def test_glsl_code_Piecewise_deep(): + p = glsl_code(2*Piecewise((x, x < 1), (x**2, True))) + s = \ +"""\ +2*((x < 1) ? ( + x +) +: ( + pow(x, 2.0) +))\ +""" + assert p == s + + +def test_glsl_code_settings(): + raises(TypeError, lambda: glsl_code(sin(x), method="garbage")) + + +def test_glsl_code_Indexed(): + n, m, o = symbols('n m o', integer=True) + i, j, k = Idx('i', n), Idx('j', m), Idx('k', o) + p = GLSLPrinter() + p._not_c = set() + + x = IndexedBase('x')[j] + assert p._print_Indexed(x) == 'x[j]' + A = IndexedBase('A')[i, j] + assert p._print_Indexed(A) == 'A[%s]' % (m*i+j) + B = IndexedBase('B')[i, j, k] + assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k) + + assert p._not_c == set() + +def test_glsl_code_list_tuple_Tuple(): + assert glsl_code([1,2,3,4]) == 'vec4(1, 2, 3, 4)' + assert glsl_code([1,2,3],glsl_types=False) == 'float[3](1, 2, 3)' + assert glsl_code([1,2,3]) == glsl_code((1,2,3)) + assert glsl_code([1,2,3]) == glsl_code(Tuple(1,2,3)) + + m = MatrixSymbol('A',3,4) + assert glsl_code([m[0],m[1]]) + +def test_glsl_code_loops_matrix_vector(): + n, m = symbols('n m', integer=True) + A = IndexedBase('A') + x = IndexedBase('x') + y = IndexedBase('y') + i = Idx('i', m) + j = Idx('j', n) + + s = ( + 'for (int i=0; i0), (y, True)), sin(z)]) + A = MatrixSymbol('A', 3, 1) + assert glsl_code(mat, assign_to=A) == ( +'''A[0][0] = x*y; +if (y > 0) { + A[1][0] = x + 2; +} +else { + A[1][0] = y; +} +A[2][0] = sin(z);''' ) + assert glsl_code(Matrix([A[0],A[1]])) + # Test using MatrixElements in expressions + expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0] + assert glsl_code(expr) == ( +'''((x > 0) ? ( + 2*A[2][0] +) +: ( + A[2][0] +)) + sin(A[1][0]) + A[0][0]''' ) + + # Test using MatrixElements in a Matrix + q = MatrixSymbol('q', 5, 1) + M = MatrixSymbol('M', 3, 3) + m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])], + [q[1,0] + q[2,0], q[3, 0], 5], + [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]]) + assert glsl_code(m,M) == ( +'''M[0][0] = sin(q[1]); +M[0][1] = 0; +M[0][2] = cos(q[2]); +M[1][0] = q[1] + q[2]; +M[1][1] = q[3]; +M[1][2] = 5; +M[2][0] = 2*q[4]/q[1]; +M[2][1] = sqrt(q[0]) + 4; +M[2][2] = 0;''' + ) + +def test_Matrices_1x7(): + gl = glsl_code + A = Matrix([1,2,3,4,5,6,7]) + assert gl(A) == 'float[7](1, 2, 3, 4, 5, 6, 7)' + assert gl(A.transpose()) == 'float[7](1, 2, 3, 4, 5, 6, 7)' + +def test_Matrices_1x7_array_type_int(): + gl = glsl_code + A = Matrix([1,2,3,4,5,6,7]) + assert gl(A, array_type='int') == 'int[7](1, 2, 3, 4, 5, 6, 7)' + +def test_Tuple_array_type_custom(): + gl = glsl_code + A = symbols('a b c') + assert gl(A, array_type='AbcType', glsl_types=False) == 'AbcType[3](a, b, c)' + +def test_Matrices_1x7_spread_assign_to_symbols(): + gl = glsl_code + A = Matrix([1,2,3,4,5,6,7]) + assign_to = symbols('x.a x.b x.c x.d x.e x.f x.g') + assert gl(A, assign_to=assign_to) == textwrap.dedent('''\ + x.a = 1; + x.b = 2; + x.c = 3; + x.d = 4; + x.e = 5; + x.f = 6; + x.g = 7;''' + ) + +def test_spread_assign_to_nested_symbols(): + gl = glsl_code + expr = ((1,2,3), (1,2,3)) + assign_to = (symbols('a b c'), symbols('x y z')) + assert gl(expr, assign_to=assign_to) == textwrap.dedent('''\ + a = 1; + b = 2; + c = 3; + x = 1; + y = 2; + z = 3;''' + ) + +def test_spread_assign_to_deeply_nested_symbols(): + gl = glsl_code + a, b, c, x, y, z = symbols('a b c x y z') + expr = (((1,2),3), ((1,2),3)) + assign_to = (((a, b), c), ((x, y), z)) + assert gl(expr, assign_to=assign_to) == textwrap.dedent('''\ + a = 1; + b = 2; + c = 3; + x = 1; + y = 2; + z = 3;''' + ) + +def test_matrix_of_tuples_spread_assign_to_symbols(): + gl = glsl_code + with warns_deprecated_sympy(): + expr = Matrix([[(1,2),(3,4)],[(5,6),(7,8)]]) + assign_to = (symbols('a b'), symbols('c d'), symbols('e f'), symbols('g h')) + assert gl(expr, assign_to) == textwrap.dedent('''\ + a = 1; + b = 2; + c = 3; + d = 4; + e = 5; + f = 6; + g = 7; + h = 8;''' + ) + +def test_cannot_assign_to_cause_mismatched_length(): + expr = (1, 2) + assign_to = symbols('x y z') + raises(ValueError, lambda: glsl_code(expr, assign_to)) + +def test_matrix_4x4_assign(): + gl = glsl_code + expr = MatrixSymbol('A',4,4) * MatrixSymbol('B',4,4) + MatrixSymbol('C',4,4) + assign_to = MatrixSymbol('X',4,4) + assert gl(expr, assign_to=assign_to) == textwrap.dedent('''\ + X[0][0] = A[0][0]*B[0][0] + A[0][1]*B[1][0] + A[0][2]*B[2][0] + A[0][3]*B[3][0] + C[0][0]; + X[0][1] = A[0][0]*B[0][1] + A[0][1]*B[1][1] + A[0][2]*B[2][1] + A[0][3]*B[3][1] + C[0][1]; + X[0][2] = A[0][0]*B[0][2] + A[0][1]*B[1][2] + A[0][2]*B[2][2] + A[0][3]*B[3][2] + C[0][2]; + X[0][3] = A[0][0]*B[0][3] + A[0][1]*B[1][3] + A[0][2]*B[2][3] + A[0][3]*B[3][3] + C[0][3]; + X[1][0] = A[1][0]*B[0][0] + A[1][1]*B[1][0] + A[1][2]*B[2][0] + A[1][3]*B[3][0] + C[1][0]; + X[1][1] = A[1][0]*B[0][1] + A[1][1]*B[1][1] + A[1][2]*B[2][1] + A[1][3]*B[3][1] + C[1][1]; + X[1][2] = A[1][0]*B[0][2] + A[1][1]*B[1][2] + A[1][2]*B[2][2] + A[1][3]*B[3][2] + C[1][2]; + X[1][3] = A[1][0]*B[0][3] + A[1][1]*B[1][3] + A[1][2]*B[2][3] + A[1][3]*B[3][3] + C[1][3]; + X[2][0] = A[2][0]*B[0][0] + A[2][1]*B[1][0] + A[2][2]*B[2][0] + A[2][3]*B[3][0] + C[2][0]; + X[2][1] = A[2][0]*B[0][1] + A[2][1]*B[1][1] + A[2][2]*B[2][1] + A[2][3]*B[3][1] + C[2][1]; + X[2][2] = A[2][0]*B[0][2] + A[2][1]*B[1][2] + A[2][2]*B[2][2] + A[2][3]*B[3][2] + C[2][2]; + X[2][3] = A[2][0]*B[0][3] + A[2][1]*B[1][3] + A[2][2]*B[2][3] + A[2][3]*B[3][3] + C[2][3]; + X[3][0] = A[3][0]*B[0][0] + A[3][1]*B[1][0] + A[3][2]*B[2][0] + A[3][3]*B[3][0] + C[3][0]; + X[3][1] = A[3][0]*B[0][1] + A[3][1]*B[1][1] + A[3][2]*B[2][1] + A[3][3]*B[3][1] + C[3][1]; + X[3][2] = A[3][0]*B[0][2] + A[3][1]*B[1][2] + A[3][2]*B[2][2] + A[3][3]*B[3][2] + C[3][2]; + X[3][3] = A[3][0]*B[0][3] + A[3][1]*B[1][3] + A[3][2]*B[2][3] + A[3][3]*B[3][3] + C[3][3];''' + ) + +def test_1xN_vecs(): + gl = glsl_code + for i in range(1,10): + A = Matrix(range(i)) + assert gl(A.transpose()) == gl(A) + assert gl(A,mat_transpose=True) == gl(A) + if i > 1: + if i <= 4: + assert gl(A) == 'vec%s(%s)' % (i,', '.join(str(s) for s in range(i))) + else: + assert gl(A) == 'float[%s](%s)' % (i,', '.join(str(s) for s in range(i))) + +def test_MxN_mats(): + generatedAssertions='def test_misc_mats():\n' + for i in range(1,6): + for j in range(1,6): + A = Matrix([[x + y*j for x in range(j)] for y in range(i)]) + gl = glsl_code(A) + glTransposed = glsl_code(A,mat_transpose=True) + generatedAssertions+=' mat = '+StrPrinter()._print(A)+'\n\n' + generatedAssertions+=' gl = \'\'\''+gl+'\'\'\'\n' + generatedAssertions+=' glTransposed = \'\'\''+glTransposed+'\'\'\'\n\n' + generatedAssertions+=' assert glsl_code(mat) == gl\n' + generatedAssertions+=' assert glsl_code(mat,mat_transpose=True) == glTransposed\n' + if i == 1 and j == 1: + assert gl == '0' + elif i <= 4 and j <= 4 and i>1 and j>1: + assert gl.startswith('mat%s' % j) + assert glTransposed.startswith('mat%s' % i) + elif i == 1 and j <= 4: + assert gl.startswith('vec') + elif j == 1 and i <= 4: + assert gl.startswith('vec') + elif i == 1: + assert gl.startswith('float[%s]('% j*i) + assert glTransposed.startswith('float[%s]('% j*i) + elif j == 1: + assert gl.startswith('float[%s]('% i*j) + assert glTransposed.startswith('float[%s]('% i*j) + else: + assert gl.startswith('float[%s](' % (i*j)) + assert glTransposed.startswith('float[%s](' % (i*j)) + glNested = glsl_code(A,mat_nested=True) + glNestedTransposed = glsl_code(A,mat_transpose=True,mat_nested=True) + assert glNested.startswith('float[%s][%s]' % (i,j)) + assert glNestedTransposed.startswith('float[%s][%s]' % (j,i)) + generatedAssertions+=' glNested = \'\'\''+glNested+'\'\'\'\n' + generatedAssertions+=' glNestedTransposed = \'\'\''+glNestedTransposed+'\'\'\'\n\n' + generatedAssertions+=' assert glsl_code(mat,mat_nested=True) == glNested\n' + generatedAssertions+=' assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed\n\n' + generateAssertions = False # set this to true to write bake these generated tests to a file + if generateAssertions: + gen = open('test_glsl_generated_matrices.py','w') + gen.write(generatedAssertions) + gen.close() + + +# these assertions were generated from the previous function +# glsl has complicated rules and this makes it easier to look over all the cases +def test_misc_mats(): + + mat = Matrix([[0]]) + + gl = '''0''' + glTransposed = '''0''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([[0, 1]]) + + gl = '''vec2(0, 1)''' + glTransposed = '''vec2(0, 1)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([[0, 1, 2]]) + + gl = '''vec3(0, 1, 2)''' + glTransposed = '''vec3(0, 1, 2)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([[0, 1, 2, 3]]) + + gl = '''vec4(0, 1, 2, 3)''' + glTransposed = '''vec4(0, 1, 2, 3)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([[0, 1, 2, 3, 4]]) + + gl = '''float[5](0, 1, 2, 3, 4)''' + glTransposed = '''float[5](0, 1, 2, 3, 4)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([ +[0], +[1]]) + + gl = '''vec2(0, 1)''' + glTransposed = '''vec2(0, 1)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([ +[0, 1], +[2, 3]]) + + gl = '''mat2(0, 1, 2, 3)''' + glTransposed = '''mat2(0, 2, 1, 3)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([ +[0, 1, 2], +[3, 4, 5]]) + + gl = '''mat3x2(0, 1, 2, 3, 4, 5)''' + glTransposed = '''mat2x3(0, 3, 1, 4, 2, 5)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([ +[0, 1, 2, 3], +[4, 5, 6, 7]]) + + gl = '''mat4x2(0, 1, 2, 3, 4, 5, 6, 7)''' + glTransposed = '''mat2x4(0, 4, 1, 5, 2, 6, 3, 7)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([ +[0, 1, 2, 3, 4], +[5, 6, 7, 8, 9]]) + + gl = '''float[10]( + 0, 1, 2, 3, 4, + 5, 6, 7, 8, 9 +) /* a 2x5 matrix */''' + glTransposed = '''float[10]( + 0, 5, + 1, 6, + 2, 7, + 3, 8, + 4, 9 +) /* a 5x2 matrix */''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + glNested = '''float[2][5]( + float[](0, 1, 2, 3, 4), + float[](5, 6, 7, 8, 9) +)''' + glNestedTransposed = '''float[5][2]( + float[](0, 5), + float[](1, 6), + float[](2, 7), + float[](3, 8), + float[](4, 9) +)''' + + assert glsl_code(mat,mat_nested=True) == glNested + assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed + + mat = Matrix([ +[0], +[1], +[2]]) + + gl = '''vec3(0, 1, 2)''' + glTransposed = '''vec3(0, 1, 2)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([ +[0, 1], +[2, 3], +[4, 5]]) + + gl = '''mat2x3(0, 1, 2, 3, 4, 5)''' + glTransposed = '''mat3x2(0, 2, 4, 1, 3, 5)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([ +[0, 1, 2], +[3, 4, 5], +[6, 7, 8]]) + + gl = '''mat3(0, 1, 2, 3, 4, 5, 6, 7, 8)''' + glTransposed = '''mat3(0, 3, 6, 1, 4, 7, 2, 5, 8)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([ +[0, 1, 2, 3], +[4, 5, 6, 7], +[8, 9, 10, 11]]) + + gl = '''mat4x3(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)''' + glTransposed = '''mat3x4(0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([ +[ 0, 1, 2, 3, 4], +[ 5, 6, 7, 8, 9], +[10, 11, 12, 13, 14]]) + + gl = '''float[15]( + 0, 1, 2, 3, 4, + 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14 +) /* a 3x5 matrix */''' + glTransposed = '''float[15]( + 0, 5, 10, + 1, 6, 11, + 2, 7, 12, + 3, 8, 13, + 4, 9, 14 +) /* a 5x3 matrix */''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + glNested = '''float[3][5]( + float[]( 0, 1, 2, 3, 4), + float[]( 5, 6, 7, 8, 9), + float[](10, 11, 12, 13, 14) +)''' + glNestedTransposed = '''float[5][3]( + float[](0, 5, 10), + float[](1, 6, 11), + float[](2, 7, 12), + float[](3, 8, 13), + float[](4, 9, 14) +)''' + + assert glsl_code(mat,mat_nested=True) == glNested + assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed + + mat = Matrix([ +[0], +[1], +[2], +[3]]) + + gl = '''vec4(0, 1, 2, 3)''' + glTransposed = '''vec4(0, 1, 2, 3)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([ +[0, 1], +[2, 3], +[4, 5], +[6, 7]]) + + gl = '''mat2x4(0, 1, 2, 3, 4, 5, 6, 7)''' + glTransposed = '''mat4x2(0, 2, 4, 6, 1, 3, 5, 7)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([ +[0, 1, 2], +[3, 4, 5], +[6, 7, 8], +[9, 10, 11]]) + + gl = '''mat3x4(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)''' + glTransposed = '''mat4x3(0, 3, 6, 9, 1, 4, 7, 10, 2, 5, 8, 11)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([ +[ 0, 1, 2, 3], +[ 4, 5, 6, 7], +[ 8, 9, 10, 11], +[12, 13, 14, 15]]) + + gl = '''mat4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)''' + glTransposed = '''mat4(0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([ +[ 0, 1, 2, 3, 4], +[ 5, 6, 7, 8, 9], +[10, 11, 12, 13, 14], +[15, 16, 17, 18, 19]]) + + gl = '''float[20]( + 0, 1, 2, 3, 4, + 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19 +) /* a 4x5 matrix */''' + glTransposed = '''float[20]( + 0, 5, 10, 15, + 1, 6, 11, 16, + 2, 7, 12, 17, + 3, 8, 13, 18, + 4, 9, 14, 19 +) /* a 5x4 matrix */''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + glNested = '''float[4][5]( + float[]( 0, 1, 2, 3, 4), + float[]( 5, 6, 7, 8, 9), + float[](10, 11, 12, 13, 14), + float[](15, 16, 17, 18, 19) +)''' + glNestedTransposed = '''float[5][4]( + float[](0, 5, 10, 15), + float[](1, 6, 11, 16), + float[](2, 7, 12, 17), + float[](3, 8, 13, 18), + float[](4, 9, 14, 19) +)''' + + assert glsl_code(mat,mat_nested=True) == glNested + assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed + + mat = Matrix([ +[0], +[1], +[2], +[3], +[4]]) + + gl = '''float[5](0, 1, 2, 3, 4)''' + glTransposed = '''float[5](0, 1, 2, 3, 4)''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + + mat = Matrix([ +[0, 1], +[2, 3], +[4, 5], +[6, 7], +[8, 9]]) + + gl = '''float[10]( + 0, 1, + 2, 3, + 4, 5, + 6, 7, + 8, 9 +) /* a 5x2 matrix */''' + glTransposed = '''float[10]( + 0, 2, 4, 6, 8, + 1, 3, 5, 7, 9 +) /* a 2x5 matrix */''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + glNested = '''float[5][2]( + float[](0, 1), + float[](2, 3), + float[](4, 5), + float[](6, 7), + float[](8, 9) +)''' + glNestedTransposed = '''float[2][5]( + float[](0, 2, 4, 6, 8), + float[](1, 3, 5, 7, 9) +)''' + + assert glsl_code(mat,mat_nested=True) == glNested + assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed + + mat = Matrix([ +[ 0, 1, 2], +[ 3, 4, 5], +[ 6, 7, 8], +[ 9, 10, 11], +[12, 13, 14]]) + + gl = '''float[15]( + 0, 1, 2, + 3, 4, 5, + 6, 7, 8, + 9, 10, 11, + 12, 13, 14 +) /* a 5x3 matrix */''' + glTransposed = '''float[15]( + 0, 3, 6, 9, 12, + 1, 4, 7, 10, 13, + 2, 5, 8, 11, 14 +) /* a 3x5 matrix */''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + glNested = '''float[5][3]( + float[]( 0, 1, 2), + float[]( 3, 4, 5), + float[]( 6, 7, 8), + float[]( 9, 10, 11), + float[](12, 13, 14) +)''' + glNestedTransposed = '''float[3][5]( + float[](0, 3, 6, 9, 12), + float[](1, 4, 7, 10, 13), + float[](2, 5, 8, 11, 14) +)''' + + assert glsl_code(mat,mat_nested=True) == glNested + assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed + + mat = Matrix([ +[ 0, 1, 2, 3], +[ 4, 5, 6, 7], +[ 8, 9, 10, 11], +[12, 13, 14, 15], +[16, 17, 18, 19]]) + + gl = '''float[20]( + 0, 1, 2, 3, + 4, 5, 6, 7, + 8, 9, 10, 11, + 12, 13, 14, 15, + 16, 17, 18, 19 +) /* a 5x4 matrix */''' + glTransposed = '''float[20]( + 0, 4, 8, 12, 16, + 1, 5, 9, 13, 17, + 2, 6, 10, 14, 18, + 3, 7, 11, 15, 19 +) /* a 4x5 matrix */''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + glNested = '''float[5][4]( + float[]( 0, 1, 2, 3), + float[]( 4, 5, 6, 7), + float[]( 8, 9, 10, 11), + float[](12, 13, 14, 15), + float[](16, 17, 18, 19) +)''' + glNestedTransposed = '''float[4][5]( + float[](0, 4, 8, 12, 16), + float[](1, 5, 9, 13, 17), + float[](2, 6, 10, 14, 18), + float[](3, 7, 11, 15, 19) +)''' + + assert glsl_code(mat,mat_nested=True) == glNested + assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed + + mat = Matrix([ +[ 0, 1, 2, 3, 4], +[ 5, 6, 7, 8, 9], +[10, 11, 12, 13, 14], +[15, 16, 17, 18, 19], +[20, 21, 22, 23, 24]]) + + gl = '''float[25]( + 0, 1, 2, 3, 4, + 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24 +) /* a 5x5 matrix */''' + glTransposed = '''float[25]( + 0, 5, 10, 15, 20, + 1, 6, 11, 16, 21, + 2, 7, 12, 17, 22, + 3, 8, 13, 18, 23, + 4, 9, 14, 19, 24 +) /* a 5x5 matrix */''' + + assert glsl_code(mat) == gl + assert glsl_code(mat,mat_transpose=True) == glTransposed + glNested = '''float[5][5]( + float[]( 0, 1, 2, 3, 4), + float[]( 5, 6, 7, 8, 9), + float[](10, 11, 12, 13, 14), + float[](15, 16, 17, 18, 19), + float[](20, 21, 22, 23, 24) +)''' + glNestedTransposed = '''float[5][5]( + float[](0, 5, 10, 15, 20), + float[](1, 6, 11, 16, 21), + float[](2, 7, 12, 17, 22), + float[](3, 8, 13, 18, 23), + float[](4, 9, 14, 19, 24) +)''' + + assert glsl_code(mat,mat_nested=True) == glNested + assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed diff --git a/shared/package-files/71/71fae6f8b9d7399ef7a50a67fe45d25f0d01876e760e9b1f3f82861e53cdcb78/builder_binary.h b/shared/package-files/71/71fae6f8b9d7399ef7a50a67fe45d25f0d01876e760e9b1f3f82861e53cdcb78/builder_binary.h new file mode 100644 index 0000000000000000000000000000000000000000..d0e761ae9684132240f21ee335a996bdda081a63 --- /dev/null +++ b/shared/package-files/71/71fae6f8b9d7399ef7a50a67fe45d25f0d01876e760e9b1f3f82861e53cdcb78/builder_binary.h @@ -0,0 +1,993 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/array/array_base.h" +#include "arrow/array/array_binary.h" +#include "arrow/array/builder_base.h" +#include "arrow/array/data.h" +#include "arrow/buffer.h" +#include "arrow/buffer_builder.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/binary_view_util.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +/// \addtogroup binary-builders +/// +/// @{ + +// ---------------------------------------------------------------------- +// Binary and String + +template +class BaseBinaryBuilder + : public ArrayBuilder, + public internal::ArrayBuilderExtraOps, std::string_view> { + public: + using TypeClass = TYPE; + using offset_type = typename TypeClass::offset_type; + + explicit BaseBinaryBuilder(MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : ArrayBuilder(pool, alignment), + offsets_builder_(pool, alignment), + value_data_builder_(pool, alignment) {} + + BaseBinaryBuilder(const std::shared_ptr& type, MemoryPool* pool) + : BaseBinaryBuilder(pool) {} + + Status Append(const uint8_t* value, offset_type length) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppendNextOffset(); + // Safety check for UBSAN. + if (ARROW_PREDICT_TRUE(length > 0)) { + ARROW_RETURN_NOT_OK(ValidateOverflow(length)); + ARROW_RETURN_NOT_OK(value_data_builder_.Append(value, length)); + } + + UnsafeAppendToBitmap(true); + return Status::OK(); + } + + Status Append(const char* value, offset_type length) { + return Append(reinterpret_cast(value), length); + } + + Status Append(std::string_view value) { + return Append(value.data(), static_cast(value.size())); + } + + /// Extend the last appended value by appending more data at the end + /// + /// Unlike Append, this does not create a new offset. + Status ExtendCurrent(const uint8_t* value, offset_type length) { + // Safety check for UBSAN. + if (ARROW_PREDICT_TRUE(length > 0)) { + ARROW_RETURN_NOT_OK(ValidateOverflow(length)); + ARROW_RETURN_NOT_OK(value_data_builder_.Append(value, length)); + } + return Status::OK(); + } + + Status ExtendCurrent(std::string_view value) { + return ExtendCurrent(reinterpret_cast(value.data()), + static_cast(value.size())); + } + + Status AppendNulls(int64_t length) final { + const int64_t num_bytes = value_data_builder_.length(); + ARROW_RETURN_NOT_OK(Reserve(length)); + for (int64_t i = 0; i < length; ++i) { + offsets_builder_.UnsafeAppend(static_cast(num_bytes)); + } + UnsafeAppendToBitmap(length, false); + return Status::OK(); + } + + Status AppendNull() final { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppendNextOffset(); + UnsafeAppendToBitmap(false); + return Status::OK(); + } + + Status AppendEmptyValue() final { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppendNextOffset(); + UnsafeAppendToBitmap(true); + return Status::OK(); + } + + Status AppendEmptyValues(int64_t length) final { + const int64_t num_bytes = value_data_builder_.length(); + ARROW_RETURN_NOT_OK(Reserve(length)); + for (int64_t i = 0; i < length; ++i) { + offsets_builder_.UnsafeAppend(static_cast(num_bytes)); + } + UnsafeAppendToBitmap(length, true); + return Status::OK(); + } + + /// \brief Append without checking capacity + /// + /// Offsets and data should have been presized using Reserve() and + /// ReserveData(), respectively. + void UnsafeAppend(const uint8_t* value, offset_type length) { + UnsafeAppendNextOffset(); + value_data_builder_.UnsafeAppend(value, length); + UnsafeAppendToBitmap(true); + } + + void UnsafeAppend(const char* value, offset_type length) { + UnsafeAppend(reinterpret_cast(value), length); + } + + void UnsafeAppend(const std::string& value) { + UnsafeAppend(value.c_str(), static_cast(value.size())); + } + + void UnsafeAppend(std::string_view value) { + UnsafeAppend(value.data(), static_cast(value.size())); + } + + /// Like ExtendCurrent, but do not check capacity + void UnsafeExtendCurrent(const uint8_t* value, offset_type length) { + value_data_builder_.UnsafeAppend(value, length); + } + + void UnsafeExtendCurrent(std::string_view value) { + UnsafeExtendCurrent(reinterpret_cast(value.data()), + static_cast(value.size())); + } + + void UnsafeAppendNull() { + const int64_t num_bytes = value_data_builder_.length(); + offsets_builder_.UnsafeAppend(static_cast(num_bytes)); + UnsafeAppendToBitmap(false); + } + + void UnsafeAppendEmptyValue() { + const int64_t num_bytes = value_data_builder_.length(); + offsets_builder_.UnsafeAppend(static_cast(num_bytes)); + UnsafeAppendToBitmap(true); + } + + /// \brief Append a sequence of strings in one shot. + /// + /// \param[in] values a vector of strings + /// \param[in] valid_bytes an optional sequence of bytes where non-zero + /// indicates a valid (non-null) value + /// \return Status + Status AppendValues(const std::vector& values, + const uint8_t* valid_bytes = NULLPTR) { + std::size_t total_length = std::accumulate( + values.begin(), values.end(), 0ULL, + [](uint64_t sum, const std::string& str) { return sum + str.size(); }); + ARROW_RETURN_NOT_OK(Reserve(values.size())); + ARROW_RETURN_NOT_OK(ReserveData(total_length)); + + if (valid_bytes != NULLPTR) { + for (std::size_t i = 0; i < values.size(); ++i) { + UnsafeAppendNextOffset(); + if (valid_bytes[i]) { + value_data_builder_.UnsafeAppend( + reinterpret_cast(values[i].data()), values[i].size()); + } + } + } else { + for (const auto& value : values) { + UnsafeAppendNextOffset(); + value_data_builder_.UnsafeAppend(reinterpret_cast(value.data()), + value.size()); + } + } + + UnsafeAppendToBitmap(valid_bytes, values.size()); + return Status::OK(); + } + + /// \brief Append a sequence of nul-terminated strings in one shot. + /// If one of the values is NULL, it is processed as a null + /// value even if the corresponding valid_bytes entry is 1. + /// + /// \param[in] values a contiguous C array of nul-terminated char * + /// \param[in] length the number of values to append + /// \param[in] valid_bytes an optional sequence of bytes where non-zero + /// indicates a valid (non-null) value + /// \return Status + Status AppendValues(const char** values, int64_t length, + const uint8_t* valid_bytes = NULLPTR) { + std::size_t total_length = 0; + std::vector value_lengths(length); + bool have_null_value = false; + for (int64_t i = 0; i < length; ++i) { + if (values[i] != NULLPTR) { + auto value_length = strlen(values[i]); + value_lengths[i] = value_length; + total_length += value_length; + } else { + have_null_value = true; + } + } + ARROW_RETURN_NOT_OK(Reserve(length)); + ARROW_RETURN_NOT_OK(ReserveData(total_length)); + + if (valid_bytes) { + int64_t valid_bytes_offset = 0; + for (int64_t i = 0; i < length; ++i) { + UnsafeAppendNextOffset(); + if (valid_bytes[i]) { + if (values[i]) { + value_data_builder_.UnsafeAppend(reinterpret_cast(values[i]), + value_lengths[i]); + } else { + UnsafeAppendToBitmap(valid_bytes + valid_bytes_offset, + i - valid_bytes_offset); + UnsafeAppendToBitmap(false); + valid_bytes_offset = i + 1; + } + } + } + UnsafeAppendToBitmap(valid_bytes + valid_bytes_offset, length - valid_bytes_offset); + } else { + if (have_null_value) { + std::vector valid_vector(length, 0); + for (int64_t i = 0; i < length; ++i) { + UnsafeAppendNextOffset(); + if (values[i]) { + value_data_builder_.UnsafeAppend(reinterpret_cast(values[i]), + value_lengths[i]); + valid_vector[i] = 1; + } + } + UnsafeAppendToBitmap(valid_vector.data(), length); + } else { + for (int64_t i = 0; i < length; ++i) { + UnsafeAppendNextOffset(); + value_data_builder_.UnsafeAppend(reinterpret_cast(values[i]), + value_lengths[i]); + } + UnsafeAppendToBitmap(NULLPTR, length); + } + } + return Status::OK(); + } + + Status AppendArraySlice(const ArraySpan& array, int64_t offset, + int64_t length) override { + auto bitmap = array.GetValues(0, 0); + auto offsets = array.GetValues(1); + auto data = array.GetValues(2, 0); + auto total_length = offsets[offset + length] - offsets[offset]; + ARROW_RETURN_NOT_OK(Reserve(length)); + ARROW_RETURN_NOT_OK(ReserveData(total_length)); + for (int64_t i = 0; i < length; i++) { + if (!bitmap || bit_util::GetBit(bitmap, array.offset + offset + i)) { + const offset_type start = offsets[offset + i]; + const offset_type end = offsets[offset + i + 1]; + UnsafeAppend(data + start, end - start); + } else { + UnsafeAppendNull(); + } + } + return Status::OK(); + } + + void Reset() override { + ArrayBuilder::Reset(); + offsets_builder_.Reset(); + value_data_builder_.Reset(); + } + + Status ValidateOverflow(int64_t new_bytes) { + auto new_size = value_data_builder_.length() + new_bytes; + if (ARROW_PREDICT_FALSE(new_size > memory_limit())) { + return Status::CapacityError("array cannot contain more than ", memory_limit(), + " bytes, have ", new_size); + } else { + return Status::OK(); + } + } + + Status Resize(int64_t capacity) override { + ARROW_RETURN_NOT_OK(CheckCapacity(capacity)); + // One more than requested for offsets + ARROW_RETURN_NOT_OK(offsets_builder_.Resize(capacity + 1)); + return ArrayBuilder::Resize(capacity); + } + + /// \brief Ensures there is enough allocated capacity to append the indicated + /// number of bytes to the value data buffer without additional allocations + Status ReserveData(int64_t elements) { + ARROW_RETURN_NOT_OK(ValidateOverflow(elements)); + return value_data_builder_.Reserve(elements); + } + + Status FinishInternal(std::shared_ptr* out) override { + // Write final offset (values length) + ARROW_RETURN_NOT_OK(AppendNextOffset()); + + // These buffers' padding zeroed by BufferBuilder + std::shared_ptr offsets, value_data, null_bitmap; + ARROW_RETURN_NOT_OK(offsets_builder_.Finish(&offsets)); + ARROW_RETURN_NOT_OK(value_data_builder_.Finish(&value_data)); + ARROW_RETURN_NOT_OK(null_bitmap_builder_.Finish(&null_bitmap)); + + *out = ArrayData::Make(type(), length_, {null_bitmap, offsets, value_data}, + null_count_, 0); + Reset(); + return Status::OK(); + } + + /// \return data pointer of the value date builder + const uint8_t* value_data() const { return value_data_builder_.data(); } + /// \return size of values buffer so far + int64_t value_data_length() const { return value_data_builder_.length(); } + /// \return capacity of values buffer + int64_t value_data_capacity() const { return value_data_builder_.capacity(); } + + /// \return data pointer of the value date builder + const offset_type* offsets_data() const { return offsets_builder_.data(); } + + /// Temporary access to a value. + /// + /// This pointer becomes invalid on the next modifying operation. + const uint8_t* GetValue(int64_t i, offset_type* out_length) const { + const offset_type* offsets = offsets_builder_.data(); + const auto offset = offsets[i]; + if (i == (length_ - 1)) { + *out_length = static_cast(value_data_builder_.length()) - offset; + } else { + *out_length = offsets[i + 1] - offset; + } + return value_data_builder_.data() + offset; + } + + offset_type offset(int64_t i) const { return offsets_data()[i]; } + + /// Temporary access to a value. + /// + /// This view becomes invalid on the next modifying operation. + std::string_view GetView(int64_t i) const { + offset_type value_length; + const uint8_t* value_data = GetValue(i, &value_length); + return std::string_view(reinterpret_cast(value_data), value_length); + } + + // Cannot make this a static attribute because of linking issues + static constexpr int64_t memory_limit() { + return std::numeric_limits::max() - 1; + } + + protected: + TypedBufferBuilder offsets_builder_; + TypedBufferBuilder value_data_builder_; + + Status AppendNextOffset() { + const int64_t num_bytes = value_data_builder_.length(); + return offsets_builder_.Append(static_cast(num_bytes)); + } + + void UnsafeAppendNextOffset() { + const int64_t num_bytes = value_data_builder_.length(); + offsets_builder_.UnsafeAppend(static_cast(num_bytes)); + } +}; + +/// \class BinaryBuilder +/// \brief Builder class for variable-length binary data +class ARROW_EXPORT BinaryBuilder : public BaseBinaryBuilder { + public: + using BaseBinaryBuilder::BaseBinaryBuilder; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + std::shared_ptr type() const override { return binary(); } +}; + +/// \class StringBuilder +/// \brief Builder class for UTF8 strings +class ARROW_EXPORT StringBuilder : public BinaryBuilder { + public: + using BinaryBuilder::BinaryBuilder; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + std::shared_ptr type() const override { return utf8(); } +}; + +/// \class LargeBinaryBuilder +/// \brief Builder class for large variable-length binary data +class ARROW_EXPORT LargeBinaryBuilder : public BaseBinaryBuilder { + public: + using BaseBinaryBuilder::BaseBinaryBuilder; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + std::shared_ptr type() const override { return large_binary(); } +}; + +/// \class LargeStringBuilder +/// \brief Builder class for large UTF8 strings +class ARROW_EXPORT LargeStringBuilder : public LargeBinaryBuilder { + public: + using LargeBinaryBuilder::LargeBinaryBuilder; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + std::shared_ptr type() const override { return large_utf8(); } +}; + +// ---------------------------------------------------------------------- +// BinaryViewBuilder, StringViewBuilder +// +// These builders do not support building raw pointer view arrays. + +namespace internal { + +// We allocate medium-sized memory chunks and accumulate data in those, which +// may result in some waste if there are many large-ish strings. If a string +// comes along that does not fit into a block, we allocate a new block and +// write into that. +// +// Later we can implement optimizations to continuing filling underfull blocks +// after encountering a large string that required allocating a new block. +class ARROW_EXPORT StringHeapBuilder { + public: + static constexpr int64_t kDefaultBlocksize = 32 << 10; // 32KB + + StringHeapBuilder(MemoryPool* pool, int64_t alignment) + : pool_(pool), alignment_(alignment) {} + + void SetBlockSize(int64_t blocksize) { blocksize_ = blocksize; } + + using c_type = BinaryViewType::c_type; + + template + std::conditional_t, c_type> Append(const uint8_t* value, + int64_t length) { + if (length <= BinaryViewType::kInlineSize) { + return util::ToInlineBinaryView(value, static_cast(length)); + } + + if constexpr (Safe) { + ARROW_RETURN_NOT_OK(Reserve(length)); + } + + auto v = util::ToNonInlineBinaryView(value, static_cast(length), + static_cast(blocks_.size() - 1), + current_offset_); + + memcpy(current_out_buffer_, value, static_cast(length)); + current_out_buffer_ += length; + current_remaining_bytes_ -= length; + current_offset_ += static_cast(length); + return v; + } + + static constexpr int64_t ValueSizeLimit() { + return std::numeric_limits::max(); + } + + /// \brief Ensure that the indicated number of bytes can be appended via + /// UnsafeAppend operations without the need to allocate more memory + Status Reserve(int64_t num_bytes) { + if (ARROW_PREDICT_FALSE(num_bytes > ValueSizeLimit())) { + return Status::CapacityError( + "BinaryView or StringView elements cannot reference " + "strings larger than 2GB"); + } + if (num_bytes > current_remaining_bytes_) { + ARROW_RETURN_NOT_OK(FinishLastBlock()); + current_remaining_bytes_ = num_bytes > blocksize_ ? num_bytes : blocksize_; + ARROW_ASSIGN_OR_RAISE( + std::shared_ptr new_block, + AllocateResizableBuffer(current_remaining_bytes_, alignment_, pool_)); + current_offset_ = 0; + current_out_buffer_ = new_block->mutable_data(); + blocks_.emplace_back(std::move(new_block)); + } + return Status::OK(); + } + + void Reset() { + current_offset_ = 0; + current_out_buffer_ = NULLPTR; + current_remaining_bytes_ = 0; + blocks_.clear(); + } + + int64_t current_remaining_bytes() const { return current_remaining_bytes_; } + + Result>> Finish() { + if (!blocks_.empty()) { + ARROW_RETURN_NOT_OK(FinishLastBlock()); + } + current_offset_ = 0; + current_out_buffer_ = NULLPTR; + current_remaining_bytes_ = 0; + return std::move(blocks_); + } + + private: + Status FinishLastBlock() { + if (current_remaining_bytes_ > 0) { + // Avoid leaking uninitialized bytes from the allocator + ARROW_RETURN_NOT_OK( + blocks_.back()->Resize(blocks_.back()->size() - current_remaining_bytes_, + /*shrink_to_fit=*/true)); + blocks_.back()->ZeroPadding(); + } + return Status::OK(); + } + + MemoryPool* pool_; + int64_t alignment_; + int64_t blocksize_ = kDefaultBlocksize; + std::vector> blocks_; + + int32_t current_offset_ = 0; + uint8_t* current_out_buffer_ = NULLPTR; + int64_t current_remaining_bytes_ = 0; +}; + +} // namespace internal + +class ARROW_EXPORT BinaryViewBuilder : public ArrayBuilder { + public: + using TypeClass = BinaryViewType; + + // this constructor provided for MakeBuilder compatibility + BinaryViewBuilder(const std::shared_ptr&, MemoryPool* pool); + + explicit BinaryViewBuilder(MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : ArrayBuilder(pool, alignment), + data_builder_(pool, alignment), + data_heap_builder_(pool, alignment) {} + + /// Set the size for future preallocated data buffers. + /// + /// The default size is 32KB, so after each 32KB of string data appended to the builder + /// a new data buffer will be allocated. Adjust this to a larger value to decrease the + /// frequency of allocation, or to a smaller value to lower the overhead of each + /// allocation. + void SetBlockSize(int64_t blocksize) { data_heap_builder_.SetBlockSize(blocksize); } + + /// The number of bytes which can be appended to this builder without allocating another + /// data buffer. + int64_t current_block_bytes_remaining() const { + return data_heap_builder_.current_remaining_bytes(); + } + + Status Append(const uint8_t* value, int64_t length) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppendToBitmap(true); + ARROW_ASSIGN_OR_RAISE(auto v, + data_heap_builder_.Append(value, length)); + data_builder_.UnsafeAppend(v); + return Status::OK(); + } + + Status Append(const char* value, int64_t length) { + return Append(reinterpret_cast(value), length); + } + + Status Append(std::string_view value) { + return Append(value.data(), static_cast(value.size())); + } + + /// \brief Append without checking capacity + /// + /// Builder should have been presized using Reserve() and ReserveData(), + /// respectively, and the value must not be larger than 2GB + void UnsafeAppend(const uint8_t* value, int64_t length) { + UnsafeAppendToBitmap(true); + auto v = data_heap_builder_.Append(value, length); + data_builder_.UnsafeAppend(v); + } + + void UnsafeAppend(const char* value, int64_t length) { + UnsafeAppend(reinterpret_cast(value), length); + } + + void UnsafeAppend(const std::string& value) { + UnsafeAppend(value.c_str(), static_cast(value.size())); + } + + void UnsafeAppend(std::string_view value) { + UnsafeAppend(value.data(), static_cast(value.size())); + } + + /// \brief Ensures there is enough allocated available capacity in the + /// out-of-line data heap to append the indicated number of bytes without + /// additional allocations + Status ReserveData(int64_t length); + + Status AppendNulls(int64_t length) final { + ARROW_RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend(length, BinaryViewType::c_type{}); + UnsafeSetNull(length); + return Status::OK(); + } + + /// \brief Append a single null element + Status AppendNull() final { + ARROW_RETURN_NOT_OK(Reserve(1)); + data_builder_.UnsafeAppend(BinaryViewType::c_type{}); + UnsafeAppendToBitmap(false); + return Status::OK(); + } + + /// \brief Append a empty element (length-0 inline string) + Status AppendEmptyValue() final { + ARROW_RETURN_NOT_OK(Reserve(1)); + data_builder_.UnsafeAppend(BinaryViewType::c_type{}); + UnsafeAppendToBitmap(true); + return Status::OK(); + } + + /// \brief Append several empty elements + Status AppendEmptyValues(int64_t length) final { + ARROW_RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend(length, BinaryViewType::c_type{}); + UnsafeSetNotNull(length); + return Status::OK(); + } + + void UnsafeAppendNull() { + data_builder_.UnsafeAppend(BinaryViewType::c_type{}); + UnsafeAppendToBitmap(false); + } + + void UnsafeAppendEmptyValue() { + data_builder_.UnsafeAppend(BinaryViewType::c_type{}); + UnsafeAppendToBitmap(true); + } + + /// \brief Append a slice of a BinaryViewArray passed as an ArraySpan. Copies + /// the underlying out-of-line string memory to avoid memory lifetime issues + Status AppendArraySlice(const ArraySpan& array, int64_t offset, + int64_t length) override; + + void Reset() override; + + Status Resize(int64_t capacity) override { + ARROW_RETURN_NOT_OK(CheckCapacity(capacity)); + capacity = std::max(capacity, kMinBuilderCapacity); + ARROW_RETURN_NOT_OK(data_builder_.Resize(capacity)); + return ArrayBuilder::Resize(capacity); + } + + Status FinishInternal(std::shared_ptr* out) override; + + std::shared_ptr type() const override { return binary_view(); } + + protected: + TypedBufferBuilder data_builder_; + + // Accumulates out-of-line data in fixed-size chunks which are then attached + // to the resulting ArrayData + internal::StringHeapBuilder data_heap_builder_; +}; + +class ARROW_EXPORT StringViewBuilder : public BinaryViewBuilder { + public: + using BinaryViewBuilder::BinaryViewBuilder; + std::shared_ptr type() const override { return utf8_view(); } +}; + +// ---------------------------------------------------------------------- +// FixedSizeBinaryBuilder + +class ARROW_EXPORT FixedSizeBinaryBuilder : public ArrayBuilder { + public: + using TypeClass = FixedSizeBinaryType; + + explicit FixedSizeBinaryBuilder(const std::shared_ptr& type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment); + + Status Append(const uint8_t* value) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppend(value); + return Status::OK(); + } + + Status Append(const char* value) { + return Append(reinterpret_cast(value)); + } + + Status Append(std::string_view view) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppend(view); + return Status::OK(); + } + + Status Append(const std::string& s) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppend(s); + return Status::OK(); + } + + Status Append(const Buffer& s) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppend(s); + return Status::OK(); + } + + Status Append(const std::shared_ptr& s) { return Append(*s); } + + template + Status Append(const std::array& value) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppend( + std::string_view(reinterpret_cast(value.data()), value.size())); + return Status::OK(); + } + + Status AppendValues(const uint8_t* data, int64_t length, + const uint8_t* valid_bytes = NULLPTR); + + Status AppendValues(const uint8_t* data, int64_t length, const uint8_t* validity, + int64_t bitmap_offset); + + Status AppendNull() final; + Status AppendNulls(int64_t length) final; + + Status AppendEmptyValue() final; + Status AppendEmptyValues(int64_t length) final; + + Status AppendArraySlice(const ArraySpan& array, int64_t offset, + int64_t length) override { + return AppendValues( + array.GetValues(1, 0) + ((array.offset + offset) * byte_width_), length, + array.GetValues(0, 0), array.offset + offset); + } + + void UnsafeAppend(const uint8_t* value) { + UnsafeAppendToBitmap(true); + if (ARROW_PREDICT_TRUE(byte_width_ > 0)) { + byte_builder_.UnsafeAppend(value, byte_width_); + } + } + + void UnsafeAppend(const char* value) { + UnsafeAppend(reinterpret_cast(value)); + } + + void UnsafeAppend(std::string_view value) { +#ifndef NDEBUG + CheckValueSize(static_cast(value.size())); +#endif + UnsafeAppend(reinterpret_cast(value.data())); + } + + void UnsafeAppend(const Buffer& s) { UnsafeAppend(std::string_view{s}); } + + void UnsafeAppend(const std::shared_ptr& s) { UnsafeAppend(*s); } + + void UnsafeAppendNull() { + UnsafeAppendToBitmap(false); + byte_builder_.UnsafeAppend(/*num_copies=*/byte_width_, 0); + } + + Status ValidateOverflow(int64_t new_bytes) const { + auto new_size = byte_builder_.length() + new_bytes; + if (ARROW_PREDICT_FALSE(new_size > memory_limit())) { + return Status::CapacityError("array cannot contain more than ", memory_limit(), + " bytes, have ", new_size); + } else { + return Status::OK(); + } + } + + /// \brief Ensures there is enough allocated capacity to append the indicated + /// number of bytes to the value data buffer without additional allocations + Status ReserveData(int64_t elements) { + ARROW_RETURN_NOT_OK(ValidateOverflow(elements)); + return byte_builder_.Reserve(elements); + } + + void Reset() override; + Status Resize(int64_t capacity) override; + Status FinishInternal(std::shared_ptr* out) override; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + /// \return size of values buffer so far + int64_t value_data_length() const { return byte_builder_.length(); } + + int32_t byte_width() const { return byte_width_; } + + /// Temporary access to a value. + /// + /// This pointer becomes invalid on the next modifying operation. + const uint8_t* GetValue(int64_t i) const; + + /// Temporary mutable access to a value. + /// + /// This pointer becomes invalid on the next modifying operation. + uint8_t* GetMutableValue(int64_t i) { + uint8_t* data_ptr = byte_builder_.mutable_data(); + return data_ptr + i * byte_width_; + } + + /// Temporary mutable access to a value. + /// + /// This view becomes invalid on the next modifying operation. + std::string_view GetView(int64_t i) const; + + /// Advance builder without allocating nor writing any values + /// + /// The internal pointer is advanced by `length` values and the same number + /// of non-null entries are appended to the validity bitmap. + /// This method assumes that the `length` values were populated directly, + /// for example using `GetMutableValue`. + void UnsafeAdvance(int64_t length) { + byte_builder_.UnsafeAdvance(length * byte_width_); + UnsafeAppendToBitmap(length, true); + } + + /// Advance builder without allocating nor writing any values + /// + /// The internal pointer is advanced by `length` values and the same number + /// of validity bits are appended to the validity bitmap. + /// This method assumes that the `length` values were populated directly, + /// for example using `GetMutableValue`. + void UnsafeAdvance(int64_t length, const uint8_t* validity, int64_t valid_bits_offset) { + byte_builder_.UnsafeAdvance(length * byte_width_); + UnsafeAppendToBitmap(validity, valid_bits_offset, length); + } + + static constexpr int64_t memory_limit() { + return std::numeric_limits::max() - 1; + } + + std::shared_ptr type() const override { + return fixed_size_binary(byte_width_); + } + + protected: + int32_t byte_width_; + BufferBuilder byte_builder_; + + void CheckValueSize(int64_t size); +}; + +/// @} + +// ---------------------------------------------------------------------- +// Chunked builders: build a sequence of BinaryArray or StringArray that are +// limited to a particular size (to the upper limit of 2GB) + +namespace internal { + +class ARROW_EXPORT ChunkedBinaryBuilder { + public: + explicit ChunkedBinaryBuilder(int32_t max_chunk_value_length, + MemoryPool* pool = default_memory_pool()); + + ChunkedBinaryBuilder(int32_t max_chunk_value_length, int32_t max_chunk_length, + MemoryPool* pool = default_memory_pool()); + + virtual ~ChunkedBinaryBuilder() = default; + + Status Append(const uint8_t* value, int32_t length) { + if (ARROW_PREDICT_FALSE(length + builder_->value_data_length() > + max_chunk_value_length_)) { + if (builder_->value_data_length() == 0) { + // The current item is larger than max_chunk_size_; + // this chunk will be oversize and hold *only* this item + ARROW_RETURN_NOT_OK(builder_->Append(value, length)); + return NextChunk(); + } + // The current item would cause builder_->value_data_length() to exceed + // max_chunk_size_, so finish this chunk and append the current item to the next + // chunk + ARROW_RETURN_NOT_OK(NextChunk()); + return Append(value, length); + } + + if (ARROW_PREDICT_FALSE(builder_->length() == max_chunk_length_)) { + // The current item would cause builder_->length() to exceed max_chunk_length_, so + // finish this chunk and append the current item to the next chunk + ARROW_RETURN_NOT_OK(NextChunk()); + } + + return builder_->Append(value, length); + } + + Status Append(std::string_view value) { + return Append(reinterpret_cast(value.data()), + static_cast(value.size())); + } + + Status AppendNull() { + if (ARROW_PREDICT_FALSE(builder_->length() == max_chunk_length_)) { + ARROW_RETURN_NOT_OK(NextChunk()); + } + return builder_->AppendNull(); + } + + Status Reserve(int64_t values); + + virtual Status Finish(ArrayVector* out); + + protected: + Status NextChunk(); + + // maximum total character data size per chunk + int64_t max_chunk_value_length_; + + // maximum elements allowed per chunk + int64_t max_chunk_length_ = kListMaximumElements; + + // when Reserve() would cause builder_ to exceed its max_chunk_length_, + // add to extra_capacity_ instead and wait to reserve until the next chunk + int64_t extra_capacity_ = 0; + + std::unique_ptr builder_; + std::vector> chunks_; +}; + +class ARROW_EXPORT ChunkedStringBuilder : public ChunkedBinaryBuilder { + public: + using ChunkedBinaryBuilder::ChunkedBinaryBuilder; + + Status Finish(ArrayVector* out) override; +}; + +} // namespace internal + +} // namespace arrow diff --git a/shared/package-files/71/71fdc0dd5e9f87b742c06c520e5416f1dbca3bfd44165020edab4ad091874360/qconfig_mapping_utils.py b/shared/package-files/71/71fdc0dd5e9f87b742c06c520e5416f1dbca3bfd44165020edab4ad091874360/qconfig_mapping_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0b906a1777de0168511190a4d4d6ec4442a36b99 --- /dev/null +++ b/shared/package-files/71/71fdc0dd5e9f87b742c06c520e5416f1dbca3bfd44165020edab4ad091874360/qconfig_mapping_utils.py @@ -0,0 +1,343 @@ +import torch +import re +from collections import defaultdict, OrderedDict +from typing import Callable, Any, Dict, Tuple, Set, List, Union +from torch.ao.quantization import QConfig +from torch.ao.quantization.qconfig import _add_module_to_qconfig_obs_ctr, QConfigAny, qconfig_equals +from torch.ao.quantization.observer import ( + _is_activation_post_process, +) +from torch.ao.quantization.backend_config import ( + BackendConfig, + DTypeConfig, +) +from torch.ao.quantization.backend_config.utils import ( + get_module_to_qat_module, +) + +from torch.fx import ( + GraphModule, +) +from torch.fx.graph import ( + Graph, +) +from torch.ao.nn.intrinsic import _FusedModule + +from ..utils import ( + _parent_name, + get_qconfig_dtypes, +) +from ..qconfig_mapping import ( + _OBJECT_TYPE_DICT_KEY, + _MODULE_NAME_DICT_KEY, + _MODULE_NAME_REGEX_DICT_KEY, + QConfigMapping, +) + +__all__: List[str] = [] + + + +def _maybe_adjust_qconfig_for_module_name_object_type_order( + qconfig_mapping: QConfigMapping, + cur_module_path: str, + cur_object_type: Callable, + cur_object_type_idx: int, + fallback_qconfig: QConfigAny, +) -> QConfigAny: + for (module_name, object_type, index), qconfig in qconfig_mapping.module_name_object_type_order_qconfigs.items(): + if ( + (module_name == cur_module_path) and + (object_type == cur_object_type) and + (index == cur_object_type_idx) + ): + return qconfig + return fallback_qconfig + + +def _update_qconfig_for_fusion(model: GraphModule, qconfig_mapping: QConfigMapping): + """ + Update the QConfigMapping to account for fused modules such as LinearReLU. + This assumes the QConfigMapping's attributes have already been converted to OrderedDicts. + """ + object_type_dict = qconfig_mapping.object_type_qconfigs + if len(object_type_dict) == 0: + return qconfig_mapping + + modules = dict(model.named_modules()) + + for node in model.graph.nodes: + if node.op == 'call_module' and node.target in modules: + maybe_fused_module = modules[str(node.target)] + if not isinstance(maybe_fused_module, _FusedModule): + continue + + ops = list(maybe_fused_module._modules.values()) + fused_qconfig = object_type_dict.get(type(ops[0]), None) + + # Raise an error if the modules in the fused module have + # different qconfigs specified in the qconfig_dict + # TODO: currently it only works for modules, + # need to make this work for torch.nn.functional.relu + # TODO: currently it only works for object_type configurations, + # ideally it should work for different types of configurations, + # maybe we want to redesign this part + for op in ops[1:]: + if not qconfig_equals(object_type_dict.get(type(op), None), fused_qconfig): + raise LookupError( + "During fusion, we need to specify the same " + + f"qconfigs for all module types in {type(maybe_fused_module)} " + + f"offending type: {type(op)}") + + if fused_qconfig is not None: + object_type_dict[type(maybe_fused_module)] = fused_qconfig + +def _generate_node_name_to_qconfig( + root: torch.nn.Module, + modules: Dict[str, torch.nn.Module], + input_graph: Graph, + qconfig_mapping: QConfigMapping, + node_name_to_scope: Dict[str, Tuple[str, type]]) -> Dict[str, QConfigAny]: + global_qconfig = qconfig_mapping.global_qconfig + node_name_to_qconfig = {} + + # example: + # + # {'foo.bar': {F.linear: 0, F.conv2d: 1, ...}, ...} + # + # meaning in submodule 'foo.bar', we have seen 0 F.linear and + # 1 F.conv2d invocations so far. + submodule_to_object_type_to_cur_idx: Dict[str, Dict[Callable, int]] = \ + defaultdict(lambda: defaultdict(int)) + for node in input_graph.nodes: + qconfig = None + if node.op == "get_attr": + module_name, _ = _parent_name(node.target) + qconfig = _maybe_adjust_qconfig_for_module_type_or_name( + qconfig_mapping, type(modules[module_name]), module_name, global_qconfig) + qconfig_with_device_check = _add_module_to_qconfig_obs_ctr(qconfig, modules.get(node.target, None)) + elif node.op == "call_function": + # precedence: module_name_qconfig + # > function_qconfig > global_qconfig + # module_name takes precedence over function qconfig + function_qconfig = _get_object_type_qconfig( + qconfig_mapping, node.target, global_qconfig) + module_path, module_type = node_name_to_scope[node.name] + qconfig = _maybe_adjust_qconfig_for_module_type_or_name( + qconfig_mapping, module_type, module_path, function_qconfig) + + cur_object_type_idx = \ + submodule_to_object_type_to_cur_idx[module_path][node.target] + submodule_to_object_type_to_cur_idx[module_path][node.target] += 1 + qconfig = _maybe_adjust_qconfig_for_module_name_object_type_order( + qconfig_mapping, module_path, node.target, cur_object_type_idx, qconfig) + qconfig_with_device_check = _add_module_to_qconfig_obs_ctr(qconfig, modules.get(node.target, None)) + + elif node.op == "call_method": + module_path, module_type = node_name_to_scope[node.name] + # first use node.target (string) to get the qconfig + # this is to support configs like + # "object_type": [("reshape", qconfig)] + qconfig = _maybe_adjust_qconfig_for_module_type_or_name( + qconfig_mapping, node.target, module_path, global_qconfig) + # if there is no special config for the method, we'll fall back to the + # config for the module that contains the call_method node + qconfig = _maybe_adjust_qconfig_for_module_type_or_name( + qconfig_mapping, module_type, module_path, qconfig) + # currently call_method does not support modifying qconfig + # by order, we can add this later if it is needed. + qconfig_with_device_check = _add_module_to_qconfig_obs_ctr(qconfig, modules.get(node.target, None)) + + elif node.op == 'call_module': + # if the node is an observer, just continue - don't add it to the qconfig_map + if _is_activation_post_process(modules[node.target]): + continue + qconfig = _maybe_adjust_qconfig_for_module_type_or_name( + qconfig_mapping, type(modules[node.target]), node.target, global_qconfig) + + module_path, module_type = node_name_to_scope[node.name] + # Note: for call_module, the module_path is the current module's name. + # to meaningfully count invocations, we need to count them in the parent + # module. + parent_name, _ = _parent_name(module_path) + cur_object_type_idx = \ + submodule_to_object_type_to_cur_idx[parent_name][module_type] + submodule_to_object_type_to_cur_idx[parent_name][module_type] += 1 + qconfig = _maybe_adjust_qconfig_for_module_name_object_type_order( + qconfig_mapping, parent_name, module_type, cur_object_type_idx, + qconfig) + qconfig_with_device_check = _add_module_to_qconfig_obs_ctr(qconfig, modules.get(node.target, None)) + + # regex is not supported eager mode propagate_qconfig_, we'll + # need to set the qconfig explicitly here in case regex + # is used + modules[node.target].qconfig = qconfig_with_device_check + else: + qconfig_with_device_check = None + + node_name_to_qconfig[node.name] = qconfig_with_device_check + return node_name_to_qconfig + + +def _check_is_valid_config_dict(config_dict: Any, allowed_keys: Set[str], dict_name: str) -> None: + r""" Checks if the given config_dict has the correct keys + + Args: + `config_dict`: dictionary whose keys we want to check + """ + + for k in config_dict.keys(): + if k not in allowed_keys: + raise ValueError( + 'Expected ' + dict_name + ' to have the following keys: ' + + str(allowed_keys) + '. But found \'' + k + + '\' instead.') + + +def _compare_prepare_convert_qconfig_mappings( + prepare_qconfig_mapping: QConfigMapping, + convert_qconfig_mapping: QConfigMapping): + r""" Compare the qconfig_mapping passed in convert to the one from prepare and check the values + + Args: + `prepare_qconfig_mapping`: configuration for prepare quantization step + `convert_qconfig_mapping`: configuration for convert quantization step + """ + assert qconfig_equals(prepare_qconfig_mapping.global_qconfig, convert_qconfig_mapping.global_qconfig), \ + "Expected global qconfigs to be the same in the prepare and convert quantization configs" + prepare_dicts: List[OrderedDict] = [ + prepare_qconfig_mapping.object_type_qconfigs, + prepare_qconfig_mapping.module_name_qconfigs, + prepare_qconfig_mapping.module_name_regex_qconfigs, + ] + convert_dicts: List[OrderedDict] = [ + convert_qconfig_mapping.object_type_qconfigs, + convert_qconfig_mapping.module_name_qconfigs, + convert_qconfig_mapping.module_name_regex_qconfigs, + ] + dict_names = [_OBJECT_TYPE_DICT_KEY, _MODULE_NAME_DICT_KEY, _MODULE_NAME_REGEX_DICT_KEY] + for i in range(len(prepare_dicts)): + for name in prepare_dicts[i].keys(): + assert name in convert_dicts[i], f"Missing key {dict_names[i]} {name} in convert QConfigMapping \ + when it was present in prepare" + assert convert_dicts[i][name] is None \ + or qconfig_equals(prepare_dicts[i][name], convert_dicts[i][name]), \ + f"Expected convert QConfigMapping to have the same qconfig as prepare for key {dict_names[i]} {name}; \ + prepare: {prepare_dicts[i][name]}; convert: {convert_dicts[i][name]}" + +def _is_qconfig_supported_by_dtype_configs(qconfig: QConfig, dtype_configs: List[DTypeConfig]): + for dtype_config in dtype_configs: + is_dynamic = dtype_config.is_dynamic + if is_dynamic is None: + is_dynamic = False + input_dtype = dtype_config.input_dtype or torch.float + weight_dtype = dtype_config.weight_dtype or torch.float + bias_dtype = dtype_config.bias_dtype or torch.float + output_dtype = dtype_config.output_dtype or torch.float + qconfig_activation_dtype, qconfig_weight_dtype, qconfig_input_act_is_dynamic = \ + get_qconfig_dtypes(qconfig) + qconfig_bias_dtype = torch.float16 \ + if ( + qconfig_activation_dtype == torch.float16 + and qconfig_weight_dtype == torch.float16 + and not is_dynamic + ) else torch.float + + if is_dynamic: + is_match = qconfig_input_act_is_dynamic and \ + input_dtype == qconfig_activation_dtype and \ + output_dtype == torch.float and \ + weight_dtype == qconfig_weight_dtype + else: + is_match = input_dtype == qconfig_activation_dtype and \ + output_dtype == qconfig_activation_dtype and \ + weight_dtype == qconfig_weight_dtype and \ + bias_dtype == qconfig_bias_dtype + if is_match: + return True + return False + +def _get_object_type_qconfig( + qconfig_mapping: QConfigMapping, + object_type: Union[Callable, str], + fallback_qconfig: QConfigAny) -> QConfigAny: + return qconfig_mapping.object_type_qconfigs.get(object_type, fallback_qconfig) + + +def _get_module_name_regex_qconfig(qconfig_mapping, module_name, fallback_qconfig): + for regex_pattern, qconfig in qconfig_mapping.module_name_regex_qconfigs.items(): + if re.match(regex_pattern, module_name): + # first match wins + return qconfig + return fallback_qconfig + + +def _get_module_name_qconfig(qconfig_mapping, module_name, fallback_qconfig): + if module_name == '': + # module name qconfig not found + return fallback_qconfig + if module_name in qconfig_mapping.module_name_qconfigs: + return qconfig_mapping.module_name_qconfigs[module_name] + else: + parent, _ = _parent_name(module_name) + return _get_module_name_qconfig(qconfig_mapping, parent, fallback_qconfig) + + +def _maybe_adjust_qconfig_for_module_type_or_name(qconfig_mapping, module_type, module_name, global_qconfig): + # get qconfig for module_name, + # fallback to module_name_regex_qconfig, module_type_qconfig, + # global_qconfig if necessary + module_type_qconfig = _get_object_type_qconfig( + qconfig_mapping, module_type, global_qconfig) + module_name_regex_qconfig = _get_module_name_regex_qconfig( + qconfig_mapping, module_name, module_type_qconfig) + module_name_qconfig = _get_module_name_qconfig( + qconfig_mapping, module_name, module_name_regex_qconfig) + return module_name_qconfig + + +def _get_flattened_qconfig_dict(qconfig_mapping: QConfigMapping) -> Dict[Union[Callable, str], QConfigAny]: + """ flatten the global, object_type and module_name qconfig + to the same qconfig_dict so that it can be used by + propagate_qconfig_ function. + "module_name_regex" is ignored for now since it's not supported + in propagate_qconfig_, but it can be fixed later. + + For example: + Input: { + "": qconfig, + "object_type": [ + (torch.add, qconfig) + ], + "module_name": [ + ("conv", qconfig) + ] + } + + Output: { + "": qconfig, + torch.add: qconfig, + "conv": qconfig + } + """ + flattened: Dict[Union[Callable, str], QConfigAny] = {"": qconfig_mapping.global_qconfig} + for obj, qconfig in qconfig_mapping.object_type_qconfigs.items(): + flattened[obj] = qconfig + for obj, qconfig in qconfig_mapping.module_name_qconfigs.items(): + flattened[obj] = qconfig + return flattened + + +def _update_qconfig_for_qat( + qconfig_mapping: QConfigMapping, + backend_config: BackendConfig): + """ + Update the qconfig_mapping to account for module swaps during QAT. + During QAT we perform a module swap on the nn.Module types to the corresponding nn.qat.modules types. + """ + module_to_qat_module_class = get_module_to_qat_module(backend_config) + object_type_dict = qconfig_mapping.object_type_qconfigs + new_object_type_dict = object_type_dict.copy() + for k, v in new_object_type_dict.items(): + if k in module_to_qat_module_class: + object_type_dict[module_to_qat_module_class[k]] = v diff --git a/shared/package-files/73/73014c28efa9830b27d47f10f496f9f19e99ac1ac2a0dd2ca8907462e9c17d29/G_S_U_B_.py b/shared/package-files/73/73014c28efa9830b27d47f10f496f9f19e99ac1ac2a0dd2ca8907462e9c17d29/G_S_U_B_.py new file mode 100644 index 0000000000000000000000000000000000000000..ca1aff8b0680bf22550c460819627b4d2b14a463 --- /dev/null +++ b/shared/package-files/73/73014c28efa9830b27d47f10f496f9f19e99ac1ac2a0dd2ca8907462e9c17d29/G_S_U_B_.py @@ -0,0 +1,13 @@ +from .otBase import BaseTTXConverter + + +class table_G_S_U_B_(BaseTTXConverter): + """Glyph Substitution table + + The ``GSUB`` table contains glyph-substitution rules used in + OpenType Layout. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/gsub + """ + + pass diff --git a/shared/package-files/73/7301e7c54fe04a5f3de0fe7d853df842603a5338100f7a9717dca18039f381a3/mul.h b/shared/package-files/73/7301e7c54fe04a5f3de0fe7d853df842603a5338100f7a9717dca18039f381a3/mul.h new file mode 100644 index 0000000000000000000000000000000000000000..1e0264228c4dcd307d001911f852eee54329e5ae --- /dev/null +++ b/shared/package-files/73/7301e7c54fe04a5f3de0fe7d853df842603a5338100f7a9717dca18039f381a3/mul.h @@ -0,0 +1,53 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::mul.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor mul(const at::Tensor & self, const at::Tensor & other) { + return at::_ops::mul_Tensor::call(self, other); +} + +// aten::mul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & mul_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) { + return at::_ops::mul_out::call(self, other, out); +} +// aten::mul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & mul_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) { + return at::_ops::mul_out::call(self, other, out); +} + +// aten::mul.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor mul(const at::Tensor & self, const at::Scalar & other) { + return at::_ops::mul_Scalar::call(self, other); +} + +// aten::mul.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & mul_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & other) { + return at::_ops::mul_Scalar_out::call(self, other, out); +} +// aten::mul.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & mul_outf(const at::Tensor & self, const at::Scalar & other, at::Tensor & out) { + return at::_ops::mul_Scalar_out::call(self, other, out); +} + +} diff --git a/shared/package-files/73/730296014347b79621ddd5046c56bc53dbb840f7a6c14cdcf7bfbb06ea210abd/is_distributed_ops.h b/shared/package-files/73/730296014347b79621ddd5046c56bc53dbb840f7a6c14cdcf7bfbb06ea210abd/is_distributed_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..f77c55550e1b5645a5540c3d6e077725ed92578c --- /dev/null +++ b/shared/package-files/73/730296014347b79621ddd5046c56bc53dbb840f7a6c14cdcf7bfbb06ea210abd/is_distributed_ops.h @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API is_distributed { + using schema = bool (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::is_distributed") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "is_distributed(Tensor self) -> bool") + static bool call(const at::Tensor & self); + static bool redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/73/73032a08974569141018cd63e0ccd57a93a6bb9b751c85fad3edd3d165be8e07/__init__.py b/shared/package-files/73/73032a08974569141018cd63e0ccd57a93a6bb9b751c85fad3edd3d165be8e07/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c53b961e9494353094150da627341a9e950e3f35 --- /dev/null +++ b/shared/package-files/73/73032a08974569141018cd63e0ccd57a93a6bb9b751c85fad3edd3d165be8e07/__init__.py @@ -0,0 +1,40 @@ +from . import dynamic # noqa: F403 +from . import functional # noqa: F403 +from . import modules # noqa: F403 +from .modules import * # noqa: F403 +from .modules import MaxPool2d + +__all__ = [ + 'BatchNorm2d', + 'BatchNorm3d', + 'Conv1d', + 'Conv2d', + 'Conv3d', + 'ConvTranspose1d', + 'ConvTranspose2d', + 'ConvTranspose3d', + 'DeQuantize', + 'Dropout', + 'ELU', + 'Embedding', + 'EmbeddingBag', + 'GroupNorm', + 'Hardswish', + 'InstanceNorm1d', + 'InstanceNorm2d', + 'InstanceNorm3d', + 'LayerNorm', + 'LeakyReLU', + 'Linear', + 'LSTM', + 'MultiheadAttention', + 'PReLU', + 'Quantize', + 'ReLU6', + 'Sigmoid', + 'Softmax', + # Wrapper modules + 'FloatFunctional', + 'FXFloatFunctional', + 'QFunctional', +] diff --git a/shared/package-files/73/73040b0ce75c25b018d84eddafce7de72cee361d7f621f34aff3bc5864f684c6/test_grid_finder.py b/shared/package-files/73/73040b0ce75c25b018d84eddafce7de72cee361d7f621f34aff3bc5864f684c6/test_grid_finder.py new file mode 100644 index 0000000000000000000000000000000000000000..6b397675ee10098a93545cc712a4b3c07384cbc2 --- /dev/null +++ b/shared/package-files/73/73040b0ce75c25b018d84eddafce7de72cee361d7f621f34aff3bc5864f684c6/test_grid_finder.py @@ -0,0 +1,34 @@ +import numpy as np +import pytest + +from matplotlib.transforms import Bbox +from mpl_toolkits.axisartist.grid_finder import ( + _find_line_box_crossings, FormatterPrettyPrint, MaxNLocator) + + +def test_find_line_box_crossings(): + x = np.array([-3, -2, -1, 0., 1, 2, 3, 2, 1, 0, -1, -2, -3, 5]) + y = np.arange(len(x)) + bbox = Bbox.from_extents(-2, 3, 2, 12.5) + left, right, bottom, top = _find_line_box_crossings( + np.column_stack([x, y]), bbox) + ((lx0, ly0), la0), ((lx1, ly1), la1), = left + ((rx0, ry0), ra0), ((rx1, ry1), ra1), = right + ((bx0, by0), ba0), = bottom + ((tx0, ty0), ta0), = top + assert (lx0, ly0, la0) == (-2, 11, 135) + assert (lx1, ly1, la1) == pytest.approx((-2., 12.125, 7.125016)) + assert (rx0, ry0, ra0) == (2, 5, 45) + assert (rx1, ry1, ra1) == (2, 7, 135) + assert (bx0, by0, ba0) == (0, 3, 45) + assert (tx0, ty0, ta0) == pytest.approx((1., 12.5, 7.125016)) + + +def test_pretty_print_format(): + locator = MaxNLocator() + locs, nloc, factor = locator(0, 100) + + fmt = FormatterPrettyPrint() + + assert fmt("left", None, locs) == \ + [r'$\mathdefault{%d}$' % (l, ) for l in locs] diff --git a/shared/package-files/73/7309e72d1193954253c636991ef9f630b0acaab4d7fa7e3bec02ab9b29a05b9d/cli.py b/shared/package-files/73/7309e72d1193954253c636991ef9f630b0acaab4d7fa7e3bec02ab9b29a05b9d/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..37f4392d9d671fd4b87b19b0b57cfec7a692c23d --- /dev/null +++ b/shared/package-files/73/7309e72d1193954253c636991ef9f630b0acaab4d7fa7e3bec02ab9b29a05b9d/cli.py @@ -0,0 +1,67 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from __future__ import annotations + +import argparse + +from ....base.context import context, locate_prefix_by_name +from ....cli.common import validate_prefix +from ....cli.conda_argparse import add_parser_prefix +from ....exceptions import CondaEnvException +from ... import CondaSubcommand, hookimpl + + +def get_parsed_args(argv: list[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser( + "conda doctor", + description="Display a health report for your environment.", + ) + parser.add_argument( + "-v", + "--verbose", + action="store_true", + help="generate a detailed environment health report", + ) + add_parser_prefix(parser) + args = parser.parse_args(argv) + + return args + + +def get_prefix(args: argparse.Namespace) -> str: + """ + Determine the correct prefix to use provided the CLI arguments and the context object. + + When not specified via CLI options, the default is the currently active prefix + """ + if args.name: + return locate_prefix_by_name(args.name) + + if args.prefix: + return validate_prefix(args.prefix) + + if context.active_prefix: + return context.active_prefix + + raise CondaEnvException( + "No environment specified. Activate an environment or specify the " + "environment via `--name` or `--prefix`." + ) + + +def execute(argv: list[str]) -> None: + """Run conda doctor subcommand.""" + from .health_checks import display_health_checks + + args = get_parsed_args(argv) + prefix = get_prefix(args) + display_health_checks(prefix, verbose=args.verbose) + + +@hookimpl +def conda_subcommands(): + yield CondaSubcommand( + name="doctor", + summary="A subcommand that displays environment health report", + action=execute, + ) diff --git a/shared/package-files/73/730ab874c93cee624748192d2b59a2609fbce46fb74f74664f6d2fed2142a67a/timeout.py b/shared/package-files/73/730ab874c93cee624748192d2b59a2609fbce46fb74f74664f6d2fed2142a67a/timeout.py new file mode 100644 index 0000000000000000000000000000000000000000..78e18a6272482e3946de83c0274badc4a5cfcdfa --- /dev/null +++ b/shared/package-files/73/730ab874c93cee624748192d2b59a2609fbce46fb74f74664f6d2fed2142a67a/timeout.py @@ -0,0 +1,271 @@ +from __future__ import absolute_import + +import time + +# The default socket timeout, used by httplib to indicate that no timeout was; specified by the user +from socket import _GLOBAL_DEFAULT_TIMEOUT, getdefaulttimeout + +from ..exceptions import TimeoutStateError + +# A sentinel value to indicate that no timeout was specified by the user in +# urllib3 +_Default = object() + + +# Use time.monotonic if available. +current_time = getattr(time, "monotonic", time.time) + + +class Timeout(object): + """Timeout configuration. + + Timeouts can be defined as a default for a pool: + + .. code-block:: python + + timeout = Timeout(connect=2.0, read=7.0) + http = PoolManager(timeout=timeout) + response = http.request('GET', 'http://example.com/') + + Or per-request (which overrides the default for the pool): + + .. code-block:: python + + response = http.request('GET', 'http://example.com/', timeout=Timeout(10)) + + Timeouts can be disabled by setting all the parameters to ``None``: + + .. code-block:: python + + no_timeout = Timeout(connect=None, read=None) + response = http.request('GET', 'http://example.com/, timeout=no_timeout) + + + :param total: + This combines the connect and read timeouts into one; the read timeout + will be set to the time leftover from the connect attempt. In the + event that both a connect timeout and a total are specified, or a read + timeout and a total are specified, the shorter timeout will be applied. + + Defaults to None. + + :type total: int, float, or None + + :param connect: + The maximum amount of time (in seconds) to wait for a connection + attempt to a server to succeed. Omitting the parameter will default the + connect timeout to the system default, probably `the global default + timeout in socket.py + `_. + None will set an infinite timeout for connection attempts. + + :type connect: int, float, or None + + :param read: + The maximum amount of time (in seconds) to wait between consecutive + read operations for a response from the server. Omitting the parameter + will default the read timeout to the system default, probably `the + global default timeout in socket.py + `_. + None will set an infinite timeout. + + :type read: int, float, or None + + .. note:: + + Many factors can affect the total amount of time for urllib3 to return + an HTTP response. + + For example, Python's DNS resolver does not obey the timeout specified + on the socket. Other factors that can affect total request time include + high CPU load, high swap, the program running at a low priority level, + or other behaviors. + + In addition, the read and total timeouts only measure the time between + read operations on the socket connecting the client and the server, + not the total amount of time for the request to return a complete + response. For most requests, the timeout is raised because the server + has not sent the first byte in the specified time. This is not always + the case; if a server streams one byte every fifteen seconds, a timeout + of 20 seconds will not trigger, even though the request will take + several minutes to complete. + + If your goal is to cut off any request after a set amount of wall clock + time, consider having a second "watcher" thread to cut off a slow + request. + """ + + #: A sentinel object representing the default timeout value + DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT + + def __init__(self, total=None, connect=_Default, read=_Default): + self._connect = self._validate_timeout(connect, "connect") + self._read = self._validate_timeout(read, "read") + self.total = self._validate_timeout(total, "total") + self._start_connect = None + + def __repr__(self): + return "%s(connect=%r, read=%r, total=%r)" % ( + type(self).__name__, + self._connect, + self._read, + self.total, + ) + + # __str__ provided for backwards compatibility + __str__ = __repr__ + + @classmethod + def resolve_default_timeout(cls, timeout): + return getdefaulttimeout() if timeout is cls.DEFAULT_TIMEOUT else timeout + + @classmethod + def _validate_timeout(cls, value, name): + """Check that a timeout attribute is valid. + + :param value: The timeout value to validate + :param name: The name of the timeout attribute to validate. This is + used to specify in error messages. + :return: The validated and casted version of the given value. + :raises ValueError: If it is a numeric value less than or equal to + zero, or the type is not an integer, float, or None. + """ + if value is _Default: + return cls.DEFAULT_TIMEOUT + + if value is None or value is cls.DEFAULT_TIMEOUT: + return value + + if isinstance(value, bool): + raise ValueError( + "Timeout cannot be a boolean value. It must " + "be an int, float or None." + ) + try: + float(value) + except (TypeError, ValueError): + raise ValueError( + "Timeout value %s was %s, but it must be an " + "int, float or None." % (name, value) + ) + + try: + if value <= 0: + raise ValueError( + "Attempted to set %s timeout to %s, but the " + "timeout cannot be set to a value less " + "than or equal to 0." % (name, value) + ) + except TypeError: + # Python 3 + raise ValueError( + "Timeout value %s was %s, but it must be an " + "int, float or None." % (name, value) + ) + + return value + + @classmethod + def from_float(cls, timeout): + """Create a new Timeout from a legacy timeout value. + + The timeout value used by httplib.py sets the same timeout on the + connect(), and recv() socket requests. This creates a :class:`Timeout` + object that sets the individual timeouts to the ``timeout`` value + passed to this function. + + :param timeout: The legacy timeout value. + :type timeout: integer, float, sentinel default object, or None + :return: Timeout object + :rtype: :class:`Timeout` + """ + return Timeout(read=timeout, connect=timeout) + + def clone(self): + """Create a copy of the timeout object + + Timeout properties are stored per-pool but each request needs a fresh + Timeout object to ensure each one has its own start/stop configured. + + :return: a copy of the timeout object + :rtype: :class:`Timeout` + """ + # We can't use copy.deepcopy because that will also create a new object + # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to + # detect the user default. + return Timeout(connect=self._connect, read=self._read, total=self.total) + + def start_connect(self): + """Start the timeout clock, used during a connect() attempt + + :raises urllib3.exceptions.TimeoutStateError: if you attempt + to start a timer that has been started already. + """ + if self._start_connect is not None: + raise TimeoutStateError("Timeout timer has already been started.") + self._start_connect = current_time() + return self._start_connect + + def get_connect_duration(self): + """Gets the time elapsed since the call to :meth:`start_connect`. + + :return: Elapsed time in seconds. + :rtype: float + :raises urllib3.exceptions.TimeoutStateError: if you attempt + to get duration for a timer that hasn't been started. + """ + if self._start_connect is None: + raise TimeoutStateError( + "Can't get connect duration for timer that has not started." + ) + return current_time() - self._start_connect + + @property + def connect_timeout(self): + """Get the value to use when setting a connection timeout. + + This will be a positive float or integer, the value None + (never timeout), or the default system timeout. + + :return: Connect timeout. + :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None + """ + if self.total is None: + return self._connect + + if self._connect is None or self._connect is self.DEFAULT_TIMEOUT: + return self.total + + return min(self._connect, self.total) + + @property + def read_timeout(self): + """Get the value for the read timeout. + + This assumes some time has elapsed in the connection timeout and + computes the read timeout appropriately. + + If self.total is set, the read timeout is dependent on the amount of + time taken by the connect timeout. If the connection time has not been + established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be + raised. + + :return: Value to use for the read timeout. + :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None + :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect` + has not yet been called on this object. + """ + if ( + self.total is not None + and self.total is not self.DEFAULT_TIMEOUT + and self._read is not None + and self._read is not self.DEFAULT_TIMEOUT + ): + # In case the connect timeout has not yet been established. + if self._start_connect is None: + return self._read + return max(0, min(self.total - self.get_connect_duration(), self._read)) + elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT: + return max(0, self.total - self.get_connect_duration()) + else: + return self._read diff --git a/shared/package-files/73/730bf483279b90b2f48c81567d563836debd01df7f71b5e33846ae87fd1010fc/utils.py b/shared/package-files/73/730bf483279b90b2f48c81567d563836debd01df7f71b5e33846ae87fd1010fc/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..98720ba36d7f76a7bcd8afc0c93de3cd9c489d12 --- /dev/null +++ b/shared/package-files/73/730bf483279b90b2f48c81567d563836debd01df7f71b5e33846ae87fd1010fc/utils.py @@ -0,0 +1,897 @@ +"""Utility functions, mostly for internal use.""" +import os +import inspect +import warnings +import colorsys +from contextlib import contextmanager +from urllib.request import urlopen, urlretrieve +from types import ModuleType + +import numpy as np +import pandas as pd +import matplotlib as mpl +from matplotlib.colors import to_rgb +import matplotlib.pyplot as plt +from matplotlib.cbook import normalize_kwargs + +from seaborn._core.typing import deprecated +from seaborn.external.version import Version +from seaborn.external.appdirs import user_cache_dir + +__all__ = ["desaturate", "saturate", "set_hls_values", "move_legend", + "despine", "get_dataset_names", "get_data_home", "load_dataset"] + +DATASET_SOURCE = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master" +DATASET_NAMES_URL = f"{DATASET_SOURCE}/dataset_names.txt" + + +def ci_to_errsize(cis, heights): + """Convert intervals to error arguments relative to plot heights. + + Parameters + ---------- + cis : 2 x n sequence + sequence of confidence interval limits + heights : n sequence + sequence of plot heights + + Returns + ------- + errsize : 2 x n array + sequence of error size relative to height values in correct + format as argument for plt.bar + + """ + cis = np.atleast_2d(cis).reshape(2, -1) + heights = np.atleast_1d(heights) + errsize = [] + for i, (low, high) in enumerate(np.transpose(cis)): + h = heights[i] + elow = h - low + ehigh = high - h + errsize.append([elow, ehigh]) + + errsize = np.asarray(errsize).T + return errsize + + +def _draw_figure(fig): + """Force draw of a matplotlib figure, accounting for back-compat.""" + # See https://github.com/matplotlib/matplotlib/issues/19197 for context + fig.canvas.draw() + if fig.stale: + try: + fig.draw(fig.canvas.get_renderer()) + except AttributeError: + pass + + +def _default_color(method, hue, color, kws, saturation=1): + """If needed, get a default color by using the matplotlib property cycle.""" + + if hue is not None: + # This warning is probably user-friendly, but it's currently triggered + # in a FacetGrid context and I don't want to mess with that logic right now + # if color is not None: + # msg = "`color` is ignored when `hue` is assigned." + # warnings.warn(msg) + return None + + kws = kws.copy() + kws.pop("label", None) + + if color is not None: + if saturation < 1: + color = desaturate(color, saturation) + return color + + elif method.__name__ == "plot": + + color = normalize_kwargs(kws, mpl.lines.Line2D).get("color") + scout, = method([], [], scalex=False, scaley=False, color=color) + color = scout.get_color() + scout.remove() + + elif method.__name__ == "scatter": + + # Matplotlib will raise if the size of x/y don't match s/c, + # and the latter might be in the kws dict + scout_size = max( + np.atleast_1d(kws.get(key, [])).shape[0] + for key in ["s", "c", "fc", "facecolor", "facecolors"] + ) + scout_x = scout_y = np.full(scout_size, np.nan) + + scout = method(scout_x, scout_y, **kws) + facecolors = scout.get_facecolors() + + if not len(facecolors): + # Handle bug in matplotlib <= 3.2 (I think) + # This will limit the ability to use non color= kwargs to specify + # a color in versions of matplotlib with the bug, but trying to + # work out what the user wanted by re-implementing the broken logic + # of inspecting the kwargs is probably too brittle. + single_color = False + else: + single_color = np.unique(facecolors, axis=0).shape[0] == 1 + + # Allow the user to specify an array of colors through various kwargs + if "c" not in kws and single_color: + color = to_rgb(facecolors[0]) + + scout.remove() + + elif method.__name__ == "bar": + + # bar() needs masked, not empty data, to generate a patch + scout, = method([np.nan], [np.nan], **kws) + color = to_rgb(scout.get_facecolor()) + scout.remove() + # Axes.bar adds both a patch and a container + method.__self__.containers.pop(-1) + + elif method.__name__ == "fill_between": + + kws = normalize_kwargs(kws, mpl.collections.PolyCollection) + scout = method([], [], **kws) + facecolor = scout.get_facecolor() + color = to_rgb(facecolor[0]) + scout.remove() + + if saturation < 1: + color = desaturate(color, saturation) + + return color + + +def desaturate(color, prop): + """Decrease the saturation channel of a color by some percent. + + Parameters + ---------- + color : matplotlib color + hex, rgb-tuple, or html color name + prop : float + saturation channel of color will be multiplied by this value + + Returns + ------- + new_color : rgb tuple + desaturated color code in RGB tuple representation + + """ + # Check inputs + if not 0 <= prop <= 1: + raise ValueError("prop must be between 0 and 1") + + # Get rgb tuple rep + rgb = to_rgb(color) + + # Short circuit to avoid floating point issues + if prop == 1: + return rgb + + # Convert to hls + h, l, s = colorsys.rgb_to_hls(*rgb) + + # Desaturate the saturation channel + s *= prop + + # Convert back to rgb + new_color = colorsys.hls_to_rgb(h, l, s) + + return new_color + + +def saturate(color): + """Return a fully saturated color with the same hue. + + Parameters + ---------- + color : matplotlib color + hex, rgb-tuple, or html color name + + Returns + ------- + new_color : rgb tuple + saturated color code in RGB tuple representation + + """ + return set_hls_values(color, s=1) + + +def set_hls_values(color, h=None, l=None, s=None): # noqa + """Independently manipulate the h, l, or s channels of a color. + + Parameters + ---------- + color : matplotlib color + hex, rgb-tuple, or html color name + h, l, s : floats between 0 and 1, or None + new values for each channel in hls space + + Returns + ------- + new_color : rgb tuple + new color code in RGB tuple representation + + """ + # Get an RGB tuple representation + rgb = to_rgb(color) + vals = list(colorsys.rgb_to_hls(*rgb)) + for i, val in enumerate([h, l, s]): + if val is not None: + vals[i] = val + + rgb = colorsys.hls_to_rgb(*vals) + return rgb + + +def axlabel(xlabel, ylabel, **kwargs): + """Grab current axis and label it. + + DEPRECATED: will be removed in a future version. + + """ + msg = "This function is deprecated and will be removed in a future version" + warnings.warn(msg, FutureWarning) + ax = plt.gca() + ax.set_xlabel(xlabel, **kwargs) + ax.set_ylabel(ylabel, **kwargs) + + +def remove_na(vector): + """Helper method for removing null values from data vectors. + + Parameters + ---------- + vector : vector object + Must implement boolean masking with [] subscript syntax. + + Returns + ------- + clean_clean : same type as ``vector`` + Vector of data with null values removed. May be a copy or a view. + + """ + return vector[pd.notnull(vector)] + + +def get_color_cycle(): + """Return the list of colors in the current matplotlib color cycle + + Parameters + ---------- + None + + Returns + ------- + colors : list + List of matplotlib colors in the current cycle, or dark gray if + the current color cycle is empty. + """ + cycler = mpl.rcParams['axes.prop_cycle'] + return cycler.by_key()['color'] if 'color' in cycler.keys else [".15"] + + +def despine(fig=None, ax=None, top=True, right=True, left=False, + bottom=False, offset=None, trim=False): + """Remove the top and right spines from plot(s). + + fig : matplotlib figure, optional + Figure to despine all axes of, defaults to the current figure. + ax : matplotlib axes, optional + Specific axes object to despine. Ignored if fig is provided. + top, right, left, bottom : boolean, optional + If True, remove that spine. + offset : int or dict, optional + Absolute distance, in points, spines should be moved away + from the axes (negative values move spines inward). A single value + applies to all spines; a dict can be used to set offset values per + side. + trim : bool, optional + If True, limit spines to the smallest and largest major tick + on each non-despined axis. + + Returns + ------- + None + + """ + # Get references to the axes we want + if fig is None and ax is None: + axes = plt.gcf().axes + elif fig is not None: + axes = fig.axes + elif ax is not None: + axes = [ax] + + for ax_i in axes: + for side in ["top", "right", "left", "bottom"]: + # Toggle the spine objects + is_visible = not locals()[side] + ax_i.spines[side].set_visible(is_visible) + if offset is not None and is_visible: + try: + val = offset.get(side, 0) + except AttributeError: + val = offset + ax_i.spines[side].set_position(('outward', val)) + + # Potentially move the ticks + if left and not right: + maj_on = any( + t.tick1line.get_visible() + for t in ax_i.yaxis.majorTicks + ) + min_on = any( + t.tick1line.get_visible() + for t in ax_i.yaxis.minorTicks + ) + ax_i.yaxis.set_ticks_position("right") + for t in ax_i.yaxis.majorTicks: + t.tick2line.set_visible(maj_on) + for t in ax_i.yaxis.minorTicks: + t.tick2line.set_visible(min_on) + + if bottom and not top: + maj_on = any( + t.tick1line.get_visible() + for t in ax_i.xaxis.majorTicks + ) + min_on = any( + t.tick1line.get_visible() + for t in ax_i.xaxis.minorTicks + ) + ax_i.xaxis.set_ticks_position("top") + for t in ax_i.xaxis.majorTicks: + t.tick2line.set_visible(maj_on) + for t in ax_i.xaxis.minorTicks: + t.tick2line.set_visible(min_on) + + if trim: + # clip off the parts of the spines that extend past major ticks + xticks = np.asarray(ax_i.get_xticks()) + if xticks.size: + firsttick = np.compress(xticks >= min(ax_i.get_xlim()), + xticks)[0] + lasttick = np.compress(xticks <= max(ax_i.get_xlim()), + xticks)[-1] + ax_i.spines['bottom'].set_bounds(firsttick, lasttick) + ax_i.spines['top'].set_bounds(firsttick, lasttick) + newticks = xticks.compress(xticks <= lasttick) + newticks = newticks.compress(newticks >= firsttick) + ax_i.set_xticks(newticks) + + yticks = np.asarray(ax_i.get_yticks()) + if yticks.size: + firsttick = np.compress(yticks >= min(ax_i.get_ylim()), + yticks)[0] + lasttick = np.compress(yticks <= max(ax_i.get_ylim()), + yticks)[-1] + ax_i.spines['left'].set_bounds(firsttick, lasttick) + ax_i.spines['right'].set_bounds(firsttick, lasttick) + newticks = yticks.compress(yticks <= lasttick) + newticks = newticks.compress(newticks >= firsttick) + ax_i.set_yticks(newticks) + + +def move_legend(obj, loc, **kwargs): + """ + Recreate a plot's legend at a new location. + + The name is a slight misnomer. Matplotlib legends do not expose public + control over their position parameters. So this function creates a new legend, + copying over the data from the original object, which is then removed. + + Parameters + ---------- + obj : the object with the plot + This argument can be either a seaborn or matplotlib object: + + - :class:`seaborn.FacetGrid` or :class:`seaborn.PairGrid` + - :class:`matplotlib.axes.Axes` or :class:`matplotlib.figure.Figure` + + loc : str or int + Location argument, as in :meth:`matplotlib.axes.Axes.legend`. + + kwargs + Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.legend`. + + Examples + -------- + + .. include:: ../docstrings/move_legend.rst + + """ + # This is a somewhat hackish solution that will hopefully be obviated by + # upstream improvements to matplotlib legends that make them easier to + # modify after creation. + + from seaborn.axisgrid import Grid # Avoid circular import + + # Locate the legend object and a method to recreate the legend + if isinstance(obj, Grid): + old_legend = obj.legend + legend_func = obj.figure.legend + elif isinstance(obj, mpl.axes.Axes): + old_legend = obj.legend_ + legend_func = obj.legend + elif isinstance(obj, mpl.figure.Figure): + if obj.legends: + old_legend = obj.legends[-1] + else: + old_legend = None + legend_func = obj.legend + else: + err = "`obj` must be a seaborn Grid or matplotlib Axes or Figure instance." + raise TypeError(err) + + if old_legend is None: + err = f"{obj} has no legend attached." + raise ValueError(err) + + # Extract the components of the legend we need to reuse + # Import here to avoid a circular import + from seaborn._compat import get_legend_handles + handles = get_legend_handles(old_legend) + labels = [t.get_text() for t in old_legend.get_texts()] + + # Handle the case where the user is trying to override the labels + if (new_labels := kwargs.pop("labels", None)) is not None: + if len(new_labels) != len(labels): + err = "Length of new labels does not match existing legend." + raise ValueError(err) + labels = new_labels + + # Extract legend properties that can be passed to the recreation method + # (Vexingly, these don't all round-trip) + legend_kws = inspect.signature(mpl.legend.Legend).parameters + props = {k: v for k, v in old_legend.properties().items() if k in legend_kws} + + # Delegate default bbox_to_anchor rules to matplotlib + props.pop("bbox_to_anchor") + + # Try to propagate the existing title and font properties; respect new ones too + title = props.pop("title") + if "title" in kwargs: + title.set_text(kwargs.pop("title")) + title_kwargs = {k: v for k, v in kwargs.items() if k.startswith("title_")} + for key, val in title_kwargs.items(): + title.set(**{key[6:]: val}) + kwargs.pop(key) + + # Try to respect the frame visibility + kwargs.setdefault("frameon", old_legend.legendPatch.get_visible()) + + # Remove the old legend and create the new one + props.update(kwargs) + old_legend.remove() + new_legend = legend_func(handles, labels, loc=loc, **props) + new_legend.set_title(title.get_text(), title.get_fontproperties()) + + # Let the Grid object continue to track the correct legend object + if isinstance(obj, Grid): + obj._legend = new_legend + + +def _kde_support(data, bw, gridsize, cut, clip): + """Establish support for a kernel density estimate.""" + support_min = max(data.min() - bw * cut, clip[0]) + support_max = min(data.max() + bw * cut, clip[1]) + support = np.linspace(support_min, support_max, gridsize) + + return support + + +def ci(a, which=95, axis=None): + """Return a percentile range from an array of values.""" + p = 50 - which / 2, 50 + which / 2 + return np.nanpercentile(a, p, axis) + + +def get_dataset_names(): + """Report available example datasets, useful for reporting issues. + + Requires an internet connection. + + """ + with urlopen(DATASET_NAMES_URL) as resp: + txt = resp.read() + + dataset_names = [name.strip() for name in txt.decode().split("\n")] + return list(filter(None, dataset_names)) + + +def get_data_home(data_home=None): + """Return a path to the cache directory for example datasets. + + This directory is used by :func:`load_dataset`. + + If the ``data_home`` argument is not provided, it will use a directory + specified by the `SEABORN_DATA` environment variable (if it exists) + or otherwise default to an OS-appropriate user cache location. + + """ + if data_home is None: + data_home = os.environ.get("SEABORN_DATA", user_cache_dir("seaborn")) + data_home = os.path.expanduser(data_home) + if not os.path.exists(data_home): + os.makedirs(data_home) + return data_home + + +def load_dataset(name, cache=True, data_home=None, **kws): + """Load an example dataset from the online repository (requires internet). + + This function provides quick access to a small number of example datasets + that are useful for documenting seaborn or generating reproducible examples + for bug reports. It is not necessary for normal usage. + + Note that some of the datasets have a small amount of preprocessing applied + to define a proper ordering for categorical variables. + + Use :func:`get_dataset_names` to see a list of available datasets. + + Parameters + ---------- + name : str + Name of the dataset (``{name}.csv`` on + https://github.com/mwaskom/seaborn-data). + cache : boolean, optional + If True, try to load from the local cache first, and save to the cache + if a download is required. + data_home : string, optional + The directory in which to cache data; see :func:`get_data_home`. + kws : keys and values, optional + Additional keyword arguments are passed to passed through to + :func:`pandas.read_csv`. + + Returns + ------- + df : :class:`pandas.DataFrame` + Tabular data, possibly with some preprocessing applied. + + """ + # A common beginner mistake is to assume that one's personal data needs + # to be passed through this function to be usable with seaborn. + # Let's provide a more helpful error than you would otherwise get. + if isinstance(name, pd.DataFrame): + err = ( + "This function accepts only strings (the name of an example dataset). " + "You passed a pandas DataFrame. If you have your own dataset, " + "it is not necessary to use this function before plotting." + ) + raise TypeError(err) + + url = f"{DATASET_SOURCE}/{name}.csv" + + if cache: + cache_path = os.path.join(get_data_home(data_home), os.path.basename(url)) + if not os.path.exists(cache_path): + if name not in get_dataset_names(): + raise ValueError(f"'{name}' is not one of the example datasets.") + urlretrieve(url, cache_path) + full_path = cache_path + else: + full_path = url + + df = pd.read_csv(full_path, **kws) + + if df.iloc[-1].isnull().all(): + df = df.iloc[:-1] + + # Set some columns as a categorical type with ordered levels + + if name == "tips": + df["day"] = pd.Categorical(df["day"], ["Thur", "Fri", "Sat", "Sun"]) + df["sex"] = pd.Categorical(df["sex"], ["Male", "Female"]) + df["time"] = pd.Categorical(df["time"], ["Lunch", "Dinner"]) + df["smoker"] = pd.Categorical(df["smoker"], ["Yes", "No"]) + + elif name == "flights": + months = df["month"].str[:3] + df["month"] = pd.Categorical(months, months.unique()) + + elif name == "exercise": + df["time"] = pd.Categorical(df["time"], ["1 min", "15 min", "30 min"]) + df["kind"] = pd.Categorical(df["kind"], ["rest", "walking", "running"]) + df["diet"] = pd.Categorical(df["diet"], ["no fat", "low fat"]) + + elif name == "titanic": + df["class"] = pd.Categorical(df["class"], ["First", "Second", "Third"]) + df["deck"] = pd.Categorical(df["deck"], list("ABCDEFG")) + + elif name == "penguins": + df["sex"] = df["sex"].str.title() + + elif name == "diamonds": + df["color"] = pd.Categorical( + df["color"], ["D", "E", "F", "G", "H", "I", "J"], + ) + df["clarity"] = pd.Categorical( + df["clarity"], ["IF", "VVS1", "VVS2", "VS1", "VS2", "SI1", "SI2", "I1"], + ) + df["cut"] = pd.Categorical( + df["cut"], ["Ideal", "Premium", "Very Good", "Good", "Fair"], + ) + + elif name == "taxis": + df["pickup"] = pd.to_datetime(df["pickup"]) + df["dropoff"] = pd.to_datetime(df["dropoff"]) + + elif name == "seaice": + df["Date"] = pd.to_datetime(df["Date"]) + + elif name == "dowjones": + df["Date"] = pd.to_datetime(df["Date"]) + + return df + + +def axis_ticklabels_overlap(labels): + """Return a boolean for whether the list of ticklabels have overlaps. + + Parameters + ---------- + labels : list of matplotlib ticklabels + + Returns + ------- + overlap : boolean + True if any of the labels overlap. + + """ + if not labels: + return False + try: + bboxes = [l.get_window_extent() for l in labels] + overlaps = [b.count_overlaps(bboxes) for b in bboxes] + return max(overlaps) > 1 + except RuntimeError: + # Issue on macos backend raises an error in the above code + return False + + +def axes_ticklabels_overlap(ax): + """Return booleans for whether the x and y ticklabels on an Axes overlap. + + Parameters + ---------- + ax : matplotlib Axes + + Returns + ------- + x_overlap, y_overlap : booleans + True when the labels on that axis overlap. + + """ + return (axis_ticklabels_overlap(ax.get_xticklabels()), + axis_ticklabels_overlap(ax.get_yticklabels())) + + +def locator_to_legend_entries(locator, limits, dtype): + """Return levels and formatted levels for brief numeric legends.""" + raw_levels = locator.tick_values(*limits).astype(dtype) + + # The locator can return ticks outside the limits, clip them here + raw_levels = [l for l in raw_levels if l >= limits[0] and l <= limits[1]] + + class dummy_axis: + def get_view_interval(self): + return limits + + if isinstance(locator, mpl.ticker.LogLocator): + formatter = mpl.ticker.LogFormatter() + else: + formatter = mpl.ticker.ScalarFormatter() + # Avoid having an offset/scientific notation which we don't currently + # have any way of representing in the legend + formatter.set_useOffset(False) + formatter.set_scientific(False) + formatter.axis = dummy_axis() + + formatted_levels = formatter.format_ticks(raw_levels) + + return raw_levels, formatted_levels + + +def relative_luminance(color): + """Calculate the relative luminance of a color according to W3C standards + + Parameters + ---------- + color : matplotlib color or sequence of matplotlib colors + Hex code, rgb-tuple, or html color name. + + Returns + ------- + luminance : float(s) between 0 and 1 + + """ + rgb = mpl.colors.colorConverter.to_rgba_array(color)[:, :3] + rgb = np.where(rgb <= .03928, rgb / 12.92, ((rgb + .055) / 1.055) ** 2.4) + lum = rgb.dot([.2126, .7152, .0722]) + try: + return lum.item() + except ValueError: + return lum + + +def to_utf8(obj): + """Return a string representing a Python object. + + Strings (i.e. type ``str``) are returned unchanged. + + Byte strings (i.e. type ``bytes``) are returned as UTF-8-decoded strings. + + For other objects, the method ``__str__()`` is called, and the result is + returned as a string. + + Parameters + ---------- + obj : object + Any Python object + + Returns + ------- + s : str + UTF-8-decoded string representation of ``obj`` + + """ + if isinstance(obj, str): + return obj + try: + return obj.decode(encoding="utf-8") + except AttributeError: # obj is not bytes-like + return str(obj) + + +def _check_argument(param, options, value, prefix=False): + """Raise if value for param is not in options.""" + if prefix and value is not None: + failure = not any(value.startswith(p) for p in options if isinstance(p, str)) + else: + failure = value not in options + if failure: + raise ValueError( + f"The value for `{param}` must be one of {options}, " + f"but {repr(value)} was passed." + ) + return value + + +def _assign_default_kwargs(kws, call_func, source_func): + """Assign default kwargs for call_func using values from source_func.""" + # This exists so that axes-level functions and figure-level functions can + # both call a Plotter method while having the default kwargs be defined in + # the signature of the axes-level function. + # An alternative would be to have a decorator on the method that sets its + # defaults based on those defined in the axes-level function. + # Then the figure-level function would not need to worry about defaults. + # I am not sure which is better. + needed = inspect.signature(call_func).parameters + defaults = inspect.signature(source_func).parameters + + for param in needed: + if param in defaults and param not in kws: + kws[param] = defaults[param].default + + return kws + + +def adjust_legend_subtitles(legend): + """ + Make invisible-handle "subtitles" entries look more like titles. + + Note: This function is not part of the public API and may be changed or removed. + + """ + # Legend title not in rcParams until 3.0 + font_size = plt.rcParams.get("legend.title_fontsize", None) + hpackers = legend.findobj(mpl.offsetbox.VPacker)[0].get_children() + for hpack in hpackers: + draw_area, text_area = hpack.get_children() + handles = draw_area.get_children() + if not all(artist.get_visible() for artist in handles): + draw_area.set_width(0) + for text in text_area.get_children(): + if font_size is not None: + text.set_size(font_size) + + +def _deprecate_ci(errorbar, ci): + """ + Warn on usage of ci= and convert to appropriate errorbar= arg. + + ci was deprecated when errorbar was added in 0.12. It should not be removed + completely for some time, but it can be moved out of function definitions + (and extracted from kwargs) after one cycle. + + """ + if ci is not deprecated and ci != "deprecated": + if ci is None: + errorbar = None + elif ci == "sd": + errorbar = "sd" + else: + errorbar = ("ci", ci) + msg = ( + "\n\nThe `ci` parameter is deprecated. " + f"Use `errorbar={repr(errorbar)}` for the same effect.\n" + ) + warnings.warn(msg, FutureWarning, stacklevel=3) + + return errorbar + + +def _get_transform_functions(ax, axis): + """Return the forward and inverse transforms for a given axis.""" + axis_obj = getattr(ax, f"{axis}axis") + transform = axis_obj.get_transform() + return transform.transform, transform.inverted().transform + + +@contextmanager +def _disable_autolayout(): + """Context manager for preventing rc-controlled auto-layout behavior.""" + # This is a workaround for an issue in matplotlib, for details see + # https://github.com/mwaskom/seaborn/issues/2914 + # The only affect of this rcParam is to set the default value for + # layout= in plt.figure, so we could just do that instead. + # But then we would need to own the complexity of the transition + # from tight_layout=True -> layout="tight". This seems easier, + # but can be removed when (if) that is simpler on the matplotlib side, + # or if the layout algorithms are improved to handle figure legends. + orig_val = mpl.rcParams["figure.autolayout"] + try: + mpl.rcParams["figure.autolayout"] = False + yield + finally: + mpl.rcParams["figure.autolayout"] = orig_val + + +def _version_predates(lib: ModuleType, version: str) -> bool: + """Helper function for checking version compatibility.""" + return Version(lib.__version__) < Version(version) + + +def _scatter_legend_artist(**kws): + + kws = normalize_kwargs(kws, mpl.collections.PathCollection) + + edgecolor = kws.pop("edgecolor", None) + rc = mpl.rcParams + line_kws = { + "linestyle": "", + "marker": kws.pop("marker", "o"), + "markersize": np.sqrt(kws.pop("s", rc["lines.markersize"] ** 2)), + "markerfacecolor": kws.pop("facecolor", kws.get("color")), + "markeredgewidth": kws.pop("linewidth", 0), + **kws, + } + + if edgecolor is not None: + if edgecolor == "face": + line_kws["markeredgecolor"] = line_kws["markerfacecolor"] + else: + line_kws["markeredgecolor"] = edgecolor + + return mpl.lines.Line2D([], [], **line_kws) + + +def _get_patch_legend_artist(fill): + + def legend_artist(**kws): + + color = kws.pop("color", None) + if color is not None: + if fill: + kws["facecolor"] = color + else: + kws["edgecolor"] = color + kws["facecolor"] = "none" + + return mpl.patches.Rectangle((0, 0), 0, 0, **kws) + + return legend_artist diff --git a/shared/package-files/73/730c6e1690aecd3d8ea4fadb3060c4e0d84cf786aa6d416586e46541e799d1c1/polygamma_native.h b/shared/package-files/73/730c6e1690aecd3d8ea4fadb3060c4e0d84cf786aa6d416586e46541e799d1c1/polygamma_native.h new file mode 100644 index 0000000000000000000000000000000000000000..e58f09a9924da56a1271ac7297079fa5b33a206e --- /dev/null +++ b/shared/package-files/73/730c6e1690aecd3d8ea4fadb3060c4e0d84cf786aa6d416586e46541e799d1c1/polygamma_native.h @@ -0,0 +1,24 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_polygamma_out : public at::meta::structured_polygamma { +void impl(int64_t n, const at::Tensor & self, const at::Tensor & out); +}; +TORCH_API at::Tensor & polygamma_(at::Tensor & self, int64_t n); +} // namespace native +} // namespace at diff --git a/shared/package-files/73/730ccdbbbbe55677d2d49e1d5e222b9831cbb5f4016be3c8a6c9e7f8e2a6887e/flash_attention.py b/shared/package-files/73/730ccdbbbbe55677d2d49e1d5e222b9831cbb5f4016be3c8a6c9e7f8e2a6887e/flash_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..d024ba7ab005f9566542768595aa632b1de1b8aa --- /dev/null +++ b/shared/package-files/73/730ccdbbbbe55677d2d49e1d5e222b9831cbb5f4016be3c8a6c9e7f8e2a6887e/flash_attention.py @@ -0,0 +1,456 @@ +""" +Fused Attention +=============== +This is a Triton implementation of the Flash Attention algorithm +(see: Dao et al., https://arxiv.org/pdf/2205.14135v2.pdf; Rabe and Staats https://arxiv.org/pdf/2112.05682v2.pdf) + +Sequence Parallel implementation inspired by HazyResearch +(see https://github.com/HazyResearch/flash-attention/blob/main/flash_attn/flash_attn_triton.py) +""" + +import torch + +from .. import cdiv, jit +from .. import language as tl + + +@jit +def _fwd_kernel(Q, K, V, sm_scale, # + L, # + Out, # + stride_qz, stride_qh, stride_qm, stride_qk, # + stride_kz, stride_kh, stride_kn, stride_kk, # + stride_vz, stride_vh, stride_vn, stride_vk, # + stride_oz, stride_oh, stride_om, stride_on, # + Z, H, N_CTX, # + Z_H_N_CTX, # + BLOCK_M: tl.constexpr, BLOCK_DMODEL: tl.constexpr, # + BLOCK_N: tl.constexpr, # + IS_CAUSAL: tl.constexpr # + ): + start_m = tl.program_id(0) + off_hz = tl.program_id(1) + qvk_offset = off_hz * stride_qh + vk_offset = qvk_offset // stride_qm + + K_block_ptr = tl.make_block_ptr( + base=K, + shape=(BLOCK_DMODEL, Z_H_N_CTX), + strides=(stride_kk, stride_kn), + offsets=(0, vk_offset), + block_shape=(BLOCK_DMODEL, BLOCK_N), + order=(0, 1), + ) + V_block_ptr = tl.make_block_ptr( + base=V, + shape=(Z_H_N_CTX, BLOCK_DMODEL), + strides=(stride_vn, stride_vk), + offsets=(vk_offset, 0), + block_shape=(BLOCK_N, BLOCK_DMODEL), + order=(1, 0), + ) + # initialize offsets + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + offs_n = tl.arange(0, BLOCK_N) + # initialize pointer to m and l + m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf") + l_i = tl.zeros([BLOCK_M], dtype=tl.float32) + acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32) + # credits to: Adam P. Goucher (https://github.com/apgoucher): + # scale sm_scale by 1/log_2(e) and use + # 2^x instead of exp in the loop because CSE and LICM + # don't work as expected with `exp` in the loop + qk_scale = sm_scale * 1.44269504 + # load q: it will stay in SRAM throughout + + offs_k = tl.arange(0, BLOCK_DMODEL) + Q_ptrs = Q + qvk_offset + offs_m[:, None] * stride_qm + offs_k[None, :] * stride_qk + q = tl.load(Q_ptrs) + + q = (q * qk_scale).to(K.dtype.element_ty) + lo = 0 + hi = (start_m + 1) * BLOCK_M if IS_CAUSAL else N_CTX + for start_n in range(lo, hi, BLOCK_N): + # -- load k, v -- + k = tl.load(K_block_ptr) + v = tl.load(V_block_ptr) + # -- compute qk --- + qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) + if IS_CAUSAL: + qk = tl.where(offs_m[:, None] >= (start_n + offs_n[None, :]), qk, float("-inf")) + qk += tl.dot(q, k, allow_tf32=True) + # -- compute scaling constant --- + m_i_new = tl.maximum(m_i, tl.max(qk, 1)) + alpha = tl.math.exp2(m_i - m_i_new) + p = tl.math.exp2(qk - m_i_new[:, None]) + # -- scale and update acc -- + acc *= alpha[:, None] + acc += tl.dot(p.to(V.dtype.element_ty), v, allow_tf32=True) + # -- update m_i and l_i -- + l_i = l_i * alpha + tl.sum(p, 1) + m_i = m_i_new + # update pointers + K_block_ptr = tl.advance(K_block_ptr, (0, BLOCK_N)) + V_block_ptr = tl.advance(V_block_ptr, (BLOCK_N, 0)) + # write back l and m + acc = acc / l_i[:, None] + l_ptrs = L + off_hz * N_CTX + offs_m + tl.store(l_ptrs, m_i + tl.math.log2(l_i)) + # write back O + O_block_ptr = tl.make_block_ptr( + base=Out, + shape=(Z_H_N_CTX, BLOCK_DMODEL), + strides=(stride_om, stride_on), + offsets=(vk_offset + start_m * BLOCK_M, 0), + block_shape=(BLOCK_M, BLOCK_DMODEL), + order=(1, 0), + ) + # O_ptrs = Out + qvk_offset + offs_m[:, None] * stride_qm + offs_k[None, :] * stride_qk + tl.store(O_block_ptr, acc.to(K.dtype.element_ty)) + + +@jit +def _bwd_preprocess( + Out, + DO, + Delta, + BLOCK_M: tl.constexpr, + D_HEAD: tl.constexpr, +): + off_m = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M) + off_n = tl.arange(0, D_HEAD) + # load + o = tl.load(Out + off_m[:, None] * D_HEAD + off_n[None, :]).to(tl.float32) + do = tl.load(DO + off_m[:, None] * D_HEAD + off_n[None, :]).to(tl.float32) + # compute + delta = tl.sum(o * do, axis=1) + # write-back + tl.store(Delta + off_m, delta) + + +@jit +def _bwd_kernel_one_col_block(Q, K, V, sm_scale, qk_scale, # + Out, DO, # + DQ, DK, DV, # + L, # + D, # + Q_block_ptr, K_block_ptr, V_block_ptr, # + DO_block_ptr, DQ_block_ptr, DK_block_ptr, DV_block_ptr, # + stride_dqa, stride_qz, stride_qh, stride_qm, stride_qk, # + stride_kz, stride_kh, stride_kn, stride_kk, # + stride_vz, stride_vh, stride_vn, stride_vk, # + Z, H, N_CTX, # + off_h, off_z, off_hz, start_n, num_block, # + BLOCK_M: tl.constexpr, BLOCK_DMODEL: tl.constexpr, # + BLOCK_N: tl.constexpr, # + SEQUENCE_PARALLEL: tl.constexpr, # + CAUSAL: tl.constexpr, # + MMA_V3: tl.constexpr # + ): + if CAUSAL: + lo = start_n * BLOCK_M + else: + lo = 0 + + Q_offset = (off_z * stride_qz + off_h * stride_qh) // stride_qm + DQ_offset = off_z * stride_qz + off_h * stride_qh + K_offset = (off_z * stride_kz + off_h * stride_kh) // stride_kn + V_offset = (off_z * stride_vz + off_h * stride_vh) // stride_vn + if SEQUENCE_PARALLEL: + DQ_offset += stride_dqa.to(tl.int64) * start_n + DQ_offset = DQ_offset // stride_qm + + Q_block_ptr = tl.advance(Q_block_ptr, (lo + Q_offset, 0)) + K_block_ptr = tl.advance(K_block_ptr, (start_n * BLOCK_M + K_offset, 0)) + V_block_ptr = tl.advance(V_block_ptr, (start_n * BLOCK_M + V_offset, 0)) + DO_block_ptr = tl.advance(DO_block_ptr, (lo + Q_offset, 0)) + DQ_block_ptr = tl.advance(DQ_block_ptr, (lo + DQ_offset, 0)) + DK_block_ptr = tl.advance(DK_block_ptr, (start_n * BLOCK_M + K_offset, 0)) + DV_block_ptr = tl.advance(DV_block_ptr, (start_n * BLOCK_M + V_offset, 0)) + + # initialize row/col offsets + offs_n = start_n * BLOCK_M + tl.arange(0, BLOCK_M) + offs_m = tl.arange(0, BLOCK_N) + # pointer to row-wise quantities in value-like data + D_ptrs = D + off_hz * N_CTX + l_ptrs = L + off_hz * N_CTX + # initialize dv amd dk + dv = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32) + dk = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32) + # k and v stay in SRAM throughout + k = tl.load(K_block_ptr) + v = tl.load(V_block_ptr) + # loop over rows + for start_m in range(lo, num_block * BLOCK_M, BLOCK_M): + offs_m_curr = start_m + offs_m + # load q, k, v, do on-chip + q = tl.load(Q_block_ptr) + # recompute p = softmax(qk, dim=-1).T + # NOTE: `do` is pre-divided by `l`; no normalization here + if CAUSAL: + qk = tl.where(offs_m_curr[:, None] >= (offs_n[None, :]), float(0.0), float("-inf")) + else: + qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) + qk += tl.dot(q, tl.trans(k)) + qk *= qk_scale + l_i = tl.load(l_ptrs + offs_m_curr) + p = tl.math.exp2(qk - l_i[:, None]) + # compute dv + do = tl.load(DO_block_ptr) + dv += tl.dot(tl.trans(p.to(Q.dtype.element_ty)), do, allow_tf32=True) + # compute dp = dot(v, do) + Di = tl.load(D_ptrs + offs_m_curr) + # dp = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) - Di[:, None] + dp = tl.dot(do, tl.trans(v), allow_tf32=True) + # compute ds = p * (dp - delta[:, None]) + ds = (p * (dp - Di[:, None]) * sm_scale).to(Q.dtype.element_ty) + # compute dk = dot(ds.T, q) + dk += tl.dot(tl.trans(ds), q, allow_tf32=True) + # compute dq + if not SEQUENCE_PARALLEL: + dq = tl.load(DQ_block_ptr) + dq += tl.dot(ds, k, allow_tf32=True) + tl.store(DQ_block_ptr, dq.to(Q.dtype.element_ty)) + elif SEQUENCE_PARALLEL: + if MMA_V3: + dq = tl.dot(ds, k, allow_tf32=True) + else: + # not work with mma v3, becuase M % 64 != 0 + dq = tl.trans(tl.dot(tl.trans(k), tl.trans(ds), allow_tf32=True)) + tl.store(DQ_block_ptr, dq.to(Q.dtype.element_ty)) + + # increment pointers + DQ_block_ptr = tl.advance(DQ_block_ptr, (BLOCK_M, 0)) + Q_block_ptr = tl.advance(Q_block_ptr, (BLOCK_M, 0)) + DO_block_ptr = tl.advance(DO_block_ptr, (BLOCK_M, 0)) + # write-back + tl.store(DV_block_ptr, dv.to(V.dtype.element_ty)) + tl.store(DK_block_ptr, dk.to(K.dtype.element_ty)) + + +@jit +def _bwd_kernel(Q, K, V, sm_scale, # + Out, DO, # + DQ, DK, DV, # + L, # + D, # + stride_dqa, stride_qz, stride_qh, stride_qm, stride_qk, # + stride_kz, stride_kh, stride_kn, stride_kk, # + stride_vz, stride_vh, stride_vn, stride_vk, # + Z, H, N_CTX, # + Z_H_N_CTX, # + SQ_Z_H_N_CTX, # + BLOCK_M: tl.constexpr, BLOCK_DMODEL: tl.constexpr, # + BLOCK_N: tl.constexpr, # + SEQUENCE_PARALLEL: tl.constexpr, # + CAUSAL: tl.constexpr, # + MMA_V3: tl.constexpr # + ): + qk_scale = sm_scale * 1.44269504 + off_hz = tl.program_id(0) + off_z = off_hz // H + off_h = off_hz % H + + Q_block_ptr = tl.make_block_ptr( + base=Q, + shape=(Z_H_N_CTX, BLOCK_DMODEL), + strides=(stride_qm, stride_qk), + offsets=(0, 0), + block_shape=(BLOCK_M, BLOCK_DMODEL), + order=(1, 0), + ) + K_block_ptr = tl.make_block_ptr( + base=K, + shape=(Z_H_N_CTX, BLOCK_DMODEL), + strides=(stride_kn, stride_kk), + offsets=(0, 0), + block_shape=(BLOCK_M, BLOCK_DMODEL), + order=(1, 0), + ) + V_block_ptr = tl.make_block_ptr( + base=V, + shape=(Z_H_N_CTX, BLOCK_DMODEL), + strides=(stride_vn, stride_vk), + offsets=(0, 0), + block_shape=(BLOCK_M, BLOCK_DMODEL), + order=(1, 0), + ) + DO_block_ptr = tl.make_block_ptr( + base=DO, + shape=(Z_H_N_CTX, BLOCK_DMODEL), + strides=(stride_qm, stride_qk), + offsets=(0, 0), + block_shape=(BLOCK_M, BLOCK_DMODEL), + order=(1, 0), + ) + if SEQUENCE_PARALLEL: + DQ_block_ptr = tl.make_block_ptr( + base=DQ, + shape=(SQ_Z_H_N_CTX, BLOCK_DMODEL), + strides=(stride_qm, stride_qk), + offsets=(0, 0), + block_shape=(BLOCK_M, BLOCK_DMODEL), + order=(1, 0), + ) + else: + DQ_block_ptr = tl.make_block_ptr( + base=DQ, + shape=(Z_H_N_CTX, BLOCK_DMODEL), + strides=(stride_qm, stride_qk), + offsets=(0, 0), + block_shape=(BLOCK_M, BLOCK_DMODEL), + order=(1, 0), + ) + + DK_block_ptr = tl.make_block_ptr( + base=DK, + shape=(Z_H_N_CTX, BLOCK_DMODEL), + strides=(stride_kn, stride_kk), + offsets=(0, 0), + block_shape=(BLOCK_M, BLOCK_DMODEL), + order=(1, 0), + ) + DV_block_ptr = tl.make_block_ptr( + base=DV, + shape=(Z_H_N_CTX, BLOCK_DMODEL), + strides=(stride_vn, stride_vk), + offsets=(0, 0), + block_shape=(BLOCK_M, BLOCK_DMODEL), + order=(1, 0), + ) + + num_block_n = tl.cdiv(N_CTX, BLOCK_N) + if not SEQUENCE_PARALLEL: + for start_n in range(0, num_block_n): + _bwd_kernel_one_col_block(Q, K, V, sm_scale, qk_scale, Out, DO, # + DQ, DK, DV, # + L, # + D, # + Q_block_ptr, K_block_ptr, V_block_ptr, # + DO_block_ptr, DQ_block_ptr, DK_block_ptr, DV_block_ptr, # + stride_dqa, stride_qz, stride_qh, stride_qm, stride_qk, # + stride_kz, stride_kh, stride_kn, stride_kk, # + stride_vz, stride_vh, stride_vn, stride_vk, # + Z, H, N_CTX, # + off_h, off_z, off_hz, start_n, num_block_n, # + BLOCK_M=BLOCK_M, BLOCK_DMODEL=BLOCK_DMODEL, # + BLOCK_N=BLOCK_N, # + SEQUENCE_PARALLEL=SEQUENCE_PARALLEL, # + CAUSAL=CAUSAL, # + MMA_V3=MMA_V3 # + ) + else: + start_n = tl.program_id(1) + _bwd_kernel_one_col_block(Q, K, V, sm_scale, qk_scale, Out, DO, # + DQ, DK, DV, # + L, # + D, # + Q_block_ptr, K_block_ptr, V_block_ptr, # + DO_block_ptr, DQ_block_ptr, DK_block_ptr, DV_block_ptr, # + stride_dqa, stride_qz, stride_qh, stride_qm, stride_qk, # + stride_kz, stride_kh, stride_kn, stride_kk, # + stride_vz, stride_vh, stride_vn, stride_vk, # + Z, H, N_CTX, # + off_h, off_z, off_hz, start_n, num_block_n, # + BLOCK_M=BLOCK_M, BLOCK_DMODEL=BLOCK_DMODEL, # + BLOCK_N=BLOCK_N, # + SEQUENCE_PARALLEL=SEQUENCE_PARALLEL, # + CAUSAL=CAUSAL, # + MMA_V3=MMA_V3 # + ) + + +class _attention(torch.autograd.Function): + + @staticmethod + def forward(ctx, q, k, v, causal, sm_scale, sequence_parallel=False): + # only support for Ampere now + capability = torch.cuda.get_device_capability() + if capability[0] < 8: + raise RuntimeError("Flash attention currently only supported for compute capability >= 80") + BLOCK_M = 128 + BLOCK_N = 64 + # shape constraints + Lq, Lk, Lv = q.shape[-1], k.shape[-1], v.shape[-1] + assert Lq == Lk and Lk == Lv + assert Lk in {16, 32, 64, 128} + o = torch.empty_like(q) + grid = (cdiv(q.shape[2], BLOCK_M), q.shape[0] * q.shape[1], 1) + L = torch.empty((q.shape[0] * q.shape[1], q.shape[2]), device=q.device, dtype=torch.float32) + num_warps = 4 if Lk <= 64 else 8 + _fwd_kernel[grid]( + q, k, v, sm_scale, # + L, # + o, # + q.stride(0), q.stride(1), q.stride(2), q.stride(3), # + k.stride(0), k.stride(1), k.stride(2), k.stride(3), # + v.stride(0), v.stride(1), v.stride(2), v.stride(3), # + o.stride(0), o.stride(1), o.stride(2), o.stride(3), # + q.shape[0], q.shape[1], q.shape[2], # + q.shape[0] * q.shape[1] * q.shape[2], # + BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N, BLOCK_DMODEL=Lk, # + IS_CAUSAL=causal, # + num_warps=num_warps, # + num_stages=4 # + ) + + ctx.save_for_backward(q, k, v, o, L) + ctx.grid = grid + ctx.sm_scale = sm_scale + ctx.BLOCK_DMODEL = Lk + ctx.causal = causal + ctx.sequence_parallel = sequence_parallel + return o + + @staticmethod + def backward(ctx, do): + capability = torch.cuda.get_device_capability() + MMA_V3 = capability[0] >= 9 + BLOCK = 128 + q, k, v, o, L = ctx.saved_tensors + sequence_parallel = ctx.sequence_parallel + seq_len_kv = k.shape[2] + do = do.contiguous() + if sequence_parallel: + replicas = cdiv(seq_len_kv, BLOCK) + new_dq_shape = (replicas, ) + q.shape + dq = torch.zeros(new_dq_shape, device=q.device, dtype=q.dtype) + else: + dq = torch.zeros_like(q, dtype=q.dtype) + dk = torch.empty_like(k) + dv = torch.empty_like(v) + delta = torch.empty_like(L) + _bwd_preprocess[(cdiv(q.shape[2], BLOCK) * ctx.grid[1], )]( + o, + do, + delta, + BLOCK_M=BLOCK, + D_HEAD=ctx.BLOCK_DMODEL, + ) + _bwd_kernel[(ctx.grid[1], cdiv(seq_len_kv, BLOCK) if sequence_parallel else 1)]( + q, k, v, ctx.sm_scale, # + o, do, # + dq, dk, dv, # + L, # + delta, # + o.numel(), q.stride(0), q.stride(1), q.stride(2), q.stride(3), # + k.stride(0), k.stride(1), k.stride(2), k.stride(3), # + v.stride(0), v.stride(1), v.stride(2), v.stride(3), # + q.shape[0], q.shape[1], q.shape[2], # + q.shape[0] * q.shape[1] * q.shape[2], # + cdiv(seq_len_kv, BLOCK) * q.shape[0] * q.shape[1] * q.shape[2], # + BLOCK_M=BLOCK, BLOCK_N=BLOCK, # + BLOCK_DMODEL=ctx.BLOCK_DMODEL, # + SEQUENCE_PARALLEL=sequence_parallel, # + CAUSAL=ctx.causal, # + MMA_V3=MMA_V3, # + num_warps=8, # + num_stages=1 # + ) + + if len(dq.shape) == 5: + dq = dq.sum(dim=0) + return dq, dk, dv, None, None, None + + +attention = _attention.apply diff --git a/shared/package-files/73/730e88dc1c62d11dbf0c3db2d560fe0074d847fb9f02d37dced0ad0c6ca94273/test_reductions.py b/shared/package-files/73/730e88dc1c62d11dbf0c3db2d560fe0074d847fb9f02d37dced0ad0c6ca94273/test_reductions.py new file mode 100644 index 0000000000000000000000000000000000000000..991dbf41c808794f9a53a3f3351a9b6e79a7c6fd --- /dev/null +++ b/shared/package-files/73/730e88dc1c62d11dbf0c3db2d560fe0074d847fb9f02d37dced0ad0c6ca94273/test_reductions.py @@ -0,0 +1,218 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import Timedelta +import pandas._testing as tm +from pandas.core import nanops +from pandas.core.arrays import TimedeltaArray + + +class TestReductions: + @pytest.mark.parametrize("name", ["std", "min", "max", "median", "mean"]) + @pytest.mark.parametrize("skipna", [True, False]) + def test_reductions_empty(self, name, skipna): + tdi = pd.TimedeltaIndex([]) + arr = tdi.array + + result = getattr(tdi, name)(skipna=skipna) + assert result is pd.NaT + + result = getattr(arr, name)(skipna=skipna) + assert result is pd.NaT + + @pytest.mark.parametrize("skipna", [True, False]) + def test_sum_empty(self, skipna): + tdi = pd.TimedeltaIndex([]) + arr = tdi.array + + result = tdi.sum(skipna=skipna) + assert isinstance(result, Timedelta) + assert result == Timedelta(0) + + result = arr.sum(skipna=skipna) + assert isinstance(result, Timedelta) + assert result == Timedelta(0) + + def test_min_max(self, unit): + dtype = f"m8[{unit}]" + arr = TimedeltaArray._from_sequence( + ["3h", "3h", "NaT", "2h", "5h", "4h"], dtype=dtype + ) + + result = arr.min() + expected = Timedelta("2h") + assert result == expected + + result = arr.max() + expected = Timedelta("5h") + assert result == expected + + result = arr.min(skipna=False) + assert result is pd.NaT + + result = arr.max(skipna=False) + assert result is pd.NaT + + def test_sum(self): + tdi = pd.TimedeltaIndex(["3h", "3h", "NaT", "2h", "5h", "4h"]) + arr = tdi.array + + result = arr.sum(skipna=True) + expected = Timedelta(hours=17) + assert isinstance(result, Timedelta) + assert result == expected + + result = tdi.sum(skipna=True) + assert isinstance(result, Timedelta) + assert result == expected + + result = arr.sum(skipna=False) + assert result is pd.NaT + + result = tdi.sum(skipna=False) + assert result is pd.NaT + + result = arr.sum(min_count=9) + assert result is pd.NaT + + result = tdi.sum(min_count=9) + assert result is pd.NaT + + result = arr.sum(min_count=1) + assert isinstance(result, Timedelta) + assert result == expected + + result = tdi.sum(min_count=1) + assert isinstance(result, Timedelta) + assert result == expected + + def test_npsum(self): + # GH#25282, GH#25335 np.sum should return a Timedelta, not timedelta64 + tdi = pd.TimedeltaIndex(["3h", "3h", "2h", "5h", "4h"]) + arr = tdi.array + + result = np.sum(tdi) + expected = Timedelta(hours=17) + assert isinstance(result, Timedelta) + assert result == expected + + result = np.sum(arr) + assert isinstance(result, Timedelta) + assert result == expected + + def test_sum_2d_skipna_false(self): + arr = np.arange(8).astype(np.int64).view("m8[s]").astype("m8[ns]").reshape(4, 2) + arr[-1, -1] = "Nat" + + tda = TimedeltaArray._from_sequence(arr) + + result = tda.sum(skipna=False) + assert result is pd.NaT + + result = tda.sum(axis=0, skipna=False) + expected = pd.TimedeltaIndex([Timedelta(seconds=12), pd.NaT])._values + tm.assert_timedelta_array_equal(result, expected) + + result = tda.sum(axis=1, skipna=False) + expected = pd.TimedeltaIndex( + [ + Timedelta(seconds=1), + Timedelta(seconds=5), + Timedelta(seconds=9), + pd.NaT, + ] + )._values + tm.assert_timedelta_array_equal(result, expected) + + # Adding a Timestamp makes this a test for DatetimeArray.std + @pytest.mark.parametrize( + "add", + [ + Timedelta(0), + pd.Timestamp("2021-01-01"), + pd.Timestamp("2021-01-01", tz="UTC"), + pd.Timestamp("2021-01-01", tz="Asia/Tokyo"), + ], + ) + def test_std(self, add): + tdi = pd.TimedeltaIndex(["0h", "4h", "NaT", "4h", "0h", "2h"]) + add + arr = tdi.array + + result = arr.std(skipna=True) + expected = Timedelta(hours=2) + assert isinstance(result, Timedelta) + assert result == expected + + result = tdi.std(skipna=True) + assert isinstance(result, Timedelta) + assert result == expected + + if getattr(arr, "tz", None) is None: + result = nanops.nanstd(np.asarray(arr), skipna=True) + assert isinstance(result, np.timedelta64) + assert result == expected + + result = arr.std(skipna=False) + assert result is pd.NaT + + result = tdi.std(skipna=False) + assert result is pd.NaT + + if getattr(arr, "tz", None) is None: + result = nanops.nanstd(np.asarray(arr), skipna=False) + assert isinstance(result, np.timedelta64) + assert np.isnat(result) + + def test_median(self): + tdi = pd.TimedeltaIndex(["0h", "3h", "NaT", "5h06m", "0h", "2h"]) + arr = tdi.array + + result = arr.median(skipna=True) + expected = Timedelta(hours=2) + assert isinstance(result, Timedelta) + assert result == expected + + result = tdi.median(skipna=True) + assert isinstance(result, Timedelta) + assert result == expected + + result = arr.median(skipna=False) + assert result is pd.NaT + + result = tdi.median(skipna=False) + assert result is pd.NaT + + def test_mean(self): + tdi = pd.TimedeltaIndex(["0h", "3h", "NaT", "5h06m", "0h", "2h"]) + arr = tdi._data + + # manually verified result + expected = Timedelta(arr.dropna()._ndarray.mean()) + + result = arr.mean() + assert result == expected + result = arr.mean(skipna=False) + assert result is pd.NaT + + result = arr.dropna().mean(skipna=False) + assert result == expected + + result = arr.mean(axis=0) + assert result == expected + + def test_mean_2d(self): + tdi = pd.timedelta_range("14 days", periods=6) + tda = tdi._data.reshape(3, 2) + + result = tda.mean(axis=0) + expected = tda[1] + tm.assert_timedelta_array_equal(result, expected) + + result = tda.mean(axis=1) + expected = tda[:, 0] + Timedelta(hours=12) + tm.assert_timedelta_array_equal(result, expected) + + result = tda.mean(axis=None) + expected = tdi.mean() + assert result == expected diff --git a/shared/package-files/73/7312237e8e5d201d920b4130f057cfdf1b0be9baafaa246826e6d93204fcc206/iso8859_13.py b/shared/package-files/73/7312237e8e5d201d920b4130f057cfdf1b0be9baafaa246826e6d93204fcc206/iso8859_13.py new file mode 100644 index 0000000000000000000000000000000000000000..6f8eab2b821481b9ab33398a4219e54b5fe1445b --- /dev/null +++ b/shared/package-files/73/7312237e8e5d201d920b4130f057cfdf1b0be9baafaa246826e6d93204fcc206/iso8859_13.py @@ -0,0 +1,307 @@ +""" Python Character Mapping Codec iso8859_13 generated from 'MAPPINGS/ISO8859/8859-13.TXT' with gencodec.py. + +"""#" + +import codecs + +### Codec APIs + +class Codec(codecs.Codec): + + def encode(self,input,errors='strict'): + return codecs.charmap_encode(input,errors,encoding_table) + + def decode(self,input,errors='strict'): + return codecs.charmap_decode(input,errors,decoding_table) + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input, final=False): + return codecs.charmap_encode(input,self.errors,encoding_table)[0] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input, final=False): + return codecs.charmap_decode(input,self.errors,decoding_table)[0] + +class StreamWriter(Codec,codecs.StreamWriter): + pass + +class StreamReader(Codec,codecs.StreamReader): + pass + +### encodings module API + +def getregentry(): + return codecs.CodecInfo( + name='iso8859-13', + encode=Codec().encode, + decode=Codec().decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamreader=StreamReader, + streamwriter=StreamWriter, + ) + + +### Decoding Table + +decoding_table = ( + '\x00' # 0x00 -> NULL + '\x01' # 0x01 -> START OF HEADING + '\x02' # 0x02 -> START OF TEXT + '\x03' # 0x03 -> END OF TEXT + '\x04' # 0x04 -> END OF TRANSMISSION + '\x05' # 0x05 -> ENQUIRY + '\x06' # 0x06 -> ACKNOWLEDGE + '\x07' # 0x07 -> BELL + '\x08' # 0x08 -> BACKSPACE + '\t' # 0x09 -> HORIZONTAL TABULATION + '\n' # 0x0A -> LINE FEED + '\x0b' # 0x0B -> VERTICAL TABULATION + '\x0c' # 0x0C -> FORM FEED + '\r' # 0x0D -> CARRIAGE RETURN + '\x0e' # 0x0E -> SHIFT OUT + '\x0f' # 0x0F -> SHIFT IN + '\x10' # 0x10 -> DATA LINK ESCAPE + '\x11' # 0x11 -> DEVICE CONTROL ONE + '\x12' # 0x12 -> DEVICE CONTROL TWO + '\x13' # 0x13 -> DEVICE CONTROL THREE + '\x14' # 0x14 -> DEVICE CONTROL FOUR + '\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE + '\x16' # 0x16 -> SYNCHRONOUS IDLE + '\x17' # 0x17 -> END OF TRANSMISSION BLOCK + '\x18' # 0x18 -> CANCEL + '\x19' # 0x19 -> END OF MEDIUM + '\x1a' # 0x1A -> SUBSTITUTE + '\x1b' # 0x1B -> ESCAPE + '\x1c' # 0x1C -> FILE SEPARATOR + '\x1d' # 0x1D -> GROUP SEPARATOR + '\x1e' # 0x1E -> RECORD SEPARATOR + '\x1f' # 0x1F -> UNIT SEPARATOR + ' ' # 0x20 -> SPACE + '!' # 0x21 -> EXCLAMATION MARK + '"' # 0x22 -> QUOTATION MARK + '#' # 0x23 -> NUMBER SIGN + '$' # 0x24 -> DOLLAR SIGN + '%' # 0x25 -> PERCENT SIGN + '&' # 0x26 -> AMPERSAND + "'" # 0x27 -> APOSTROPHE + '(' # 0x28 -> LEFT PARENTHESIS + ')' # 0x29 -> RIGHT PARENTHESIS + '*' # 0x2A -> ASTERISK + '+' # 0x2B -> PLUS SIGN + ',' # 0x2C -> COMMA + '-' # 0x2D -> HYPHEN-MINUS + '.' # 0x2E -> FULL STOP + '/' # 0x2F -> SOLIDUS + '0' # 0x30 -> DIGIT ZERO + '1' # 0x31 -> DIGIT ONE + '2' # 0x32 -> DIGIT TWO + '3' # 0x33 -> DIGIT THREE + '4' # 0x34 -> DIGIT FOUR + '5' # 0x35 -> DIGIT FIVE + '6' # 0x36 -> DIGIT SIX + '7' # 0x37 -> DIGIT SEVEN + '8' # 0x38 -> DIGIT EIGHT + '9' # 0x39 -> DIGIT NINE + ':' # 0x3A -> COLON + ';' # 0x3B -> SEMICOLON + '<' # 0x3C -> LESS-THAN SIGN + '=' # 0x3D -> EQUALS SIGN + '>' # 0x3E -> GREATER-THAN SIGN + '?' # 0x3F -> QUESTION MARK + '@' # 0x40 -> COMMERCIAL AT + 'A' # 0x41 -> LATIN CAPITAL LETTER A + 'B' # 0x42 -> LATIN CAPITAL LETTER B + 'C' # 0x43 -> LATIN CAPITAL LETTER C + 'D' # 0x44 -> LATIN CAPITAL LETTER D + 'E' # 0x45 -> LATIN CAPITAL LETTER E + 'F' # 0x46 -> LATIN CAPITAL LETTER F + 'G' # 0x47 -> LATIN CAPITAL LETTER G + 'H' # 0x48 -> LATIN CAPITAL LETTER H + 'I' # 0x49 -> LATIN CAPITAL LETTER I + 'J' # 0x4A -> LATIN CAPITAL LETTER J + 'K' # 0x4B -> LATIN CAPITAL LETTER K + 'L' # 0x4C -> LATIN CAPITAL LETTER L + 'M' # 0x4D -> LATIN CAPITAL LETTER M + 'N' # 0x4E -> LATIN CAPITAL LETTER N + 'O' # 0x4F -> LATIN CAPITAL LETTER O + 'P' # 0x50 -> LATIN CAPITAL LETTER P + 'Q' # 0x51 -> LATIN CAPITAL LETTER Q + 'R' # 0x52 -> LATIN CAPITAL LETTER R + 'S' # 0x53 -> LATIN CAPITAL LETTER S + 'T' # 0x54 -> LATIN CAPITAL LETTER T + 'U' # 0x55 -> LATIN CAPITAL LETTER U + 'V' # 0x56 -> LATIN CAPITAL LETTER V + 'W' # 0x57 -> LATIN CAPITAL LETTER W + 'X' # 0x58 -> LATIN CAPITAL LETTER X + 'Y' # 0x59 -> LATIN CAPITAL LETTER Y + 'Z' # 0x5A -> LATIN CAPITAL LETTER Z + '[' # 0x5B -> LEFT SQUARE BRACKET + '\\' # 0x5C -> REVERSE SOLIDUS + ']' # 0x5D -> RIGHT SQUARE BRACKET + '^' # 0x5E -> CIRCUMFLEX ACCENT + '_' # 0x5F -> LOW LINE + '`' # 0x60 -> GRAVE ACCENT + 'a' # 0x61 -> LATIN SMALL LETTER A + 'b' # 0x62 -> LATIN SMALL LETTER B + 'c' # 0x63 -> LATIN SMALL LETTER C + 'd' # 0x64 -> LATIN SMALL LETTER D + 'e' # 0x65 -> LATIN SMALL LETTER E + 'f' # 0x66 -> LATIN SMALL LETTER F + 'g' # 0x67 -> LATIN SMALL LETTER G + 'h' # 0x68 -> LATIN SMALL LETTER H + 'i' # 0x69 -> LATIN SMALL LETTER I + 'j' # 0x6A -> LATIN SMALL LETTER J + 'k' # 0x6B -> LATIN SMALL LETTER K + 'l' # 0x6C -> LATIN SMALL LETTER L + 'm' # 0x6D -> LATIN SMALL LETTER M + 'n' # 0x6E -> LATIN SMALL LETTER N + 'o' # 0x6F -> LATIN SMALL LETTER O + 'p' # 0x70 -> LATIN SMALL LETTER P + 'q' # 0x71 -> LATIN SMALL LETTER Q + 'r' # 0x72 -> LATIN SMALL LETTER R + 's' # 0x73 -> LATIN SMALL LETTER S + 't' # 0x74 -> LATIN SMALL LETTER T + 'u' # 0x75 -> LATIN SMALL LETTER U + 'v' # 0x76 -> LATIN SMALL LETTER V + 'w' # 0x77 -> LATIN SMALL LETTER W + 'x' # 0x78 -> LATIN SMALL LETTER X + 'y' # 0x79 -> LATIN SMALL LETTER Y + 'z' # 0x7A -> LATIN SMALL LETTER Z + '{' # 0x7B -> LEFT CURLY BRACKET + '|' # 0x7C -> VERTICAL LINE + '}' # 0x7D -> RIGHT CURLY BRACKET + '~' # 0x7E -> TILDE + '\x7f' # 0x7F -> DELETE + '\x80' # 0x80 -> + '\x81' # 0x81 -> + '\x82' # 0x82 -> + '\x83' # 0x83 -> + '\x84' # 0x84 -> + '\x85' # 0x85 -> + '\x86' # 0x86 -> + '\x87' # 0x87 -> + '\x88' # 0x88 -> + '\x89' # 0x89 -> + '\x8a' # 0x8A -> + '\x8b' # 0x8B -> + '\x8c' # 0x8C -> + '\x8d' # 0x8D -> + '\x8e' # 0x8E -> + '\x8f' # 0x8F -> + '\x90' # 0x90 -> + '\x91' # 0x91 -> + '\x92' # 0x92 -> + '\x93' # 0x93 -> + '\x94' # 0x94 -> + '\x95' # 0x95 -> + '\x96' # 0x96 -> + '\x97' # 0x97 -> + '\x98' # 0x98 -> + '\x99' # 0x99 -> + '\x9a' # 0x9A -> + '\x9b' # 0x9B -> + '\x9c' # 0x9C -> + '\x9d' # 0x9D -> + '\x9e' # 0x9E -> + '\x9f' # 0x9F -> + '\xa0' # 0xA0 -> NO-BREAK SPACE + '\u201d' # 0xA1 -> RIGHT DOUBLE QUOTATION MARK + '\xa2' # 0xA2 -> CENT SIGN + '\xa3' # 0xA3 -> POUND SIGN + '\xa4' # 0xA4 -> CURRENCY SIGN + '\u201e' # 0xA5 -> DOUBLE LOW-9 QUOTATION MARK + '\xa6' # 0xA6 -> BROKEN BAR + '\xa7' # 0xA7 -> SECTION SIGN + '\xd8' # 0xA8 -> LATIN CAPITAL LETTER O WITH STROKE + '\xa9' # 0xA9 -> COPYRIGHT SIGN + '\u0156' # 0xAA -> LATIN CAPITAL LETTER R WITH CEDILLA + '\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + '\xac' # 0xAC -> NOT SIGN + '\xad' # 0xAD -> SOFT HYPHEN + '\xae' # 0xAE -> REGISTERED SIGN + '\xc6' # 0xAF -> LATIN CAPITAL LETTER AE + '\xb0' # 0xB0 -> DEGREE SIGN + '\xb1' # 0xB1 -> PLUS-MINUS SIGN + '\xb2' # 0xB2 -> SUPERSCRIPT TWO + '\xb3' # 0xB3 -> SUPERSCRIPT THREE + '\u201c' # 0xB4 -> LEFT DOUBLE QUOTATION MARK + '\xb5' # 0xB5 -> MICRO SIGN + '\xb6' # 0xB6 -> PILCROW SIGN + '\xb7' # 0xB7 -> MIDDLE DOT + '\xf8' # 0xB8 -> LATIN SMALL LETTER O WITH STROKE + '\xb9' # 0xB9 -> SUPERSCRIPT ONE + '\u0157' # 0xBA -> LATIN SMALL LETTER R WITH CEDILLA + '\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + '\xbc' # 0xBC -> VULGAR FRACTION ONE QUARTER + '\xbd' # 0xBD -> VULGAR FRACTION ONE HALF + '\xbe' # 0xBE -> VULGAR FRACTION THREE QUARTERS + '\xe6' # 0xBF -> LATIN SMALL LETTER AE + '\u0104' # 0xC0 -> LATIN CAPITAL LETTER A WITH OGONEK + '\u012e' # 0xC1 -> LATIN CAPITAL LETTER I WITH OGONEK + '\u0100' # 0xC2 -> LATIN CAPITAL LETTER A WITH MACRON + '\u0106' # 0xC3 -> LATIN CAPITAL LETTER C WITH ACUTE + '\xc4' # 0xC4 -> LATIN CAPITAL LETTER A WITH DIAERESIS + '\xc5' # 0xC5 -> LATIN CAPITAL LETTER A WITH RING ABOVE + '\u0118' # 0xC6 -> LATIN CAPITAL LETTER E WITH OGONEK + '\u0112' # 0xC7 -> LATIN CAPITAL LETTER E WITH MACRON + '\u010c' # 0xC8 -> LATIN CAPITAL LETTER C WITH CARON + '\xc9' # 0xC9 -> LATIN CAPITAL LETTER E WITH ACUTE + '\u0179' # 0xCA -> LATIN CAPITAL LETTER Z WITH ACUTE + '\u0116' # 0xCB -> LATIN CAPITAL LETTER E WITH DOT ABOVE + '\u0122' # 0xCC -> LATIN CAPITAL LETTER G WITH CEDILLA + '\u0136' # 0xCD -> LATIN CAPITAL LETTER K WITH CEDILLA + '\u012a' # 0xCE -> LATIN CAPITAL LETTER I WITH MACRON + '\u013b' # 0xCF -> LATIN CAPITAL LETTER L WITH CEDILLA + '\u0160' # 0xD0 -> LATIN CAPITAL LETTER S WITH CARON + '\u0143' # 0xD1 -> LATIN CAPITAL LETTER N WITH ACUTE + '\u0145' # 0xD2 -> LATIN CAPITAL LETTER N WITH CEDILLA + '\xd3' # 0xD3 -> LATIN CAPITAL LETTER O WITH ACUTE + '\u014c' # 0xD4 -> LATIN CAPITAL LETTER O WITH MACRON + '\xd5' # 0xD5 -> LATIN CAPITAL LETTER O WITH TILDE + '\xd6' # 0xD6 -> LATIN CAPITAL LETTER O WITH DIAERESIS + '\xd7' # 0xD7 -> MULTIPLICATION SIGN + '\u0172' # 0xD8 -> LATIN CAPITAL LETTER U WITH OGONEK + '\u0141' # 0xD9 -> LATIN CAPITAL LETTER L WITH STROKE + '\u015a' # 0xDA -> LATIN CAPITAL LETTER S WITH ACUTE + '\u016a' # 0xDB -> LATIN CAPITAL LETTER U WITH MACRON + '\xdc' # 0xDC -> LATIN CAPITAL LETTER U WITH DIAERESIS + '\u017b' # 0xDD -> LATIN CAPITAL LETTER Z WITH DOT ABOVE + '\u017d' # 0xDE -> LATIN CAPITAL LETTER Z WITH CARON + '\xdf' # 0xDF -> LATIN SMALL LETTER SHARP S (German) + '\u0105' # 0xE0 -> LATIN SMALL LETTER A WITH OGONEK + '\u012f' # 0xE1 -> LATIN SMALL LETTER I WITH OGONEK + '\u0101' # 0xE2 -> LATIN SMALL LETTER A WITH MACRON + '\u0107' # 0xE3 -> LATIN SMALL LETTER C WITH ACUTE + '\xe4' # 0xE4 -> LATIN SMALL LETTER A WITH DIAERESIS + '\xe5' # 0xE5 -> LATIN SMALL LETTER A WITH RING ABOVE + '\u0119' # 0xE6 -> LATIN SMALL LETTER E WITH OGONEK + '\u0113' # 0xE7 -> LATIN SMALL LETTER E WITH MACRON + '\u010d' # 0xE8 -> LATIN SMALL LETTER C WITH CARON + '\xe9' # 0xE9 -> LATIN SMALL LETTER E WITH ACUTE + '\u017a' # 0xEA -> LATIN SMALL LETTER Z WITH ACUTE + '\u0117' # 0xEB -> LATIN SMALL LETTER E WITH DOT ABOVE + '\u0123' # 0xEC -> LATIN SMALL LETTER G WITH CEDILLA + '\u0137' # 0xED -> LATIN SMALL LETTER K WITH CEDILLA + '\u012b' # 0xEE -> LATIN SMALL LETTER I WITH MACRON + '\u013c' # 0xEF -> LATIN SMALL LETTER L WITH CEDILLA + '\u0161' # 0xF0 -> LATIN SMALL LETTER S WITH CARON + '\u0144' # 0xF1 -> LATIN SMALL LETTER N WITH ACUTE + '\u0146' # 0xF2 -> LATIN SMALL LETTER N WITH CEDILLA + '\xf3' # 0xF3 -> LATIN SMALL LETTER O WITH ACUTE + '\u014d' # 0xF4 -> LATIN SMALL LETTER O WITH MACRON + '\xf5' # 0xF5 -> LATIN SMALL LETTER O WITH TILDE + '\xf6' # 0xF6 -> LATIN SMALL LETTER O WITH DIAERESIS + '\xf7' # 0xF7 -> DIVISION SIGN + '\u0173' # 0xF8 -> LATIN SMALL LETTER U WITH OGONEK + '\u0142' # 0xF9 -> LATIN SMALL LETTER L WITH STROKE + '\u015b' # 0xFA -> LATIN SMALL LETTER S WITH ACUTE + '\u016b' # 0xFB -> LATIN SMALL LETTER U WITH MACRON + '\xfc' # 0xFC -> LATIN SMALL LETTER U WITH DIAERESIS + '\u017c' # 0xFD -> LATIN SMALL LETTER Z WITH DOT ABOVE + '\u017e' # 0xFE -> LATIN SMALL LETTER Z WITH CARON + '\u2019' # 0xFF -> RIGHT SINGLE QUOTATION MARK +) + +### Encoding table +encoding_table=codecs.charmap_build(decoding_table) diff --git a/shared/package-files/73/73139cdf7e3235223d31ace11bd1d3f2cd4e0978e40d6af7663d899f21d2dd9e/test_adjoint.py b/shared/package-files/73/73139cdf7e3235223d31ace11bd1d3f2cd4e0978e40d6af7663d899f21d2dd9e/test_adjoint.py new file mode 100644 index 0000000000000000000000000000000000000000..7106b5740b1dc7c32f2c6f5ecb9d286b5e1dd222 --- /dev/null +++ b/shared/package-files/73/73139cdf7e3235223d31ace11bd1d3f2cd4e0978e40d6af7663d899f21d2dd9e/test_adjoint.py @@ -0,0 +1,34 @@ +from sympy.core import symbols, S +from sympy.functions import adjoint, conjugate, transpose +from sympy.matrices.expressions import MatrixSymbol, Adjoint, trace, Transpose +from sympy.matrices import eye, Matrix + +n, m, l, k, p = symbols('n m l k p', integer=True) +A = MatrixSymbol('A', n, m) +B = MatrixSymbol('B', m, l) +C = MatrixSymbol('C', n, n) + + +def test_adjoint(): + Sq = MatrixSymbol('Sq', n, n) + + assert Adjoint(A).shape == (m, n) + assert Adjoint(A*B).shape == (l, n) + assert adjoint(Adjoint(A)) == A + assert isinstance(Adjoint(Adjoint(A)), Adjoint) + + assert conjugate(Adjoint(A)) == Transpose(A) + assert transpose(Adjoint(A)) == Adjoint(Transpose(A)) + + assert Adjoint(eye(3)).doit() == eye(3) + + assert Adjoint(S(5)).doit() == S(5) + + assert Adjoint(Matrix([[1, 2], [3, 4]])).doit() == Matrix([[1, 3], [2, 4]]) + + assert adjoint(trace(Sq)) == conjugate(trace(Sq)) + assert trace(adjoint(Sq)) == conjugate(trace(Sq)) + + assert Adjoint(Sq)[0, 1] == conjugate(Sq[1, 0]) + + assert Adjoint(A*B).doit() == Adjoint(B) * Adjoint(A) diff --git a/shared/package-files/73/73167ba0aabddb88fcfe00e894bfc80d5e0248ddaf5ca93a4bb0c8c365a54dcf/basic.py b/shared/package-files/73/73167ba0aabddb88fcfe00e894bfc80d5e0248ddaf5ca93a4bb0c8c365a54dcf/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..8837dacbae1a571717b0b8e0a3bb883dfb80d96f --- /dev/null +++ b/shared/package-files/73/73167ba0aabddb88fcfe00e894bfc80d5e0248ddaf5ca93a4bb0c8c365a54dcf/basic.py @@ -0,0 +1,665 @@ +""" + pygments.lexers.basic + ~~~~~~~~~~~~~~~~~~~~~ + + Lexers for BASIC like languages (other than VB.net). + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import re + +from pygments.lexer import RegexLexer, bygroups, default, words, include +from pygments.token import Comment, Error, Keyword, Name, Number, \ + Punctuation, Operator, String, Text, Whitespace +from pygments.lexers import _vbscript_builtins + + +__all__ = ['BlitzBasicLexer', 'BlitzMaxLexer', 'MonkeyLexer', 'CbmBasicV2Lexer', + 'QBasicLexer', 'VBScriptLexer', 'BBCBasicLexer'] + + +class BlitzMaxLexer(RegexLexer): + """ + For BlitzMax source code. + + .. versionadded:: 1.4 + """ + + name = 'BlitzMax' + url = 'http://blitzbasic.com' + aliases = ['blitzmax', 'bmax'] + filenames = ['*.bmx'] + mimetypes = ['text/x-bmx'] + + bmax_vopwords = r'\b(Shl|Shr|Sar|Mod)\b' + bmax_sktypes = r'@{1,2}|[!#$%]' + bmax_lktypes = r'\b(Int|Byte|Short|Float|Double|Long)\b' + bmax_name = r'[a-z_]\w*' + bmax_var = (r'(%s)(?:(?:([ \t]*)(%s)|([ \t]*:[ \t]*\b(?:Shl|Shr|Sar|Mod)\b)' + r'|([ \t]*)(:)([ \t]*)(?:%s|(%s)))(?:([ \t]*)(Ptr))?)') % \ + (bmax_name, bmax_sktypes, bmax_lktypes, bmax_name) + bmax_func = bmax_var + r'?((?:[ \t]|\.\.\n)*)([(])' + + flags = re.MULTILINE | re.IGNORECASE + tokens = { + 'root': [ + # Text + (r'\s+', Whitespace), + (r'(\.\.)(\n)', bygroups(Text, Whitespace)), # Line continuation + # Comments + (r"'.*?\n", Comment.Single), + (r'([ \t]*)\bRem\n(\n|.)*?\s*\bEnd([ \t]*)Rem', Comment.Multiline), + # Data types + ('"', String.Double, 'string'), + # Numbers + (r'[0-9]+\.[0-9]*(?!\.)', Number.Float), + (r'\.[0-9]*(?!\.)', Number.Float), + (r'[0-9]+', Number.Integer), + (r'\$[0-9a-f]+', Number.Hex), + (r'\%[10]+', Number.Bin), + # Other + (r'(?:(?:(:)?([ \t]*)(:?%s|([+\-*/&|~]))|Or|And|Not|[=<>^]))' % + (bmax_vopwords), Operator), + (r'[(),.:\[\]]', Punctuation), + (r'(?:#[\w \t]*)', Name.Label), + (r'(?:\?[\w \t]*)', Comment.Preproc), + # Identifiers + (r'\b(New)\b([ \t]?)([(]?)(%s)' % (bmax_name), + bygroups(Keyword.Reserved, Whitespace, Punctuation, Name.Class)), + (r'\b(Import|Framework|Module)([ \t]+)(%s\.%s)' % + (bmax_name, bmax_name), + bygroups(Keyword.Reserved, Whitespace, Keyword.Namespace)), + (bmax_func, bygroups(Name.Function, Whitespace, Keyword.Type, + Operator, Whitespace, Punctuation, Whitespace, + Keyword.Type, Name.Class, Whitespace, + Keyword.Type, Whitespace, Punctuation)), + (bmax_var, bygroups(Name.Variable, Whitespace, Keyword.Type, Operator, + Whitespace, Punctuation, Whitespace, Keyword.Type, + Name.Class, Whitespace, Keyword.Type)), + (r'\b(Type|Extends)([ \t]+)(%s)' % (bmax_name), + bygroups(Keyword.Reserved, Whitespace, Name.Class)), + # Keywords + (r'\b(Ptr)\b', Keyword.Type), + (r'\b(Pi|True|False|Null|Self|Super)\b', Keyword.Constant), + (r'\b(Local|Global|Const|Field)\b', Keyword.Declaration), + (words(( + 'TNullMethodException', 'TNullFunctionException', + 'TNullObjectException', 'TArrayBoundsException', + 'TRuntimeException'), prefix=r'\b', suffix=r'\b'), Name.Exception), + (words(( + 'Strict', 'SuperStrict', 'Module', 'ModuleInfo', + 'End', 'Return', 'Continue', 'Exit', 'Public', 'Private', + 'Var', 'VarPtr', 'Chr', 'Len', 'Asc', 'SizeOf', 'Sgn', 'Abs', 'Min', 'Max', + 'New', 'Release', 'Delete', 'Incbin', 'IncbinPtr', 'IncbinLen', + 'Framework', 'Include', 'Import', 'Extern', 'EndExtern', + 'Function', 'EndFunction', 'Type', 'EndType', 'Extends', 'Method', 'EndMethod', + 'Abstract', 'Final', 'If', 'Then', 'Else', 'ElseIf', 'EndIf', + 'For', 'To', 'Next', 'Step', 'EachIn', 'While', 'Wend', 'EndWhile', + 'Repeat', 'Until', 'Forever', 'Select', 'Case', 'Default', 'EndSelect', + 'Try', 'Catch', 'EndTry', 'Throw', 'Assert', 'Goto', 'DefData', 'ReadData', + 'RestoreData'), prefix=r'\b', suffix=r'\b'), + Keyword.Reserved), + # Final resolve (for variable names and such) + (r'(%s)' % (bmax_name), Name.Variable), + ], + 'string': [ + (r'""', String.Double), + (r'"C?', String.Double, '#pop'), + (r'[^"]+', String.Double), + ], + } + + +class BlitzBasicLexer(RegexLexer): + """ + For BlitzBasic source code. + + .. versionadded:: 2.0 + """ + + name = 'BlitzBasic' + url = 'http://blitzbasic.com' + aliases = ['blitzbasic', 'b3d', 'bplus'] + filenames = ['*.bb', '*.decls'] + mimetypes = ['text/x-bb'] + + bb_sktypes = r'@{1,2}|[#$%]' + bb_name = r'[a-z]\w*' + bb_var = (r'(%s)(?:([ \t]*)(%s)|([ \t]*)([.])([ \t]*)(?:(%s)))?') % \ + (bb_name, bb_sktypes, bb_name) + + flags = re.MULTILINE | re.IGNORECASE + tokens = { + 'root': [ + # Text + (r'\s+', Whitespace), + # Comments + (r";.*?\n", Comment.Single), + # Data types + ('"', String.Double, 'string'), + # Numbers + (r'[0-9]+\.[0-9]*(?!\.)', Number.Float), + (r'\.[0-9]+(?!\.)', Number.Float), + (r'[0-9]+', Number.Integer), + (r'\$[0-9a-f]+', Number.Hex), + (r'\%[10]+', Number.Bin), + # Other + (words(('Shl', 'Shr', 'Sar', 'Mod', 'Or', 'And', 'Not', + 'Abs', 'Sgn', 'Handle', 'Int', 'Float', 'Str', + 'First', 'Last', 'Before', 'After'), + prefix=r'\b', suffix=r'\b'), + Operator), + (r'([+\-*/~=<>^])', Operator), + (r'[(),:\[\]\\]', Punctuation), + (r'\.([ \t]*)(%s)' % bb_name, Name.Label), + # Identifiers + (r'\b(New)\b([ \t]+)(%s)' % (bb_name), + bygroups(Keyword.Reserved, Whitespace, Name.Class)), + (r'\b(Gosub|Goto)\b([ \t]+)(%s)' % (bb_name), + bygroups(Keyword.Reserved, Whitespace, Name.Label)), + (r'\b(Object)\b([ \t]*)([.])([ \t]*)(%s)\b' % (bb_name), + bygroups(Operator, Whitespace, Punctuation, Whitespace, Name.Class)), + (r'\b%s\b([ \t]*)(\()' % bb_var, + bygroups(Name.Function, Whitespace, Keyword.Type, Whitespace, Punctuation, + Whitespace, Name.Class, Whitespace, Punctuation)), + (r'\b(Function)\b([ \t]+)%s' % bb_var, + bygroups(Keyword.Reserved, Whitespace, Name.Function, Whitespace, Keyword.Type, + Whitespace, Punctuation, Whitespace, Name.Class)), + (r'\b(Type)([ \t]+)(%s)' % (bb_name), + bygroups(Keyword.Reserved, Whitespace, Name.Class)), + # Keywords + (r'\b(Pi|True|False|Null)\b', Keyword.Constant), + (r'\b(Local|Global|Const|Field|Dim)\b', Keyword.Declaration), + (words(( + 'End', 'Return', 'Exit', 'Chr', 'Len', 'Asc', 'New', 'Delete', 'Insert', + 'Include', 'Function', 'Type', 'If', 'Then', 'Else', 'ElseIf', 'EndIf', + 'For', 'To', 'Next', 'Step', 'Each', 'While', 'Wend', + 'Repeat', 'Until', 'Forever', 'Select', 'Case', 'Default', + 'Goto', 'Gosub', 'Data', 'Read', 'Restore'), prefix=r'\b', suffix=r'\b'), + Keyword.Reserved), + # Final resolve (for variable names and such) + # (r'(%s)' % (bb_name), Name.Variable), + (bb_var, bygroups(Name.Variable, Whitespace, Keyword.Type, + Whitespace, Punctuation, Whitespace, Name.Class)), + ], + 'string': [ + (r'""', String.Double), + (r'"C?', String.Double, '#pop'), + (r'[^"\n]+', String.Double), + ], + } + + +class MonkeyLexer(RegexLexer): + """ + For + `Monkey `_ + source code. + + .. versionadded:: 1.6 + """ + + name = 'Monkey' + aliases = ['monkey'] + filenames = ['*.monkey'] + mimetypes = ['text/x-monkey'] + + name_variable = r'[a-z_]\w*' + name_function = r'[A-Z]\w*' + name_constant = r'[A-Z_][A-Z0-9_]*' + name_class = r'[A-Z]\w*' + name_module = r'[a-z0-9_]*' + + keyword_type = r'(?:Int|Float|String|Bool|Object|Array|Void)' + # ? == Bool // % == Int // # == Float // $ == String + keyword_type_special = r'[?%#$]' + + flags = re.MULTILINE + + tokens = { + 'root': [ + # Text + (r'\s+', Whitespace), + # Comments + (r"'.*", Comment), + (r'(?i)^#rem\b', Comment.Multiline, 'comment'), + # preprocessor directives + (r'(?i)^(?:#If|#ElseIf|#Else|#EndIf|#End|#Print|#Error)\b', Comment.Preproc), + # preprocessor variable (any line starting with '#' that is not a directive) + (r'^#', Comment.Preproc, 'variables'), + # String + ('"', String.Double, 'string'), + # Numbers + (r'[0-9]+\.[0-9]*(?!\.)', Number.Float), + (r'\.[0-9]+(?!\.)', Number.Float), + (r'[0-9]+', Number.Integer), + (r'\$[0-9a-fA-Z]+', Number.Hex), + (r'\%[10]+', Number.Bin), + # Native data types + (r'\b%s\b' % keyword_type, Keyword.Type), + # Exception handling + (r'(?i)\b(?:Try|Catch|Throw)\b', Keyword.Reserved), + (r'Throwable', Name.Exception), + # Builtins + (r'(?i)\b(?:Null|True|False)\b', Name.Builtin), + (r'(?i)\b(?:Self|Super)\b', Name.Builtin.Pseudo), + (r'\b(?:HOST|LANG|TARGET|CONFIG)\b', Name.Constant), + # Keywords + (r'(?i)^(Import)(\s+)(.*)(\n)', + bygroups(Keyword.Namespace, Whitespace, Name.Namespace, Whitespace)), + (r'(?i)^Strict\b.*\n', Keyword.Reserved), + (r'(?i)(Const|Local|Global|Field)(\s+)', + bygroups(Keyword.Declaration, Whitespace), 'variables'), + (r'(?i)(New|Class|Interface|Extends|Implements)(\s+)', + bygroups(Keyword.Reserved, Whitespace), 'classname'), + (r'(?i)(Function|Method)(\s+)', + bygroups(Keyword.Reserved, Whitespace), 'funcname'), + (r'(?i)(?:End|Return|Public|Private|Extern|Property|' + r'Final|Abstract)\b', Keyword.Reserved), + # Flow Control stuff + (r'(?i)(?:If|Then|Else|ElseIf|EndIf|' + r'Select|Case|Default|' + r'While|Wend|' + r'Repeat|Until|Forever|' + r'For|To|Until|Step|EachIn|Next|' + r'Exit|Continue)(?=\s)', Keyword.Reserved), + # not used yet + (r'(?i)\b(?:Module|Inline)\b', Keyword.Reserved), + # Array + (r'[\[\]]', Punctuation), + # Other + (r'<=|>=|<>|\*=|/=|\+=|-=|&=|~=|\|=|[-&*/^+=<>|~]', Operator), + (r'(?i)(?:Not|Mod|Shl|Shr|And|Or)', Operator.Word), + (r'[(){}!#,.:]', Punctuation), + # catch the rest + (r'%s\b' % name_constant, Name.Constant), + (r'%s\b' % name_function, Name.Function), + (r'%s\b' % name_variable, Name.Variable), + ], + 'funcname': [ + (r'(?i)%s\b' % name_function, Name.Function), + (r':', Punctuation, 'classname'), + (r'\s+', Whitespace), + (r'\(', Punctuation, 'variables'), + (r'\)', Punctuation, '#pop') + ], + 'classname': [ + (r'%s\.' % name_module, Name.Namespace), + (r'%s\b' % keyword_type, Keyword.Type), + (r'%s\b' % name_class, Name.Class), + # array (of given size) + (r'(\[)(\s*)(\d*)(\s*)(\])', + bygroups(Punctuation, Whitespace, Number.Integer, Whitespace, Punctuation)), + # generics + (r'\s+(?!<)', Whitespace, '#pop'), + (r'<', Punctuation, '#push'), + (r'>', Punctuation, '#pop'), + (r'\n', Whitespace, '#pop'), + default('#pop') + ], + 'variables': [ + (r'%s\b' % name_constant, Name.Constant), + (r'%s\b' % name_variable, Name.Variable), + (r'%s' % keyword_type_special, Keyword.Type), + (r'\s+', Whitespace), + (r':', Punctuation, 'classname'), + (r',', Punctuation, '#push'), + default('#pop') + ], + 'string': [ + (r'[^"~]+', String.Double), + (r'~q|~n|~r|~t|~z|~~', String.Escape), + (r'"', String.Double, '#pop'), + ], + 'comment': [ + (r'(?i)^#rem.*?', Comment.Multiline, "#push"), + (r'(?i)^#end.*?', Comment.Multiline, "#pop"), + (r'\n', Comment.Multiline), + (r'.+', Comment.Multiline), + ], + } + + +class CbmBasicV2Lexer(RegexLexer): + """ + For CBM BASIC V2 sources. + + .. versionadded:: 1.6 + """ + name = 'CBM BASIC V2' + aliases = ['cbmbas'] + filenames = ['*.bas'] + + flags = re.IGNORECASE + + tokens = { + 'root': [ + (r'rem.*\n', Comment.Single), + (r'\s+', Whitespace), + (r'new|run|end|for|to|next|step|go(to|sub)?|on|return|stop|cont' + r'|if|then|input#?|read|wait|load|save|verify|poke|sys|print#?' + r'|list|clr|cmd|open|close|get#?', Keyword.Reserved), + (r'data|restore|dim|let|def|fn', Keyword.Declaration), + (r'tab|spc|sgn|int|abs|usr|fre|pos|sqr|rnd|log|exp|cos|sin|tan|atn' + r'|peek|len|val|asc|(str|chr|left|right|mid)\$', Name.Builtin), + (r'[-+*/^<>=]', Operator), + (r'not|and|or', Operator.Word), + (r'"[^"\n]*.', String), + (r'\d+|[-+]?\d*\.\d*(e[-+]?\d+)?', Number.Float), + (r'[(),:;]', Punctuation), + (r'\w+[$%]?', Name), + ] + } + + def analyse_text(text): + # if it starts with a line number, it shouldn't be a "modern" Basic + # like VB.net + if re.match(r'^\d+', text): + return 0.2 + + +class QBasicLexer(RegexLexer): + """ + For + `QBasic `_ + source code. + + .. versionadded:: 2.0 + """ + + name = 'QBasic' + aliases = ['qbasic', 'basic'] + filenames = ['*.BAS', '*.bas'] + mimetypes = ['text/basic'] + + declarations = ('DATA', 'LET') + + functions = ( + 'ABS', 'ASC', 'ATN', 'CDBL', 'CHR$', 'CINT', 'CLNG', + 'COMMAND$', 'COS', 'CSNG', 'CSRLIN', 'CVD', 'CVDMBF', 'CVI', + 'CVL', 'CVS', 'CVSMBF', 'DATE$', 'ENVIRON$', 'EOF', 'ERDEV', + 'ERDEV$', 'ERL', 'ERR', 'EXP', 'FILEATTR', 'FIX', 'FRE', + 'FREEFILE', 'HEX$', 'INKEY$', 'INP', 'INPUT$', 'INSTR', 'INT', + 'IOCTL$', 'LBOUND', 'LCASE$', 'LEFT$', 'LEN', 'LOC', 'LOF', + 'LOG', 'LPOS', 'LTRIM$', 'MID$', 'MKD$', 'MKDMBF$', 'MKI$', + 'MKL$', 'MKS$', 'MKSMBF$', 'OCT$', 'PEEK', 'PEN', 'PLAY', + 'PMAP', 'POINT', 'POS', 'RIGHT$', 'RND', 'RTRIM$', 'SADD', + 'SCREEN', 'SEEK', 'SETMEM', 'SGN', 'SIN', 'SPACE$', 'SPC', + 'SQR', 'STICK', 'STR$', 'STRIG', 'STRING$', 'TAB', 'TAN', + 'TIME$', 'TIMER', 'UBOUND', 'UCASE$', 'VAL', 'VARPTR', + 'VARPTR$', 'VARSEG' + ) + + metacommands = ('$DYNAMIC', '$INCLUDE', '$STATIC') + + operators = ('AND', 'EQV', 'IMP', 'NOT', 'OR', 'XOR') + + statements = ( + 'BEEP', 'BLOAD', 'BSAVE', 'CALL', 'CALL ABSOLUTE', + 'CALL INTERRUPT', 'CALLS', 'CHAIN', 'CHDIR', 'CIRCLE', 'CLEAR', + 'CLOSE', 'CLS', 'COLOR', 'COM', 'COMMON', 'CONST', 'DATA', + 'DATE$', 'DECLARE', 'DEF FN', 'DEF SEG', 'DEFDBL', 'DEFINT', + 'DEFLNG', 'DEFSNG', 'DEFSTR', 'DEF', 'DIM', 'DO', 'LOOP', + 'DRAW', 'END', 'ENVIRON', 'ERASE', 'ERROR', 'EXIT', 'FIELD', + 'FILES', 'FOR', 'NEXT', 'FUNCTION', 'GET', 'GOSUB', 'GOTO', + 'IF', 'THEN', 'INPUT', 'INPUT #', 'IOCTL', 'KEY', 'KEY', + 'KILL', 'LET', 'LINE', 'LINE INPUT', 'LINE INPUT #', 'LOCATE', + 'LOCK', 'UNLOCK', 'LPRINT', 'LSET', 'MID$', 'MKDIR', 'NAME', + 'ON COM', 'ON ERROR', 'ON KEY', 'ON PEN', 'ON PLAY', + 'ON STRIG', 'ON TIMER', 'ON UEVENT', 'ON', 'OPEN', 'OPEN COM', + 'OPTION BASE', 'OUT', 'PAINT', 'PALETTE', 'PCOPY', 'PEN', + 'PLAY', 'POKE', 'PRESET', 'PRINT', 'PRINT #', 'PRINT USING', + 'PSET', 'PUT', 'PUT', 'RANDOMIZE', 'READ', 'REDIM', 'REM', + 'RESET', 'RESTORE', 'RESUME', 'RETURN', 'RMDIR', 'RSET', 'RUN', + 'SCREEN', 'SEEK', 'SELECT CASE', 'SHARED', 'SHELL', 'SLEEP', + 'SOUND', 'STATIC', 'STOP', 'STRIG', 'SUB', 'SWAP', 'SYSTEM', + 'TIME$', 'TIMER', 'TROFF', 'TRON', 'TYPE', 'UEVENT', 'UNLOCK', + 'VIEW', 'WAIT', 'WHILE', 'WEND', 'WIDTH', 'WINDOW', 'WRITE' + ) + + keywords = ( + 'ACCESS', 'ALIAS', 'ANY', 'APPEND', 'AS', 'BASE', 'BINARY', + 'BYVAL', 'CASE', 'CDECL', 'DOUBLE', 'ELSE', 'ELSEIF', 'ENDIF', + 'INTEGER', 'IS', 'LIST', 'LOCAL', 'LONG', 'LOOP', 'MOD', + 'NEXT', 'OFF', 'ON', 'OUTPUT', 'RANDOM', 'SIGNAL', 'SINGLE', + 'STEP', 'STRING', 'THEN', 'TO', 'UNTIL', 'USING', 'WEND' + ) + + tokens = { + 'root': [ + (r'\n+', Text), + (r'\s+', Text.Whitespace), + (r'^(\s*)(\d*)(\s*)(REM .*)$', + bygroups(Text.Whitespace, Name.Label, Text.Whitespace, + Comment.Single)), + (r'^(\s*)(\d+)(\s*)', + bygroups(Text.Whitespace, Name.Label, Text.Whitespace)), + (r'(?=[\s]*)(\w+)(?=[\s]*=)', Name.Variable.Global), + (r'(?=[^"]*)\'.*$', Comment.Single), + (r'"[^\n"]*"', String.Double), + (r'(END)(\s+)(FUNCTION|IF|SELECT|SUB)', + bygroups(Keyword.Reserved, Text.Whitespace, Keyword.Reserved)), + (r'(DECLARE)(\s+)([A-Z]+)(\s+)(\S+)', + bygroups(Keyword.Declaration, Text.Whitespace, Name.Variable, + Text.Whitespace, Name)), + (r'(DIM)(\s+)(SHARED)(\s+)([^\s(]+)', + bygroups(Keyword.Declaration, Text.Whitespace, Name.Variable, + Text.Whitespace, Name.Variable.Global)), + (r'(DIM)(\s+)([^\s(]+)', + bygroups(Keyword.Declaration, Text.Whitespace, Name.Variable.Global)), + (r'^(\s*)([a-zA-Z_]+)(\s*)(\=)', + bygroups(Text.Whitespace, Name.Variable.Global, Text.Whitespace, + Operator)), + (r'(GOTO|GOSUB)(\s+)(\w+\:?)', + bygroups(Keyword.Reserved, Text.Whitespace, Name.Label)), + (r'(SUB)(\s+)(\w+\:?)', + bygroups(Keyword.Reserved, Text.Whitespace, Name.Label)), + include('declarations'), + include('functions'), + include('metacommands'), + include('operators'), + include('statements'), + include('keywords'), + (r'[a-zA-Z_]\w*[$@#&!]', Name.Variable.Global), + (r'[a-zA-Z_]\w*\:', Name.Label), + (r'\-?\d*\.\d+[@|#]?', Number.Float), + (r'\-?\d+[@|#]', Number.Float), + (r'\-?\d+#?', Number.Integer.Long), + (r'\-?\d+#?', Number.Integer), + (r'!=|==|:=|\.=|<<|>>|[-~+/\\*%=<>&^|?:!.]', Operator), + (r'[\[\]{}(),;]', Punctuation), + (r'[\w]+', Name.Variable.Global), + ], + # can't use regular \b because of X$() + # XXX: use words() here + 'declarations': [ + (r'\b(%s)(?=\(|\b)' % '|'.join(map(re.escape, declarations)), + Keyword.Declaration), + ], + 'functions': [ + (r'\b(%s)(?=\(|\b)' % '|'.join(map(re.escape, functions)), + Keyword.Reserved), + ], + 'metacommands': [ + (r'\b(%s)(?=\(|\b)' % '|'.join(map(re.escape, metacommands)), + Keyword.Constant), + ], + 'operators': [ + (r'\b(%s)(?=\(|\b)' % '|'.join(map(re.escape, operators)), Operator.Word), + ], + 'statements': [ + (r'\b(%s)\b' % '|'.join(map(re.escape, statements)), + Keyword.Reserved), + ], + 'keywords': [ + (r'\b(%s)\b' % '|'.join(keywords), Keyword), + ], + } + + def analyse_text(text): + if '$DYNAMIC' in text or '$STATIC' in text: + return 0.9 + + +class VBScriptLexer(RegexLexer): + """ + VBScript is scripting language that is modeled on Visual Basic. + + .. versionadded:: 2.4 + """ + name = 'VBScript' + aliases = ['vbscript'] + filenames = ['*.vbs', '*.VBS'] + flags = re.IGNORECASE + + tokens = { + 'root': [ + (r"'[^\n]*", Comment.Single), + (r'\s+', Whitespace), + ('"', String.Double, 'string'), + ('&h[0-9a-f]+', Number.Hex), + # Float variant 1, for example: 1., 1.e2, 1.2e3 + (r'[0-9]+\.[0-9]*(e[+-]?[0-9]+)?', Number.Float), + (r'\.[0-9]+(e[+-]?[0-9]+)?', Number.Float), # Float variant 2, for example: .1, .1e2 + (r'[0-9]+e[+-]?[0-9]+', Number.Float), # Float variant 3, for example: 123e45 + (r'[0-9]+', Number.Integer), + ('#.+#', String), # date or time value + (r'(dim)(\s+)([a-z_][a-z0-9_]*)', + bygroups(Keyword.Declaration, Whitespace, Name.Variable), 'dim_more'), + (r'(function|sub)(\s+)([a-z_][a-z0-9_]*)', + bygroups(Keyword.Declaration, Whitespace, Name.Function)), + (r'(class)(\s+)([a-z_][a-z0-9_]*)', + bygroups(Keyword.Declaration, Whitespace, Name.Class)), + (r'(const)(\s+)([a-z_][a-z0-9_]*)', + bygroups(Keyword.Declaration, Whitespace, Name.Constant)), + (r'(end)(\s+)(class|function|if|property|sub|with)', + bygroups(Keyword, Whitespace, Keyword)), + (r'(on)(\s+)(error)(\s+)(goto)(\s+)(0)', + bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword, Whitespace, Number.Integer)), + (r'(on)(\s+)(error)(\s+)(resume)(\s+)(next)', + bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword, Whitespace, Keyword)), + (r'(option)(\s+)(explicit)', bygroups(Keyword, Whitespace, Keyword)), + (r'(property)(\s+)(get|let|set)(\s+)([a-z_][a-z0-9_]*)', + bygroups(Keyword.Declaration, Whitespace, Keyword.Declaration, Whitespace, Name.Property)), + (r'rem\s.*[^\n]*', Comment.Single), + (words(_vbscript_builtins.KEYWORDS, suffix=r'\b'), Keyword), + (words(_vbscript_builtins.OPERATORS), Operator), + (words(_vbscript_builtins.OPERATOR_WORDS, suffix=r'\b'), Operator.Word), + (words(_vbscript_builtins.BUILTIN_CONSTANTS, suffix=r'\b'), Name.Constant), + (words(_vbscript_builtins.BUILTIN_FUNCTIONS, suffix=r'\b'), Name.Builtin), + (words(_vbscript_builtins.BUILTIN_VARIABLES, suffix=r'\b'), Name.Builtin), + (r'[a-z_][a-z0-9_]*', Name), + (r'\b_\n', Operator), + (words(r'(),.:'), Punctuation), + (r'.+(\n)?', Error) + ], + 'dim_more': [ + (r'(\s*)(,)(\s*)([a-z_][a-z0-9]*)', + bygroups(Whitespace, Punctuation, Whitespace, Name.Variable)), + default('#pop'), + ], + 'string': [ + (r'[^"\n]+', String.Double), + (r'\"\"', String.Double), + (r'"', String.Double, '#pop'), + (r'\n', Error, '#pop'), # Unterminated string + ], + } + + +class BBCBasicLexer(RegexLexer): + """ + BBC Basic was supplied on the BBC Micro, and later Acorn RISC OS. + It is also used by BBC Basic For Windows. + + .. versionadded:: 2.4 + """ + base_keywords = ['OTHERWISE', 'AND', 'DIV', 'EOR', 'MOD', 'OR', 'ERROR', + 'LINE', 'OFF', 'STEP', 'SPC', 'TAB', 'ELSE', 'THEN', + 'OPENIN', 'PTR', 'PAGE', 'TIME', 'LOMEM', 'HIMEM', 'ABS', + 'ACS', 'ADVAL', 'ASC', 'ASN', 'ATN', 'BGET', 'COS', 'COUNT', + 'DEG', 'ERL', 'ERR', 'EVAL', 'EXP', 'EXT', 'FALSE', 'FN', + 'GET', 'INKEY', 'INSTR', 'INT', 'LEN', 'LN', 'LOG', 'NOT', + 'OPENUP', 'OPENOUT', 'PI', 'POINT', 'POS', 'RAD', 'RND', + 'SGN', 'SIN', 'SQR', 'TAN', 'TO', 'TRUE', 'USR', 'VAL', + 'VPOS', 'CHR$', 'GET$', 'INKEY$', 'LEFT$', 'MID$', + 'RIGHT$', 'STR$', 'STRING$', 'EOF', 'PTR', 'PAGE', 'TIME', + 'LOMEM', 'HIMEM', 'SOUND', 'BPUT', 'CALL', 'CHAIN', 'CLEAR', + 'CLOSE', 'CLG', 'CLS', 'DATA', 'DEF', 'DIM', 'DRAW', 'END', + 'ENDPROC', 'ENVELOPE', 'FOR', 'GOSUB', 'GOTO', 'GCOL', 'IF', + 'INPUT', 'LET', 'LOCAL', 'MODE', 'MOVE', 'NEXT', 'ON', + 'VDU', 'PLOT', 'PRINT', 'PROC', 'READ', 'REM', 'REPEAT', + 'REPORT', 'RESTORE', 'RETURN', 'RUN', 'STOP', 'COLOUR', + 'TRACE', 'UNTIL', 'WIDTH', 'OSCLI'] + + basic5_keywords = ['WHEN', 'OF', 'ENDCASE', 'ENDIF', 'ENDWHILE', 'CASE', + 'CIRCLE', 'FILL', 'ORIGIN', 'POINT', 'RECTANGLE', 'SWAP', + 'WHILE', 'WAIT', 'MOUSE', 'QUIT', 'SYS', 'INSTALL', + 'LIBRARY', 'TINT', 'ELLIPSE', 'BEATS', 'TEMPO', 'VOICES', + 'VOICE', 'STEREO', 'OVERLAY', 'APPEND', 'AUTO', 'CRUNCH', + 'DELETE', 'EDIT', 'HELP', 'LIST', 'LOAD', 'LVAR', 'NEW', + 'OLD', 'RENUMBER', 'SAVE', 'TEXTLOAD', 'TEXTSAVE', + 'TWIN', 'TWINO', 'INSTALL', 'SUM', 'BEAT'] + + + name = 'BBC Basic' + aliases = ['bbcbasic'] + filenames = ['*.bbc'] + + tokens = { + 'root': [ + (r"[0-9]+", Name.Label), + (r"(\*)([^\n]*)", + bygroups(Keyword.Pseudo, Comment.Special)), + default('code'), + ], + + 'code': [ + (r"(REM)([^\n]*)", + bygroups(Keyword.Declaration, Comment.Single)), + (r'\n', Whitespace, 'root'), + (r'\s+', Whitespace), + (r':', Comment.Preproc), + + # Some special cases to make functions come out nicer + (r'(DEF)(\s*)(FN|PROC)([A-Za-z_@][\w@]*)', + bygroups(Keyword.Declaration, Whitespace, + Keyword.Declaration, Name.Function)), + (r'(FN|PROC)([A-Za-z_@][\w@]*)', + bygroups(Keyword, Name.Function)), + + (r'(GOTO|GOSUB|THEN|RESTORE)(\s*)(\d+)', + bygroups(Keyword, Whitespace, Name.Label)), + + (r'(TRUE|FALSE)', Keyword.Constant), + (r'(PAGE|LOMEM|HIMEM|TIME|WIDTH|ERL|ERR|REPORT\$|POS|VPOS|VOICES)', + Keyword.Pseudo), + + (words(base_keywords), Keyword), + (words(basic5_keywords), Keyword), + + ('"', String.Double, 'string'), + + ('%[01]{1,32}', Number.Bin), + ('&[0-9a-f]{1,8}', Number.Hex), + + (r'[+-]?[0-9]+\.[0-9]*(E[+-]?[0-9]+)?', Number.Float), + (r'[+-]?\.[0-9]+(E[+-]?[0-9]+)?', Number.Float), + (r'[+-]?[0-9]+E[+-]?[0-9]+', Number.Float), + (r'[+-]?\d+', Number.Integer), + + (r'([A-Za-z_@][\w@]*[%$]?)', Name.Variable), + (r'([+\-]=|[$!|?+\-*/%^=><();]|>=|<=|<>|<<|>>|>>>|,)', Operator), + ], + 'string': [ + (r'[^"\n]+', String.Double), + (r'"', String.Double, '#pop'), + (r'\n', Error, 'root'), # Unterminated string + ], + } + + def analyse_text(text): + if text.startswith('10REM >') or text.startswith('REM >'): + return 0.9 diff --git a/shared/package-files/73/7318d0f9132b0c8aa11761a5ac39957a94067d0bc38543e9a947297a97e5896c/channeldata-index.html.j2 b/shared/package-files/73/7318d0f9132b0c8aa11761a5ac39957a94067d0bc38543e9a947297a97e5896c/channeldata-index.html.j2 new file mode 100644 index 0000000000000000000000000000000000000000..aa9a302c6a798634ccf8dfd6e1f3da9b4dedbf77 --- /dev/null +++ b/shared/package-files/73/7318d0f9132b0c8aa11761a5ac39957a94067d0bc38543e9a947297a97e5896c/channeldata-index.html.j2 @@ -0,0 +1,106 @@ +{%- set use_linux_64 = 'linux-64' in subdirs -%} +{%- set use_osx_64 = 'osx-64' in subdirs -%} +{%- set use_win_64 = 'win-64' in subdirs -%} +{%- set use_noarch = 'noarch' in subdirs -%} + + + {{ title }} + + + +

{{ title }}

+

RSS Feed   channeldata.json

+ {% for subdir in subdirs %}{{ subdir }}   {% endfor %} + + + + + + + + {% if use_linux_64 %}{% endif %} + {% if use_osx_64 %}{% endif %} + {% if use_win_64 %}{% endif %} + {% if use_noarch %}{% endif %} + + +{% for name, record in packages|dictsort %} + + + + + + + {% if use_linux_64 %}{% endif %} + {% if use_osx_64 %}{% endif %} + {% if use_win_64 %}{% endif %} + {% if use_noarch %}{% endif %} + + +{%- endfor %} +
PackageLatest VersionDocDevLicenselinux-64osx-64win-64noarchSummary
{{ name | add_href(record.home) }}{{ record.version | truncate(14, True, '') }}{% if record.doc_url %}doc{% endif %}{% if record.dev_url %}dev{% endif %}{% if record.license %}{{ record.license.split(' ')[0] | truncate(15, True, '') }}{% endif %}{% if 'linux-64' in record.subdirs %}X{% endif %}{% if 'osx-64' in record.subdirs %}X{% endif %}{% if 'win-64' in record.subdirs %}X{% endif %}{% if 'noarch' in record.subdirs %}X{% endif %}{{ record.summary | escape | truncate(75) }}
+
Updated: {{ current_time|strftime("%Y-%m-%d %H:%M:%S %z") }} - Files: {{ packages|length }}
+ + diff --git a/shared/package-files/73/731ad8723eeb283dca474a099fcd8334af067b1ece2d218c7df32e69782db77b/METADATA b/shared/package-files/73/731ad8723eeb283dca474a099fcd8334af067b1ece2d218c7df32e69782db77b/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8902258b8d05889cdf0a467235991527d6e77249 --- /dev/null +++ b/shared/package-files/73/731ad8723eeb283dca474a099fcd8334af067b1ece2d218c7df32e69782db77b/METADATA @@ -0,0 +1,322 @@ +Metadata-Version: 2.1 +Name: PySocks +Version: 1.7.1 +Summary: A Python SOCKS client module. See https://github.com/Anorov/PySocks for more information. +Home-page: https://github.com/Anorov/PySocks +Author: Anorov +Author-email: anorov.vorona@gmail.com +License: BSD +Keywords: socks,proxy +Platform: UNKNOWN +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.4 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.* +Description-Content-Type: text/markdown +License-File: LICENSE + +PySocks +======= + +PySocks lets you send traffic through SOCKS and HTTP proxy servers. It is a modern fork of [SocksiPy](http://socksipy.sourceforge.net/) with bug fixes and extra features. + +Acts as a drop-in replacement to the socket module. Seamlessly configure SOCKS proxies for any socket object by calling `socket_object.set_proxy()`. + +---------------- + +Features +======== + +* SOCKS proxy client for Python 2.7 and 3.4+ +* TCP supported +* UDP mostly supported (issues may occur in some edge cases) +* HTTP proxy client included but not supported or recommended (you should use urllib2's or requests' own HTTP proxy interface) +* urllib2 handler included. `pip install` / `setup.py install` will automatically install the `sockshandler` module. + +Installation +============ + + pip install PySocks + +Or download the tarball / `git clone` and... + + python setup.py install + +These will install both the `socks` and `sockshandler` modules. + +Alternatively, include just `socks.py` in your project. + +-------------------------------------------- + +*Warning:* PySocks/SocksiPy only supports HTTP proxies that use CONNECT tunneling. Certain HTTP proxies may not work with this library. If you wish to use HTTP (not SOCKS) proxies, it is recommended that you rely on your HTTP client's native proxy support (`proxies` dict for `requests`, or `urllib2.ProxyHandler` for `urllib2`) instead. + +-------------------------------------------- + +Usage +===== + +## socks.socksocket ## + + import socks + + s = socks.socksocket() # Same API as socket.socket in the standard lib + + s.set_proxy(socks.SOCKS5, "localhost") # SOCKS4 and SOCKS5 use port 1080 by default + # Or + s.set_proxy(socks.SOCKS4, "localhost", 4444) + # Or + s.set_proxy(socks.HTTP, "5.5.5.5", 8888) + + # Can be treated identical to a regular socket object + s.connect(("www.somesite.com", 80)) + s.sendall("GET / HTTP/1.1 ...") + print s.recv(4096) + +## Monkeypatching ## + +To monkeypatch the entire standard library with a single default proxy: + + import urllib2 + import socket + import socks + + socks.set_default_proxy(socks.SOCKS5, "localhost") + socket.socket = socks.socksocket + + urllib2.urlopen("http://www.somesite.com/") # All requests will pass through the SOCKS proxy + +Note that monkeypatching may not work for all standard modules or for all third party modules, and generally isn't recommended. Monkeypatching is usually an anti-pattern in Python. + +## urllib2 Handler ## + +Example use case with the `sockshandler` urllib2 handler. Note that you must import both `socks` and `sockshandler`, as the handler is its own module separate from PySocks. The module is included in the PyPI package. + + import urllib2 + import socks + from sockshandler import SocksiPyHandler + + opener = urllib2.build_opener(SocksiPyHandler(socks.SOCKS5, "127.0.0.1", 9050)) + print opener.open("http://www.somesite.com/") # All requests made by the opener will pass through the SOCKS proxy + +-------------------------------------------- + +Original SocksiPy README attached below, amended to reflect API changes. + +-------------------------------------------- + +SocksiPy + +A Python SOCKS module. + +(C) 2006 Dan-Haim. All rights reserved. + +See LICENSE file for details. + + +*WHAT IS A SOCKS PROXY?* + +A SOCKS proxy is a proxy server at the TCP level. In other words, it acts as +a tunnel, relaying all traffic going through it without modifying it. +SOCKS proxies can be used to relay traffic using any network protocol that +uses TCP. + +*WHAT IS SOCKSIPY?* + +This Python module allows you to create TCP connections through a SOCKS +proxy without any special effort. +It also supports relaying UDP packets with a SOCKS5 proxy. + +*PROXY COMPATIBILITY* + +SocksiPy is compatible with three different types of proxies: + +1. SOCKS Version 4 (SOCKS4), including the SOCKS4a extension. +2. SOCKS Version 5 (SOCKS5). +3. HTTP Proxies which support tunneling using the CONNECT method. + +*SYSTEM REQUIREMENTS* + +Being written in Python, SocksiPy can run on any platform that has a Python +interpreter and TCP/IP support. +This module has been tested with Python 2.3 and should work with greater versions +just as well. + + +INSTALLATION +------------- + +Simply copy the file "socks.py" to your Python's `lib/site-packages` directory, +and you're ready to go. [Editor's note: it is better to use `python setup.py install` for PySocks] + + +USAGE +------ + +First load the socks module with the command: + + >>> import socks + >>> + +The socks module provides a class called `socksocket`, which is the base to all of the module's functionality. + +The `socksocket` object has the same initialization parameters as the normal socket +object to ensure maximal compatibility, however it should be noted that `socksocket` will only function with family being `AF_INET` and +type being either `SOCK_STREAM` or `SOCK_DGRAM`. +Generally, it is best to initialize the `socksocket` object with no parameters + + >>> s = socks.socksocket() + >>> + +The `socksocket` object has an interface which is very similiar to socket's (in fact +the `socksocket` class is derived from socket) with a few extra methods. +To select the proxy server you would like to use, use the `set_proxy` method, whose +syntax is: + + set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]]) + +Explanation of the parameters: + +`proxy_type` - The type of the proxy server. This can be one of three possible +choices: `PROXY_TYPE_SOCKS4`, `PROXY_TYPE_SOCKS5` and `PROXY_TYPE_HTTP` for SOCKS4, +SOCKS5 and HTTP servers respectively. `SOCKS4`, `SOCKS5`, and `HTTP` are all aliases, respectively. + +`addr` - The IP address or DNS name of the proxy server. + +`port` - The port of the proxy server. Defaults to 1080 for socks and 8080 for http. + +`rdns` - This is a boolean flag than modifies the behavior regarding DNS resolving. +If it is set to True, DNS resolving will be preformed remotely, on the server. +If it is set to False, DNS resolving will be preformed locally. Please note that +setting this to True with SOCKS4 servers actually use an extension to the protocol, +called SOCKS4a, which may not be supported on all servers (SOCKS5 and http servers +always support DNS). The default is True. + +`username` - For SOCKS5 servers, this allows simple username / password authentication +with the server. For SOCKS4 servers, this parameter will be sent as the userid. +This parameter is ignored if an HTTP server is being used. If it is not provided, +authentication will not be used (servers may accept unauthenticated requests). + +`password` - This parameter is valid only for SOCKS5 servers and specifies the +respective password for the username provided. + +Example of usage: + + >>> s.set_proxy(socks.SOCKS5, "socks.example.com") # uses default port 1080 + >>> s.set_proxy(socks.SOCKS4, "socks.test.com", 1081) + +After the set_proxy method has been called, simply call the connect method with the +traditional parameters to establish a connection through the proxy: + + >>> s.connect(("www.sourceforge.net", 80)) + >>> + +Connection will take a bit longer to allow negotiation with the proxy server. +Please note that calling connect without calling `set_proxy` earlier will connect +without a proxy (just like a regular socket). + +Errors: Any errors in the connection process will trigger exceptions. The exception +may either be generated by the underlying socket layer or may be custom module +exceptions, whose details follow: + +class `ProxyError` - This is a base exception class. It is not raised directly but +rather all other exception classes raised by this module are derived from it. +This allows an easy way to catch all proxy-related errors. It descends from `IOError`. + +All `ProxyError` exceptions have an attribute `socket_err`, which will contain either a +caught `socket.error` exception, or `None` if there wasn't any. + +class `GeneralProxyError` - When thrown, it indicates a problem which does not fall +into another category. + +* `Sent invalid data` - This error means that unexpected data has been received from +the server. The most common reason is that the server specified as the proxy is +not really a SOCKS4/SOCKS5/HTTP proxy, or maybe the proxy type specified is wrong. + +* `Connection closed unexpectedly` - The proxy server unexpectedly closed the connection. +This may indicate that the proxy server is experiencing network or software problems. + +* `Bad proxy type` - This will be raised if the type of the proxy supplied to the +set_proxy function was not one of `SOCKS4`/`SOCKS5`/`HTTP`. + +* `Bad input` - This will be raised if the `connect()` method is called with bad input +parameters. + +class `SOCKS5AuthError` - This indicates that the connection through a SOCKS5 server +failed due to an authentication problem. + +* `Authentication is required` - This will happen if you use a SOCKS5 server which +requires authentication without providing a username / password at all. + +* `All offered authentication methods were rejected` - This will happen if the proxy +requires a special authentication method which is not supported by this module. + +* `Unknown username or invalid password` - Self descriptive. + +class `SOCKS5Error` - This will be raised for SOCKS5 errors which are not related to +authentication. +The parameter is a tuple containing a code, as given by the server, +and a description of the +error. The possible errors, according to the RFC, are: + +* `0x01` - General SOCKS server failure - If for any reason the proxy server is unable to +fulfill your request (internal server error). +* `0x02` - connection not allowed by ruleset - If the address you're trying to connect to +is blacklisted on the server or requires authentication. +* `0x03` - Network unreachable - The target could not be contacted. A router on the network +had replied with a destination net unreachable error. +* `0x04` - Host unreachable - The target could not be contacted. A router on the network +had replied with a destination host unreachable error. +* `0x05` - Connection refused - The target server has actively refused the connection +(the requested port is closed). +* `0x06` - TTL expired - The TTL value of the SYN packet from the proxy to the target server +has expired. This usually means that there are network problems causing the packet +to be caught in a router-to-router "ping-pong". +* `0x07` - Command not supported - For instance if the server does not support UDP. +* `0x08` - Address type not supported - The client has provided an invalid address type. +When using this module, this error should not occur. + +class `SOCKS4Error` - This will be raised for SOCKS4 errors. The parameter is a tuple +containing a code and a description of the error, as given by the server. The +possible error, according to the specification are: + +* `0x5B` - Request rejected or failed - Will be raised in the event of an failure for any +reason other then the two mentioned next. +* `0x5C` - request rejected because SOCKS server cannot connect to identd on the client - +The Socks server had tried an ident lookup on your computer and has failed. In this +case you should run an identd server and/or configure your firewall to allow incoming +connections to local port 113 from the remote server. +* `0x5D` - request rejected because the client program and identd report different user-ids - +The Socks server had performed an ident lookup on your computer and has received a +different userid than the one you have provided. Change your userid (through the +username parameter of the set_proxy method) to match and try again. + +class `HTTPError` - This will be raised for HTTP errors. The message will contain +the HTTP status code and provided error message. + +After establishing the connection, the object behaves like a standard socket. + +Methods like `makefile()` and `settimeout()` should behave just like regular sockets. +Call the `close()` method to close the connection. + +In addition to the `socksocket` class, an additional function worth mentioning is the +`set_default_proxy` function. The parameters are the same as the `set_proxy` method. +This function will set default proxy settings for newly created `socksocket` objects, +in which the proxy settings haven't been changed via the `set_proxy` method. +This is quite useful if you wish to force 3rd party modules to use a SOCKS proxy, +by overriding the socket object. +For example: + + >>> socks.set_default_proxy(socks.SOCKS5, "socks.example.com") + >>> socket.socket = socks.socksocket + >>> urllib.urlopen("http://www.sourceforge.net/") + + +PROBLEMS +--------- + +Please open a GitHub issue at https://github.com/Anorov/PySocks + + diff --git a/shared/package-files/73/731cc3e41e1e9f93856e509aa3fb81ea0594b8c82875aaf5872c6fb1cd7bb086/pytz.py b/shared/package-files/73/731cc3e41e1e9f93856e509aa3fb81ea0594b8c82875aaf5872c6fb1cd7bb086/pytz.py new file mode 100644 index 0000000000000000000000000000000000000000..5ac18907f24f7bed1144a71d22ff77a22ffa7d45 --- /dev/null +++ b/shared/package-files/73/731cc3e41e1e9f93856e509aa3fb81ea0594b8c82875aaf5872c6fb1cd7bb086/pytz.py @@ -0,0 +1,54 @@ +# This file is part of Hypothesis, which may be found at +# https://github.com/HypothesisWorks/hypothesis/ +# +# Copyright the Hypothesis Authors. +# Individual contributors are listed in AUTHORS.rst and the git log. +# +# This Source Code Form is subject to the terms of the Mozilla Public License, +# v. 2.0. If a copy of the MPL was not distributed with this file, You can +# obtain one at https://mozilla.org/MPL/2.0/. + +""" +---------------- +hypothesis[pytz] +---------------- + +This module provides :pypi:`pytz` timezones. + +You can use this strategy to make +:py:func:`hypothesis.strategies.datetimes` and +:py:func:`hypothesis.strategies.times` produce timezone-aware values. +""" + +import datetime as dt + +import pytz +from pytz.tzfile import StaticTzInfo # type: ignore # considered private by typeshed + +from hypothesis import strategies as st +from hypothesis.strategies._internal.utils import cacheable, defines_strategy + +__all__ = ["timezones"] + + +@cacheable +@defines_strategy() +def timezones() -> st.SearchStrategy[dt.tzinfo]: + """Any timezone in the Olsen database, as a pytz tzinfo object. + + This strategy minimises to UTC, or the smallest possible fixed + offset, and is designed for use with + :py:func:`hypothesis.strategies.datetimes`. + """ + all_timezones = [pytz.timezone(tz) for tz in pytz.all_timezones] + # Some timezones have always had a constant offset from UTC. This makes + # them simpler than timezones with daylight savings, and the smaller the + # absolute offset the simpler they are. Of course, UTC is even simpler! + static: list = [pytz.UTC] + static += sorted( + (t for t in all_timezones if isinstance(t, StaticTzInfo)), + key=lambda tz: abs(tz.utcoffset(dt.datetime(2000, 1, 1))), + ) + # Timezones which have changed UTC offset; best ordered by name. + dynamic = [tz for tz in all_timezones if tz not in static] + return st.sampled_from(static + dynamic) diff --git a/shared/package-files/73/731cd9051ba3b6a9fc32a53ca07b71a95bbd67de2dafd8cb0f77fc61094850db/SobolEngineOpsUtils.h b/shared/package-files/73/731cd9051ba3b6a9fc32a53ca07b71a95bbd67de2dafd8cb0f77fc61094850db/SobolEngineOpsUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..17e42ebe84a0e8b0906a76ba9c937c6c46027caa --- /dev/null +++ b/shared/package-files/73/731cd9051ba3b6a9fc32a53ca07b71a95bbd67de2dafd8cb0f77fc61094850db/SobolEngineOpsUtils.h @@ -0,0 +1,55 @@ +/// This file contains some tensor-agnostic operations to be used in the +/// core functions of the `SobolEngine` +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#include +#endif + +namespace at::native::sobol_utils { + +/// Function to return the minimum of number of bits to represent the integer `n` +inline int64_t bit_length(const int64_t n) { + int64_t nbits, nloc; + for (nloc = n, nbits = 0; nloc > 0; nloc /= 2, nbits++); + return nbits; +} + +/// Function to get the position of the rightmost zero in the bit representation of an integer +/// This value is the zero-indexed position +inline int64_t rightmost_zero(const int64_t n) { + int64_t z, i; + for (z = n, i = 0; z % 2 == 1; z /= 2, i++); + return i; +} + +/// Function to get a subsequence of bits in the representation of an integer starting from +/// `pos` and of length `length` +inline int64_t bitsubseq(const int64_t n, const int64_t pos, const int64_t length) { + return (n >> pos) & ((1 << length) - 1); +} + +/// Function to perform the inner product between a batched square matrix and a power of 2 vector +inline at::Tensor cdot_pow2(const at::Tensor& bmat) { + at::Tensor inter = at::arange(bmat.size(-1) - 1, -1, -1, bmat.options()); + inter = at::pow(2, inter).expand_as(bmat); + return at::mul(inter, bmat).sum(-1); +} + +/// All definitions below this point are data. These are constant, and should not be modified +/// without notice + +constexpr int64_t MAXDIM = 21201; +constexpr int64_t MAXDEG = 18; +constexpr int64_t MAXBIT = 30; +constexpr int64_t LARGEST_NUMBER = 1 << MAXBIT; +constexpr float RECIPD = 1.0 / LARGEST_NUMBER; + +extern const int64_t poly[MAXDIM]; +extern const int64_t initsobolstate[MAXDIM][MAXDEG]; + +} // namespace at::native::sobol_utils diff --git a/shared/package-files/73/7320f5d9f2316c77dec78d230fdfa5428af6cf5c3ebbd3f35fb2bd6b38867d5b/slice_scatter_compositeexplicitautograd_dispatch.h b/shared/package-files/73/7320f5d9f2316c77dec78d230fdfa5428af6cf5c3ebbd3f35fb2bd6b38867d5b/slice_scatter_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f53c1b6de3f318e3e5b7ad04dfacbf8f602d6a8a --- /dev/null +++ b/shared/package-files/73/7320f5d9f2316c77dec78d230fdfa5428af6cf5c3ebbd3f35fb2bd6b38867d5b/slice_scatter_compositeexplicitautograd_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & slice_scatter_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & src, int64_t dim=0, c10::optional start=c10::nullopt, c10::optional end=c10::nullopt, int64_t step=1); +TORCH_API at::Tensor & slice_scatter_outf(const at::Tensor & self, const at::Tensor & src, int64_t dim, c10::optional start, c10::optional end, int64_t step, at::Tensor & out); +TORCH_API at::Tensor & slice_scatter_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & src, int64_t dim=0, c10::optional start=c10::nullopt, c10::optional end=c10::nullopt, c10::SymInt step=1); +TORCH_API at::Tensor & slice_scatter_symint_outf(const at::Tensor & self, const at::Tensor & src, int64_t dim, c10::optional start, c10::optional end, c10::SymInt step, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/73/7321de43e4f7840f6b509532993d5d6e2fb5a596e7e4181f746e8de4cb634e53/test_link.py b/shared/package-files/73/7321de43e4f7840f6b509532993d5d6e2fb5a596e7e4181f746e8de4cb634e53/test_link.py new file mode 100644 index 0000000000000000000000000000000000000000..96db08e079c4684b86af856441b9eb8ddc1b59bc --- /dev/null +++ b/shared/package-files/73/7321de43e4f7840f6b509532993d5d6e2fb5a596e7e4181f746e8de4cb634e53/test_link.py @@ -0,0 +1,271 @@ +""" +Test functions for genmod.families.links +""" + +import numpy as np +from numpy.testing import assert_allclose, assert_array_less, assert_equal +import pytest +from scipy import stats + +from statsmodels.genmod import families +from statsmodels.tools import numdiff as nd + +# Family instances +links = families.links +logit = links.Logit() +inverse_power = links.InversePower() +sqrt = links.Sqrt() +inverse_squared = links.InverseSquared() +identity = links.Identity() +log = links.Log() +logc = links.LogC() +probit = links.Probit() +cauchy = links.Cauchy() +cloglog = links.CLogLog() +loglog = links.LogLog() +negbinom = links.NegativeBinomial() + +# TODO: parametrize all these tess +Links = [ + logit, + inverse_power, + sqrt, + inverse_squared, + identity, + log, + logc, + probit, + cauchy, + cloglog, + loglog, + negbinom, +] + +# links with defined second derivative of inverse link. +LinksISD = [ + inverse_power, + sqrt, + inverse_squared, + identity, + logc, + cauchy, + probit, + loglog, +] + + +def get_domainvalue(link, rng): + """ + Get a value in the domain for a given family. + """ + z = -np.log(rng.uniform(0, 1)) + if isinstance(link, links.CLogLog): # prone to overflow + z = min(z, 3) + elif isinstance(link, links.LogLog): + z = max(z, -3) + elif isinstance(link, (links.NegativeBinomial, links.LogC)): + # domain is negative numbers + z = -z + return z + + +def test_inverse(): + # Logic check that link.inverse(link) and link(link.inverse) + # are the identity. + rs = np.random.RandomState(3285) + + for link in Links: + for _ in range(10): + p = rs.uniform(0, 1) # In domain for all families + d = link.inverse(link(p)) + assert_allclose(d, p, atol=1e-8, err_msg=str(link)) + + z = get_domainvalue(link, rs) + d = link(link.inverse(z)) + assert_allclose(d, z, atol=1e-8, err_msg=str(link)) + + +def test_deriv(): + # Check link function derivatives using numeric differentiation. + + rs = np.random.RandomState(24235) + + for link in Links: + for _ in range(10): + p = rs.uniform(0, 1) + if isinstance(link, links.Cauchy): + p = np.clip(p, 0.03, 0.97) + d = link.deriv(p) + da = nd.approx_fprime(np.r_[p], link) + assert_allclose(d, da, rtol=1e-6, atol=1e-6, err_msg=str(link)) + if not isinstance( + link, (type(inverse_power), type(inverse_squared), type(logc)) + ): + # check monotonically increasing + assert_array_less(-d, 0) + + +def test_deriv2(): + # Check link function second derivatives using numeric differentiation. + + rs = np.random.RandomState(24235) + + for link in Links: + for _ in range(10): + p = rs.uniform(0, 1) + p = np.clip(p, 0.01, 0.99) + if isinstance(link, links.cauchy): + p = np.clip(p, 0.03, 0.97) + d = link.deriv2(p) + da = nd.approx_fprime(np.r_[p], link.deriv) + assert_allclose(d, da, rtol=5e-6, atol=1e-6, err_msg=str(link)) + + +def test_inverse_deriv(): + # Logic check that inverse_deriv equals 1/link.deriv(link.inverse) + rs = np.random.RandomState(128192810) + for link in Links: + for _ in range(10): + z = get_domainvalue(link, rs) + d = link.inverse_deriv(z) + f = 1 / link.deriv(link.inverse(z)) + assert_allclose(d, f, rtol=1e-8, atol=1e-10, err_msg=str(link)) + + +def test_inverse_deriv2(): + # Check second derivative of inverse link using numeric differentiation. + + rs = np.random.RandomState(24235) + + for link in LinksISD: + for _ in range(10): + z = get_domainvalue(link, rs) + d2 = link.inverse_deriv2(z) + d2a = nd.approx_fprime(np.r_[z], link.inverse_deriv) + assert_allclose(d2, d2a, rtol=5e-6, atol=1e-6, err_msg=str(link)) + + +def test_invlogit_stability(): + z = [ + 1123.4910007309222, + 1483.952316802719, + 1344.86033748641, + 706.339159002542, + 1167.9986375146532, + 663.8345826933115, + 1496.3691686913917, + 1563.0763842182257, + 1587.4309332296314, + 697.1173174974248, + 1333.7256198289665, + 1388.7667560586933, + 819.7605431778434, + 1479.9204150555015, + 1078.5642245164856, + 480.10338454985896, + 1112.691659145772, + 534.1061908007274, + 918.2011296406588, + 1280.8808515887802, + 758.3890788775948, + 673.503699841035, + 1556.7043357878208, + 819.5269028006679, + 1262.5711060356423, + 1098.7271535253608, + 1482.811928490097, + 796.198809756532, + 893.7946963941745, + 470.3304989319786, + 1427.77079226037, + 1365.2050226373822, + 1492.4193201661922, + 871.9922191949931, + 768.4735925445908, + 732.9222777654679, + 812.2382651982667, + 495.06449978924525, + ] + zinv = logit.inverse(z) + assert_equal(zinv, np.ones_like(z)) + + +class MyCLogLog(links.Link): + + def __call__(self, p): + # p = self._clean(p) + return np.log(-np.log(1 - p)) + + def inverse(self, z): + return 1 - np.exp(-np.exp(z)) + + def deriv(self, p): + # p = self._clean(p) + return 1.0 / ((p - 1) * (np.log(1 - p))) + + +class CasesCDFLink: + # just as namespace to hold cases for test_cdflink + + link_pairs = [ + (links.CDFLink(dbn=stats.gumbel_l), links.CLogLog()), + (links.CDFLink(dbn=stats.gumbel_r), links.LogLog()), + (links.CDFLink(dbn=stats.norm), links.Probit()), + (links.CDFLink(dbn=stats.logistic), links.Logit()), + (links.CDFLink(dbn=stats.t(1)), links.Cauchy()), + # approximation of t by normal is not good enough for rtol, atol + # (links.CDFLink(dbn=stats.t(1000000)), links.Probit()), + (MyCLogLog(), links.CLogLog()), # not a cdflink, but compares + ] + + methods = [ + "__call__", + "deriv", + "inverse", + "inverse_deriv", + "deriv2", + "inverse_deriv2", + ] + + p = np.linspace(0, 1, 6) + eps = 1e-3 + p = np.clip(p, eps, 1 - eps) + + +@pytest.mark.parametrize("m", CasesCDFLink.methods) +@pytest.mark.parametrize("link1, link2", CasesCDFLink.link_pairs) +def test_cdflink(m, link1, link2): + p = CasesCDFLink.p + res1 = getattr(link1, m)(p) + res2 = getattr(link2, m)(p) + + assert_allclose(res1, res2, atol=1e-8, rtol=1e-8) + + +def test_link_base_class_placeholders(): + # Link is a generic base class documented as laying out the methods + # "expected of any subclass"; __call__/inverse/deriv are explicitly + # documented as placeholders. They are not abstract (no exception is + # raised); the base implementation just returns the NotImplementedError + # type itself, which is what a concrete subclass is supposed to + # override. Exercise that placeholder contract directly, since every + # concrete link in this module overrides inverse/deriv and so never + # actually runs the base-class bodies. + link = links.Link() + assert link(0.5) is NotImplementedError + assert link.inverse(0.5) is NotImplementedError + assert link.deriv(0.5) is NotImplementedError + + +def test_cdflink_deriv2_numdiff(): + # deriv2_numdiff is a numerical-differentiation fallback for the + # second derivative of the link function (central difference of + # `deriv`). It should agree with CDFLink's analytic deriv2 (which + # is computed via inverse_deriv2 rather than by differencing) to + # numerical-differentiation accuracy. + link = links.CDFLink(dbn=stats.norm) + p = np.linspace(0.05, 0.95, 9) + + analytic = link.deriv2(p) + numeric = link.deriv2_numdiff(p) + assert_allclose(numeric, analytic, rtol=5e-6, atol=1e-6) diff --git a/shared/package-files/73/7323a172490e1751ee71f442779856d709ac30b582ca6e3eb3cfd81a03bd91eb/hp2626-12x40 b/shared/package-files/73/7323a172490e1751ee71f442779856d709ac30b582ca6e3eb3cfd81a03bd91eb/hp2626-12x40 new file mode 100644 index 0000000000000000000000000000000000000000..131b46d0b40311b1e1f081e273d2bfe20fa77c8f Binary files /dev/null and b/shared/package-files/73/7323a172490e1751ee71f442779856d709ac30b582ca6e3eb3cfd81a03bd91eb/hp2626-12x40 differ diff --git a/shared/package-files/73/73242afc25be72a4d5606e67db240a239e7620384c9e5199a853eead1cdd524e/CUDATensorMethods.cuh b/shared/package-files/73/73242afc25be72a4d5606e67db240a239e7620384c9e5199a853eead1cdd524e/CUDATensorMethods.cuh new file mode 100644 index 0000000000000000000000000000000000000000..e4e89ea1cdb77da1d7866ffe99c64dabfd735d27 --- /dev/null +++ b/shared/package-files/73/73242afc25be72a4d5606e67db240a239e7620384c9e5199a853eead1cdd524e/CUDATensorMethods.cuh @@ -0,0 +1,15 @@ +#pragma once + +#include +#include + +#include +#include +#include + +namespace at { +template <> +inline __half* Tensor::data() const { + return reinterpret_cast<__half*>(data()); +} +} // namespace at diff --git a/shared/package-files/73/732502b261c039d19d7e7f8dd57d512c353fee8963f5c70e20de019d6b43e781/vecm_e6_jmulti_colo_lagorder.txt b/shared/package-files/73/732502b261c039d19d7e7f8dd57d512c353fee8963f5c70e20de019d6b43e781/vecm_e6_jmulti_colo_lagorder.txt new file mode 100644 index 0000000000000000000000000000000000000000..a2f11e99b521c661da0c526d20c7cf5a587e73ec --- /dev/null +++ b/shared/package-files/73/732502b261c039d19d7e7f8dd57d512c353fee8963f5c70e20de019d6b43e781/vecm_e6_jmulti_colo_lagorder.txt @@ -0,0 +1,13 @@ +*** Sun, 21 Aug 2016 09:34:48 *** +OPTIMAL ENDOGENOUS LAGS FROM INFORMATION CRITERIA + +endogenous variables: Dp R +deterministic variables: CONST TREND +sample range: [1975 Q1, 1998 Q4], T = 96 + +optimal number of lags (searched up to 10 lags of 1. differences): +Akaike Info Criterion: 3 +Final Prediction Error: 3 +Hannan-Quinn Criterion: 3 +Schwarz Criterion: 3 + diff --git a/shared/package-files/73/73274860b6522376f65c856a54e677e59e5eb3d0a07c38b33bc7401095ad4083/test_pairwise.py b/shared/package-files/73/73274860b6522376f65c856a54e677e59e5eb3d0a07c38b33bc7401095ad4083/test_pairwise.py new file mode 100644 index 0000000000000000000000000000000000000000..89d8375feb972849c6f77947f3554418051bd00b --- /dev/null +++ b/shared/package-files/73/73274860b6522376f65c856a54e677e59e5eb3d0a07c38b33bc7401095ad4083/test_pairwise.py @@ -0,0 +1,751 @@ +""" + +Created on Wed Mar 28 15:34:18 2012 + +Author: Josef Perktold +""" + +from statsmodels.compat.python import asbytes + +from io import BytesIO +import warnings + +import numpy as np +from numpy.testing import ( + assert_, + assert_allclose, + assert_almost_equal, + assert_equal, +) +import pandas as pd +import pytest + +from statsmodels.stats.libqsturng import qsturng +from statsmodels.stats.multicomp import MultiComparison, pairwise_tukeyhsd, tukeyhsd + +ss = """\ + 43.9 1 1 + 39.0 1 2 + 46.7 1 3 + 43.8 1 4 + 44.2 1 5 + 47.7 1 6 + 43.6 1 7 + 38.9 1 8 + 43.6 1 9 + 40.0 1 10 + 89.8 2 1 + 87.1 2 2 + 92.7 2 3 + 90.6 2 4 + 87.7 2 5 + 92.4 2 6 + 86.1 2 7 + 88.1 2 8 + 90.8 2 9 + 89.1 2 10 + 68.4 3 1 + 69.3 3 2 + 68.5 3 3 + 66.4 3 4 + 70.0 3 5 + 68.1 3 6 + 70.6 3 7 + 65.2 3 8 + 63.8 3 9 + 69.2 3 10 + 36.2 4 1 + 45.2 4 2 + 40.7 4 3 + 40.5 4 4 + 39.3 4 5 + 40.3 4 6 + 43.2 4 7 + 38.7 4 8 + 40.9 4 9 + 39.7 4 10""" + +# idx Treatment StressReduction +ss2 = """\ +1 mental 2 +2 mental 2 +3 mental 3 +4 mental 4 +5 mental 4 +6 mental 5 +7 mental 3 +8 mental 4 +9 mental 4 +10 mental 4 +11 physical 4 +12 physical 4 +13 physical 3 +14 physical 5 +15 physical 4 +16 physical 1 +17 physical 1 +18 physical 2 +19 physical 3 +20 physical 3 +21 medical 1 +22 medical 2 +23 medical 2 +24 medical 2 +25 medical 3 +26 medical 2 +27 medical 3 +28 medical 1 +29 medical 3 +30 medical 1""" + +ss3 = """\ +1 24.5 +1 23.5 +1 26.4 +1 27.1 +1 29.9 +2 28.4 +2 34.2 +2 29.5 +2 32.2 +2 30.1 +3 26.1 +3 28.3 +3 24.3 +3 26.2 +3 27.8""" + +ss5 = """\ +2 - 3\t4.340\t0.691\t7.989\t*** +2 - 1\t4.600\t0.951\t8.249\t*** +3 - 2\t-4.340\t-7.989\t-0.691\t*** +3 - 1\t0.260\t-3.389\t3.909\t- +1 - 2\t-4.600\t-8.249\t-0.951\t*** +1 - 3\t-0.260\t-3.909\t3.389\t- +""" + +# result in R: library(rstatix) +# games_howell_test(df, StressReduction ~ Treatment, conf.level = 0.99) +ss2_unequal = """\ +1\tStressReduction\tmedical\tmental\t1.8888888888888888\t0.7123347940930316\t3.0654429836847461\t0.000196\t*** +2\tStressReduction\tmedical\tphysical\t0.8888888888888888\t-0.8105797509636128\t2.5883575287413905\t0.206000\tns +3\tStressReduction\tmental\tphysical\t-1.0000000000000000\t-2.6647460755237473\t0.6647460755237473\t0.127000\tns +""" + +cylinders = np.array( + [ + 8, + 8, + 8, + 8, + 8, + 8, + 8, + 8, + 8, + 8, + 4, + 8, + 8, + 8, + 8, + 8, + 8, + 8, + 8, + 8, + 4, + 6, + 6, + 6, + 4, + 4, + 4, + 4, + 4, + 4, + 6, + 8, + 8, + 8, + 8, + 4, + 4, + 4, + 4, + 8, + 8, + 8, + 8, + 6, + 6, + 6, + 6, + 4, + 4, + 4, + 4, + 6, + 6, + 6, + 6, + 4, + 4, + 4, + 4, + 4, + 8, + 4, + 6, + 6, + 8, + 8, + 8, + 8, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 6, + 6, + 4, + 6, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + ] +) +cyl_labels = np.array( + [ + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "France", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "Japan", + "USA", + "USA", + "USA", + "Japan", + "Germany", + "France", + "Germany", + "Sweden", + "Germany", + "USA", + "USA", + "USA", + "USA", + "USA", + "Germany", + "USA", + "USA", + "France", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "Germany", + "Japan", + "USA", + "USA", + "USA", + "USA", + "Germany", + "Japan", + "Japan", + "USA", + "Sweden", + "USA", + "France", + "Japan", + "Germany", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "USA", + "Germany", + "Japan", + "Japan", + "USA", + "USA", + "Japan", + "Japan", + "Japan", + "Japan", + "Japan", + "Japan", + "USA", + "USA", + "USA", + "USA", + "Japan", + "USA", + "USA", + "USA", + "Germany", + "USA", + "USA", + "USA", + ] +) + +# accommodate recfromtxt for python 3.2, requires bytes +ss = asbytes(ss) +ss2 = asbytes(ss2) +ss3 = asbytes(ss3) +ss5 = asbytes(ss5) +ss2_unequal = asbytes(ss2_unequal) + +dta = pd.read_csv(BytesIO(ss), sep=r"\s+", header=None, engine="python") +dta.columns = "Rust", "Brand", "Replication" +dta2 = pd.read_csv(BytesIO(ss2), sep=r"\s+", header=None, engine="python") +dta2.columns = "idx", "Treatment", "StressReduction" +dta2["Treatment"] = dta2["Treatment"].map(lambda v: v.encode("utf-8")) +dta3 = pd.read_csv(BytesIO(ss3), sep=r"\s+", header=None, engine="python") +dta3.columns = ["Brand", "Relief"] +dta5 = pd.read_csv(BytesIO(ss5), sep=r"\t", header=None, engine="python") +dta5.columns = ["pair", "mean", "lower", "upper", "sig"] +for col in ("pair", "sig"): + dta5[col] = dta5[col].map(lambda v: v.encode("utf-8")) +sas_ = dta5.iloc[[1, 3, 2]] +games_howell_r_result = pd.read_csv( + BytesIO(ss2_unequal), sep=r"\t", header=None, engine="python" +) +games_howell_r_result.columns = [ + "idx", + "y", + "group1", + "group2", + "meandiff", + "lower", + "upper", + "pvalue", + "sig", +] +for col in ("y", "group1", "group2", "sig"): + games_howell_r_result[col] = games_howell_r_result[col].map( + lambda v: v.encode("utf-8") + ) + + +def get_thsd(mci, alpha=0.05): + var_ = np.var(mci.groupstats.groupdemean(), ddof=len(mci.groupsunique)) + means = mci.groupstats.groupmean + nobs = mci.groupstats.groupnobs + resi = tukeyhsd( + means, + nobs, + var_, + df=None, + alpha=alpha, + q_crit=qsturng(1 - alpha, len(means), (nobs - 1).sum()), + ) + # print resi[4] + var2 = (mci.groupstats.groupvarwithin() * (nobs - 1.0)).sum() / (nobs - 1.0).sum() + # print nobs, (nobs - 1).sum() + # print mci.groupstats.groupvarwithin() + assert_almost_equal(var_, var2, decimal=14) + return resi + + +class CheckTuckeyHSDMixin: + + @classmethod + def setup_class_(cls): + cls.mc = MultiComparison(cls.endog, cls.groups) + if hasattr(cls, "use_var"): + cls.res = cls.mc.tukeyhsd(alpha=cls.alpha, use_var=cls.use_var) + else: + cls.res = cls.mc.tukeyhsd(alpha=cls.alpha) + + def test_multicomptukey(self): + assert_almost_equal(self.res.meandiffs, self.meandiff2, decimal=14) + assert_almost_equal(self.res.confint, self.confint2, decimal=2) + assert_equal(self.res.reject, self.reject2) + + def test_group_tukey(self): + if hasattr(self, "use_var") and self.use_var == "unequal": + # in unequal variance case, we feed groupvarwithin, no need to test total variance + return + res_t = get_thsd(self.mc, alpha=self.alpha) + assert_almost_equal(res_t[4], self.confint2, decimal=2) + + def test_shortcut_function(self): + # check wrapper function + if hasattr(self, "use_var"): + res = pairwise_tukeyhsd( + self.endog, self.groups, alpha=self.alpha, use_var=self.use_var + ) + else: + res = pairwise_tukeyhsd(self.endog, self.groups, alpha=self.alpha) + assert_almost_equal(res.confint, self.res.confint, decimal=14) + + @pytest.mark.smoke + @pytest.mark.thread_unsafe(reason="Uses matplotlib") + @pytest.mark.matplotlib + def test_plot_simultaneous_ci(self, close_figures): + self.res._simultaneous_ci() + reference = self.res.groupsunique[1] + self.res.plot_simultaneous(comparison_name=reference) + + +class TestTuckeyHSD2(CheckTuckeyHSDMixin): + + @classmethod + def setup_class(cls): + # balanced case + cls.endog = dta2["StressReduction"] + cls.groups = dta2["Treatment"] + cls.alpha = 0.05 + cls.setup_class_() # in super + + # from R + tukeyhsd2s = np.array( + [ + 1.5, + 1, + -0.5, + 0.3214915, + -0.1785085, + -1.678509, + 2.678509, + 2.178509, + 0.6785085, + 0.01056279, + 0.1079035, + 0.5513904, + ] + ).reshape(3, 4, order="F") + cls.meandiff2 = tukeyhsd2s[:, 0] + cls.confint2 = tukeyhsd2s[:, 1:3] + pvals = tukeyhsd2s[:, 3] + cls.reject2 = pvals < 0.05 + + def test_table_names_default_group_order(self): + t = self.res._results_table + # if the group_order parameter is not used, the groups should + # be reported in alphabetical order + expected_order = [ + (b"medical", b"mental"), + (b"medical", b"physical"), + (b"mental", b"physical"), + ] + for i in range(1, 4): + first_group = t[i][0].data + second_group = t[i][1].data + assert_((first_group, second_group) == expected_order[i - 1]) + + def test_table_names_custom_group_order(self): + # if the group_order parameter is used, the groups should + # be reported in the specified order + mc = MultiComparison( + self.endog, self.groups, group_order=[b"physical", b"medical", b"mental"] + ) + res = mc.tukeyhsd(alpha=self.alpha) + # print(res) + t = res._results_table + expected_order = [ + (b"physical", b"medical"), + (b"physical", b"mental"), + (b"medical", b"mental"), + ] + for i in range(1, 4): + first_group = t[i][0].data + second_group = t[i][1].data + assert_((first_group, second_group) == expected_order[i - 1]) + + frame = res.summary_frame() + assert_equal(frame["p-adj"], res.pvalues) + assert_equal(frame["meandiff"], res.meandiffs) + # Why are we working with binary strings, old time numpy? + group_t = [b"medical", b"mental", b"mental"] + group_c = [b"physical", b"physical", b"medical"] + assert frame["group_t"].to_list() == group_t + assert frame["group_c"].to_list() == group_c + + +class TestTuckeyHSD2Pandas(TestTuckeyHSD2): + + @classmethod + def setup_class(cls): + super().setup_class() + + cls.endog = pd.Series(cls.endog) + # we are working with bytes on python 3, not with strings in this case + cls.groups = pd.Series(cls.groups, dtype=object) + + def test_incorrect_output(self): + # too few groups + with pytest.raises(ValueError): + MultiComparison(np.array([1] * 10), [1, 2] * 4) + # too many groups + with pytest.raises(ValueError): + MultiComparison(np.array([1] * 10), [1, 2] * 6) + # just one group + with pytest.raises(ValueError): + MultiComparison(np.array([1] * 10), [1] * 10) + + # group_order does not select all observations, only one group left + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + with pytest.raises(ValueError): + MultiComparison(np.array([1] * 10), [1, 2] * 5, group_order=[1]) + + # group_order does not select all observations, + # we do tukey_hsd with reduced set of observations + data = np.arange(15) + groups = np.repeat([1, 2, 3], 5) + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + mod1 = MultiComparison(np.array(data), groups, group_order=[1, 2]) + assert_equal(len(w), 1) + assert issubclass(w[0].category, UserWarning) + + res1 = mod1.tukeyhsd(alpha=0.01) + mod2 = MultiComparison(np.array(data[:10]), groups[:10]) + res2 = mod2.tukeyhsd(alpha=0.01) + + attributes = [ + "confint", + "data", + "df_total", + "groups", + "groupsunique", + "meandiffs", + "q_crit", + "reject", + "reject2", + "std_pairs", + "variance", + ] + for att in attributes: + err_msg = att + "failed" + assert_allclose( + getattr(res1, att), getattr(res2, att), rtol=1e-14, err_msg=err_msg + ) + + attributes = [ + "data", + "datali", + "groupintlab", + "groups", + "groupsunique", + "ngroups", + "nobs", + "pairindices", + ] + for att in attributes: + err_msg = att + "failed" + assert_allclose( + getattr(mod1, att), getattr(mod2, att), rtol=1e-14, err_msg=err_msg + ) + + +class TestTuckeyHSD2s(CheckTuckeyHSDMixin): + @classmethod + def setup_class(cls): + # unbalanced case + cls.endog = dta2["StressReduction"][3:29] + cls.groups = dta2["Treatment"][3:29] + cls.alpha = 0.01 + cls.setup_class_() + + # from R + tukeyhsd2s = np.array( + [ + 1.8888888888888889, + 0.888888888888889, + -1, + 0.2658549, + -0.5908785, + -2.587133, + 3.511923, + 2.368656, + 0.5871331, + 0.002837638, + 0.150456, + 0.1266072, + ] + ).reshape(3, 4, order="F") + cls.meandiff2 = tukeyhsd2s[:, 0] + cls.confint2 = tukeyhsd2s[:, 1:3] + pvals = tukeyhsd2s[:, 3] + cls.reject2 = pvals < 0.01 + + +class TestTukeyHSD2sUnequal(CheckTuckeyHSDMixin): + + @classmethod + def setup_class(cls): + # Games-Howell test + cls.endog = dta2["StressReduction"][3:29] + cls.groups = dta2["Treatment"][3:29] + cls.alpha = 0.01 + cls.use_var = "unequal" + cls.setup_class_() + + # from R: library(rstatix) + cls.meandiff2 = games_howell_r_result["meandiff"] + cls.confint2 = ( + games_howell_r_result[["lower", "upper"]] + .astype(float) + .values.reshape((3, 2)) + ) + cls.reject2 = games_howell_r_result["sig"] == asbytes("***") + + +class TestTuckeyHSD3(CheckTuckeyHSDMixin): + + @classmethod + def setup_class(cls): + # SAS case + cls.endog = dta3["Relief"] + cls.groups = dta3["Brand"] + cls.alpha = 0.05 + cls.setup_class_() + # super(cls, cls).setup_class_() + # CheckTuckeyHSD.setup_class_() + cls.meandiff2 = sas_["mean"] + cls.confint2 = sas_[["lower", "upper"]].astype(float).values.reshape((3, 2)) + cls.reject2 = sas_["sig"] == asbytes("***") + + +class TestTuckeyHSD4(CheckTuckeyHSDMixin): + + @classmethod + def setup_class(cls): + # unbalanced case verified in Matlab + cls.endog = cylinders + cls.groups = cyl_labels + cls.alpha = 0.05 + cls.setup_class_() + cls.res._simultaneous_ci() + + # from Matlab + cls.halfwidth2 = np.array( + [ + 1.5228335685980883, + 0.9794949704444682, + 0.78673802805533644, + 2.3321237694566364, + 0.57355135882752939, + ] + ) + cls.meandiff2 = np.array( + [ + 0.22222222222222232, + 0.13333333333333375, + 0.0, + 2.2898550724637685, + -0.088888888888888573, + -0.22222222222222232, + 2.0676328502415462, + -0.13333333333333375, + 2.1565217391304348, + 2.2898550724637685, + ] + ) + cls.confint2 = np.array( + [ + -2.32022210717, + 2.76466655161, + -2.247517583, + 2.51418424967, + -3.66405224956, + 3.66405224956, + 0.113960166573, + 4.46574997835, + -1.87278583908, + 1.6950080613, + -3.529655688, + 3.08521124356, + 0.568180988881, + 3.5670847116, + -3.31822643175, + 3.05155976508, + 0.951206924521, + 3.36183655374, + -0.74487911754, + 5.32458926247, + ] + ).reshape(10, 2) + cls.reject2 = np.array( + [False, False, False, True, False, False, True, False, True, False] + ) + + def test_hochberg_intervals(self): + assert_almost_equal(self.res.halfwidths, self.halfwidth2, 4) + + +@pytest.mark.smoke +@pytest.mark.thread_unsafe(reason="Uses matplotlib") +@pytest.mark.matplotlib +def test_plot(close_figures): + # SMOKE test + cylinders_adj = cylinders.astype(float) + # avoid zero division, zero within variance in France and Sweden + cylinders_adj[[10, 28]] += 0.05 + alpha = 0.05 + mc = MultiComparison(cylinders_adj, cyl_labels) + resth = mc.tukeyhsd(alpha=alpha, use_var="equal") + resgh = mc.tukeyhsd(alpha=alpha, use_var="unequal") + resth.plot_simultaneous() + resgh.plot_simultaneous() + + +def test_tukeyhsd_invalid_use_var_raises(): + cylinders_adj = cylinders.astype(float) + cylinders_adj[[10, 28]] += 0.05 + mc = MultiComparison(cylinders_adj, cyl_labels) + with pytest.raises(ValueError, match="use_var"): + mc.tukeyhsd(use_var="not-a-use-var") diff --git a/shared/package-files/73/7327baf9523b271bdbe090df6b547f7fbb251038d85147cce1e74567f7b45e21/_test_internal.pyi b/shared/package-files/73/7327baf9523b271bdbe090df6b547f7fbb251038d85147cce1e74567f7b45e21/_test_internal.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1e6c272f16fa2bd3ae75af412bc6ae3270158ce4 --- /dev/null +++ b/shared/package-files/73/7327baf9523b271bdbe090df6b547f7fbb251038d85147cce1e74567f7b45e21/_test_internal.pyi @@ -0,0 +1,9 @@ +import numpy as np + +def have_fenv() -> bool: ... +def random_double(size: int, rng: np.random.RandomState) -> np.float64: ... +def test_add_round(size: int, mode: str, rng: np.random.RandomState): ... + +def _dd_exp(xhi: float, xlo: float) -> tuple[float, float]: ... +def _dd_log(xhi: float, xlo: float) -> tuple[float, float]: ... +def _dd_expm1(xhi: float, xlo: float) -> tuple[float, float]: ... diff --git a/shared/package-files/73/732a4839e33f81ae0871811725f91ef741cd2c9d5b1e684cfae521e76c10111e/estimator.css b/shared/package-files/73/732a4839e33f81ae0871811725f91ef741cd2c9d5b1e684cfae521e76c10111e/estimator.css new file mode 100644 index 0000000000000000000000000000000000000000..ece8781c6bd76af4d3350b476430d6ecf2c9ed4c --- /dev/null +++ b/shared/package-files/73/732a4839e33f81ae0871811725f91ef741cd2c9d5b1e684cfae521e76c10111e/estimator.css @@ -0,0 +1,413 @@ +#$id { + /* Definition of color scheme common for light and dark mode */ + --sklearn-color-text: #000; + --sklearn-color-text-muted: #666; + --sklearn-color-line: gray; + /* Definition of color scheme for unfitted estimators */ + --sklearn-color-unfitted-level-0: #fff5e6; + --sklearn-color-unfitted-level-1: #f6e4d2; + --sklearn-color-unfitted-level-2: #ffe0b3; + --sklearn-color-unfitted-level-3: chocolate; + /* Definition of color scheme for fitted estimators */ + --sklearn-color-fitted-level-0: #f0f8ff; + --sklearn-color-fitted-level-1: #d4ebff; + --sklearn-color-fitted-level-2: #b3dbfd; + --sklearn-color-fitted-level-3: cornflowerblue; + + /* Specific color for light theme */ + --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black))); + --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white))); + --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black))); + --sklearn-color-icon: #696969; + + @media (prefers-color-scheme: dark) { + /* Redefinition of color scheme for dark theme */ + --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white))); + --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111))); + --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white))); + --sklearn-color-icon: #878787; + } +} + +#$id { + color: var(--sklearn-color-text); +} + +#$id pre { + padding: 0; +} + +#$id input.sk-hidden--visually { + border: 0; + clip: rect(1px 1px 1px 1px); + clip: rect(1px, 1px, 1px, 1px); + height: 1px; + margin: -1px; + overflow: hidden; + padding: 0; + position: absolute; + width: 1px; +} + +#$id div.sk-dashed-wrapped { + border: 1px dashed var(--sklearn-color-line); + margin: 0 0.4em 0.5em 0.4em; + box-sizing: border-box; + padding-bottom: 0.4em; + background-color: var(--sklearn-color-background); +} + +#$id div.sk-container { + /* jupyter's `normalize.less` sets `[hidden] { display: none; }` + but bootstrap.min.css set `[hidden] { display: none !important; }` + so we also need the `!important` here to be able to override the + default hidden behavior on the sphinx rendered scikit-learn.org. + See: https://github.com/scikit-learn/scikit-learn/issues/21755 */ + display: inline-block !important; + position: relative; +} + +#$id div.sk-text-repr-fallback { + display: none; +} + +div.sk-parallel-item, +div.sk-serial, +div.sk-item { + /* draw centered vertical line to link estimators */ + background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background)); + background-size: 2px 100%; + background-repeat: no-repeat; + background-position: center center; +} + +/* Parallel-specific style estimator block */ + +#$id div.sk-parallel-item::after { + content: ""; + width: 100%; + border-bottom: 2px solid var(--sklearn-color-text-on-default-background); + flex-grow: 1; +} + +#$id div.sk-parallel { + display: flex; + align-items: stretch; + justify-content: center; + background-color: var(--sklearn-color-background); + position: relative; +} + +#$id div.sk-parallel-item { + display: flex; + flex-direction: column; +} + +#$id div.sk-parallel-item:first-child::after { + align-self: flex-end; + width: 50%; +} + +#$id div.sk-parallel-item:last-child::after { + align-self: flex-start; + width: 50%; +} + +#$id div.sk-parallel-item:only-child::after { + width: 0; +} + +/* Serial-specific style estimator block */ + +#$id div.sk-serial { + display: flex; + flex-direction: column; + align-items: center; + background-color: var(--sklearn-color-background); + padding-right: 1em; + padding-left: 1em; +} + + +/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is +clickable and can be expanded/collapsed. +- Pipeline and ColumnTransformer use this feature and define the default style +- Estimators will overwrite some part of the style using the `sk-estimator` class +*/ + +/* Pipeline and ColumnTransformer style (default) */ + +#$id div.sk-toggleable { + /* Default theme specific background. It is overwritten whether we have a + specific estimator or a Pipeline/ColumnTransformer */ + background-color: var(--sklearn-color-background); +} + +/* Toggleable label */ +#$id label.sk-toggleable__label { + cursor: pointer; + display: flex; + width: 100%; + margin-bottom: 0; + padding: 0.5em; + box-sizing: border-box; + text-align: center; + align-items: start; + justify-content: space-between; + gap: 0.5em; +} + +#$id label.sk-toggleable__label .caption { + font-size: 0.6rem; + font-weight: lighter; + color: var(--sklearn-color-text-muted); +} + +#$id label.sk-toggleable__label-arrow:before { + /* Arrow on the left of the label */ + content: "▸"; + float: left; + margin-right: 0.25em; + color: var(--sklearn-color-icon); +} + +#$id label.sk-toggleable__label-arrow:hover:before { + color: var(--sklearn-color-text); +} + +/* Toggleable content - dropdown */ + +#$id div.sk-toggleable__content { + display: none; + text-align: left; + /* unfitted */ + background-color: var(--sklearn-color-unfitted-level-0); +} + +#$id div.sk-toggleable__content.fitted { + /* fitted */ + background-color: var(--sklearn-color-fitted-level-0); +} + +#$id div.sk-toggleable__content pre { + margin: 0.2em; + border-radius: 0.25em; + color: var(--sklearn-color-text); + /* unfitted */ + background-color: var(--sklearn-color-unfitted-level-0); +} + +#$id div.sk-toggleable__content.fitted pre { + /* unfitted */ + background-color: var(--sklearn-color-fitted-level-0); +} + +#$id input.sk-toggleable__control:checked~div.sk-toggleable__content { + /* Expand drop-down */ + display: block; + width: 100%; + overflow: visible; +} + +#$id input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before { + content: "▾"; +} + +/* Pipeline/ColumnTransformer-specific style */ + +#$id div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label { + color: var(--sklearn-color-text); + background-color: var(--sklearn-color-unfitted-level-2); +} + +#$id div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label { + background-color: var(--sklearn-color-fitted-level-2); +} + +/* Estimator-specific style */ + +/* Colorize estimator box */ +#$id div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label { + /* unfitted */ + background-color: var(--sklearn-color-unfitted-level-2); +} + +#$id div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label { + /* fitted */ + background-color: var(--sklearn-color-fitted-level-2); +} + +#$id div.sk-label label.sk-toggleable__label, +#$id div.sk-label label { + /* The background is the default theme color */ + color: var(--sklearn-color-text-on-default-background); +} + +/* On hover, darken the color of the background */ +#$id div.sk-label:hover label.sk-toggleable__label { + color: var(--sklearn-color-text); + background-color: var(--sklearn-color-unfitted-level-2); +} + +/* Label box, darken color on hover, fitted */ +#$id div.sk-label.fitted:hover label.sk-toggleable__label.fitted { + color: var(--sklearn-color-text); + background-color: var(--sklearn-color-fitted-level-2); +} + +/* Estimator label */ + +#$id div.sk-label label { + font-family: monospace; + font-weight: bold; + display: inline-block; + line-height: 1.2em; +} + +#$id div.sk-label-container { + text-align: center; +} + +/* Estimator-specific */ +#$id div.sk-estimator { + font-family: monospace; + border: 1px dotted var(--sklearn-color-border-box); + border-radius: 0.25em; + box-sizing: border-box; + margin-bottom: 0.5em; + /* unfitted */ + background-color: var(--sklearn-color-unfitted-level-0); +} + +#$id div.sk-estimator.fitted { + /* fitted */ + background-color: var(--sklearn-color-fitted-level-0); +} + +/* on hover */ +#$id div.sk-estimator:hover { + /* unfitted */ + background-color: var(--sklearn-color-unfitted-level-2); +} + +#$id div.sk-estimator.fitted:hover { + /* fitted */ + background-color: var(--sklearn-color-fitted-level-2); +} + +/* Specification for estimator info (e.g. "i" and "?") */ + +/* Common style for "i" and "?" */ + +.sk-estimator-doc-link, +a:link.sk-estimator-doc-link, +a:visited.sk-estimator-doc-link { + float: right; + font-size: smaller; + line-height: 1em; + font-family: monospace; + background-color: var(--sklearn-color-background); + border-radius: 1em; + height: 1em; + width: 1em; + text-decoration: none !important; + margin-left: 0.5em; + text-align: center; + /* unfitted */ + border: var(--sklearn-color-unfitted-level-1) 1pt solid; + color: var(--sklearn-color-unfitted-level-1); +} + +.sk-estimator-doc-link.fitted, +a:link.sk-estimator-doc-link.fitted, +a:visited.sk-estimator-doc-link.fitted { + /* fitted */ + border: var(--sklearn-color-fitted-level-1) 1pt solid; + color: var(--sklearn-color-fitted-level-1); +} + +/* On hover */ +div.sk-estimator:hover .sk-estimator-doc-link:hover, +.sk-estimator-doc-link:hover, +div.sk-label-container:hover .sk-estimator-doc-link:hover, +.sk-estimator-doc-link:hover { + /* unfitted */ + background-color: var(--sklearn-color-unfitted-level-3); + color: var(--sklearn-color-background); + text-decoration: none; +} + +div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover, +.sk-estimator-doc-link.fitted:hover, +div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover, +.sk-estimator-doc-link.fitted:hover { + /* fitted */ + background-color: var(--sklearn-color-fitted-level-3); + color: var(--sklearn-color-background); + text-decoration: none; +} + +/* Span, style for the box shown on hovering the info icon */ +.sk-estimator-doc-link span { + display: none; + z-index: 9999; + position: relative; + font-weight: normal; + right: .2ex; + padding: .5ex; + margin: .5ex; + width: min-content; + min-width: 20ex; + max-width: 50ex; + color: var(--sklearn-color-text); + box-shadow: 2pt 2pt 4pt #999; + /* unfitted */ + background: var(--sklearn-color-unfitted-level-0); + border: .5pt solid var(--sklearn-color-unfitted-level-3); +} + +.sk-estimator-doc-link.fitted span { + /* fitted */ + background: var(--sklearn-color-fitted-level-0); + border: var(--sklearn-color-fitted-level-3); +} + +.sk-estimator-doc-link:hover span { + display: block; +} + +/* "?"-specific style due to the `` HTML tag */ + +#$id a.estimator_doc_link { + float: right; + font-size: 1rem; + line-height: 1em; + font-family: monospace; + background-color: var(--sklearn-color-background); + border-radius: 1rem; + height: 1rem; + width: 1rem; + text-decoration: none; + /* unfitted */ + color: var(--sklearn-color-unfitted-level-1); + border: var(--sklearn-color-unfitted-level-1) 1pt solid; +} + +#$id a.estimator_doc_link.fitted { + /* fitted */ + border: var(--sklearn-color-fitted-level-1) 1pt solid; + color: var(--sklearn-color-fitted-level-1); +} + +/* On hover */ +#$id a.estimator_doc_link:hover { + /* unfitted */ + background-color: var(--sklearn-color-unfitted-level-3); + color: var(--sklearn-color-background); + text-decoration: none; +} + +#$id a.estimator_doc_link.fitted:hover { + /* fitted */ + background-color: var(--sklearn-color-fitted-level-3); +} diff --git a/shared/package-files/73/732ac54da87bb847121a6cd0a6f71cc65328b9c5e131ba7cb582a83211a7919c/exp_meta.h b/shared/package-files/73/732ac54da87bb847121a6cd0a6f71cc65328b9c5e131ba7cb582a83211a7919c/exp_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..0fb15f44bc794f0c59bced73b98ff5b967ac35da --- /dev/null +++ b/shared/package-files/73/732ac54da87bb847121a6cd0a6f71cc65328b9c5e131ba7cb582a83211a7919c/exp_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_exp : public TensorIteratorBase { + + + void meta(const at::Tensor & self); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/73/732b34b561a2d5508f58c4d9b8a69d70dfdb4e8cff6ea2ac0c7484573b95dc21/medium.py b/shared/package-files/73/732b34b561a2d5508f58c4d9b8a69d70dfdb4e8cff6ea2ac0c7484573b95dc21/medium.py new file mode 100644 index 0000000000000000000000000000000000000000..764b68caad5865b8f3cee028a14cfa304796b4c0 --- /dev/null +++ b/shared/package-files/73/732b34b561a2d5508f58c4d9b8a69d70dfdb4e8cff6ea2ac0c7484573b95dc21/medium.py @@ -0,0 +1,253 @@ +""" +**Contains** + +* Medium +""" +from sympy.physics.units import second, meter, kilogram, ampere + +__all__ = ['Medium'] + +from sympy.core.basic import Basic +from sympy.core.symbol import Str +from sympy.core.sympify import _sympify +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.physics.units import speed_of_light, u0, e0 + + +c = speed_of_light.convert_to(meter/second) +_e0mksa = e0.convert_to(ampere**2*second**4/(kilogram*meter**3)) +_u0mksa = u0.convert_to(meter*kilogram/(ampere**2*second**2)) + + +class Medium(Basic): + + """ + This class represents an optical medium. The prime reason to implement this is + to facilitate refraction, Fermat's principle, etc. + + Explanation + =========== + + An optical medium is a material through which electromagnetic waves propagate. + The permittivity and permeability of the medium define how electromagnetic + waves propagate in it. + + + Parameters + ========== + + name: string + The display name of the Medium. + + permittivity: Sympifyable + Electric permittivity of the space. + + permeability: Sympifyable + Magnetic permeability of the space. + + n: Sympifyable + Index of refraction of the medium. + + + Examples + ======== + + >>> from sympy.abc import epsilon, mu + >>> from sympy.physics.optics import Medium + >>> m1 = Medium('m1') + >>> m2 = Medium('m2', epsilon, mu) + >>> m1.intrinsic_impedance + 149896229*pi*kilogram*meter**2/(1250000*ampere**2*second**3) + >>> m2.refractive_index + 299792458*meter*sqrt(epsilon*mu)/second + + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Optical_medium + + """ + + def __new__(cls, name, permittivity=None, permeability=None, n=None): + if not isinstance(name, Str): + name = Str(name) + + permittivity = _sympify(permittivity) if permittivity is not None else permittivity + permeability = _sympify(permeability) if permeability is not None else permeability + n = _sympify(n) if n is not None else n + + if n is not None: + if permittivity is not None and permeability is None: + permeability = n**2/(c**2*permittivity) + return MediumPP(name, permittivity, permeability) + elif permeability is not None and permittivity is None: + permittivity = n**2/(c**2*permeability) + return MediumPP(name, permittivity, permeability) + elif permittivity is not None and permittivity is not None: + raise ValueError("Specifying all of permittivity, permeability, and n is not allowed") + else: + return MediumN(name, n) + elif permittivity is not None and permeability is not None: + return MediumPP(name, permittivity, permeability) + elif permittivity is None and permeability is None: + return MediumPP(name, _e0mksa, _u0mksa) + else: + raise ValueError("Arguments are underspecified. Either specify n or any two of permittivity, " + "permeability, and n") + + @property + def name(self): + return self.args[0] + + @property + def speed(self): + """ + Returns speed of the electromagnetic wave travelling in the medium. + + Examples + ======== + + >>> from sympy.physics.optics import Medium + >>> m = Medium('m') + >>> m.speed + 299792458*meter/second + >>> m2 = Medium('m2', n=1) + >>> m.speed == m2.speed + True + + """ + return c / self.n + + @property + def refractive_index(self): + """ + Returns refractive index of the medium. + + Examples + ======== + + >>> from sympy.physics.optics import Medium + >>> m = Medium('m') + >>> m.refractive_index + 1 + + """ + return (c/self.speed) + + +class MediumN(Medium): + + """ + Represents an optical medium for which only the refractive index is known. + Useful for simple ray optics. + + This class should never be instantiated directly. + Instead it should be instantiated indirectly by instantiating Medium with + only n specified. + + Examples + ======== + >>> from sympy.physics.optics import Medium + >>> m = Medium('m', n=2) + >>> m + MediumN(Str('m'), 2) + """ + + def __new__(cls, name, n): + obj = super(Medium, cls).__new__(cls, name, n) + return obj + + @property + def n(self): + return self.args[1] + + +class MediumPP(Medium): + """ + Represents an optical medium for which the permittivity and permeability are known. + + This class should never be instantiated directly. Instead it should be + instantiated indirectly by instantiating Medium with any two of + permittivity, permeability, and n specified, or by not specifying any + of permittivity, permeability, or n, in which case default values for + permittivity and permeability will be used. + + Examples + ======== + >>> from sympy.physics.optics import Medium + >>> from sympy.abc import epsilon, mu + >>> m1 = Medium('m1', permittivity=epsilon, permeability=mu) + >>> m1 + MediumPP(Str('m1'), epsilon, mu) + >>> m2 = Medium('m2') + >>> m2 + MediumPP(Str('m2'), 625000*ampere**2*second**4/(22468879468420441*pi*kilogram*meter**3), pi*kilogram*meter/(2500000*ampere**2*second**2)) + """ + + + def __new__(cls, name, permittivity, permeability): + obj = super(Medium, cls).__new__(cls, name, permittivity, permeability) + return obj + + @property + def intrinsic_impedance(self): + """ + Returns intrinsic impedance of the medium. + + Explanation + =========== + + The intrinsic impedance of a medium is the ratio of the + transverse components of the electric and magnetic fields + of the electromagnetic wave travelling in the medium. + In a region with no electrical conductivity it simplifies + to the square root of ratio of magnetic permeability to + electric permittivity. + + Examples + ======== + + >>> from sympy.physics.optics import Medium + >>> m = Medium('m') + >>> m.intrinsic_impedance + 149896229*pi*kilogram*meter**2/(1250000*ampere**2*second**3) + + """ + return sqrt(self.permeability / self.permittivity) + + @property + def permittivity(self): + """ + Returns electric permittivity of the medium. + + Examples + ======== + + >>> from sympy.physics.optics import Medium + >>> m = Medium('m') + >>> m.permittivity + 625000*ampere**2*second**4/(22468879468420441*pi*kilogram*meter**3) + + """ + return self.args[1] + + @property + def permeability(self): + """ + Returns magnetic permeability of the medium. + + Examples + ======== + + >>> from sympy.physics.optics import Medium + >>> m = Medium('m') + >>> m.permeability + pi*kilogram*meter/(2500000*ampere**2*second**2) + + """ + return self.args[2] + + @property + def n(self): + return c*sqrt(self.permittivity*self.permeability) diff --git a/shared/package-files/73/732b7379b4b75bb145afda9e27d805487abf6cec1493d6915655d61df9d5ad1b/TLSA.py b/shared/package-files/73/732b7379b4b75bb145afda9e27d805487abf6cec1493d6915655d61df9d5ad1b/TLSA.py new file mode 100644 index 0000000000000000000000000000000000000000..4dffc5534c9a218f82552acc572d06d346a6b07e --- /dev/null +++ b/shared/package-files/73/732b7379b4b75bb145afda9e27d805487abf6cec1493d6915655d61df9d5ad1b/TLSA.py @@ -0,0 +1,9 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import dns.immutable +import dns.rdtypes.tlsabase + + +@dns.immutable.immutable +class TLSA(dns.rdtypes.tlsabase.TLSABase): + """TLSA record""" diff --git a/shared/package-files/73/732f891d986178fd9cd3387646ddb4bfd70e8c5c5ab72abf73aba1b8f2a26ad7/_load_setup_py_data.py b/shared/package-files/73/732f891d986178fd9cd3387646ddb4bfd70e8c5c5ab72abf73aba1b8f2a26ad7/_load_setup_py_data.py new file mode 100644 index 0000000000000000000000000000000000000000..9180c404fccefa44a69310ac37f62a69b4e73ccf --- /dev/null +++ b/shared/package-files/73/732f891d986178fd9cd3387646ddb4bfd70e8c5c5ab72abf73aba1b8f2a26ad7/_load_setup_py_data.py @@ -0,0 +1,168 @@ +# Copyright (C) 2014 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +import logging +import os +import sys + + +def load_setup_py_data( + setup_file, + from_recipe_dir=False, + recipe_dir=None, + work_dir=None, + permit_undefined_jinja=True, +): + _setuptools_data = {} + log = logging.getLogger(__name__) + + import distutils.core + + import setuptools + + cd_to_work = False + path_backup = sys.path + + def _change_cwd(target_dir): + cd_to_work = True + try: + cwd = os.getcwd() + except OSError: + cwd = recipe_dir or work_dir + os.chdir(target_dir) + # this is very important - or else if versioneer or otherwise is in the start folder, + # things will pick up the wrong versioneer/whatever! + sys.path.insert(0, target_dir) + return cd_to_work, cwd + + if from_recipe_dir and recipe_dir: + setup_file = os.path.abspath(os.path.join(recipe_dir, setup_file)) + # if the setup_file is not in the recipe dir itself, but is say specified as '../setup.py' + setup_root, _ = os.path.split(setup_file) + if os.path.abspath(setup_root) != os.path.abspath(recipe_dir): + cd_to_work, cwd = _change_cwd(setup_root) + elif os.path.exists(work_dir): + cd_to_work, cwd = _change_cwd(work_dir) + if not os.path.isabs(setup_file): + setup_file = os.path.join(work_dir, setup_file) + else: + message = ( + "Did not find setup.py file in manually specified location, and source " + "not downloaded yet." + ) + if permit_undefined_jinja: + log.debug(message) + return {} + else: + raise RuntimeError(message) + + setup_cfg_data = {} + try: + try: + # Recommended for setuptools 61.0.0+ + # (though may disappear in the future) + from setuptools.config.setupcfg import read_configuration + except ImportError: + from setuptools.config import read_configuration + except ImportError: + pass # setuptools <30.3.0 cannot read metadata / options from 'setup.cfg' + else: + setup_cfg = os.path.join(os.path.dirname(setup_file), "setup.cfg") + if os.path.isfile(setup_cfg): + # read_configuration returns a dict of dicts. Each dict (keys: 'metadata', + # 'options'), if present, provides keyword arguments for the setup function. + for kwargs in read_configuration(setup_cfg).values(): + # explicit arguments to setup.cfg take priority over values in setup.py + setup_cfg_data.update(kwargs) + + def setup(**kw): + _setuptools_data.update(kw) + # values in setup.cfg take priority over explicit arguments to setup.py + _setuptools_data.update(setup_cfg_data) + + # Patch setuptools, distutils + setuptools_setup = setuptools.setup + distutils_setup = distutils.core.setup + numpy_setup = None + + versioneer = None + if "versioneer" in sys.modules: + versioneer = sys.modules["versioneer"] + del sys.modules["versioneer"] + + try: + # numpy.distutils deprecated in Python 3.12+ + # see https://numpy.org/doc/stable/reference/distutils_status_migration.html + import numpy.distutils.core + + numpy_setup = numpy.distutils.core.setup + numpy.distutils.core.setup = setup + except ImportError: + log.debug("Failed to import numpy for setup patch. Is numpy installed?") + + setuptools.setup = distutils.core.setup = setup + ns = { + "__name__": "__main__", + "__doc__": None, + "__file__": setup_file, + } + if os.path.isfile(setup_file): + with open(setup_file) as f: + code = compile(f.read(), setup_file, "exec", dont_inherit=1) + exec(code, ns, ns) + else: + if not permit_undefined_jinja: + raise TypeError(f"{setup_file} is not a file that can be read") + + sys.modules["versioneer"] = versioneer + + distutils.core.setup = distutils_setup + setuptools.setup = setuptools_setup + if numpy_setup: + numpy.distutils.core.setup = numpy_setup + + if cd_to_work: + os.chdir(cwd) + # remove our workdir from sys.path + sys.path = path_backup + return _setuptools_data + + +if __name__ == "__main__": + import argparse + import json + + parser = argparse.ArgumentParser(description="run setup.py file to obtain metadata") + parser.add_argument( + "work_dir", + help=( + "path to work dir, where we'll write the output data " + "json, and potentially also where setup.py should be found" + ), + ) + parser.add_argument("setup_file", help="path or filename of setup.py file") + parser.add_argument( + "--from-recipe-dir", + help="look for setup.py file in recipe dir (as opposed to work dir)", + default=False, + action="store_true", + ) + parser.add_argument( + "--recipe-dir", + help="(optional) path to recipe dir, where setup.py should be found", + ) + + parser.add_argument( + "--permit-undefined-jinja", + help="look for setup.py file in recipe dir (as opposed to work dir)", + default=False, + action="store_true", + ) + args = parser.parse_args() + # we get back a dict of the setup data + data = load_setup_py_data(**args.__dict__) + with open( + os.path.join(args.work_dir, "conda_build_loaded_setup_py.json"), "w" + ) as f: + # this is lossy. Anything that can't be serialized is either forced to None or + # removed completely. + json.dump(data, f, skipkeys=True, default=lambda x: None) diff --git a/shared/package-files/73/732fbe76195ab4219a07bf1dbb5974d48fad3fe79bdaf69780b715506feb7f12/special_bessel_j0_ops.h b/shared/package-files/73/732fbe76195ab4219a07bf1dbb5974d48fad3fe79bdaf69780b715506feb7f12/special_bessel_j0_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..312e2cc9753e03daf126579019b7173ca6ce4fee --- /dev/null +++ b/shared/package-files/73/732fbe76195ab4219a07bf1dbb5974d48fad3fe79bdaf69780b715506feb7f12/special_bessel_j0_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API special_bessel_j0 { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::special_bessel_j0") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_bessel_j0(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API special_bessel_j0_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::special_bessel_j0") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_bessel_j0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/73/73302d00c50e9047b47cd1fab6eee1501c0a4d87d86f99c9d4aa1717a7564fa0/comm_tensor.py b/shared/package-files/73/73302d00c50e9047b47cd1fab6eee1501c0a4d87d86f99c9d4aa1717a7564fa0/comm_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..292f5b2508612fdebda008e42e5260b97f1e2c07 --- /dev/null +++ b/shared/package-files/73/73302d00c50e9047b47cd1fab6eee1501c0a4d87d86f99c9d4aa1717a7564fa0/comm_tensor.py @@ -0,0 +1,247 @@ +from dataclasses import dataclass +from functools import partial +from typing import Any, List, Optional, Tuple + +import torch +from torch._C import _disabled_torch_function_impl +from torch.fx.experimental.proxy_tensor import ( + _ProxyTensor, + fetch_object_proxy, + get_innermost_proxy_mode, + get_proxy_slot, + set_proxy_slot, + track_tensor_tree, +) +from torch.utils import _pytree as pytree +from torch.utils._mode_utils import no_dispatch +from torch.utils._pytree import tree_flatten, tree_map, tree_map_only + + +@dataclass +class _CommResult: + # a custom type wrapping both inplace output tensor and work handle + _tensor: torch.Tensor + _work: torch.distributed._Work + + +def _wait_comm(comm_result: _CommResult): + # This function is only used by tracing mode as a call_function node right + # before consuming a collective result tensor. + comm_result._work.wait() + return comm_result._tensor + + +def _wrap_comm_result(result: Tuple[Any, Any]) -> Tuple[Any, Any]: + def wrap(work, e): + assert isinstance(e, torch.Tensor), ( + "Excepting collection of tensors as the first element in the " + "return value of communication operations." + ) + + return _CommResult(e, work) + + # E.g., + # allreduce_ returns ([tensor], work) + # allgather_ returns ([[tensor1, tensor2]], work) + work = result[1] + return (tree_map(partial(wrap, work), result[0]), work) + + +def _get_tracer() -> Optional[torch.fx.Tracer]: + mode = get_innermost_proxy_mode() + if mode is None: + return None + return mode.tracer + + +class CommTensor(torch.Tensor): + r""" + A Tensor subclass to wrap input tensors for collective communications. + + This Tensor subclass works for both eager and tracing mode. + In eager mode, it will record whether the inplace collective communication + has been launched using this Tensor and remember the corresponding work + handle. If yes, it will explicitly call wait() in the ``__torch_dispatch__`` + function before subsequent operations consuming the value of the Tensor. + + In tracing mode, ``CommTensor`` inserts two node into the graph using the + ``__torch_dispatch__`` function. + 1. The first node is inserted right after the + communication, wrapping both the inplace output tensor and the returned + work handle into a custom ``_CommResult`` type. We have to do this because + ``ProxyTorchDispatchMode`` only handles ``torch.Tensor``, ``_ProxyTensor``, + and ``torch.nn.Parameter`` objects and will treat the work handle + as a constant and embed that into the graph. As a result, during execution, + it will use the work handle created during tracing and will lead to wrong + result. The solution in this test is to manually create a proxy on the + return value of ``allreduce_`` which is ``([tensor], work)``, and wrap that + to ``[(_CommResult(tensor, work)), work]``. In this way, subsequent nodes can + directly consume ``_CommResult``. + 2. The second node is inserted right before any subsequent node reads from + ``_CommResult``. It will call ``wait()`` on the stashed work handle to ensure + that computation waits for communication. + """ + + _supported_comms: List[str] = [ + "_allgather_base_", + "_reduce_scatter_base_", + "allreduce_", + "allgather_", + "alltoall_", + "broadcast_", + "reduce_scatter_", + "scatter_", + ] + + _tensor: torch.Tensor + _work: Optional[torch.distributed._Work] + + @staticmethod + def __new__(cls, tensor: torch.Tensor): + t = tensor._tensor if isinstance(tensor, CommTensor) else tensor + if get_innermost_proxy_mode() is None: + # noop for eager mode + return tensor + + # Use non-CommTensor to avoid nested CommTensor Wrapping + r = torch.Tensor._make_subclass(cls, t, require_grad=t.requires_grad) + # The tensor object wrapped by this CommTensor + # NB: THIS CAN BE A CommTensor; see test_nested_comm_tensor_wrapping + r._tensor = tensor # type: ignore[attr-defined] + # Record the LAST `work` object returned by collective communication + # operations. If this is None, it means no collectives have called + # since last time a tensor is wrapped by CommTensor + r._work = None # type: ignore[attr-defined] + return r + + def __repr__(self): + return f"CommTensor({self._tensor}, work={self._work})" + + # disable __torch_function__ so that CommTensor can recursively dispatch + # with ProxyTorchDispatchMode in make_fx + __torch_function__ = _disabled_torch_function_impl + + @classmethod + def _is_supported(cls, op_name): + return any(comm in op_name for comm in cls._supported_comms) + + @classmethod + def __torch_dispatch__(cls, func, types, args=(), kwargs=None): + # shared states when unwrapping args + tracer: Optional[torch.fx.Tracer] = None + work: Optional[torch.distributed._Work] = None + + # wrapped ._tensor if this is a CommTensor, and insert/call wait() + # if communication has been launched on this tensor. + def unwrap(e: Any): + if isinstance(e, CommTensor): + nonlocal tracer, work + + work = e._work + # TODO(ezyang): I don't really understand what's going on + # here, but it seems that tracer doesn't reflect whether or + # not there is ambient tracing going on, but rather, whether + # or not we will trace THIS particular invocation. If we + # have a nested CommTensor, the outer layer doesn't actually + # trace and we only trace the inner layer + if not isinstance(e._tensor, CommTensor): + tracer = _get_tracer() + + if work is not None: + if tracer is not None: + # insert a node to the traced graph. + proxy_res = tracer.create_proxy( # type: ignore[union-attr] + "call_function", + _wait_comm, + (get_proxy_slot(e._tensor, tracer).proxy,), + {}, + name="wait_comm", + ) + # HACK: update the proxy for the inplace output + set_proxy_slot(e._tensor, tracer, proxy_res) + # For eager mode, simply wait. + # During tracing, still need to wait here, to make sure the + # execution during tracing is correct. + work.wait() + + # communication has been waited, stop propagating CommTensor + return e._tensor + else: + return e + + def wrap(e: Any): + return CommTensor(e) if isinstance(e, torch.Tensor) else e + + def set_work(work: torch.distributed._Work, e: Any): + if isinstance(e, CommTensor): + e._work = work # type: ignore[attr-defined] + elif isinstance(e, torch.Tensor): + raise RuntimeError( + "Type of output tensors from collective communication during " + "tracing should always be CommTensor instead of torch.Tensor" + ) + return e + + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + + if cls._is_supported(func.__name__): + if tracer is not None: + # in tracing mode, get proxies for args + proxy_args, proxy_kwargs = tree_map_only( + _ProxyTensor, + lambda e: e.proxy, + tree_map_only( + torch.Tensor, + fetch_object_proxy(tracer), + (unwrapped_args, unwrapped_kwargs), + ), + ) + + # get proxy for output tuple + proxy_res = func(*proxy_args, **proxy_kwargs) + assert isinstance(proxy_res, torch.fx.Proxy) + # insert a node that wraps the output tuple into + # _CommResult(tensor, work) + comm_result_proxy = tracer.create_proxy( # type: ignore[union-attr] + "call_function", + _wrap_comm_result, + (proxy_res,), + {}, + name="comm_result", + ) + + with no_dispatch(): + # disable dispatch to avoid trigger ProxyTorchDispatchMode logic + out = func(*unwrapped_args, **unwrapped_kwargs) + + # wrap output with the proxy of _CommResult, so that subsequent + # ops and link to it. + track_tensor_tree(out, comm_result_proxy, constant=None, tracer=tracer) + + # N.B.: we still need to remember the work handle here, and wait + # for it later to make sure the execution during tracing is + # correct. Also, remember comm is already launched + # args[0] is always the collection of output tensors + pytree.tree_map_(partial(set_work, out[1]), args[0]) + + # HACK: update the proxy on the input argument as this is an + # inplace collective communication. + flat_args, args_spec = tree_flatten(unwrapped_args[0]) + flat_out, out_spec = tree_flatten(out[0]) + for a, o in zip(flat_args, flat_out): + set_proxy_slot(a, tracer, get_proxy_slot(o, tracer)) + + return out + else: + # in eager mode, simply remember work handle as an attribute + out = func(*unwrapped_args, **unwrapped_kwargs) + pytree.tree_map_(partial(set_work, out[1]), args[0]) + return out + else: + if work is not None: + return func(*unwrapped_args, **unwrapped_kwargs) + else: + # we need to propagate CommTensor wrapping until the first + # subsequent operation has waited for it. + return tree_map(wrap, func(*unwrapped_args, **unwrapped_kwargs)) diff --git a/shared/package-files/73/7331a26cbfb8a0fa1fc75a424adfe1ae8ccd6c794e3eba86bfa9bed1dfa24dda/_tokenizer.py b/shared/package-files/73/7331a26cbfb8a0fa1fc75a424adfe1ae8ccd6c794e3eba86bfa9bed1dfa24dda/_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..b1fb207c7f1cc96cec7f17df34e0ecdfd94994a3 --- /dev/null +++ b/shared/package-files/73/7331a26cbfb8a0fa1fc75a424adfe1ae8ccd6c794e3eba86bfa9bed1dfa24dda/_tokenizer.py @@ -0,0 +1,188 @@ +import contextlib +import re +from dataclasses import dataclass +from typing import Dict, Iterator, NoReturn, Optional, Tuple, Union + +from .specifiers import Specifier + + +@dataclass +class Token: + name: str + text: str + position: int + + +class ParserSyntaxError(Exception): + """The provided source text could not be parsed correctly.""" + + def __init__( + self, + message: str, + *, + source: str, + span: Tuple[int, int], + ) -> None: + self.span = span + self.message = message + self.source = source + + super().__init__() + + def __str__(self) -> str: + marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^" + return "\n ".join([self.message, self.source, marker]) + + +DEFAULT_RULES: "Dict[str, Union[str, re.Pattern[str]]]" = { + "LEFT_PARENTHESIS": r"\(", + "RIGHT_PARENTHESIS": r"\)", + "LEFT_BRACKET": r"\[", + "RIGHT_BRACKET": r"\]", + "SEMICOLON": r";", + "COMMA": r",", + "QUOTED_STRING": re.compile( + r""" + ( + ('[^']*') + | + ("[^"]*") + ) + """, + re.VERBOSE, + ), + "OP": r"(===|==|~=|!=|<=|>=|<|>)", + "BOOLOP": r"\b(or|and)\b", + "IN": r"\bin\b", + "NOT": r"\bnot\b", + "VARIABLE": re.compile( + r""" + \b( + python_version + |python_full_version + |os[._]name + |sys[._]platform + |platform_(release|system) + |platform[._](version|machine|python_implementation) + |python_implementation + |implementation_(name|version) + |extra + )\b + """, + re.VERBOSE, + ), + "SPECIFIER": re.compile( + Specifier._operator_regex_str + Specifier._version_regex_str, + re.VERBOSE | re.IGNORECASE, + ), + "AT": r"\@", + "URL": r"[^ \t]+", + "IDENTIFIER": r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b", + "WS": r"[ \t]+", + "END": r"$", +} + + +class Tokenizer: + """Context-sensitive token parsing. + + Provides methods to examine the input stream to check whether the next token + matches. + """ + + def __init__( + self, + source: str, + *, + rules: "Dict[str, Union[str, re.Pattern[str]]]", + ) -> None: + self.source = source + self.rules: Dict[str, re.Pattern[str]] = { + name: re.compile(pattern) for name, pattern in rules.items() + } + self.next_token: Optional[Token] = None + self.position = 0 + + def consume(self, name: str) -> None: + """Move beyond provided token name, if at current position.""" + if self.check(name): + self.read() + + def check(self, name: str, *, peek: bool = False) -> bool: + """Check whether the next token has the provided name. + + By default, if the check succeeds, the token *must* be read before + another check. If `peek` is set to `True`, the token is not loaded and + would need to be checked again. + """ + assert ( + self.next_token is None + ), f"Cannot check for {name!r}, already have {self.next_token!r}" + assert name in self.rules, f"Unknown token name: {name!r}" + + expression = self.rules[name] + + match = expression.match(self.source, self.position) + if match is None: + return False + if not peek: + self.next_token = Token(name, match[0], self.position) + return True + + def expect(self, name: str, *, expected: str) -> Token: + """Expect a certain token name next, failing with a syntax error otherwise. + + The token is *not* read. + """ + if not self.check(name): + raise self.raise_syntax_error(f"Expected {expected}") + return self.read() + + def read(self) -> Token: + """Consume the next token and return it.""" + token = self.next_token + assert token is not None + + self.position += len(token.text) + self.next_token = None + + return token + + def raise_syntax_error( + self, + message: str, + *, + span_start: Optional[int] = None, + span_end: Optional[int] = None, + ) -> NoReturn: + """Raise ParserSyntaxError at the given position.""" + span = ( + self.position if span_start is None else span_start, + self.position if span_end is None else span_end, + ) + raise ParserSyntaxError( + message, + source=self.source, + span=span, + ) + + @contextlib.contextmanager + def enclosing_tokens(self, open_token: str, close_token: str) -> Iterator[bool]: + if self.check(open_token): + open_position = self.position + self.read() + else: + open_position = None + + yield open_position is not None + + if open_position is None: + return + + if not self.check(close_token): + self.raise_syntax_error( + f"Expected closing {close_token}", + span_start=open_position, + ) + + self.read() diff --git a/shared/package-files/73/73342c27cf55f625d3db90c5fc8e7340ffdf85a51872dbfb1d0a8cb1e43ec5da/iso8859-3.enc b/shared/package-files/73/73342c27cf55f625d3db90c5fc8e7340ffdf85a51872dbfb1d0a8cb1e43ec5da/iso8859-3.enc new file mode 100644 index 0000000000000000000000000000000000000000..c914bce7af30184725481de6daf9ec14644fd53f --- /dev/null +++ b/shared/package-files/73/73342c27cf55f625d3db90c5fc8e7340ffdf85a51872dbfb1d0a8cb1e43ec5da/iso8859-3.enc @@ -0,0 +1,20 @@ +# Encoding file: iso8859-3, single-byte +S +003F 0 1 +00 +0000000100020003000400050006000700080009000A000B000C000D000E000F +0010001100120013001400150016001700180019001A001B001C001D001E001F +0020002100220023002400250026002700280029002A002B002C002D002E002F +0030003100320033003400350036003700380039003A003B003C003D003E003F +0040004100420043004400450046004700480049004A004B004C004D004E004F +0050005100520053005400550056005700580059005A005B005C005D005E005F +0060006100620063006400650066006700680069006A006B006C006D006E006F +0070007100720073007400750076007700780079007A007B007C007D007E007F +0080008100820083008400850086008700880089008A008B008C008D008E008F +0090009100920093009400950096009700980099009A009B009C009D009E009F +00A0012602D800A300A40000012400A700A80130015E011E013400AD0000017B +00B0012700B200B300B400B5012500B700B80131015F011F013500BD0000017C +00C000C100C2000000C4010A010800C700C800C900CA00CB00CC00CD00CE00CF +000000D100D200D300D4012000D600D7011C00D900DA00DB00DC016C015C00DF +00E000E100E2000000E4010B010900E700E800E900EA00EB00EC00ED00EE00EF +000000F100F200F300F4012100F600F7011D00F900FA00FB00FC016D015D02D9 diff --git a/shared/package-files/73/733695f21bd8e899e6127daac94dff7f3732fcfe79697553d3d3b31a78494fd2/__init__.py b/shared/package-files/73/733695f21bd8e899e6127daac94dff7f3732fcfe79697553d3d3b31a78494fd2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dcfe1c4237e69054b582a0fa52f710b25a1d7914 --- /dev/null +++ b/shared/package-files/73/733695f21bd8e899e6127daac94dff7f3732fcfe79697553d3d3b31a78494fd2/__init__.py @@ -0,0 +1,28 @@ +""" +Module to read ARFF files +========================= +ARFF is the standard data format for WEKA. +It is a text file format which support numerical, string and data values. +The format can also represent missing data and sparse data. + +Notes +----- +The ARFF support in ``scipy.io`` provides file reading functionality only. +For more extensive ARFF functionality, see `liac-arff +`_. + +See the `WEKA website `_ +for more details about the ARFF format and available datasets. + +""" +from ._arffread import * +from . import _arffread + +# Deprecated namespaces, to be removed in v2.0.0 +from .import arffread + +__all__ = _arffread.__all__ + ['arffread'] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/shared/package-files/73/733a64ac4ba9dea00383b3e02800bff707a0065bf9e5afbbea024c9b42f867f0/test_feather.py b/shared/package-files/73/733a64ac4ba9dea00383b3e02800bff707a0065bf9e5afbbea024c9b42f867f0/test_feather.py new file mode 100644 index 0000000000000000000000000000000000000000..0ab23e3b51a03dbfa1a82151703a996ec7594de7 --- /dev/null +++ b/shared/package-files/73/733a64ac4ba9dea00383b3e02800bff707a0065bf9e5afbbea024c9b42f867f0/test_feather.py @@ -0,0 +1,286 @@ +""" test feather-format compat """ +import numpy as np +import pytest + +from pandas.compat.pyarrow import ( + pa_version_under18p0, + pa_version_under19p0, +) + +import pandas as pd +import pandas._testing as tm + +from pandas.io.feather_format import read_feather, to_feather # isort:skip + +pytestmark = pytest.mark.filterwarnings( + "ignore:Passing a BlockManager to DataFrame:DeprecationWarning" +) + + +pa = pytest.importorskip("pyarrow") + + +@pytest.mark.single_cpu +class TestFeather: + def check_error_on_write(self, df, exc, err_msg): + # check that we are raising the exception + # on writing + + with pytest.raises(exc, match=err_msg): + with tm.ensure_clean() as path: + to_feather(df, path) + + def check_external_error_on_write(self, df): + # check that we are raising the exception + # on writing + + with tm.external_error_raised(Exception): + with tm.ensure_clean() as path: + to_feather(df, path) + + def check_round_trip(self, df, expected=None, write_kwargs={}, **read_kwargs): + if expected is None: + expected = df.copy() + + with tm.ensure_clean() as path: + to_feather(df, path, **write_kwargs) + + result = read_feather(path, **read_kwargs) + + tm.assert_frame_equal(result, expected) + + def test_error(self): + msg = "feather only support IO with DataFrames" + for obj in [ + pd.Series([1, 2, 3]), + 1, + "foo", + pd.Timestamp("20130101"), + np.array([1, 2, 3]), + ]: + self.check_error_on_write(obj, ValueError, msg) + + def test_basic(self): + df = pd.DataFrame( + { + "string": list("abc"), + "int": list(range(1, 4)), + "uint": np.arange(3, 6).astype("u1"), + "float": np.arange(4.0, 7.0, dtype="float64"), + "float_with_null": [1.0, np.nan, 3], + "bool": [True, False, True], + "bool_with_null": [True, np.nan, False], + "cat": pd.Categorical(list("abc")), + "dt": pd.DatetimeIndex( + list(pd.date_range("20130101", periods=3)), freq=None + ), + "dttz": pd.DatetimeIndex( + list(pd.date_range("20130101", periods=3, tz="US/Eastern")), + freq=None, + ), + "dt_with_null": [ + pd.Timestamp("20130101"), + pd.NaT, + pd.Timestamp("20130103"), + ], + "dtns": pd.DatetimeIndex( + list(pd.date_range("20130101", periods=3, freq="ns")), freq=None + ), + } + ) + df["periods"] = pd.period_range("2013", freq="M", periods=3) + df["timedeltas"] = pd.timedelta_range("1 day", periods=3) + df["intervals"] = pd.interval_range(0, 3, 3) + + assert df.dttz.dtype.tz.zone == "US/Eastern" + + expected = df.copy() + expected.loc[1, "bool_with_null"] = None + self.check_round_trip(df, expected=expected) + + def test_duplicate_columns(self): + # https://github.com/wesm/feather/issues/53 + # not currently able to handle duplicate columns + df = pd.DataFrame(np.arange(12).reshape(4, 3), columns=list("aaa")).copy() + self.check_external_error_on_write(df) + + def test_read_columns(self): + # GH 24025 + df = pd.DataFrame( + { + "col1": list("abc"), + "col2": list(range(1, 4)), + "col3": list("xyz"), + "col4": list(range(4, 7)), + } + ) + columns = ["col1", "col3"] + self.check_round_trip(df, expected=df[columns], columns=columns) + + def test_read_columns_different_order(self): + # GH 33878 + df = pd.DataFrame({"A": [1, 2], "B": ["x", "y"], "C": [True, False]}) + expected = df[["B", "A"]] + self.check_round_trip(df, expected, columns=["B", "A"]) + + def test_unsupported_other(self): + # mixed python objects + df = pd.DataFrame({"a": ["a", 1, 2.0]}) + self.check_external_error_on_write(df) + + def test_rw_use_threads(self): + df = pd.DataFrame({"A": np.arange(100000)}) + self.check_round_trip(df, use_threads=True) + self.check_round_trip(df, use_threads=False) + + def test_path_pathlib(self): + df = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD")), + index=pd.Index([f"i-{i}" for i in range(30)]), + ).reset_index() + result = tm.round_trip_pathlib(df.to_feather, read_feather) + tm.assert_frame_equal(df, result) + + def test_path_localpath(self): + df = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD")), + index=pd.Index([f"i-{i}" for i in range(30)]), + ).reset_index() + result = tm.round_trip_localpath(df.to_feather, read_feather) + tm.assert_frame_equal(df, result) + + def test_passthrough_keywords(self): + df = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD")), + index=pd.Index([f"i-{i}" for i in range(30)]), + ).reset_index() + self.check_round_trip(df, write_kwargs={"version": 1}) + + @pytest.mark.network + @pytest.mark.single_cpu + def test_http_path(self, feather_file, httpserver): + # GH 29055 + expected = read_feather(feather_file) + with open(feather_file, "rb") as f: + httpserver.serve_content(content=f.read()) + res = read_feather(httpserver.url) + tm.assert_frame_equal(expected, res) + + def test_read_feather_dtype_backend( + self, string_storage, dtype_backend, using_infer_string + ): + # GH#50765 + df = pd.DataFrame( + { + "a": pd.Series([1, np.nan, 3], dtype="Int64"), + "b": pd.Series([1, 2, 3], dtype="Int64"), + "c": pd.Series([1.5, np.nan, 2.5], dtype="Float64"), + "d": pd.Series([1.5, 2.0, 2.5], dtype="Float64"), + "e": [True, False, None], + "f": [True, False, True], + "g": ["a", "b", "c"], + "h": ["a", "b", None], + } + ) + + with tm.ensure_clean() as path: + to_feather(df, path) + with pd.option_context("mode.string_storage", string_storage): + result = read_feather(path, dtype_backend=dtype_backend) + + if dtype_backend == "pyarrow": + pa = pytest.importorskip("pyarrow") + if using_infer_string: + string_dtype = pd.ArrowDtype(pa.large_string()) + else: + string_dtype = pd.ArrowDtype(pa.string()) + else: + string_dtype = pd.StringDtype(string_storage) + + expected = pd.DataFrame( + { + "a": pd.Series([1, np.nan, 3], dtype="Int64"), + "b": pd.Series([1, 2, 3], dtype="Int64"), + "c": pd.Series([1.5, np.nan, 2.5], dtype="Float64"), + "d": pd.Series([1.5, 2.0, 2.5], dtype="Float64"), + "e": pd.Series([True, False, pd.NA], dtype="boolean"), + "f": pd.Series([True, False, True], dtype="boolean"), + "g": pd.Series(["a", "b", "c"], dtype=string_dtype), + "h": pd.Series(["a", "b", None], dtype=string_dtype), + } + ) + + if dtype_backend == "pyarrow": + from pandas.arrays import ArrowExtensionArray + + expected = pd.DataFrame( + { + col: ArrowExtensionArray(pa.array(expected[col], from_pandas=True)) + for col in expected.columns + } + ) + + if using_infer_string: + expected.columns = expected.columns.astype( + pd.StringDtype(string_storage, na_value=np.nan) + ) + tm.assert_frame_equal(result, expected) + + def test_int_columns_and_index(self): + df = pd.DataFrame({"a": [1, 2, 3]}, index=pd.Index([3, 4, 5], name="test")) + self.check_round_trip(df) + + def test_invalid_dtype_backend(self): + msg = ( + "dtype_backend numpy is invalid, only 'numpy_nullable' and " + "'pyarrow' are allowed." + ) + df = pd.DataFrame({"int": list(range(1, 4))}) + with tm.ensure_clean("tmp.feather") as path: + df.to_feather(path) + with pytest.raises(ValueError, match=msg): + read_feather(path, dtype_backend="numpy") + + def test_string_inference(self, tmp_path, using_infer_string): + # GH#54431 + path = tmp_path / "test_string_inference.p" + df = pd.DataFrame(data={"a": ["x", "y"]}) + df.to_feather(path) + with pd.option_context("future.infer_string", True): + result = read_feather(path) + dtype = pd.StringDtype(na_value=np.nan) + expected = pd.DataFrame( + data={"a": ["x", "y"]}, dtype=pd.StringDtype(na_value=np.nan) + ) + expected = pd.DataFrame( + data={"a": ["x", "y"]}, + dtype=dtype, + columns=pd.Index( + ["a"], + dtype=object + if pa_version_under19p0 and not using_infer_string + else dtype, + ), + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.skipif(pa_version_under18p0, reason="not supported before 18.0") + def test_string_inference_string_view_type(self, tmp_path): + # GH#54798 + import pyarrow as pa + from pyarrow import feather + + path = tmp_path / "string_view.parquet" + table = pa.table({"a": pa.array([None, "b", "c"], pa.string_view())}) + feather.write_feather(table, path) + + with pd.option_context("future.infer_string", True): + result = read_feather(path) + + expected = pd.DataFrame( + data={"a": [None, "b", "c"]}, dtype=pd.StringDtype(na_value=np.nan) + ) + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/73/734661220911abd25fa688678b1b4cfa7d9faedc85d9f476a675058c5111f1f6/test_timestamp.py b/shared/package-files/73/734661220911abd25fa688678b1b4cfa7d9faedc85d9f476a675058c5111f1f6/test_timestamp.py new file mode 100644 index 0000000000000000000000000000000000000000..05e1c93e1a676a977bde93dffcbdb7f389db5f37 --- /dev/null +++ b/shared/package-files/73/734661220911abd25fa688678b1b4cfa7d9faedc85d9f476a675058c5111f1f6/test_timestamp.py @@ -0,0 +1,928 @@ +""" test the scalar Timestamp """ + +import calendar +from datetime import ( + datetime, + timedelta, + timezone, +) +import locale +import time +import unicodedata + +from dateutil.tz import ( + tzlocal, + tzutc, +) +from hypothesis import ( + given, + strategies as st, +) +import numpy as np +import pytest +import pytz +from pytz import utc + +from pandas._libs.tslibs.dtypes import NpyDatetimeUnit +from pandas._libs.tslibs.timezones import ( + dateutil_gettz as gettz, + get_timezone, + maybe_get_tz, + tz_compare, +) +from pandas.compat import IS64 + +from pandas import ( + NaT, + Timedelta, + Timestamp, +) +import pandas._testing as tm + +from pandas.tseries import offsets +from pandas.tseries.frequencies import to_offset + + +class TestTimestampProperties: + def test_properties_business(self): + freq = to_offset("B") + + ts = Timestamp("2017-10-01") + assert ts.dayofweek == 6 + assert ts.day_of_week == 6 + assert ts.is_month_start # not a weekday + assert not freq.is_month_start(ts) + assert freq.is_month_start(ts + Timedelta(days=1)) + assert not freq.is_quarter_start(ts) + assert freq.is_quarter_start(ts + Timedelta(days=1)) + + ts = Timestamp("2017-09-30") + assert ts.dayofweek == 5 + assert ts.day_of_week == 5 + assert ts.is_month_end + assert not freq.is_month_end(ts) + assert freq.is_month_end(ts - Timedelta(days=1)) + assert ts.is_quarter_end + assert not freq.is_quarter_end(ts) + assert freq.is_quarter_end(ts - Timedelta(days=1)) + + @pytest.mark.parametrize( + "attr, expected", + [ + ["year", 2014], + ["month", 12], + ["day", 31], + ["hour", 23], + ["minute", 59], + ["second", 0], + ["microsecond", 0], + ["nanosecond", 0], + ["dayofweek", 2], + ["day_of_week", 2], + ["quarter", 4], + ["dayofyear", 365], + ["day_of_year", 365], + ["week", 1], + ["daysinmonth", 31], + ], + ) + @pytest.mark.parametrize("tz", [None, "US/Eastern"]) + def test_fields(self, attr, expected, tz): + # GH 10050 + # GH 13303 + ts = Timestamp("2014-12-31 23:59:00", tz=tz) + result = getattr(ts, attr) + # that we are int like + assert isinstance(result, int) + assert result == expected + + @pytest.mark.parametrize("tz", [None, "US/Eastern"]) + def test_millisecond_raises(self, tz): + ts = Timestamp("2014-12-31 23:59:00", tz=tz) + msg = "'Timestamp' object has no attribute 'millisecond'" + with pytest.raises(AttributeError, match=msg): + ts.millisecond + + @pytest.mark.parametrize( + "start", ["is_month_start", "is_quarter_start", "is_year_start"] + ) + @pytest.mark.parametrize("tz", [None, "US/Eastern"]) + def test_is_start(self, start, tz): + ts = Timestamp("2014-01-01 00:00:00", tz=tz) + assert getattr(ts, start) + + @pytest.mark.parametrize("end", ["is_month_end", "is_year_end", "is_quarter_end"]) + @pytest.mark.parametrize("tz", [None, "US/Eastern"]) + def test_is_end(self, end, tz): + ts = Timestamp("2014-12-31 23:59:59", tz=tz) + assert getattr(ts, end) + + # GH 12806 + @pytest.mark.parametrize( + "data", + [Timestamp("2017-08-28 23:00:00"), Timestamp("2017-08-28 23:00:00", tz="EST")], + ) + # error: Unsupported operand types for + ("List[None]" and "List[str]") + @pytest.mark.parametrize( + "time_locale", [None] + tm.get_locales() # type: ignore[operator] + ) + def test_names(self, data, time_locale): + # GH 17354 + # Test .day_name(), .month_name + if time_locale is None: + expected_day = "Monday" + expected_month = "August" + else: + with tm.set_locale(time_locale, locale.LC_TIME): + expected_day = calendar.day_name[0].capitalize() + expected_month = calendar.month_name[8].capitalize() + + result_day = data.day_name(time_locale) + result_month = data.month_name(time_locale) + + # Work around https://github.com/pandas-dev/pandas/issues/22342 + # different normalizations + expected_day = unicodedata.normalize("NFD", expected_day) + expected_month = unicodedata.normalize("NFD", expected_month) + + result_day = unicodedata.normalize("NFD", result_day) + result_month = unicodedata.normalize("NFD", result_month) + + assert result_day == expected_day + assert result_month == expected_month + + # Test NaT + nan_ts = Timestamp(NaT) + assert np.isnan(nan_ts.day_name(time_locale)) + assert np.isnan(nan_ts.month_name(time_locale)) + + def test_is_leap_year(self, tz_naive_fixture): + tz = tz_naive_fixture + if not IS64 and tz == tzlocal(): + # https://github.com/dateutil/dateutil/issues/197 + pytest.skip( + "tzlocal() on a 32 bit platform causes internal overflow errors" + ) + # GH 13727 + dt = Timestamp("2000-01-01 00:00:00", tz=tz) + assert dt.is_leap_year + assert isinstance(dt.is_leap_year, bool) + + dt = Timestamp("1999-01-01 00:00:00", tz=tz) + assert not dt.is_leap_year + + dt = Timestamp("2004-01-01 00:00:00", tz=tz) + assert dt.is_leap_year + + dt = Timestamp("2100-01-01 00:00:00", tz=tz) + assert not dt.is_leap_year + + def test_woy_boundary(self): + # make sure weeks at year boundaries are correct + d = datetime(2013, 12, 31) + result = Timestamp(d).week + expected = 1 # ISO standard + assert result == expected + + d = datetime(2008, 12, 28) + result = Timestamp(d).week + expected = 52 # ISO standard + assert result == expected + + d = datetime(2009, 12, 31) + result = Timestamp(d).week + expected = 53 # ISO standard + assert result == expected + + d = datetime(2010, 1, 1) + result = Timestamp(d).week + expected = 53 # ISO standard + assert result == expected + + d = datetime(2010, 1, 3) + result = Timestamp(d).week + expected = 53 # ISO standard + assert result == expected + + result = np.array( + [ + Timestamp(datetime(*args)).week + for args in [(2000, 1, 1), (2000, 1, 2), (2005, 1, 1), (2005, 1, 2)] + ] + ) + assert (result == [52, 52, 53, 53]).all() + + def test_resolution(self): + # GH#21336, GH#21365 + dt = Timestamp("2100-01-01 00:00:00.000000000") + assert dt.resolution == Timedelta(nanoseconds=1) + + # Check that the attribute is available on the class, mirroring + # the stdlib datetime behavior + assert Timestamp.resolution == Timedelta(nanoseconds=1) + + assert dt.as_unit("us").resolution == Timedelta(microseconds=1) + assert dt.as_unit("ms").resolution == Timedelta(milliseconds=1) + assert dt.as_unit("s").resolution == Timedelta(seconds=1) + + @pytest.mark.parametrize( + "date_string, expected", + [ + ("0000-2-29", 1), + ("0000-3-1", 2), + ("1582-10-14", 3), + ("-0040-1-1", 4), + ("2023-06-18", 6), + ], + ) + def test_dow_historic(self, date_string, expected): + # GH 53738 + ts = Timestamp(date_string) + dow = ts.weekday() + assert dow == expected + + @given( + ts=st.datetimes(), + sign=st.sampled_from(["-", ""]), + ) + def test_dow_parametric(self, ts, sign): + # GH 53738 + ts = ( + f"{sign}{str(ts.year).zfill(4)}" + f"-{str(ts.month).zfill(2)}" + f"-{str(ts.day).zfill(2)}" + ) + result = Timestamp(ts).weekday() + expected = ( + (np.datetime64(ts) - np.datetime64("1970-01-01")).astype("int64") - 4 + ) % 7 + assert result == expected + + +class TestTimestamp: + @pytest.mark.parametrize("tz", [None, pytz.timezone("US/Pacific")]) + def test_disallow_setting_tz(self, tz): + # GH#3746 + ts = Timestamp("2010") + msg = "Cannot directly set timezone" + with pytest.raises(AttributeError, match=msg): + ts.tz = tz + + def test_default_to_stdlib_utc(self): + assert Timestamp.utcnow().tz is timezone.utc + assert Timestamp.now("UTC").tz is timezone.utc + assert Timestamp("2016-01-01", tz="UTC").tz is timezone.utc + + def test_tz(self): + tstr = "2014-02-01 09:00" + ts = Timestamp(tstr) + local = ts.tz_localize("Asia/Tokyo") + assert local.hour == 9 + assert local == Timestamp(tstr, tz="Asia/Tokyo") + conv = local.tz_convert("US/Eastern") + assert conv == Timestamp("2014-01-31 19:00", tz="US/Eastern") + assert conv.hour == 19 + + # preserves nanosecond + ts = Timestamp(tstr) + offsets.Nano(5) + local = ts.tz_localize("Asia/Tokyo") + assert local.hour == 9 + assert local.nanosecond == 5 + conv = local.tz_convert("US/Eastern") + assert conv.nanosecond == 5 + assert conv.hour == 19 + + def test_utc_z_designator(self): + assert get_timezone(Timestamp("2014-11-02 01:00Z").tzinfo) is timezone.utc + + def test_asm8(self): + ns = [Timestamp.min._value, Timestamp.max._value, 1000] + + for n in ns: + assert ( + Timestamp(n).asm8.view("i8") == np.datetime64(n, "ns").view("i8") == n + ) + + assert Timestamp("nat").asm8.view("i8") == np.datetime64("nat", "ns").view("i8") + + def test_class_ops(self): + def compare(x, y): + assert int((Timestamp(x)._value - Timestamp(y)._value) / 1e9) == 0 + + compare(Timestamp.now(), datetime.now()) + compare(Timestamp.now("UTC"), datetime.now(pytz.timezone("UTC"))) + compare(Timestamp.now("UTC"), datetime.now(tzutc())) + compare(Timestamp.utcnow(), datetime.now(timezone.utc)) + compare(Timestamp.today(), datetime.today()) + current_time = calendar.timegm(datetime.now().utctimetuple()) + + ts_utc = Timestamp.utcfromtimestamp(current_time) + assert ts_utc.timestamp() == current_time + compare( + Timestamp.fromtimestamp(current_time), datetime.fromtimestamp(current_time) + ) + compare( + # Support tz kwarg in Timestamp.fromtimestamp + Timestamp.fromtimestamp(current_time, "UTC"), + datetime.fromtimestamp(current_time, utc), + ) + compare( + # Support tz kwarg in Timestamp.fromtimestamp + Timestamp.fromtimestamp(current_time, tz="UTC"), + datetime.fromtimestamp(current_time, utc), + ) + + date_component = datetime.now(timezone.utc) + time_component = (date_component + timedelta(minutes=10)).time() + compare( + Timestamp.combine(date_component, time_component), + datetime.combine(date_component, time_component), + ) + + def test_basics_nanos(self): + val = np.int64(946_684_800_000_000_000).view("M8[ns]") + stamp = Timestamp(val.view("i8") + 500) + assert stamp.year == 2000 + assert stamp.month == 1 + assert stamp.microsecond == 0 + assert stamp.nanosecond == 500 + + # GH 14415 + val = np.iinfo(np.int64).min + 80_000_000_000_000 + stamp = Timestamp(val) + assert stamp.year == 1677 + assert stamp.month == 9 + assert stamp.day == 21 + assert stamp.microsecond == 145224 + assert stamp.nanosecond == 192 + + def test_roundtrip(self): + # test value to string and back conversions + # further test accessors + base = Timestamp("20140101 00:00:00").as_unit("ns") + + result = Timestamp(base._value + Timedelta("5ms")._value) + assert result == Timestamp(f"{base}.005000") + assert result.microsecond == 5000 + + result = Timestamp(base._value + Timedelta("5us")._value) + assert result == Timestamp(f"{base}.000005") + assert result.microsecond == 5 + + result = Timestamp(base._value + Timedelta("5ns")._value) + assert result == Timestamp(f"{base}.000000005") + assert result.nanosecond == 5 + assert result.microsecond == 0 + + result = Timestamp(base._value + Timedelta("6ms 5us")._value) + assert result == Timestamp(f"{base}.006005") + assert result.microsecond == 5 + 6 * 1000 + + result = Timestamp(base._value + Timedelta("200ms 5us")._value) + assert result == Timestamp(f"{base}.200005") + assert result.microsecond == 5 + 200 * 1000 + + def test_hash_equivalent(self): + d = {datetime(2011, 1, 1): 5} + stamp = Timestamp(datetime(2011, 1, 1)) + assert d[stamp] == 5 + + @pytest.mark.parametrize( + "timezone, year, month, day, hour", + [["America/Chicago", 2013, 11, 3, 1], ["America/Santiago", 2021, 4, 3, 23]], + ) + def test_hash_timestamp_with_fold(self, timezone, year, month, day, hour): + # see gh-33931 + test_timezone = gettz(timezone) + transition_1 = Timestamp( + year=year, + month=month, + day=day, + hour=hour, + minute=0, + fold=0, + tzinfo=test_timezone, + ) + transition_2 = Timestamp( + year=year, + month=month, + day=day, + hour=hour, + minute=0, + fold=1, + tzinfo=test_timezone, + ) + assert hash(transition_1) == hash(transition_2) + + +class TestTimestampNsOperations: + def test_nanosecond_string_parsing(self): + ts = Timestamp("2013-05-01 07:15:45.123456789") + # GH 7878 + expected_repr = "2013-05-01 07:15:45.123456789" + expected_value = 1_367_392_545_123_456_789 + assert ts._value == expected_value + assert expected_repr in repr(ts) + + ts = Timestamp("2013-05-01 07:15:45.123456789+09:00", tz="Asia/Tokyo") + assert ts._value == expected_value - 9 * 3600 * 1_000_000_000 + assert expected_repr in repr(ts) + + ts = Timestamp("2013-05-01 07:15:45.123456789", tz="UTC") + assert ts._value == expected_value + assert expected_repr in repr(ts) + + ts = Timestamp("2013-05-01 07:15:45.123456789", tz="US/Eastern") + assert ts._value == expected_value + 4 * 3600 * 1_000_000_000 + assert expected_repr in repr(ts) + + # GH 10041 + ts = Timestamp("20130501T071545.123456789") + assert ts._value == expected_value + assert expected_repr in repr(ts) + + def test_nanosecond_timestamp(self): + # GH 7610 + expected = 1_293_840_000_000_000_005 + t = Timestamp("2011-01-01") + offsets.Nano(5) + assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000005')" + assert t._value == expected + assert t.nanosecond == 5 + + t = Timestamp(t) + assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000005')" + assert t._value == expected + assert t.nanosecond == 5 + + t = Timestamp("2011-01-01 00:00:00.000000005") + assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000005')" + assert t._value == expected + assert t.nanosecond == 5 + + expected = 1_293_840_000_000_000_010 + t = t + offsets.Nano(5) + assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000010')" + assert t._value == expected + assert t.nanosecond == 10 + + t = Timestamp(t) + assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000010')" + assert t._value == expected + assert t.nanosecond == 10 + + t = Timestamp("2011-01-01 00:00:00.000000010") + assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000010')" + assert t._value == expected + assert t.nanosecond == 10 + + +class TestTimestampConversion: + def test_conversion(self): + # GH#9255 + ts = Timestamp("2000-01-01").as_unit("ns") + + result = ts.to_pydatetime() + expected = datetime(2000, 1, 1) + assert result == expected + assert type(result) == type(expected) + + result = ts.to_datetime64() + expected = np.datetime64(ts._value, "ns") + assert result == expected + assert type(result) == type(expected) + assert result.dtype == expected.dtype + + def test_to_period_tz_warning(self): + # GH#21333 make sure a warning is issued when timezone + # info is lost + ts = Timestamp("2009-04-15 16:17:18", tz="US/Eastern") + with tm.assert_produces_warning(UserWarning): + # warning that timezone info will be lost + ts.to_period("D") + + def test_to_numpy_alias(self): + # GH 24653: alias .to_numpy() for scalars + ts = Timestamp(datetime.now()) + assert ts.to_datetime64() == ts.to_numpy() + + # GH#44460 + msg = "dtype and copy arguments are ignored" + with pytest.raises(ValueError, match=msg): + ts.to_numpy("M8[s]") + with pytest.raises(ValueError, match=msg): + ts.to_numpy(copy=True) + + +class TestNonNano: + @pytest.fixture(params=["s", "ms", "us"]) + def reso(self, request): + return request.param + + @pytest.fixture + def dt64(self, reso): + # cases that are in-bounds for nanosecond, so we can compare against + # the existing implementation. + return np.datetime64("2016-01-01", reso) + + @pytest.fixture + def ts(self, dt64): + return Timestamp._from_dt64(dt64) + + @pytest.fixture + def ts_tz(self, ts, tz_aware_fixture): + tz = maybe_get_tz(tz_aware_fixture) + return Timestamp._from_value_and_reso(ts._value, ts._creso, tz) + + def test_non_nano_construction(self, dt64, ts, reso): + assert ts._value == dt64.view("i8") + + if reso == "s": + assert ts._creso == NpyDatetimeUnit.NPY_FR_s.value + elif reso == "ms": + assert ts._creso == NpyDatetimeUnit.NPY_FR_ms.value + elif reso == "us": + assert ts._creso == NpyDatetimeUnit.NPY_FR_us.value + + def test_non_nano_fields(self, dt64, ts): + alt = Timestamp(dt64) + + assert ts.year == alt.year + assert ts.month == alt.month + assert ts.day == alt.day + assert ts.hour == ts.minute == ts.second == ts.microsecond == 0 + assert ts.nanosecond == 0 + + assert ts.to_julian_date() == alt.to_julian_date() + assert ts.weekday() == alt.weekday() + assert ts.isoweekday() == alt.isoweekday() + + def test_start_end_fields(self, ts): + assert ts.is_year_start + assert ts.is_quarter_start + assert ts.is_month_start + assert not ts.is_year_end + assert not ts.is_month_end + assert not ts.is_month_end + + # 2016-01-01 is a Friday, so is year/quarter/month start with this freq + assert ts.is_year_start + assert ts.is_quarter_start + assert ts.is_month_start + assert not ts.is_year_end + assert not ts.is_month_end + assert not ts.is_month_end + + def test_day_name(self, dt64, ts): + alt = Timestamp(dt64) + assert ts.day_name() == alt.day_name() + + def test_month_name(self, dt64, ts): + alt = Timestamp(dt64) + assert ts.month_name() == alt.month_name() + + def test_tz_convert(self, ts): + ts = Timestamp._from_value_and_reso(ts._value, ts._creso, utc) + + tz = pytz.timezone("US/Pacific") + result = ts.tz_convert(tz) + + assert isinstance(result, Timestamp) + assert result._creso == ts._creso + assert tz_compare(result.tz, tz) + + def test_repr(self, dt64, ts): + alt = Timestamp(dt64) + + assert str(ts) == str(alt) + assert repr(ts) == repr(alt) + + def test_comparison(self, dt64, ts): + alt = Timestamp(dt64) + + assert ts == dt64 + assert dt64 == ts + assert ts == alt + assert alt == ts + + assert not ts != dt64 + assert not dt64 != ts + assert not ts != alt + assert not alt != ts + + assert not ts < dt64 + assert not dt64 < ts + assert not ts < alt + assert not alt < ts + + assert not ts > dt64 + assert not dt64 > ts + assert not ts > alt + assert not alt > ts + + assert ts >= dt64 + assert dt64 >= ts + assert ts >= alt + assert alt >= ts + + assert ts <= dt64 + assert dt64 <= ts + assert ts <= alt + assert alt <= ts + + def test_cmp_cross_reso(self): + # numpy gets this wrong because of silent overflow + dt64 = np.datetime64(9223372800, "s") # won't fit in M8[ns] + ts = Timestamp._from_dt64(dt64) + + # subtracting 3600*24 gives a datetime64 that _can_ fit inside the + # nanosecond implementation bounds. + other = Timestamp(dt64 - 3600 * 24).as_unit("ns") + assert other < ts + assert other.asm8 > ts.asm8 # <- numpy gets this wrong + assert ts > other + assert ts.asm8 < other.asm8 # <- numpy gets this wrong + assert not other == ts + assert ts != other + + @pytest.mark.xfail(reason="Dispatches to np.datetime64 which is wrong") + def test_cmp_cross_reso_reversed_dt64(self): + dt64 = np.datetime64(106752, "D") # won't fit in M8[ns] + ts = Timestamp._from_dt64(dt64) + other = Timestamp(dt64 - 1) + + assert other.asm8 < ts + + def test_pickle(self, ts, tz_aware_fixture): + tz = tz_aware_fixture + tz = maybe_get_tz(tz) + ts = Timestamp._from_value_and_reso(ts._value, ts._creso, tz) + rt = tm.round_trip_pickle(ts) + assert rt._creso == ts._creso + assert rt == ts + + def test_normalize(self, dt64, ts): + alt = Timestamp(dt64) + result = ts.normalize() + assert result._creso == ts._creso + assert result == alt.normalize() + + def test_asm8(self, dt64, ts): + rt = ts.asm8 + assert rt == dt64 + assert rt.dtype == dt64.dtype + + def test_to_numpy(self, dt64, ts): + res = ts.to_numpy() + assert res == dt64 + assert res.dtype == dt64.dtype + + def test_to_datetime64(self, dt64, ts): + res = ts.to_datetime64() + assert res == dt64 + assert res.dtype == dt64.dtype + + def test_timestamp(self, dt64, ts): + alt = Timestamp(dt64) + assert ts.timestamp() == alt.timestamp() + + def test_to_period(self, dt64, ts): + alt = Timestamp(dt64) + assert ts.to_period("D") == alt.to_period("D") + + @pytest.mark.parametrize( + "td", [timedelta(days=4), Timedelta(days=4), np.timedelta64(4, "D")] + ) + def test_addsub_timedeltalike_non_nano(self, dt64, ts, td): + exp_reso = max(ts._creso, Timedelta(td)._creso) + + result = ts - td + expected = Timestamp(dt64) - td + assert isinstance(result, Timestamp) + assert result._creso == exp_reso + assert result == expected + + result = ts + td + expected = Timestamp(dt64) + td + assert isinstance(result, Timestamp) + assert result._creso == exp_reso + assert result == expected + + result = td + ts + expected = td + Timestamp(dt64) + assert isinstance(result, Timestamp) + assert result._creso == exp_reso + assert result == expected + + def test_addsub_offset(self, ts_tz): + # specifically non-Tick offset + off = offsets.YearEnd(1) + result = ts_tz + off + + assert isinstance(result, Timestamp) + assert result._creso == ts_tz._creso + if ts_tz.month == 12 and ts_tz.day == 31: + assert result.year == ts_tz.year + 1 + else: + assert result.year == ts_tz.year + assert result.day == 31 + assert result.month == 12 + assert tz_compare(result.tz, ts_tz.tz) + + result = ts_tz - off + + assert isinstance(result, Timestamp) + assert result._creso == ts_tz._creso + assert result.year == ts_tz.year - 1 + assert result.day == 31 + assert result.month == 12 + assert tz_compare(result.tz, ts_tz.tz) + + def test_sub_datetimelike_mismatched_reso(self, ts_tz): + # case with non-lossy rounding + ts = ts_tz + + # choose a unit for `other` that doesn't match ts_tz's; + # this construction ensures we get cases with other._creso < ts._creso + # and cases with other._creso > ts._creso + unit = { + NpyDatetimeUnit.NPY_FR_us.value: "ms", + NpyDatetimeUnit.NPY_FR_ms.value: "s", + NpyDatetimeUnit.NPY_FR_s.value: "us", + }[ts._creso] + other = ts.as_unit(unit) + assert other._creso != ts._creso + + result = ts - other + assert isinstance(result, Timedelta) + assert result._value == 0 + assert result._creso == max(ts._creso, other._creso) + + result = other - ts + assert isinstance(result, Timedelta) + assert result._value == 0 + assert result._creso == max(ts._creso, other._creso) + + if ts._creso < other._creso: + # Case where rounding is lossy + other2 = other + Timedelta._from_value_and_reso(1, other._creso) + exp = ts.as_unit(other.unit) - other2 + + res = ts - other2 + assert res == exp + assert res._creso == max(ts._creso, other._creso) + + res = other2 - ts + assert res == -exp + assert res._creso == max(ts._creso, other._creso) + else: + ts2 = ts + Timedelta._from_value_and_reso(1, ts._creso) + exp = ts2 - other.as_unit(ts2.unit) + + res = ts2 - other + assert res == exp + assert res._creso == max(ts._creso, other._creso) + res = other - ts2 + assert res == -exp + assert res._creso == max(ts._creso, other._creso) + + def test_sub_timedeltalike_mismatched_reso(self, ts_tz): + # case with non-lossy rounding + ts = ts_tz + + # choose a unit for `other` that doesn't match ts_tz's; + # this construction ensures we get cases with other._creso < ts._creso + # and cases with other._creso > ts._creso + unit = { + NpyDatetimeUnit.NPY_FR_us.value: "ms", + NpyDatetimeUnit.NPY_FR_ms.value: "s", + NpyDatetimeUnit.NPY_FR_s.value: "us", + }[ts._creso] + other = Timedelta(0).as_unit(unit) + assert other._creso != ts._creso + + result = ts + other + assert isinstance(result, Timestamp) + assert result == ts + assert result._creso == max(ts._creso, other._creso) + + result = other + ts + assert isinstance(result, Timestamp) + assert result == ts + assert result._creso == max(ts._creso, other._creso) + + if ts._creso < other._creso: + # Case where rounding is lossy + other2 = other + Timedelta._from_value_and_reso(1, other._creso) + exp = ts.as_unit(other.unit) + other2 + res = ts + other2 + assert res == exp + assert res._creso == max(ts._creso, other._creso) + res = other2 + ts + assert res == exp + assert res._creso == max(ts._creso, other._creso) + else: + ts2 = ts + Timedelta._from_value_and_reso(1, ts._creso) + exp = ts2 + other.as_unit(ts2.unit) + + res = ts2 + other + assert res == exp + assert res._creso == max(ts._creso, other._creso) + res = other + ts2 + assert res == exp + assert res._creso == max(ts._creso, other._creso) + + def test_addition_doesnt_downcast_reso(self): + # https://github.com/pandas-dev/pandas/pull/48748#pullrequestreview-1122635413 + ts = Timestamp(year=2022, month=1, day=1, microsecond=999999).as_unit("us") + td = Timedelta(microseconds=1).as_unit("us") + res = ts + td + assert res._creso == ts._creso + + def test_sub_timedelta64_mismatched_reso(self, ts_tz): + ts = ts_tz + + res = ts + np.timedelta64(1, "ns") + exp = ts.as_unit("ns") + np.timedelta64(1, "ns") + assert exp == res + assert exp._creso == NpyDatetimeUnit.NPY_FR_ns.value + + def test_min(self, ts): + assert ts.min <= ts + assert ts.min._creso == ts._creso + assert ts.min._value == NaT._value + 1 + + def test_max(self, ts): + assert ts.max >= ts + assert ts.max._creso == ts._creso + assert ts.max._value == np.iinfo(np.int64).max + + def test_resolution(self, ts): + expected = Timedelta._from_value_and_reso(1, ts._creso) + result = ts.resolution + assert result == expected + assert result._creso == expected._creso + + def test_out_of_ns_bounds(self): + # https://github.com/pandas-dev/pandas/issues/51060 + result = Timestamp(-52700112000, unit="s") + assert result == Timestamp("0300-01-01") + assert result.to_numpy() == np.datetime64("0300-01-01T00:00:00", "s") + + +def test_timestamp_class_min_max_resolution(): + # when accessed on the class (as opposed to an instance), we default + # to nanoseconds + assert Timestamp.min == Timestamp(NaT._value + 1) + assert Timestamp.min._creso == NpyDatetimeUnit.NPY_FR_ns.value + + assert Timestamp.max == Timestamp(np.iinfo(np.int64).max) + assert Timestamp.max._creso == NpyDatetimeUnit.NPY_FR_ns.value + + assert Timestamp.resolution == Timedelta(1) + assert Timestamp.resolution._creso == NpyDatetimeUnit.NPY_FR_ns.value + + +def test_delimited_date(): + # https://github.com/pandas-dev/pandas/issues/50231 + with tm.assert_produces_warning(None): + result = Timestamp("13-01-2000") + expected = Timestamp(2000, 1, 13) + assert result == expected + + +def test_utctimetuple(): + # GH 32174 + ts = Timestamp("2000-01-01", tz="UTC") + result = ts.utctimetuple() + expected = time.struct_time((2000, 1, 1, 0, 0, 0, 5, 1, 0)) + assert result == expected + + +def test_negative_dates(): + # https://github.com/pandas-dev/pandas/issues/50787 + ts = Timestamp("-2000-01-01") + msg = ( + " not yet supported on Timestamps which are outside the range of " + "Python's standard library. For now, please call the components you need " + r"\(such as `.year` and `.month`\) and construct your string from there.$" + ) + func = "^strftime" + with pytest.raises(NotImplementedError, match=func + msg): + ts.strftime("%Y") + + msg = ( + " not yet supported on Timestamps which " + "are outside the range of Python's standard library. " + ) + func = "^date" + with pytest.raises(NotImplementedError, match=func + msg): + ts.date() + func = "^isocalendar" + with pytest.raises(NotImplementedError, match=func + msg): + ts.isocalendar() + func = "^timetuple" + with pytest.raises(NotImplementedError, match=func + msg): + ts.timetuple() + func = "^toordinal" + with pytest.raises(NotImplementedError, match=func + msg): + ts.toordinal() diff --git a/shared/package-files/73/7347d8168ab131e2a9115ad3d7e7a9ac87b3359c394f4d4904a5bb83ed75b6ff/input_metadata.h b/shared/package-files/73/7347d8168ab131e2a9115ad3d7e7a9ac87b3359c394f4d4904a5bb83ed75b6ff/input_metadata.h new file mode 100644 index 0000000000000000000000000000000000000000..1f74e72cae7cfc7ea93ceb9ba7f1461724e99991 --- /dev/null +++ b/shared/package-files/73/7347d8168ab131e2a9115ad3d7e7a9ac87b3359c394f4d4904a5bb83ed75b6ff/input_metadata.h @@ -0,0 +1,113 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +namespace torch::autograd { + +using SymIntSmallVec = c10::SmallVector; +using MetadataShape = std::variant; + +/** + * Records TensorOptions, shape of the tensor, whether or not the Python + * dispatch key is set (tensor subclass), and, where applicable, the stream the + * corresponding operation took place on. + * + * If is_valid() is false, then the corresponding input is not used and may be + * an undefined tensor. + */ +struct TORCH_API InputMetadata { + InputMetadata() = default; + InputMetadata( + const at::TensorOptions& options, + MetadataShape input_shape, + bool is_tensor_subclass, + bool is_nested); + InputMetadata(const at::Tensor& t); + + const at::TensorOptions& options() const { + return options_; + } + + caffe2::TypeMeta dtype() const { + return options_.dtype(); + } + + at::Device device() const { + return options_.device(); + } + + at::Layout layout() const { + return options_.layout(); + } + + c10::Stream stream() const { + return stream_; + } + + bool is_tensor_subclass() const { + return is_tensor_subclass_; + } + + at::Tensor zeros_like() const; + + bool is_same_shape(const at::Tensor& grad) const; + + bool is_expandable_to_shape(const at::Tensor& grad) const; + + at::Tensor reduce_grad(at::Tensor& grad) const; + + at::Tensor maybe_reduce( + const size_t index, + at::Tensor grad, + const std::function& format_error) const; + + std::stringstream incompatible_shape_error_message( + const size_t index, + const at::Tensor& grad) const; + + bool was_default_constructed() const { + return was_default_constructed_; + } + + bool is_cpp_nested_tensor() const; + + bool is_nested_tensor() const { + return is_nested_; + } + + c10::SymIntArrayRef shape_as_dim_vector() const; + + // Danger: not thread safe, caller must protect with lock + SymIntSmallVec& mutable_shape_as_dim_vector(); + + private: + at::Tensor shape_as_tensor() const; + bool is_nestedness_same(const at::Tensor& grad) const; + bool maybe_expandable_to(const at::Tensor& grad) const; + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const at::TensorOptions options_; + MetadataShape shape_; + c10::Stream stream_ = c10::Stream(c10::Stream::Default::DEFAULT, device()); + bool is_tensor_subclass_ = false; + bool is_nested_ = false; + bool was_default_constructed_ = true; +}; +} // namespace torch::autograd diff --git a/shared/package-files/73/7348db9d83a3b09fbdfd84db7434c982034774ae6b80175f35ea981e763c9697/half_cauchy.py b/shared/package-files/73/7348db9d83a3b09fbdfd84db7434c982034774ae6b80175f35ea981e763c9697/half_cauchy.py new file mode 100644 index 0000000000000000000000000000000000000000..ef0edc6f0fe88054afe86b0e2ba13a5dc01ba092 --- /dev/null +++ b/shared/package-files/73/7348db9d83a3b09fbdfd84db7434c982034774ae6b80175f35ea981e763c9697/half_cauchy.py @@ -0,0 +1,82 @@ +import math + +import torch +from torch import inf +from torch.distributions import constraints +from torch.distributions.cauchy import Cauchy +from torch.distributions.transformed_distribution import TransformedDistribution +from torch.distributions.transforms import AbsTransform + +__all__ = ["HalfCauchy"] + + +class HalfCauchy(TransformedDistribution): + r""" + Creates a half-Cauchy distribution parameterized by `scale` where:: + + X ~ Cauchy(0, scale) + Y = |X| ~ HalfCauchy(scale) + + Example:: + + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> m = HalfCauchy(torch.tensor([1.0])) + >>> m.sample() # half-cauchy distributed with scale=1 + tensor([ 2.3214]) + + Args: + scale (float or Tensor): scale of the full Cauchy distribution + """ + arg_constraints = {"scale": constraints.positive} + support = constraints.nonnegative + has_rsample = True + + def __init__(self, scale, validate_args=None): + base_dist = Cauchy(0, scale, validate_args=False) + super().__init__(base_dist, AbsTransform(), validate_args=validate_args) + + def expand(self, batch_shape, _instance=None): + new = self._get_checked_instance(HalfCauchy, _instance) + return super().expand(batch_shape, _instance=new) + + @property + def scale(self): + return self.base_dist.scale + + @property + def mean(self): + return torch.full( + self._extended_shape(), + math.inf, + dtype=self.scale.dtype, + device=self.scale.device, + ) + + @property + def mode(self): + return torch.zeros_like(self.scale) + + @property + def variance(self): + return self.base_dist.variance + + def log_prob(self, value): + if self._validate_args: + self._validate_sample(value) + value = torch.as_tensor( + value, dtype=self.base_dist.scale.dtype, device=self.base_dist.scale.device + ) + log_prob = self.base_dist.log_prob(value) + math.log(2) + log_prob = torch.where(value >= 0, log_prob, -inf) + return log_prob + + def cdf(self, value): + if self._validate_args: + self._validate_sample(value) + return 2 * self.base_dist.cdf(value) - 1 + + def icdf(self, prob): + return self.base_dist.icdf((prob + 1) / 2) + + def entropy(self): + return self.base_dist.entropy() - math.log(2) diff --git a/shared/package-files/73/734c2ed31f293efe01712b63ee913ad6b6697faf052c6fe9373419e1ef36cc7f/joblib_0.10.0_pickle_py27_np17.pkl.lzma b/shared/package-files/73/734c2ed31f293efe01712b63ee913ad6b6697faf052c6fe9373419e1ef36cc7f/joblib_0.10.0_pickle_py27_np17.pkl.lzma new file mode 100644 index 0000000000000000000000000000000000000000..92acdd95675978ef8265e261f770749eb68d6f7c Binary files /dev/null and b/shared/package-files/73/734c2ed31f293efe01712b63ee913ad6b6697faf052c6fe9373419e1ef36cc7f/joblib_0.10.0_pickle_py27_np17.pkl.lzma differ diff --git a/shared/package-files/73/734cc6375ecf09525c4e77b52f3716b6bcce6accf546460e3d938b4da7acd79a/upsample_bicubic2d_backward_ops.h b/shared/package-files/73/734cc6375ecf09525c4e77b52f3716b6bcce6accf546460e3d938b4da7acd79a/upsample_bicubic2d_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..d759560d89157bf70e40c322fea9808b4e431d21 --- /dev/null +++ b/shared/package-files/73/734cc6375ecf09525c4e77b52f3716b6bcce6accf546460e3d938b4da7acd79a/upsample_bicubic2d_backward_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API upsample_bicubic2d_backward_grad_input { + using schema = at::Tensor & (const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, bool, c10::optional, c10::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::upsample_bicubic2d_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "grad_input") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "upsample_bicubic2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input); +}; + +struct TORCH_API upsample_bicubic2d_backward { + using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, bool, c10::optional, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::upsample_bicubic2d_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "upsample_bicubic2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor") + static at::Tensor call(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h, c10::optional scales_w); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h, c10::optional scales_w); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/73/734fd41ed3c6d219cfc2f346bb6c4f96f87fa83efef9b67ae364140929c98133/logical_not_compositeexplicitautograd_dispatch.h b/shared/package-files/73/734fd41ed3c6d219cfc2f346bb6c4f96f87fa83efef9b67ae364140929c98133/logical_not_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..4aa9f9ef76f305653c668d2f2e4cd8b5bbe6dc3f --- /dev/null +++ b/shared/package-files/73/734fd41ed3c6d219cfc2f346bb6c4f96f87fa83efef9b67ae364140929c98133/logical_not_compositeexplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor logical_not(const at::Tensor & self); +TORCH_API at::Tensor & logical_not_(at::Tensor & self); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/73/735067aed5b02f6764ad3afbc2f944a8d0e0e7d49e34ca3783226e19d470703c/foo90.f90 b/shared/package-files/73/735067aed5b02f6764ad3afbc2f944a8d0e0e7d49e34ca3783226e19d470703c/foo90.f90 new file mode 100644 index 0000000000000000000000000000000000000000..adc27b470538bc663416fb512a29c4b2bbe8d3dd --- /dev/null +++ b/shared/package-files/73/735067aed5b02f6764ad3afbc2f944a8d0e0e7d49e34ca3783226e19d470703c/foo90.f90 @@ -0,0 +1,48 @@ +module f90_return_complex + contains + function t0(value) + complex :: value + complex :: t0 + t0 = value + end function t0 + function t8(value) + complex(kind=4) :: value + complex(kind=4) :: t8 + t8 = value + end function t8 + function t16(value) + complex(kind=8) :: value + complex(kind=8) :: t16 + t16 = value + end function t16 + function td(value) + double complex :: value + double complex :: td + td = value + end function td + + subroutine s0(t0,value) + complex :: value + complex :: t0 +!f2py intent(out) t0 + t0 = value + end subroutine s0 + subroutine s8(t8,value) + complex(kind=4) :: value + complex(kind=4) :: t8 +!f2py intent(out) t8 + t8 = value + end subroutine s8 + subroutine s16(t16,value) + complex(kind=8) :: value + complex(kind=8) :: t16 +!f2py intent(out) t16 + t16 = value + end subroutine s16 + subroutine sd(td,value) + double complex :: value + double complex :: td +!f2py intent(out) td + td = value + end subroutine sd +end module f90_return_complex diff --git a/shared/package-files/73/7351da2057dfbfb1523cb1f80bb4965bdb7d9f4271a557571e511f373688d269/textview.py b/shared/package-files/73/7351da2057dfbfb1523cb1f80bb4965bdb7d9f4271a557571e511f373688d269/textview.py new file mode 100644 index 0000000000000000000000000000000000000000..a66c1a4309a617f27812a2ed544fc430192450e0 --- /dev/null +++ b/shared/package-files/73/7351da2057dfbfb1523cb1f80bb4965bdb7d9f4271a557571e511f373688d269/textview.py @@ -0,0 +1,193 @@ +"""Simple text browser for IDLE + +""" +from tkinter import Toplevel, Text, TclError,\ + HORIZONTAL, VERTICAL, NS, EW, NSEW, NONE, WORD, SUNKEN +from tkinter.ttk import Frame, Scrollbar, Button +from tkinter.messagebox import showerror + +from idlelib.colorizer import color_config + + +class AutoHideScrollbar(Scrollbar): + """A scrollbar that is automatically hidden when not needed. + + Only the grid geometry manager is supported. + """ + def set(self, lo, hi): + if float(lo) > 0.0 or float(hi) < 1.0: + self.grid() + else: + self.grid_remove() + super().set(lo, hi) + + def pack(self, **kwargs): + raise TclError(f'{self.__class__.__name__} does not support "pack"') + + def place(self, **kwargs): + raise TclError(f'{self.__class__.__name__} does not support "place"') + + +class ScrollableTextFrame(Frame): + """Display text with scrollbar(s).""" + + def __init__(self, master, wrap=NONE, **kwargs): + """Create a frame for Textview. + + master - master widget for this frame + wrap - type of text wrapping to use ('word', 'char' or 'none') + + All parameters except for 'wrap' are passed to Frame.__init__(). + + The Text widget is accessible via the 'text' attribute. + + Note: Changing the wrapping mode of the text widget after + instantiation is not supported. + """ + super().__init__(master, **kwargs) + + text = self.text = Text(self, wrap=wrap) + text.grid(row=0, column=0, sticky=NSEW) + self.grid_rowconfigure(0, weight=1) + self.grid_columnconfigure(0, weight=1) + + # vertical scrollbar + self.yscroll = AutoHideScrollbar(self, orient=VERTICAL, + takefocus=False, + command=text.yview) + self.yscroll.grid(row=0, column=1, sticky=NS) + text['yscrollcommand'] = self.yscroll.set + + # horizontal scrollbar - only when wrap is set to NONE + if wrap == NONE: + self.xscroll = AutoHideScrollbar(self, orient=HORIZONTAL, + takefocus=False, + command=text.xview) + self.xscroll.grid(row=1, column=0, sticky=EW) + text['xscrollcommand'] = self.xscroll.set + else: + self.xscroll = None + + +class ViewFrame(Frame): + "Display TextFrame and Close button." + def __init__(self, parent, contents, wrap='word'): + """Create a frame for viewing text with a "Close" button. + + parent - parent widget for this frame + contents - text to display + wrap - type of text wrapping to use ('word', 'char' or 'none') + + The Text widget is accessible via the 'text' attribute. + """ + super().__init__(parent) + self.parent = parent + self.bind('', self.ok) + self.bind('', self.ok) + self.textframe = ScrollableTextFrame(self, relief=SUNKEN, height=700) + + text = self.text = self.textframe.text + text.insert('1.0', contents) + text.configure(wrap=wrap, highlightthickness=0, state='disabled') + color_config(text) + text.focus_set() + + self.button_ok = button_ok = Button( + self, text='Close', command=self.ok, takefocus=False) + self.textframe.pack(side='top', expand=True, fill='both') + button_ok.pack(side='bottom') + + def ok(self, event=None): + """Dismiss text viewer dialog.""" + self.parent.destroy() + + +class ViewWindow(Toplevel): + "A simple text viewer dialog for IDLE." + + def __init__(self, parent, title, contents, modal=True, wrap=WORD, + *, _htest=False, _utest=False): + """Show the given text in a scrollable window with a 'close' button. + + If modal is left True, users cannot interact with other windows + until the textview window is closed. + + parent - parent of this dialog + title - string which is title of popup dialog + contents - text to display in dialog + wrap - type of text wrapping to use ('word', 'char' or 'none') + _htest - bool; change box location when running htest. + _utest - bool; don't wait_window when running unittest. + """ + super().__init__(parent) + self['borderwidth'] = 5 + # Place dialog below parent if running htest. + x = parent.winfo_rootx() + 10 + y = parent.winfo_rooty() + (10 if not _htest else 100) + self.geometry(f'=750x500+{x}+{y}') + + self.title(title) + self.viewframe = ViewFrame(self, contents, wrap=wrap) + self.protocol("WM_DELETE_WINDOW", self.ok) + self.button_ok = button_ok = Button(self, text='Close', + command=self.ok, takefocus=False) + self.viewframe.pack(side='top', expand=True, fill='both') + + self.is_modal = modal + if self.is_modal: + self.transient(parent) + self.grab_set() + if not _utest: + self.wait_window() + + def ok(self, event=None): + """Dismiss text viewer dialog.""" + if self.is_modal: + self.grab_release() + self.destroy() + + +def view_text(parent, title, contents, modal=True, wrap='word', _utest=False): + """Create text viewer for given text. + + parent - parent of this dialog + title - string which is the title of popup dialog + contents - text to display in this dialog + wrap - type of text wrapping to use ('word', 'char' or 'none') + modal - controls if users can interact with other windows while this + dialog is displayed + _utest - bool; controls wait_window on unittest + """ + return ViewWindow(parent, title, contents, modal, wrap=wrap, _utest=_utest) + + +def view_file(parent, title, filename, encoding, modal=True, wrap='word', + _utest=False): + """Create text viewer for text in filename. + + Return error message if file cannot be read. Otherwise calls view_text + with contents of the file. + """ + try: + with open(filename, 'r', encoding=encoding) as file: + contents = file.read() + except OSError: + showerror(title='File Load Error', + message=f'Unable to load file {filename!r} .', + parent=parent) + except UnicodeDecodeError as err: + showerror(title='Unicode Decode Error', + message=str(err), + parent=parent) + else: + return view_text(parent, title, contents, modal, wrap=wrap, + _utest=_utest) + return None + + +if __name__ == '__main__': + from unittest import main + main('idlelib.idle_test.test_textview', verbosity=2, exit=False) + + from idlelib.idle_test.htest import run + run(ViewWindow) diff --git a/shared/package-files/73/7352d61f45d8b5b72cf53d26273e65ca3e99015070536cd925d464ec377815cd/const.pyi b/shared/package-files/73/7352d61f45d8b5b72cf53d26273e65ca3e99015070536cd925d464ec377815cd/const.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e1cff069a10a63d022431e5a3d97999fc49983d0 --- /dev/null +++ b/shared/package-files/73/7352d61f45d8b5b72cf53d26273e65ca3e99015070536cd925d464ec377815cd/const.pyi @@ -0,0 +1,6 @@ +MODE_AUTO: int = ... +MODE_MMAP_EXT: int = ... +MODE_MMAP: int = ... +MODE_FILE: int = ... +MODE_MEMORY: int = ... +MODE_FD: int = ... diff --git a/shared/package-files/73/7358baa5daa7f66fa5f4f78c5de365856f6a884f0594b4958f60d5fa2a1807b7/cuda_random.h b/shared/package-files/73/7358baa5daa7f66fa5f4f78c5de365856f6a884f0594b4958f60d5fa2a1807b7/cuda_random.h new file mode 100644 index 0000000000000000000000000000000000000000..987ac5211d92960e335bfe2c8688a2c06fc6677d --- /dev/null +++ b/shared/package-files/73/7358baa5daa7f66fa5f4f78c5de365856f6a884f0594b4958f60d5fa2a1807b7/cuda_random.h @@ -0,0 +1,104 @@ +#pragma once + +namespace torch { +namespace jit { +namespace tensorexpr { + +constexpr auto philox_random_string = R"( + +class Philox { +public: + __device__ inline Philox(unsigned long long seed, + unsigned long long subsequence, + unsigned long long offset) { + key.x = (unsigned int)seed; + key.y = (unsigned int)(seed >> 32); + counter = make_uint4(0, 0, 0, 0); + counter.z = (unsigned int)(subsequence); + counter.w = (unsigned int)(subsequence >> 32); + STATE = 0; + incr_n(offset / 4); + } + + __device__ inline unsigned long operator()() { + if(STATE == 0) { + uint4 counter_ = counter; + uint2 key_ = key; + for(int i = 0; i < 9; i++) { + counter_ = single_round(counter_, key_); + key_.x += (kPhilox10A); key_.y += (kPhilox10B); + } + output = single_round(counter_, key_); + incr(); + } + unsigned long ret; + switch(STATE) { + case 0: ret = output.x; break; + case 1: ret = output.y; break; + case 2: ret = output.z; break; + case 3: ret = output.w; break; + } + STATE = (STATE + 1) % 4; + return ret; + } + +private: + uint4 counter; + uint4 output; + uint2 key; + unsigned int STATE; + __device__ inline void incr_n(unsigned long long n) { + unsigned int nlo = (unsigned int)(n); + unsigned int nhi = (unsigned int)(n >> 32); + counter.x += nlo; + if (counter.x < nlo) + nhi++; + counter.y += nhi; + if (nhi <= counter.y) + return; + if (++counter.z) + return; + ++counter.w; + } + __device__ inline void incr() { + if (++counter.x) + return; + if (++counter.y) + return; + if (++counter.z) + return; + ++counter.w; + } + __device__ unsigned int mulhilo32(unsigned int a, unsigned int b, + unsigned int *result_high) { + *result_high = __umulhi(a, b); + return a*b; + } + + __device__ inline uint4 single_round(uint4 ctr, uint2 key) { + unsigned int hi0; + unsigned int hi1; + unsigned int lo0 = mulhilo32(kPhiloxSA, ctr.x, &hi0); + unsigned int lo1 = mulhilo32(kPhiloxSB, ctr.z, &hi1); + + uint4 ret = {hi1 ^ ctr.y ^ key.x, lo1, hi0 ^ ctr.w ^ key.y, lo0}; + return ret; + } + + static const unsigned long kPhilox10A = 0x9E3779B9; + static const unsigned long kPhilox10B = 0xBB67AE85; + static const unsigned long kPhiloxSA = 0xD2511F53; + static const unsigned long kPhiloxSB = 0xCD9E8D57; +}; + +// Inverse of 2^32. +#define M_RAN_INVM32 2.3283064e-10f +__device__ __inline__ float Uint32ToFloat(unsigned int x) { + return x * M_RAN_INVM32; +} + +)"; + +} // namespace tensorexpr +} // namespace jit +} // namespace torch diff --git a/shared/package-files/73/73597744706c9af41794523e36ecd3f865f11d43777693aa511532368260f8cb/expr_str.py b/shared/package-files/73/73597744706c9af41794523e36ecd3f865f11d43777693aa511532368260f8cb/expr_str.py new file mode 100644 index 0000000000000000000000000000000000000000..9be2bc53cd726cff122e564544c60b4648c30e84 --- /dev/null +++ b/shared/package-files/73/73597744706c9af41794523e36ecd3f865f11d43777693aa511532368260f8cb/expr_str.py @@ -0,0 +1,716 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Generic, TypeVar + +from narwhals._expression_parsing import ExprKind, ExprNode +from narwhals._utils import ( + parse_str_strip_chars, + validate_pad_arguments, + validate_str_non_negative, +) + +if TYPE_CHECKING: + from narwhals.expr import Expr + from narwhals.typing import IntoExpr + +ExprT = TypeVar("ExprT", bound="Expr") + + +class ExprStringNamespace(Generic[ExprT]): + def __init__(self, expr: ExprT) -> None: + self._expr = expr + + def len_chars(self) -> ExprT: + r"""Return the length of each string as the number of characters. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"words": ["foo", "345", None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(words_len=nw.col("words").str.len_chars()) + ┌─────────────────────┐ + | Narwhals DataFrame | + |---------------------| + |shape: (3, 2) | + |┌───────┬───────────┐| + |│ words ┆ words_len │| + |│ --- ┆ --- │| + |│ str ┆ u32 │| + |╞═══════╪═══════════╡| + |│ foo ┆ 3 │| + |│ 345 ┆ 3 │| + |│ null ┆ null │| + |└───────┴───────────┘| + └─────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "str.len_chars")) + + def replace( + self, pattern: str, value: str | IntoExpr, *, literal: bool = False, n: int = 1 + ) -> ExprT: + r"""Replace first matching regex/literal substring with a new string value. + + Arguments: + pattern: A valid regular expression pattern. + value: String that will replace the matched substring. + literal: Treat `pattern` as a literal string. + n: Number of matches to replace. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"foo": ["123abc", "abc abc123"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(replaced=nw.col("foo").str.replace("abc", "")) + ┌──────────────────────┐ + | Narwhals DataFrame | + |----------------------| + | foo replaced| + |0 123abc 123| + |1 abc abc123 abc123| + └──────────────────────┘ + """ + return self._expr._append_node( + ExprNode( + ExprKind.ELEMENTWISE, + "str.replace", + exprs=(value,), + pattern=pattern, + literal=literal, + n=n, + str_as_lit=True, + ) + ) + + def replace_all( + self, pattern: str, value: IntoExpr, *, literal: bool = False + ) -> ExprT: + r"""Replace all matching regex/literal substring with a new string value. + + Arguments: + pattern: A valid regular expression pattern. + value: String that will replace the matched substring. + literal: Treat `pattern` as a literal string. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"foo": ["123abc", "abc abc123"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(replaced=nw.col("foo").str.replace_all("abc", "")) + ┌──────────────────────┐ + | Narwhals DataFrame | + |----------------------| + | foo replaced| + |0 123abc 123| + |1 abc abc123 123| + └──────────────────────┘ + """ + return self._expr._append_node( + ExprNode( + ExprKind.ELEMENTWISE, + "str.replace_all", + exprs=(value,), + pattern=pattern, + literal=literal, + str_as_lit=True, + ) + ) + + def strip_chars(self, characters: str | None = None) -> ExprT: + r"""Remove leading and trailing characters. + + Arguments: + characters: The set of characters to be removed. All combinations of this + set of characters will be stripped from the start and end of the string. + If set to None (default), all leading and trailing whitespace is removed + instead. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"fruits": ["apple", "\nmango"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(stripped=nw.col("fruits").str.strip_chars()).to_dict( + ... as_series=False + ... ) + {'fruits': ['apple', '\nmango'], 'stripped': ['apple', 'mango']} + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.strip_chars", characters=characters) + ) + + def strip_chars_start(self, characters: str | None = None) -> ExprT: + r"""Remove leading characters. + + Arguments: + characters: The set of characters to be removed. All combinations of this + set of characters will be stripped from the start of the string. If set + to None (default), all leading whitespace is removed instead. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> df_native = duckdb.sql( + ... r"SELECT * FROM VALUES (' apple '), (E'mango\n') df(fruits)" + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(stripped=nw.col("fruits").str.strip_chars_start()) + ┌──────────────────────┐ + | Narwhals LazyFrame | + |----------------------| + |┌─────────┬──────────┐| + |│ fruits │ stripped │| + |│ varchar │ varchar │| + |├─────────┼──────────┤| + |│ apple │ apple │| + |│ mango\n │ mango\n │| + |└─────────┴──────────┘| + └──────────────────────┘ + """ + if (characters := parse_str_strip_chars(characters)) == "": + return self._expr + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.strip_chars_start", characters=characters) + ) + + def strip_chars_end(self, characters: str | None = None) -> ExprT: + r"""Remove trailing characters. + + Arguments: + characters: The set of characters to be removed. All combinations of this + set of characters will be stripped from the end of the string. If set + to None (default), all trailing whitespace is removed instead. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"fruits": [" apple ", "mango\n"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(stripped=nw.col("fruits").str.strip_chars_end()).to_dict( + ... as_series=False + ... ) + {'fruits': [' apple ', 'mango\n'], 'stripped': [' apple', 'mango']} + """ + if (characters := parse_str_strip_chars(characters)) == "": + return self._expr + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.strip_chars_end", characters=characters) + ) + + def starts_with(self, prefix: str | IntoExpr) -> ExprT: + r"""Check if string values start with a substring. + + Arguments: + prefix: prefix substring + + Notes: + Null values are preserved, unless `self` is backed by a non-nullable pandas Series + (which does not support missing values). See [boolean columns](../concepts/boolean.md) for reference. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"fruits": ["apple", "mango", None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(has_prefix=nw.col("fruits").str.starts_with("app")) + ┌────────────────────┐ + | Narwhals DataFrame | + |--------------------| + | fruits has_prefix| + |0 apple True| + |1 mango False| + |2 NaN False| + └────────────────────┘ + """ + return self._expr._append_node( + ExprNode( + ExprKind.ELEMENTWISE, "str.starts_with", exprs=(prefix,), str_as_lit=True + ) + ) + + def ends_with(self, suffix: str | IntoExpr) -> ExprT: + r"""Check if string values end with a substring. + + Arguments: + suffix: suffix substring + + Notes: + Null values are preserved, unless `self` is backed by a non-nullable pandas Series + (which does not support missing values). See [boolean columns](../concepts/boolean.md) for reference. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"fruits": ["apple", "mango", None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(has_suffix=nw.col("fruits").str.ends_with("ngo")) + ┌────────────────────┐ + | Narwhals DataFrame | + |--------------------| + | fruits has_suffix| + |0 apple False| + |1 mango True| + |2 NaN False| + └────────────────────┘ + """ + return self._expr._append_node( + ExprNode( + ExprKind.ELEMENTWISE, "str.ends_with", exprs=(suffix,), str_as_lit=True + ) + ) + + def contains(self, pattern: str | IntoExpr, *, literal: bool = False) -> ExprT: + r"""Check if string contains a substring that matches a pattern. + + Arguments: + pattern: A Character sequence, valid regular expression pattern, or another + Expr. + literal: If True, treats the pattern as a literal string. + If False, assumes the pattern is a regular expression. + + Warning: + Passing an expression as `pattern` is only supported by DuckDB, Ibis, Polars, + PySpark and SQLFrame. Other backends, such as pandas and PyArrow, will raise + a `TypeError`. + + Notes: + Null values are preserved, unless `self` is backed by a non-nullable pandas Series + (which does not support missing values). See [boolean columns](../concepts/boolean.md) for reference. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"pets": ["cat", "dog", "rabbit and parrot"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... default_match=nw.col("pets").str.contains("cat|parrot"), + ... case_insensitive_match=nw.col("pets").str.contains("cat|(?i)parrot"), + ... ).to_native() + pyarrow.Table + pets: string + default_match: bool + case_insensitive_match: bool + ---- + pets: [["cat","dog","rabbit and parrot"]] + default_match: [[true,false,true]] + case_insensitive_match: [[true,false,true]] + """ + return self._expr._append_node( + ExprNode( + ExprKind.ELEMENTWISE, + "str.contains", + exprs=(pattern,), + literal=literal, + str_as_lit=True, + ) + ) + + def slice(self, offset: int, length: int | None = None) -> ExprT: + r"""Create subslices of the string values of an expression. + + Arguments: + offset: Start index. Negative indexing is supported. + length: Length of the slice. Must be non-negative. If set to `None` (default), + the slice is taken to the end of the string. + + Raises: + ValueError: If `length` is negative. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"s": ["pear", None, "papaya"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(s_sliced=nw.col("s").str.slice(4, length=3)) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | s s_sliced| + |0 pear | + |1 NaN NaN| + |2 papaya ya| + └──────────────────┘ + """ + if length is not None: + validate_str_non_negative("slice", "length", length) + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.slice", offset=offset, length=length) + ) + + def split(self, by: str) -> ExprT: + r"""Split the string values of an expression by a substring. + + Arguments: + by: Substring to split by. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"s": ["foo bar", "foo_bar"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("s").str.split("_").alias("s_split")) + ┌────────────────────────────┐ + | Narwhals DataFrame | + |----------------------------| + |shape: (2, 2) | + |┌─────────┬────────────────┐| + |│ s ┆ s_split │| + |│ --- ┆ --- │| + |│ str ┆ list[str] │| + |╞═════════╪════════════════╡| + |│ foo bar ┆ ["foo bar"] │| + |│ foo_bar ┆ ["foo", "bar"] │| + |└─────────┴────────────────┘| + └────────────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "str.split", by=by)) + + def head(self, n: int = 5) -> ExprT: + r"""Take the first n elements of each string. + + Arguments: + n: Number of elements to take. Negative indexing is **not** supported. + + Notes: + If the length of the string has fewer than `n` characters, the full string is returned. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"lyrics": ["taata", "taatatata", "zukkyun"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(lyrics_head=nw.col("lyrics").str.head()).to_native() + pyarrow.Table + lyrics: string + lyrics_head: string + ---- + lyrics: [["taata","taatatata","zukkyun"]] + lyrics_head: [["taata","taata","zukky"]] + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.slice", offset=0, length=n) + ) + + def tail(self, n: int = 5) -> ExprT: + r"""Take the last n elements of each string. + + Arguments: + n: Number of elements to take. Negative indexing is **not** supported. + + Notes: + If the length of the string has fewer than `n` characters, the full string is returned. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"lyrics": ["taata", "taatatata", "zukkyun"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(lyrics_tail=nw.col("lyrics").str.tail()).to_native() + pyarrow.Table + lyrics: string + lyrics_tail: string + ---- + lyrics: [["taata","taatatata","zukkyun"]] + lyrics_tail: [["taata","atata","kkyun"]] + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.slice", offset=-n, length=None) + ) + + def to_datetime(self, format: str | None = None) -> ExprT: + """Convert to Datetime dtype. + + Notes: + - pandas defaults to nanosecond time unit, Polars to microsecond. + Prior to pandas 2.0, nanoseconds were the only time unit supported + in pandas, with no ability to set any other one. The ability to + set the time unit in pandas, if the version permits, will arrive. + - timezone-aware strings are all converted to and parsed as UTC. + + Warning: + As different backends auto-infer format in different ways, if `format=None` + there is no guarantee that the result will be equal. + + Arguments: + format: Format to use for conversion. If set to None (default), the format is + inferred from the data. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": ["2020-01-01", "2020-01-02"]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a").str.to_datetime(format="%Y-%m-%d")) + ┌───────────────────────┐ + | Narwhals DataFrame | + |-----------------------| + |shape: (2, 1) | + |┌─────────────────────┐| + |│ a │| + |│ --- │| + |│ datetime[μs] │| + |╞═════════════════════╡| + |│ 2020-01-01 00:00:00 │| + |│ 2020-01-02 00:00:00 │| + |└─────────────────────┘| + └───────────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.to_datetime", format=format) + ) + + def to_date(self, format: str | None = None) -> ExprT: + """Convert to date dtype. + + Warning: + As different backends auto-infer format in different ways, if `format=None` + there is no guarantee that the result will be equal. + + Arguments: + format: Format to use for conversion. If set to None (default), the format is inferred from the data. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"a": ["2020-01-01", "2020-01-02"]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a").str.to_date(format="%Y-%m-%d")) + ┌────────────────────────────┐ + | Narwhals DataFrame | + |----------------------------| + |pyarrow.Table | + |a: date32[day] | + |---- | + |a: [[2020-01-01,2020-01-02]]| + └────────────────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.to_date", format=format) + ) + + def to_time(self, format: str | None = None) -> ExprT: + """Convert to [`narwhals.dtypes.Time`][] dtype. + + Warning: + As different backends auto-infer format in different ways, if `format=None` + there is no guarantee that the result will be equal. + + Arguments: + format: Format to use for conversion. If set to None (default), the format is + inferred from the data. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": ["12:59:21", "18:42:12"]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a").str.to_time(format="%H:%M:%S")) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | shape: (2, 1) | + | ┌──────────┐ | + | │ a │ | + | │ --- │ | + | │ time │ | + | ╞══════════╡ | + | │ 12:59:21 │ | + | │ 18:42:12 │ | + | └──────────┘ | + └──────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.to_time", format=format) + ) + + def to_uppercase(self) -> ExprT: + r"""Transform string to uppercase variant. + + Notes: + The PyArrow backend will convert 'ß' to 'ẞ' instead of 'SS'. + For more info see [the related issue](https://github.com/apache/arrow/issues/34599). + There may be other unicode-edge-case-related variations across implementations. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"fruits": ["apple", None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(upper_col=nw.col("fruits").str.to_uppercase()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | fruits upper_col| + |0 apple APPLE| + |1 NaN NaN| + └──────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "str.to_uppercase")) + + def to_lowercase(self) -> ExprT: + r"""Transform string to lowercase variant. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"fruits": ["APPLE", None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(lower_col=nw.col("fruits").str.to_lowercase()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | fruits lower_col| + |0 APPLE apple| + |1 NaN NaN| + └──────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "str.to_lowercase")) + + def to_titlecase(self) -> ExprT: + """Modify strings to their titlecase equivalent. + + Notes: + This is a form of case transform where the first letter of each word is + capitalized, with the rest of the word in lowercase. + + Word boundaries are defined by non-**alphabetic** characters, matching the + behavior of [`str.title`](https://docs.python.org/3/library/stdtypes.html#str.title) + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... { + ... "quotes": [ + ... "'e.t. phone home'", + ... "you talkin' to me?", + ... "to infinity,and BEYOND!", + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(quotes_title=nw.col("quotes").str.to_titlecase()) + ┌─────────────────────────────────────────────────────┐ + | Narwhals DataFrame | + |-----------------------------------------------------| + |shape: (3, 2) | + |┌─────────────────────────┬─────────────────────────┐| + |│ quotes ┆ quotes_title │| + |│ --- ┆ --- │| + |│ str ┆ str │| + |╞═════════════════════════╪═════════════════════════╡| + |│ 'e.t. phone home' ┆ 'E.T. Phone Home' │| + |│ you talkin' to me? ┆ You Talkin' To Me? │| + |│ to infinity,and BEYOND! ┆ To Infinity,And Beyond! │| + |└─────────────────────────┴─────────────────────────┘| + └─────────────────────────────────────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "str.to_titlecase")) + + def zfill(self, width: int) -> ExprT: + """Transform string to zero-padded variant. + + Arguments: + width: The desired length of the string after padding. If the length of the + string is greater than `width`, no padding is applied. + Must be non-negative. + + Raises: + ValueError: If `width` is negative. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"digits": ["+1", "-1", "1", None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(zfill_col=nw.col("digits").str.zfill(3)) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | digits zfill_col| + |0 +1 +01| + |1 -1 -01| + |2 1 001| + |3 NaN NaN| + └──────────────────┘ + """ + validate_str_non_negative("zfill", "width", width) + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.zfill", width=width) + ) + + def pad_start(self, length: int, fill_char: str = " ") -> ExprT: + """Pad the start of the string until it reaches the given length. + + Arguments: + length: Pad the string until it reaches this length. Strings with + length equal to or greater than this value are returned as-is. + Must be non-negative. + fill_char: The character to pad the string with. Must be exactly one + character. + + Raises: + ValueError: If `fill_char` is not a single character, or if `length` + is negative. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": ["cow", "monkey", "hippopotamus", None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(padded=nw.col("a").str.pad_start(8, "*")) + ┌─────────────────────────────┐ + | Narwhals DataFrame | + |-----------------------------| + | a padded| + |0 cow *****cow| + |1 monkey **monkey| + |2 hippopotamus hippopotamus| + |3 NaN NaN| + └─────────────────────────────┘ + """ + validate_pad_arguments("pad_start", length, fill_char) + return self._expr._append_node( + ExprNode( + ExprKind.ELEMENTWISE, "str.pad_start", length=length, fill_char=fill_char + ) + ) + + def pad_end(self, length: int, fill_char: str = " ") -> ExprT: + """Pad the end of the string until it reaches the given length. + + Arguments: + length: Pad the string until it reaches this length. Strings with + length equal to or greater than this value are returned as-is. + Must be non-negative. + fill_char: The character to pad the string with. Must be exactly one + character. + + Raises: + ValueError: If `fill_char` is not a single character, or if `length` + is negative. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": ["cow", "monkey", "hippopotamus", None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(padded=nw.col("a").str.pad_end(8, "*")) + ┌─────────────────────────────┐ + | Narwhals DataFrame | + |-----------------------------| + | a padded| + |0 cow cow*****| + |1 monkey monkey**| + |2 hippopotamus hippopotamus| + |3 NaN NaN| + └─────────────────────────────┘ + """ + validate_pad_arguments("pad_end", length, fill_char) + return self._expr._append_node( + ExprNode( + ExprKind.ELEMENTWISE, "str.pad_end", length=length, fill_char=fill_char + ) + ) diff --git a/shared/package-files/73/735c8a8045ed223f3d4986bdbe377bcaa2227a6f23c0b338bf037b533b1eb0f3/att4410v1 b/shared/package-files/73/735c8a8045ed223f3d4986bdbe377bcaa2227a6f23c0b338bf037b533b1eb0f3/att4410v1 new file mode 100644 index 0000000000000000000000000000000000000000..d7d7336bc66004b8cb23a52c0f0ee0922c1c0dc0 Binary files /dev/null and b/shared/package-files/73/735c8a8045ed223f3d4986bdbe377bcaa2227a6f23c0b338bf037b533b1eb0f3/att4410v1 differ diff --git a/shared/package-files/73/735c8a8045ed223f3d4986bdbe377bcaa2227a6f23c0b338bf037b533b1eb0f3/att5410v1 b/shared/package-files/73/735c8a8045ed223f3d4986bdbe377bcaa2227a6f23c0b338bf037b533b1eb0f3/att5410v1 new file mode 100644 index 0000000000000000000000000000000000000000..d7d7336bc66004b8cb23a52c0f0ee0922c1c0dc0 Binary files /dev/null and b/shared/package-files/73/735c8a8045ed223f3d4986bdbe377bcaa2227a6f23c0b338bf037b533b1eb0f3/att5410v1 differ diff --git a/shared/package-files/73/735c8a8045ed223f3d4986bdbe377bcaa2227a6f23c0b338bf037b533b1eb0f3/tty5410v1 b/shared/package-files/73/735c8a8045ed223f3d4986bdbe377bcaa2227a6f23c0b338bf037b533b1eb0f3/tty5410v1 new file mode 100644 index 0000000000000000000000000000000000000000..d7d7336bc66004b8cb23a52c0f0ee0922c1c0dc0 Binary files /dev/null and b/shared/package-files/73/735c8a8045ed223f3d4986bdbe377bcaa2227a6f23c0b338bf037b533b1eb0f3/tty5410v1 differ diff --git a/shared/package-files/73/735f3fe93acd80ff9212895653ee157ec2435d0d4d206a0bc1f48526b02fe192/libmambaTargets.cmake b/shared/package-files/73/735f3fe93acd80ff9212895653ee157ec2435d0d4d206a0bc1f48526b02fe192/libmambaTargets.cmake new file mode 100644 index 0000000000000000000000000000000000000000..a595b3eaef7c7e3d29e8f83a01d719c8f5984640 --- /dev/null +++ b/shared/package-files/73/735f3fe93acd80ff9212895653ee157ec2435d0d4d206a0bc1f48526b02fe192/libmambaTargets.cmake @@ -0,0 +1,108 @@ +# Generated by CMake + +if("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" LESS 2.8) + message(FATAL_ERROR "CMake >= 2.8.0 required") +endif() +if(CMAKE_VERSION VERSION_LESS "2.8.3") + message(FATAL_ERROR "CMake >= 2.8.3 required") +endif() +cmake_policy(PUSH) +cmake_policy(VERSION 2.8.3...3.24) +#---------------------------------------------------------------- +# Generated CMake target import file. +#---------------------------------------------------------------- + +# Commands may need to know the format version. +set(CMAKE_IMPORT_FILE_VERSION 1) + +# Protect against multiple inclusion, which would fail when already imported targets are added once more. +set(_cmake_targets_defined "") +set(_cmake_targets_not_defined "") +set(_cmake_expected_targets "") +foreach(_cmake_expected_target IN ITEMS libmamba) + list(APPEND _cmake_expected_targets "${_cmake_expected_target}") + if(TARGET "${_cmake_expected_target}") + list(APPEND _cmake_targets_defined "${_cmake_expected_target}") + else() + list(APPEND _cmake_targets_not_defined "${_cmake_expected_target}") + endif() +endforeach() +unset(_cmake_expected_target) +if(_cmake_targets_defined STREQUAL _cmake_expected_targets) + unset(_cmake_targets_defined) + unset(_cmake_targets_not_defined) + unset(_cmake_expected_targets) + unset(CMAKE_IMPORT_FILE_VERSION) + cmake_policy(POP) + return() +endif() +if(NOT _cmake_targets_defined STREQUAL "") + string(REPLACE ";" ", " _cmake_targets_defined_text "${_cmake_targets_defined}") + string(REPLACE ";" ", " _cmake_targets_not_defined_text "${_cmake_targets_not_defined}") + message(FATAL_ERROR "Some (but not all) targets in this export set were already defined.\nTargets Defined: ${_cmake_targets_defined_text}\nTargets not yet defined: ${_cmake_targets_not_defined_text}\n") +endif() +unset(_cmake_targets_defined) +unset(_cmake_targets_not_defined) +unset(_cmake_expected_targets) + + +# Compute the installation prefix relative to this file. +get_filename_component(_IMPORT_PREFIX "${CMAKE_CURRENT_LIST_FILE}" PATH) +get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) +get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) +get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) +if(_IMPORT_PREFIX STREQUAL "/") + set(_IMPORT_PREFIX "") +endif() + +# Create imported target libmamba +add_library(libmamba SHARED IMPORTED) + +set_target_properties(libmamba PROPERTIES + INTERFACE_COMPILE_FEATURES "cxx_std_17" + INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include" + INTERFACE_LINK_LIBRARIES "tl::expected;nlohmann_json::nlohmann_json;/opt/conda/lib/libsolv.so;/opt/conda/lib/libsolvext.so;/opt/conda/lib/libarchive.so;zstd::libzstd_shared;/opt/conda/lib/libcurl.so;/opt/conda/lib/libssl.so;/opt/conda/lib/libcrypto.so;zstd::libzstd_shared;BZip2::BZip2;yaml-cpp::yaml-cpp;reproc++;reproc;fmt::fmt;spdlog::spdlog_header_only" +) + +if(CMAKE_VERSION VERSION_LESS 2.8.12) + message(FATAL_ERROR "This file relies on consumers using CMake 2.8.12 or greater.") +endif() + +# Load information for each installed configuration. +file(GLOB _cmake_config_files "${CMAKE_CURRENT_LIST_DIR}/libmambaTargets-*.cmake") +foreach(_cmake_config_file IN LISTS _cmake_config_files) + include("${_cmake_config_file}") +endforeach() +unset(_cmake_config_file) +unset(_cmake_config_files) + +# Cleanup temporary variables. +set(_IMPORT_PREFIX) + +# Loop over all imported files and verify that they actually exist +foreach(_cmake_target IN LISTS _cmake_import_check_targets) + foreach(_cmake_file IN LISTS "_cmake_import_check_files_for_${_cmake_target}") + if(NOT EXISTS "${_cmake_file}") + message(FATAL_ERROR "The imported target \"${_cmake_target}\" references the file + \"${_cmake_file}\" +but this file does not exist. Possible reasons include: +* The file was deleted, renamed, or moved to another location. +* An install or uninstall procedure did not complete successfully. +* The installation package was faulty and contained + \"${CMAKE_CURRENT_LIST_FILE}\" +but not all the files it references. +") + endif() + endforeach() + unset(_cmake_file) + unset("_cmake_import_check_files_for_${_cmake_target}") +endforeach() +unset(_cmake_target) +unset(_cmake_import_check_targets) + +# This file does not depend on other imported targets which have +# been exported from the same project but in a separate export set. + +# Commands beyond this point should not need to know the version. +set(CMAKE_IMPORT_FILE_VERSION) +cmake_policy(POP) diff --git a/shared/package-files/73/7362d3a1c1dc9704c879a4753e6de654cc9fe4f97f8a67e3205c22e0ba6fd17b/fortran-sf8-1x3x5.dat b/shared/package-files/73/7362d3a1c1dc9704c879a4753e6de654cc9fe4f97f8a67e3205c22e0ba6fd17b/fortran-sf8-1x3x5.dat new file mode 100644 index 0000000000000000000000000000000000000000..25269ff9ea4f6dd3f8a9ca0c8ad27d399e4248f5 Binary files /dev/null and b/shared/package-files/73/7362d3a1c1dc9704c879a4753e6de654cc9fe4f97f8a67e3205c22e0ba6fd17b/fortran-sf8-1x3x5.dat differ diff --git a/shared/package-files/73/73650cc9ee09cae2eca8c5b82d4fad95aa89e9e74471728e9ec2945163023f23/adaptive_max_pool3d_backward_meta_dispatch.h b/shared/package-files/73/73650cc9ee09cae2eca8c5b82d4fad95aa89e9e74471728e9ec2945163023f23/adaptive_max_pool3d_backward_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..90f1538cbe1ef51fd4400f8e493ce7784541f5a8 --- /dev/null +++ b/shared/package-files/73/73650cc9ee09cae2eca8c5b82d4fad95aa89e9e74471728e9ec2945163023f23/adaptive_max_pool3d_backward_meta_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor adaptive_max_pool3d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices); +TORCH_API at::Tensor & adaptive_max_pool3d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices); +TORCH_API at::Tensor & adaptive_max_pool3d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices, at::Tensor & grad_input); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/73/73667fe2e6af4998714f7876843ce2b65422cf8c6e924c9fe1a9eb85dfc6e144/allclose_ops.h b/shared/package-files/73/73667fe2e6af4998714f7876843ce2b65422cf8c6e924c9fe1a9eb85dfc6e144/allclose_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..c6fb96ef8c2dea0482e71831a7fbd14be60c9d15 --- /dev/null +++ b/shared/package-files/73/73667fe2e6af4998714f7876843ce2b65422cf8c6e924c9fe1a9eb85dfc6e144/allclose_ops.h @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API allclose { + using schema = bool (const at::Tensor &, const at::Tensor &, double, double, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::allclose") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "allclose(Tensor self, Tensor other, float rtol=1e-05, float atol=1e-08, bool equal_nan=False) -> bool") + static bool call(const at::Tensor & self, const at::Tensor & other, double rtol, double atol, bool equal_nan); + static bool redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, double rtol, double atol, bool equal_nan); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/73/736829648de79347a1b08b95ee55f3ce68c55a8cb5d622f17413693b2ba19a0d/_log_softmax_meta_dispatch.h b/shared/package-files/73/736829648de79347a1b08b95ee55f3ce68c55a8cb5d622f17413693b2ba19a0d/_log_softmax_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..c6c5c2e24e3dd11aba12b2647e91bf9aa6a99a5d --- /dev/null +++ b/shared/package-files/73/736829648de79347a1b08b95ee55f3ce68c55a8cb5d622f17413693b2ba19a0d/_log_softmax_meta_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor _log_softmax(const at::Tensor & self, int64_t dim, bool half_to_float); +TORCH_API at::Tensor & _log_softmax_out(at::Tensor & out, const at::Tensor & self, int64_t dim, bool half_to_float); +TORCH_API at::Tensor & _log_softmax_outf(const at::Tensor & self, int64_t dim, bool half_to_float, at::Tensor & out); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/73/736e4bdd9e0696c1ff08ec48e1332a048173a4ed89e068c58f3ea4b2babe0626/clamp_max.h b/shared/package-files/73/736e4bdd9e0696c1ff08ec48e1332a048173a4ed89e068c58f3ea4b2babe0626/clamp_max.h new file mode 100644 index 0000000000000000000000000000000000000000..687ddcd4a4c4eb0e78016c287504158cdc586d79 --- /dev/null +++ b/shared/package-files/73/736e4bdd9e0696c1ff08ec48e1332a048173a4ed89e068c58f3ea4b2babe0626/clamp_max.h @@ -0,0 +1,63 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::clamp_max(Tensor self, Scalar max) -> Tensor +inline at::Tensor clamp_max(const at::Tensor & self, const at::Scalar & max) { + return at::_ops::clamp_max::call(self, max); +} + +// aten::clamp_max.Tensor(Tensor self, Tensor max) -> Tensor +inline at::Tensor clamp_max(const at::Tensor & self, const at::Tensor & max) { + return at::_ops::clamp_max_Tensor::call(self, max); +} + +// aten::clamp_max_(Tensor(a!) self, Scalar max) -> Tensor(a!) +inline at::Tensor & clamp_max_(at::Tensor & self, const at::Scalar & max) { + return at::_ops::clamp_max_::call(self, max); +} + +// aten::clamp_max_.Tensor(Tensor(a!) self, Tensor max) -> Tensor(a!) +inline at::Tensor & clamp_max_(at::Tensor & self, const at::Tensor & max) { + return at::_ops::clamp_max__Tensor::call(self, max); +} + +// aten::clamp_max.out(Tensor self, Scalar max, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & clamp_max_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & max) { + return at::_ops::clamp_max_out::call(self, max, out); +} +// aten::clamp_max.out(Tensor self, Scalar max, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & clamp_max_outf(const at::Tensor & self, const at::Scalar & max, at::Tensor & out) { + return at::_ops::clamp_max_out::call(self, max, out); +} + +// aten::clamp_max.Tensor_out(Tensor self, Tensor max, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & clamp_max_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & max) { + return at::_ops::clamp_max_Tensor_out::call(self, max, out); +} +// aten::clamp_max.Tensor_out(Tensor self, Tensor max, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & clamp_max_outf(const at::Tensor & self, const at::Tensor & max, at::Tensor & out) { + return at::_ops::clamp_max_Tensor_out::call(self, max, out); +} + +} diff --git a/shared/package-files/73/737031b78ff262b2afe2ca19f82193e36eea26dc653cc7f4e7c027a1d25f5721/test_holtwinters.py b/shared/package-files/73/737031b78ff262b2afe2ca19f82193e36eea26dc653cc7f4e7c027a1d25f5721/test_holtwinters.py new file mode 100644 index 0000000000000000000000000000000000000000..90bbbf156a456bccde672f73f63c842098ba36de --- /dev/null +++ b/shared/package-files/73/737031b78ff262b2afe2ca19f82193e36eea26dc653cc7f4e7c027a1d25f5721/test_holtwinters.py @@ -0,0 +1,2166 @@ +""" +Author: Terence L van Zyl +Modified: Kevin Sheppard +""" +from statsmodels.compat.pandas import MONTH_END, infer_freq +from statsmodels.compat.pytest import pytest_warns +from statsmodels.compat.scipy import BASINHOPPING_RNG + +import os +from pathlib import Path +import re +import warnings + +import numpy as np +from numpy.testing import assert_allclose, assert_almost_equal +import pandas as pd +import pytest +import scipy.stats + +from statsmodels.tools.sm_exceptions import ValueWarning +from statsmodels.tsa.holtwinters import ( + PY_SMOOTHERS, + SMOOTHERS, + ExponentialSmoothing, + Holt, + SimpleExpSmoothing, +) +from statsmodels.tsa.holtwinters._exponential_smoothers import ( + HoltWintersArgs, + _test_to_restricted, +) +from statsmodels.tsa.holtwinters._smoothers import ( + HoltWintersArgs as PyHoltWintersArgs, + to_restricted, + to_unrestricted, +) + +base, _ = os.path.split(Path(__file__).resolve()) +housing_data = pd.read_csv( + Path(base).joinpath("results", "housing-data.csv"), + index_col="DATE", + parse_dates=True, +) +housing_data = housing_data.asfreq("MS") + +SEASONALS = ("add", "mul", None) +TRENDS = ("add", "mul", None) + +# aust = pd.read_json(aust_json, typ='Series').sort_index() +data = [ + 41.727457999999999, + 24.04185, + 32.328102999999999, + 37.328707999999999, + 46.213152999999998, + 29.346326000000001, + 36.482909999999997, + 42.977719, + 48.901524999999999, + 31.180221, + 37.717880999999998, + 40.420211000000002, + 51.206862999999998, + 31.887228, + 40.978262999999998, + 43.772491000000002, + 55.558566999999996, + 33.850915000000001, + 42.076383, + 45.642291999999998, + 59.766779999999997, + 35.191876999999998, + 44.319737000000003, + 47.913736, +] +index = [ + "2005-03-01 00:00:00", + "2005-06-01 00:00:00", + "2005-09-01 00:00:00", + "2005-12-01 00:00:00", + "2006-03-01 00:00:00", + "2006-06-01 00:00:00", + "2006-09-01 00:00:00", + "2006-12-01 00:00:00", + "2007-03-01 00:00:00", + "2007-06-01 00:00:00", + "2007-09-01 00:00:00", + "2007-12-01 00:00:00", + "2008-03-01 00:00:00", + "2008-06-01 00:00:00", + "2008-09-01 00:00:00", + "2008-12-01 00:00:00", + "2009-03-01 00:00:00", + "2009-06-01 00:00:00", + "2009-09-01 00:00:00", + "2009-12-01 00:00:00", + "2010-03-01 00:00:00", + "2010-06-01 00:00:00", + "2010-09-01 00:00:00", + "2010-12-01 00:00:00", +] +idx = pd.to_datetime(index) +aust = pd.Series(data, index=pd.DatetimeIndex(idx, freq=infer_freq(idx))) + + +@pytest.fixture(scope="module") +def ses(): + rs = np.random.RandomState(0) + e = rs.standard_normal(1200) + y = e.copy() + for i in range(1, 1200): + y[i] = y[i - 1] + e[i] - 0.2 * e[i - 1] + y = y[200:] + index = pd.date_range("2000-1-1", periods=y.shape[0], freq=MONTH_END) + return pd.Series(y, index=index, name="y") + + +def _simple_dbl_exp_smoother(x, alpha, beta, l0, b0, nforecast=0): + """ + Simple, slow, direct implementation of double exp smoothing for testing + """ + n = x.shape[0] + lvals = np.zeros(n) + b = np.zeros(n) + xhat = np.zeros(n) + f = np.zeros(nforecast) + lvals[0] = l0 + b[0] = b0 + # Special case the 0 observations since index -1 is not available + xhat[0] = l0 + b0 + lvals[0] = alpha * x[0] + (1 - alpha) * (l0 + b0) + b[0] = beta * (lvals[0] - l0) + (1 - beta) * b0 + for t in range(1, n): + # Obs in index t is the time t forecast for t + 1 + lvals[t] = alpha * x[t] + (1 - alpha) * (lvals[t - 1] + b[t - 1]) + b[t] = beta * (lvals[t] - lvals[t - 1]) + (1 - beta) * b[t - 1] + + xhat[1:] = lvals[0:-1] + b[0:-1] + f[:] = lvals[-1] + np.arange(1, nforecast + 1) * b[-1] + err = x - xhat + return lvals, b, f, err, xhat + + +class TestHoltWinters: + @classmethod + def setup_class(cls): + # Changed for backwards compatibility with pandas + + # oildata_oil = pd.read_json(oildata_oil_json, + # typ='Series').sort_index() + data = [ + 446.65652290000003, + 454.47330649999998, + 455.66297400000002, + 423.63223879999998, + 456.27132790000002, + 440.58805009999998, + 425.33252010000001, + 485.14944789999998, + 506.04816210000001, + 526.79198329999997, + 514.26888899999994, + 494.21101929999998, + ] + index = [ + "1996-12-31 00:00:00", + "1997-12-31 00:00:00", + "1998-12-31 00:00:00", + "1999-12-31 00:00:00", + "2000-12-31 00:00:00", + "2001-12-31 00:00:00", + "2002-12-31 00:00:00", + "2003-12-31 00:00:00", + "2004-12-31 00:00:00", + "2005-12-31 00:00:00", + "2006-12-31 00:00:00", + "2007-12-31 00:00:00", + ] + oildata_oil = pd.Series(data, index) + oildata_oil.index = pd.DatetimeIndex( + oildata_oil.index, freq=infer_freq(oildata_oil.index) + ) + cls.oildata_oil = oildata_oil + + # air_ausair = pd.read_json(air_ausair_json, + # typ='Series').sort_index() + data = [ + 17.5534, + 21.860099999999999, + 23.886600000000001, + 26.929300000000001, + 26.888500000000001, + 28.831399999999999, + 30.075099999999999, + 30.953499999999998, + 30.185700000000001, + 31.579699999999999, + 32.577568999999997, + 33.477398000000001, + 39.021580999999998, + 41.386431999999999, + 41.596552000000003, + ] + index = [ + "1990-12-31 00:00:00", + "1991-12-31 00:00:00", + "1992-12-31 00:00:00", + "1993-12-31 00:00:00", + "1994-12-31 00:00:00", + "1995-12-31 00:00:00", + "1996-12-31 00:00:00", + "1997-12-31 00:00:00", + "1998-12-31 00:00:00", + "1999-12-31 00:00:00", + "2000-12-31 00:00:00", + "2001-12-31 00:00:00", + "2002-12-31 00:00:00", + "2003-12-31 00:00:00", + "2004-12-31 00:00:00", + ] + air_ausair = pd.Series(data, index) + air_ausair.index = pd.DatetimeIndex( + air_ausair.index, freq=infer_freq(air_ausair.index) + ) + cls.air_ausair = air_ausair + + # livestock2_livestock = pd.read_json(livestock2_livestock_json, + # typ='Series').sort_index() + data = [ + 263.91774700000002, + 268.30722200000002, + 260.662556, + 266.63941899999998, + 277.51577800000001, + 283.834045, + 290.30902800000001, + 292.474198, + 300.83069399999999, + 309.28665699999999, + 318.33108099999998, + 329.37239, + 338.88399800000002, + 339.24412599999999, + 328.60063200000002, + 314.25538499999999, + 314.45969500000001, + 321.41377899999998, + 329.78929199999999, + 346.38516499999997, + 352.29788200000002, + 348.37051500000001, + 417.56292200000001, + 417.12356999999997, + 417.749459, + 412.233904, + 411.94681700000001, + 394.69707499999998, + 401.49927000000002, + 408.27046799999999, + 414.24279999999999, + ] + index = [ + "1970-12-31 00:00:00", + "1971-12-31 00:00:00", + "1972-12-31 00:00:00", + "1973-12-31 00:00:00", + "1974-12-31 00:00:00", + "1975-12-31 00:00:00", + "1976-12-31 00:00:00", + "1977-12-31 00:00:00", + "1978-12-31 00:00:00", + "1979-12-31 00:00:00", + "1980-12-31 00:00:00", + "1981-12-31 00:00:00", + "1982-12-31 00:00:00", + "1983-12-31 00:00:00", + "1984-12-31 00:00:00", + "1985-12-31 00:00:00", + "1986-12-31 00:00:00", + "1987-12-31 00:00:00", + "1988-12-31 00:00:00", + "1989-12-31 00:00:00", + "1990-12-31 00:00:00", + "1991-12-31 00:00:00", + "1992-12-31 00:00:00", + "1993-12-31 00:00:00", + "1994-12-31 00:00:00", + "1995-12-31 00:00:00", + "1996-12-31 00:00:00", + "1997-12-31 00:00:00", + "1998-12-31 00:00:00", + "1999-12-31 00:00:00", + "2000-12-31 00:00:00", + ] + livestock2_livestock = pd.Series(data, index) + livestock2_livestock.index = pd.DatetimeIndex( + livestock2_livestock.index, + freq=infer_freq(livestock2_livestock.index), + ) + cls.livestock2_livestock = livestock2_livestock + + cls.aust = aust + cls.start_params = [ + 1.5520372162082909e-09, + 2.066338221674873e-18, + 1.727109018250519e-09, + 50.568333479425036, + 0.9129273810171223, + 0.83535867, + 0.50297119, + 0.62439273, + 0.67723128, + ] + + def test_predict(self): + fit1 = ExponentialSmoothing( + self.aust, + seasonal_periods=4, + trend="add", + seasonal="mul", + initialization_method="estimated", + ).fit(start_params=self.start_params) + fit2 = ExponentialSmoothing( + self.aust, + seasonal_periods=4, + trend="add", + seasonal="mul", + initialization_method="estimated", + ).fit(start_params=self.start_params) + # fit3 = ExponentialSmoothing(self.aust, seasonal_periods=4, + # trend='add', seasonal='mul').fit(remove_bias=True, + # use_basinhopping=True) + assert_almost_equal( + fit1.predict("2011-03-01 00:00:00", "2011-12-01 00:00:00"), + [61.3083, 37.3730, 46.9652, 51.5578], + 3, + ) + assert_almost_equal( + fit2.predict(end="2011-12-01 00:00:00"), + [61.3083, 37.3730, 46.9652, 51.5578], + 3, + ) + + # assert_almost_equal(fit3.predict('2010-10-01 00:00:00', + # '2010-10-01 00:00:00'), + # [49.087], 3) + + def test_ndarray(self): + fit1 = ExponentialSmoothing( + self.aust.values, + seasonal_periods=4, + trend="add", + seasonal="mul", + initialization_method="estimated", + ).fit(start_params=self.start_params) + assert_almost_equal(fit1.forecast(4), [61.3083, 37.3730, 46.9652, 51.5578], 3) + + # FIXME: this is passing 2019-05-22 on some platforms; what has changed? + @pytest.mark.xfail(reason="Optimizer does not converge", strict=False) + def test_forecast(self): + fit1 = ExponentialSmoothing( + self.aust, + seasonal_periods=4, + trend="add", + seasonal="add", + ).fit(method="bh", use_brute=True) + assert_almost_equal( + fit1.forecast(steps=4), [60.9542, 36.8505, 46.1628, 50.1272], 3 + ) + + def test_simple_exp_smoothing(self): + fit1 = SimpleExpSmoothing( + self.oildata_oil, initialization_method="legacy-heuristic" + ).fit(0.2, optimized=False) + fit2 = SimpleExpSmoothing( + self.oildata_oil, initialization_method="legacy-heuristic" + ).fit(0.6, optimized=False) + fit3 = SimpleExpSmoothing( + self.oildata_oil, initialization_method="estimated" + ).fit() + assert_almost_equal(fit1.forecast(1), [484.802468], 4) + assert_almost_equal( + fit1.level, + [ + 446.65652290, + 448.21987962, + 449.7084985, + 444.49324656, + 446.84886283, + 445.59670028, + 441.54386424, + 450.26498098, + 461.4216172, + 474.49569042, + 482.45033014, + 484.80246797, + ], + 4, + ) + assert_almost_equal(fit2.forecast(1), [501.837461], 4) + assert_almost_equal(fit3.forecast(1), [496.493543], 4) + assert_almost_equal(fit3.params["smoothing_level"], 0.891998, 4) + assert_almost_equal(fit3.params["initial_level"], 447.478440, 3) + + def test_holt(self): + fit1 = Holt(self.air_ausair, initialization_method="legacy-heuristic").fit( + smoothing_level=0.8, smoothing_trend=0.2, optimized=False + ) + fit2 = Holt( + self.air_ausair, + exponential=True, + initialization_method="legacy-heuristic", + ).fit(smoothing_level=0.8, smoothing_trend=0.2, optimized=False) + fit3 = Holt( + self.air_ausair, + damped_trend=True, + initialization_method="estimated", + ).fit(smoothing_level=0.8, smoothing_trend=0.2) + assert_almost_equal(fit1.forecast(5), [43.76, 45.59, 47.43, 49.27, 51.10], 2) + assert_almost_equal( + fit1.trend, + [ + 3.617628, + 3.59006512, + 3.33438212, + 3.23657639, + 2.69263502, + 2.46388914, + 2.2229097, + 1.95959226, + 1.47054601, + 1.3604894, + 1.28045881, + 1.20355193, + 1.88267152, + 2.09564416, + 1.83655482, + ], + 4, + ) + assert_almost_equal( + fit1.fittedfcast, + [ + 21.8601, + 22.032368, + 25.48461872, + 27.54058587, + 30.28813356, + 30.26106173, + 31.58122149, + 32.599234, + 33.24223906, + 32.26755382, + 33.07776017, + 33.95806605, + 34.77708354, + 40.05535303, + 43.21586036, + 43.75696849, + ], + 4, + ) + assert_almost_equal(fit2.forecast(5), [44.60, 47.24, 50.04, 53.01, 56.15], 2) + assert_almost_equal(fit3.forecast(5), [42.85, 43.81, 44.66, 45.41, 46.06], 2) + + @pytest.mark.smoke + def test_holt_damp_fit(self): + # Smoke test for parameter estimation + fit1 = SimpleExpSmoothing( + self.livestock2_livestock, initialization_method="estimated" + ).fit() + mod4 = Holt( + self.livestock2_livestock, + damped_trend=True, + initialization_method="estimated", + ) + fit4 = mod4.fit(damping_trend=0.98, method="least_squares") + mod5 = Holt( + self.livestock2_livestock, + exponential=True, + damped_trend=True, + initialization_method="estimated", + ) + fit5 = mod5.fit() + # We accept the below values as we getting a better SSE than text book + assert_almost_equal(fit1.params["smoothing_level"], 1.00, 2) + assert_almost_equal(fit1.params["smoothing_trend"], np.nan, 2) + assert_almost_equal(fit1.params["damping_trend"], np.nan, 2) + assert_almost_equal(fit1.params["initial_level"], 263.96, 1) + assert_almost_equal(fit1.params["initial_trend"], np.nan, 2) + assert_almost_equal(fit1.sse, 6761.35, 2) # 6080.26 + assert isinstance(fit1.summary().as_text(), str) + + assert_almost_equal(fit4.params["smoothing_level"], 0.98, 2) + assert_almost_equal(fit4.params["smoothing_trend"], 0.00, 2) + assert_almost_equal(fit4.params["damping_trend"], 0.98, 2) + assert_almost_equal(fit4.params["initial_level"], 257.36, 2) + assert_almost_equal(fit4.params["initial_trend"], 6.64, 2) + assert_almost_equal(fit4.sse, 6036.56, 2) # 6080.26 + assert isinstance(fit4.summary().as_text(), str) + + assert_almost_equal(fit5.params["smoothing_level"], 0.97, 2) + assert_almost_equal(fit5.params["smoothing_trend"], 0.00, 2) + assert_almost_equal(fit5.params["damping_trend"], 0.98, 2) + assert_almost_equal(fit5.params["initial_level"], 258.95, 1) + assert_almost_equal(fit5.params["initial_trend"], 1.04, 2) + assert_almost_equal(fit5.sse, 6082.00, 0) # 6100.11 + assert isinstance(fit5.summary().as_text(), str) + + def test_holt_damp_r(self): + # Test the damping parameters against the R forecast packages `ets` + # library(ets) + # livestock2_livestock <- c(...) + # res <- ets(livestock2_livestock, model='AAN', damped_trend=TRUE, + # phi=0.98) + mod = Holt( + self.livestock2_livestock, + damped_trend=True, + initialization_method="estimated", + ) + params = { + "smoothing_level": 0.97402626, + "smoothing_trend": 0.00010006, + "damping_trend": 0.98, + "initial_level": 252.59039965, + "initial_trend": 6.90265918, + } + with mod.fix_params(params): + fit = mod.fit(optimized=False) + + # Check that we captured the parameters correctly + for key, param_value in params.items(): + assert_allclose(fit.params[key], param_value) + + with mod.fix_params(params): + opt_fit = mod.fit(optimized=True) + assert_allclose(fit.sse, opt_fit.sse) + assert_allclose(opt_fit.params["initial_trend"], params["initial_trend"]) + alt_params = {k: v for k, v in params.items() if "level" not in k} + with mod.fix_params(alt_params): + alt_fit = mod.fit(optimized=True) + assert not np.allclose(alt_fit.trend.iloc[0], opt_fit.trend.iloc[0]) + # Summary output + # print(res$mse) + assert_allclose(fit.sse / mod.nobs, 195.4397924865488, atol=1e-3) + # print(res$aicc) + # TODO: this fails - different AICC definition? + # assert_allclose(fit.aicc, 282.386426659408, atol=1e-3) + # print(res$bic) + # TODO: this fails - different BIC definition? + # assert_allclose(fit.bic, 287.1563626818338) + + # print(res$states[,'l']) + # note: this array includes the initial level + desired = [ + 252.5903996514365, + 263.7992355246843, + 268.3623324350207, + 261.0312983437606, + 266.6590942700923, + 277.3958197247272, + 283.8256217863908, + 290.2962560621914, + 292.5701438129583, + 300.7655919939834, + 309.2118057241649, + 318.2377698496536, + 329.2238709362550, + 338.7709778307978, + 339.3669793596703, + 329.0127022356033, + 314.7684267018998, + 314.5948077575944, + 321.3612035017972, + 329.6924360833211, + 346.0712138652086, + 352.2534120008911, + 348.5862874190927, + 415.8839400693967, + 417.2018843196238, + 417.8435306633725, + 412.4857261252961, + 412.0647865321129, + 395.2500605270393, + 401.4367438266322, + 408.1907701386275, + 414.1814574903921, + ] + assert_allclose(np.r_[fit.params["initial_level"], fit.level], desired) + + # print(res$states[,'b']) + # note: this array includes the initial slope + desired = [ + 6.902659175332394, + 6.765062519124909, + 6.629548973536494, + 6.495537532917715, + 6.365550989616566, + 6.238702070454378, + 6.113960476763530, + 5.991730467006233, + 5.871526257315264, + 5.754346516684953, + 5.639547926790058, + 5.527116419415724, + 5.417146212898857, + 5.309238662451385, + 5.202580636191761, + 5.096941655567694, + 4.993026494493987, + 4.892645486210410, + 4.794995106664251, + 4.699468310763351, + 4.606688340205792, + 4.514725879754355, + 4.423600168391240, + 4.341595902295941, + 4.254462303550087, + 4.169010676686062, + 4.084660399498803, + 4.002512751871354, + 3.920332298146730, + 3.842166514133902, + 3.765630194200260, + 3.690553892582855, + ] + # TODO: not sure why the precision is so low here... + assert_allclose( + np.r_[fit.params["initial_trend"], fit.trend], desired, atol=1e-3 + ) + + # print(res$fitted) + desired = [ + 259.3550056432622, + 270.4289967934267, + 274.8592904290865, + 267.3969251260200, + 272.8973342399166, + 283.5097477537724, + 289.8173030536191, + 296.1681519198575, + 298.3242395451272, + 306.4048515803347, + 314.7385626924191, + 323.6543439406810, + 334.5326742248959, + 343.9740317200002, + 344.4655083831382, + 334.0077050580596, + 319.6615926665040, + 319.3896003340806, + 326.0602987063282, + 334.2979150278692, + 350.5857684386102, + 356.6778433630504, + 352.9214155841161, + 420.1387040536467, + 421.3712573771029, + 421.9291611265248, + 416.4886933168049, + 415.9872490289468, + 399.0919861792231, + 405.2020670104834, + 411.8810877289437, + ] + assert_allclose(fit.fittedvalues, desired, atol=1e-3) + + # print(forecast(res)$mean) + desired = [ + 417.7982003051233, + 421.3426082635598, + 424.8161280628277, + 428.2201774661102, + 431.5561458813270, + 434.8253949282395, + 438.0292589942138, + 441.1690457788685, + 444.2460368278302, + 447.2614880558126, + ] + assert_allclose(fit.forecast(10), desired, atol=1e-4) + + def test_hw_seasonal(self): + mod = ExponentialSmoothing( + self.aust, + seasonal_periods=4, + trend="additive", + seasonal="additive", + initialization_method="estimated", + use_boxcox=True, + ) + fit1 = mod.fit() + assert_almost_equal( + fit1.forecast(8), + [59.96, 38.63, 47.48, 51.89, 62.81, 41.0, 50.06, 54.57], + 2, + ) + + def test_hw_seasonal_add_mul(self): + mod2 = ExponentialSmoothing( + self.aust, + seasonal_periods=4, + trend="add", + seasonal="mul", + initialization_method="estimated", + use_boxcox=True, + ) + fit2 = mod2.fit() + assert_almost_equal( + fit2.forecast(8), + [61.69, 37.37, 47.22, 52.03, 65.08, 39.34, 49.72, 54.79], + 2, + ) + ExponentialSmoothing( + self.aust, + seasonal_periods=4, + trend="mul", + seasonal="add", + initialization_method="estimated", + use_boxcox=0.0, + ).fit() + ExponentialSmoothing( + self.aust, + seasonal_periods=4, + trend="multiplicative", + seasonal="multiplicative", + initialization_method="estimated", + use_boxcox=0.0, + ).fit() + # Skip since estimator is unstable + # assert_almost_equal(fit5.forecast(1), [60.60], 2) + # assert_almost_equal(fit6.forecast(1), [61.47], 2) + + def test_hw_seasonal_buggy(self): + fit3 = ExponentialSmoothing( + self.aust, + seasonal_periods=4, + seasonal="add", + initialization_method="estimated", + use_boxcox=True, + ).fit() + assert_almost_equal( + fit3.forecast(8), + [ + 59.487190, + 35.758854, + 44.600641, + 47.751384, + 59.487190, + 35.758854, + 44.600641, + 47.751384, + ], + 2, + ) + fit4 = ExponentialSmoothing( + self.aust, + seasonal_periods=4, + seasonal="mul", + initialization_method="estimated", + use_boxcox=True, + ).fit() + assert_almost_equal( + fit4.forecast(8), + [ + 59.26155037, + 35.27811302, + 44.00438543, + 47.97732693, + 59.26155037, + 35.27811302, + 44.00438543, + 47.97732693, + ], + 2, + ) + + +@pytest.mark.parametrize( + "trend_seasonal", [("mul", None), (None, "mul"), ("mul", "mul")] +) +def test_negative_multipliative(trend_seasonal): + trend, seasonal = trend_seasonal + y = -np.ones(100) + with pytest.raises(ValueError): + ExponentialSmoothing(y, trend=trend, seasonal=seasonal, seasonal_periods=10) + + +@pytest.mark.parametrize("seasonal", SEASONALS) +def test_dampen_no_trend(seasonal): + with pytest.raises(TypeError): + ExponentialSmoothing( + housing_data, + trend=False, + seasonal=seasonal, + damped_trend=True, + seasonal_periods=10, + ) + + +@pytest.mark.parametrize("seasonal", ["add", "mul"]) +def test_invalid_seasonal(seasonal): + y = pd.Series( + -np.ones(100), index=pd.date_range("2000-1-1", periods=100, freq="MS") + ) + with pytest.raises(ValueError): + ExponentialSmoothing(y, seasonal=seasonal, seasonal_periods=1) + + +def test_2d_data(): + with pytest.raises(ValueError): + ExponentialSmoothing(pd.concat([housing_data, housing_data], axis=1)).fit() + + +@pytest.mark.thread_unsafe(reason="Issues and checks warnings") +def test_infer_freq(): + hd2 = housing_data.copy() + hd2.index = list(hd2.index) + with warnings.catch_warnings(record=True) as w: + mod = ExponentialSmoothing( + hd2, trend="add", seasonal="add", initialization_method="estimated" + ) + assert len(w) == 1 + assert "ValueWarning" in str(w[0]) + assert mod.seasonal_periods == 12 + + +@pytest.mark.parametrize("trend", TRENDS) +@pytest.mark.parametrize("seasonal", SEASONALS) +def test_start_params(trend, seasonal): + rs = np.random.RandomState(98789431) + mod = ExponentialSmoothing( + housing_data, + trend=trend, + seasonal=seasonal, + initialization_method="estimated", + ) + res = mod.fit() + res2 = mod.fit( + method="basinhopping", + minimize_kwargs={ + "minimizer_kwargs": {"method": "L-BFGS-B"}, + BASINHOPPING_RNG: rs, + }, + ) + assert isinstance(res.summary().as_text(), str) + assert res2.sse < 1.01 * res.sse + assert isinstance(res2.params, dict) + + +def test_no_params_to_optimize(): + mod = ExponentialSmoothing( + housing_data, + initial_level=housing_data.iloc[0], + initialization_method="known", + ) + mod.fit(smoothing_level=0.5) + + +def test_invalid_start_param_length(): + mod = ExponentialSmoothing(housing_data, initialization_method="estimated") + with pytest.raises(ValueError): + mod.fit(start_params=np.array([0.5])) + + +def test_basin_hopping(): + rs = np.random.RandomState(98789437) + mod = ExponentialSmoothing( + housing_data, trend="add", initialization_method="estimated" + ) + res = mod.fit() + res2 = mod.fit(method="basinhopping", minimize_kwargs={BASINHOPPING_RNG: rs}) + assert isinstance(res.summary().as_text(), str) + assert isinstance(res2.summary().as_text(), str) + # Basin hopping occasionally produces a slightly larger objective + tol = 1e-5 + assert res2.sse <= res.sse + tol + res3 = mod.fit(method="basinhopping", minimize_kwargs={BASINHOPPING_RNG: rs}) + assert_almost_equal(res2.sse, res3.sse, decimal=2) + + +def test_debiased(): + mod = ExponentialSmoothing( + housing_data, trend="add", initialization_method="estimated" + ) + res = mod.fit() + res2 = mod.fit(remove_bias=True) + assert np.any(res.fittedvalues != res2.fittedvalues) + err2 = housing_data.iloc[:, 0] - res2.fittedvalues + assert_almost_equal(err2.mean(), 0.0) + assert isinstance(res.summary().as_text(), str) + assert isinstance(res2.summary().as_text(), str) + + +@pytest.mark.smoke +@pytest.mark.parametrize("trend", TRENDS) +@pytest.mark.parametrize("seasonal", SEASONALS) +def test_float_boxcox(trend, seasonal): + res = ExponentialSmoothing( + housing_data, + trend=trend, + seasonal=seasonal, + initialization_method="estimated", + use_boxcox=0.5, + ).fit() + assert_allclose(res.params["use_boxcox"], 0.5) + res = ExponentialSmoothing( + housing_data, + trend=trend, + seasonal=seasonal, + use_boxcox=0.5, + ).fit() + assert_allclose(res.params["use_boxcox"], 0.5) + + +def test_use_boxcox_fit_override(): + # Regression test: when use_boxcox is set at model init, passing + # use_boxcox to fit() should NOT be silently ignored (issue #9797). + # Before fix: fit(use_boxcox=False) on a use_boxcox=True model + # incorrectly skipped Box-Cox transformation because the override + # check was `if use_boxcox == "log"` instead of `if use_boxcox is not None`. + y = np.abs(housing_data) + 1 # ensure positive values for Box-Cox + mod = ExponentialSmoothing( + y, + trend="add", + seasonal="add", + initialization_method="estimated", + use_boxcox=True, + ) + res = mod.fit() + # With use_boxcox=True at model level, Box-Cox is applied and lambda > 0 + assert ( + res.params["use_boxcox"] != 0.0 + ), "Box-Cox lambda should not be 0 when use_boxcox=True at model init" + # When use_boxcox=True at model init, Box-Cox IS applied + # (lambda ~= 0.5 for this data, not False/0) + assert ( + res.params["lamda"] is not None + ), f"Expected fitted lambda, got {res.params['lamda']}" + + +@pytest.mark.parametrize("trend", TRENDS) +@pytest.mark.parametrize("seasonal", SEASONALS) +def test_equivalence_cython_python(trend, seasonal): + mod = ExponentialSmoothing( + housing_data, + trend=trend, + seasonal=seasonal, + initialization_method="estimated", + ) + + # Overflow in mul-mul case fixed + res = mod.fit() + assert isinstance(res.summary().as_text(), str) + + params = res.params + nobs = housing_data.shape[0] + y = np.squeeze(np.asarray(housing_data)) + m = 12 if seasonal else 0 + p = np.zeros(6 + m) + alpha = params["smoothing_level"] + beta = params["smoothing_trend"] + gamma = params["smoothing_seasonal"] + phi = params["damping_trend"] + phi = 1.0 if np.isnan(phi) else phi + l0 = params["initial_level"] + b0 = params["initial_trend"] + p[:6] = alpha, beta, gamma, l0, b0, phi + if seasonal: + p[6:] = params["initial_seasons"] + xi = np.ones_like(p).astype(np.int64) + + p_copy = p.copy() + + bounds = np.array([[0.0, 1.0]] * 3) + py_func = PY_SMOOTHERS[(seasonal, trend)] + cy_func = SMOOTHERS[(seasonal, trend)] + py_hw_args = PyHoltWintersArgs(xi, p_copy, bounds, y, m, nobs, False) + cy_hw_args = HoltWintersArgs(xi, p_copy, bounds, y, m, nobs, False) + + sse_cy = cy_func(p, cy_hw_args) + sse_py = py_func(p, py_hw_args) + assert_allclose(sse_py, sse_cy) + sse_py = py_func(p, cy_hw_args) + assert_allclose(sse_py, sse_cy) + + +def test_direct_holt_add(): + mod = SimpleExpSmoothing(housing_data, initialization_method="estimated") + res = mod.fit() + assert isinstance(res.summary().as_text(), str) + x = np.squeeze(np.asarray(mod.endog)) + alpha = res.params["smoothing_level"] + lvl, b, f, _, xhat = _simple_dbl_exp_smoother( + x, alpha, beta=0.0, l0=res.params["initial_level"], b0=0.0, nforecast=5 + ) + + assert_allclose(lvl, res.level) + assert_allclose(f, res.level.iloc[-1] * np.ones(5)) + assert_allclose(f, res.forecast(5)) + + mod = ExponentialSmoothing( + housing_data, trend="add", initialization_method="estimated" + ) + res = mod.fit() + x = np.squeeze(np.asarray(mod.endog)) + alpha = res.params["smoothing_level"] + beta = res.params["smoothing_trend"] + lvl, b, f, _, xhat = _simple_dbl_exp_smoother( + x, + alpha, + beta=beta, + l0=res.params["initial_level"], + b0=res.params["initial_trend"], + nforecast=5, + ) + + assert_allclose(xhat, res.fittedvalues) + assert_allclose(lvl + b, res.level + res.trend) + assert_allclose(lvl, res.level) + assert_allclose(b, res.trend) + assert_allclose( + f, res.level.iloc[-1] + res.trend.iloc[-1] * np.array([1, 2, 3, 4, 5]) + ) + assert_allclose(f, res.forecast(5)) + assert isinstance(res.summary().as_text(), str) + + +def test_integer_array(): + rs = np.random.RandomState(12345) + e = 10 * rs.standard_normal((1000, 2)) + y_star = np.cumsum(e[:, 0]) + y = y_star + e[:, 1] + y = y.astype(int) + res = ExponentialSmoothing(y, trend="add", initialization_method="estimated").fit() + assert res.params["smoothing_level"] != 0.0 + + +def test_damping_trend_zero(): + endog = np.arange(10) + mod = ExponentialSmoothing( + endog, + trend="add", + damped_trend=True, + initialization_method="estimated", + ) + res1 = mod.fit(smoothing_level=1, smoothing_trend=0.0, damping_trend=1e-20) + pred1 = res1.predict(start=0) + assert_allclose(pred1, np.r_[0.0, np.arange(9)], atol=1e-10) + + res2 = mod.fit(smoothing_level=1, smoothing_trend=0.0, damping_trend=0) + pred2 = res2.predict(start=0) + assert_allclose(pred2, np.r_[0.0, np.arange(9)], atol=1e-10) + + assert_allclose(pred1, pred2, atol=1e-10) + + +def test_different_inputs(): + array_input_add = [10, 20, 30, 40, 50] + series_index_add = pd.date_range(start="2000-1-1", periods=len(array_input_add)) + series_input_add = pd.Series(array_input_add, series_index_add) + + array_input_mul = [2, 4, 8, 16, 32] + series_index_mul = pd.date_range(start="2000-1-1", periods=len(array_input_mul)) + series_input_mul = pd.Series(array_input_mul, series_index_mul) + + fit1 = ExponentialSmoothing(array_input_add, trend="add").fit() + fit2 = ExponentialSmoothing(series_input_add, trend="add").fit() + fit3 = ExponentialSmoothing(array_input_mul, trend="mul").fit() + fit4 = ExponentialSmoothing(series_input_mul, trend="mul").fit() + + assert_almost_equal(fit1.predict(), [60], 1) + assert_almost_equal(fit1.predict(start=5, end=7), [60, 70, 80], 1) + assert_almost_equal(fit2.predict(), [60], 1) + assert_almost_equal(fit2.predict(start="2000-1-6", end="2000-1-8"), [60, 70, 80], 1) + assert_almost_equal(fit3.predict(), [64], 1) + assert_almost_equal(fit3.predict(start=5, end=7), [64, 128, 256], 1) + assert_almost_equal(fit4.predict(), [64], 1) + assert_almost_equal( + fit4.predict(start="2000-1-6", end="2000-1-8"), [64, 128, 256], 1 + ) + + +@pytest.fixture +def austourists(): + # austourists dataset from fpp2 package + # https://cran.r-project.org/web/packages/fpp2/index.html + data = [ + 30.05251, + 19.14850, + 25.31769, + 27.59144, + 32.07646, + 23.48796, + 28.47594, + 35.12375, + 36.83848, + 25.00702, + 30.72223, + 28.69376, + 36.64099, + 23.82461, + 29.31168, + 31.77031, + 35.17788, + 19.77524, + 29.60175, + 34.53884, + 41.27360, + 26.65586, + 28.27986, + 35.19115, + 42.20566, + 24.64917, + 32.66734, + 37.25735, + 45.24246, + 29.35048, + 36.34421, + 41.78208, + 49.27660, + 31.27540, + 37.85063, + 38.83704, + 51.23690, + 31.83855, + 41.32342, + 42.79900, + 55.70836, + 33.40714, + 42.31664, + 45.15712, + 59.57608, + 34.83733, + 44.84168, + 46.97125, + 60.01903, + 38.37118, + 46.97586, + 50.73380, + 61.64687, + 39.29957, + 52.67121, + 54.33232, + 66.83436, + 40.87119, + 51.82854, + 57.49191, + 65.25147, + 43.06121, + 54.76076, + 59.83447, + 73.25703, + 47.69662, + 61.09777, + 66.05576, + ] + index = pd.date_range("1999-03-01", "2015-12-01", freq="3MS") + return pd.Series(data, index) + + +@pytest.fixture +def simulate_expected_results_r(): + """ + obtained from ets.simulate in the R package forecast, data is from fpp2 + package. + + library(magrittr) + library(fpp2) + library(forecast) + concat <- function(...) { + return(paste(..., sep="")) + } + error <- c("A", "M") + trend <- c("A", "M", "N") + seasonal <- c("A", "M", "N") + models <- outer(error, trend, FUN = "concat") %>% + outer(seasonal, FUN = "concat") %>% as.vector + # innov from np.random.seed(0); np.random.randn(4) + innov <- c(1.76405235, 0.40015721, 0.97873798, 2.2408932) + params <- expand.grid(models, c(TRUE, FALSE)) + results <- apply(params, 1, FUN = function(p) { + tryCatch( + simulate(ets(austourists, model = p[1], damped = as.logical(p[2])), + innov = innov), + error = function(e) c(NA, NA, NA, NA)) + }) %>% t + rownames(results) <- apply(params, 1, FUN = function(x) paste(x[1], x[2])) + """ + damped = { + "AAA": [77.84173, 52.69818, 65.83254, 71.85204], + "MAA": [207.81653, 136.97700, 253.56234, 588.95800], + "MAM": [215.83822, 127.17132, 269.09483, 704.32105], + "MMM": [216.52591, 132.47637, 283.04889, 759.08043], + "AAN": [62.51423, 61.87381, 63.14735, 65.11360], + "MAN": [168.25189, 90.46201, 133.54769, 232.81738], + "MMN": [167.97747, 90.59675, 134.20300, 235.64502], + } + undamped = { + "AAA": [77.10860, 51.51669, 64.46857, 70.36349], + "MAA": [209.23158, 149.62943, 270.65579, 637.03828], + "ANA": [77.09320, 51.52384, 64.36231, 69.84786], + "MNA": [207.86986, 169.42706, 313.97960, 793.97948], + "MAM": [214.45750, 106.19605, 211.61304, 492.12223], + "MMM": [221.01861, 158.55914, 403.22625, 1389.33384], + "MNM": [215.00997, 140.93035, 309.92465, 875.07985], + "AAN": [63.66619, 63.09571, 64.45832, 66.51967], + "MAN": [172.37584, 91.51932, 134.11221, 230.98970], + "MMN": [169.88595, 97.33527, 142.97017, 252.51834], + "ANN": [60.53589, 59.51851, 60.17570, 61.63011], + "MNN": [163.01575, 112.58317, 172.21992, 338.93918], + } + return {True: damped, False: undamped} + + +@pytest.fixture +def simulate_fit_state_r(): + """ + The final state from the R model fits to get an exact comparison + Obtained with this R script: + + library(magrittr) + library(fpp2) + library(forecast) + + concat <- function(...) { + return(paste(..., sep="")) + } + + as_dict_string <- function(named) { + string <- '{' + for (name in names(named)) { + string <- concat(string, "\"", name, "\": ", named[name], ", ") + } + string <- concat(string, '}') + return(string) + } + + get_var <- function(named, name) { + if (name %in% names(named)) + val <- c(named[name]) + else + val <- c(NaN) + names(val) <- c(name) + return(val) + } + + error <- c("A", "M") + trend <- c("A", "M", "N") + seasonal <- c("A", "M", "N") + models <- outer(error, trend, FUN = "concat") %>% + outer(seasonal, FUN = "concat") %>% as.vector + + # innov from np.random.seed(0); np.random.randn(4) + innov <- c(1.76405235, 0.40015721, 0.97873798, 2.2408932) + n <- length(austourists) + 1 + + # print fit parameters and final states + for (damped in c(TRUE, FALSE)) { + print(paste("damped =", damped)) + for (model in models) { + state <- tryCatch((function(){ + fit <- ets(austourists, model = model, damped = damped) + pars <- c() + # alpha, beta, gamma, phi + for (name in c("alpha", "beta", "gamma", "phi")) { + pars <- c(pars, get_var(fit$par, name)) + } + # l, b, s1, s2, s3, s4 + states <- c() + for (name in c("l", "b", "s1", "s2", "s3", "s4")) + states <- c(states, get_var(fit$states[n,], name)) + c(pars, states) + })(), + error = function(e) rep(NA, 10)) + cat(concat("\"", model, "\": ", as_dict_string(state), ",\n")) + } + } + """ + damped = { + "AAA": { + "alpha": 0.35445427317618, + "beta": 0.0320074905894167, + "gamma": 0.399933869627979, + "phi": 0.979999965983533, + "l": 62.003405788717, + "b": 0.706524957599738, + "s1": 3.58786406600866, + "s2": -0.0747450283892903, + "s3": -11.7569356589817, + "s4": 13.3818805055271, + }, + "MAA": { + "alpha": 0.31114284033284, + "beta": 0.0472138763848083, + "gamma": 0.309502324693322, + "phi": 0.870889202791893, + "l": 59.2902342851514, + "b": 0.62538315801909, + "s1": 5.66660224738038, + "s2": 2.16097311633352, + "s3": -9.20020909069337, + "s4": 15.3505801601698, + }, + "MAM": { + "alpha": 0.483975835390643, + "beta": 0.00351728130401287, + "gamma": 0.00011309784353818, + "phi": 0.979999998322032, + "l": 63.0042707536293, + "b": 0.275035160634846, + "s1": 1.03531670491486, + "s2": 0.960515682506077, + "s3": 0.770086097577864, + "s4": 1.23412213281709, + }, + "MMM": { + "alpha": 0.523526123191035, + "beta": 0.000100021136675999, + "gamma": 0.000100013723372502, + "phi": 0.971025672907157, + "l": 63.2030316675533, + "b": 1.00458391644788, + "s1": 1.03476354353096, + "s2": 0.959953222294316, + "s3": 0.771346403552048, + "s4": 1.23394845160922, + }, + "AAN": { + "alpha": 0.014932817259302, + "beta": 0.0149327068053362, + "gamma": np.nan, + "phi": 0.979919958387887, + "l": 60.0651024395378, + "b": 0.699112782133822, + "s1": np.nan, + "s2": np.nan, + "s3": np.nan, + "s4": np.nan, + }, + "MAN": { + "alpha": 0.0144217343786778, + "beta": 0.0144216994589862, + "gamma": np.nan, + "phi": 0.979999719878659, + "l": 60.1870032363649, + "b": 0.698421913047609, + "s1": np.nan, + "s2": np.nan, + "s3": np.nan, + "s4": np.nan, + }, + "MMN": { + "alpha": 0.015489181776072, + "beta": 0.0154891632646377, + "gamma": np.nan, + "phi": 0.975139118496093, + "l": 60.1855946424729, + "b": 1.00999589024928, + "s1": np.nan, + "s2": np.nan, + "s3": np.nan, + "s4": np.nan, + }, + } + undamped = { + "AAA": { + "alpha": 0.20281951627363, + "beta": 0.000169786227368617, + "gamma": 0.464523797585052, + "phi": np.nan, + "l": 62.5598121416791, + "b": 0.578091734736357, + "s1": 2.61176734723357, + "s2": -1.24386240029203, + "s3": -12.9575427049515, + "s4": 12.2066400808086, + }, + "MAA": { + "alpha": 0.416371920801538, + "beta": 0.000100008012920072, + "gamma": 0.352943901103959, + "phi": np.nan, + "l": 62.0497742976079, + "b": 0.450130087198346, + "s1": 3.50368220490457, + "s2": -0.0544297321113539, + "s3": -11.6971093199679, + "s4": 13.1974985095916, + }, + "ANA": { + "alpha": 0.54216694759434, + "beta": np.nan, + "gamma": 0.392030170511872, + "phi": np.nan, + "l": 57.606831186929, + "b": np.nan, + "s1": 8.29613785790501, + "s2": 4.6033791939889, + "s3": -7.43956343440823, + "s4": 17.722316385643, + }, + "MNA": { + "alpha": 0.532842556756286, + "beta": np.nan, + "gamma": 0.346387433608713, + "phi": np.nan, + "l": 58.0372808528325, + "b": np.nan, + "s1": 7.70802088750111, + "s2": 4.14885814748503, + "s3": -7.72115936226225, + "s4": 17.1674660340923, + }, + "MAM": { + "alpha": 0.315621390571192, + "beta": 0.000100011993615961, + "gamma": 0.000100051297784532, + "phi": np.nan, + "l": 62.4082004238551, + "b": 0.513327867101983, + "s1": 1.03713425342421, + "s2": 0.959607104686072, + "s3": 0.770172817592091, + "s4": 1.23309264451638, + }, + "MMM": { + "alpha": 0.546068965886, + "beta": 0.0737816453485457, + "gamma": 0.000100031693302807, + "phi": np.nan, + "l": 63.8203866275649, + "b": 1.01833305374778, + "s1": 1.03725227137871, + "s2": 0.961177239042923, + "s3": 0.771173487523454, + "s4": 1.23036313932852, + }, + "MNM": { + "alpha": 0.608993139624813, + "beta": np.nan, + "gamma": 0.000167258612971303, + "phi": np.nan, + "l": 63.1472153330648, + "b": np.nan, + "s1": 1.0384840572776, + "s2": 0.961456755855531, + "s3": 0.768427399477366, + "s4": 1.23185085956321, + }, + "AAN": { + "alpha": 0.0097430554119077, + "beta": 0.00974302759255084, + "gamma": np.nan, + "phi": np.nan, + "l": 61.1430969243248, + "b": 0.759041621012503, + "s1": np.nan, + "s2": np.nan, + "s3": np.nan, + "s4": np.nan, + }, + "MAN": { + "alpha": 0.0101749952821338, + "beta": 0.0101749138539332, + "gamma": np.nan, + "phi": np.nan, + "l": 61.6020426238699, + "b": 0.761407500773051, + "s1": np.nan, + "s2": np.nan, + "s3": np.nan, + "s4": np.nan, + }, + "MMN": { + "alpha": 0.0664382968951546, + "beta": 0.000100001678373356, + "gamma": np.nan, + "phi": np.nan, + "l": 60.7206911970871, + "b": 1.01221899136391, + "s1": np.nan, + "s2": np.nan, + "s3": np.nan, + "s4": np.nan, + }, + "ANN": { + "alpha": 0.196432515825523, + "beta": np.nan, + "gamma": np.nan, + "phi": np.nan, + "l": 58.7718395431632, + "b": np.nan, + "s1": np.nan, + "s2": np.nan, + "s3": np.nan, + "s4": np.nan, + }, + "MNN": { + "alpha": 0.205985314333856, + "beta": np.nan, + "gamma": np.nan, + "phi": np.nan, + "l": 58.9770839944419, + "b": np.nan, + "s1": np.nan, + "s2": np.nan, + "s3": np.nan, + "s4": np.nan, + }, + } + return {True: damped, False: undamped} + + +@pytest.mark.parametrize("trend", TRENDS) +@pytest.mark.parametrize("seasonal", SEASONALS) +@pytest.mark.parametrize("damped", [True, False]) +@pytest.mark.parametrize("error", ["add", "mul"]) +def test_simulate_expected_r( + trend, + seasonal, + damped, + error, + austourists, + simulate_expected_results_r, + simulate_fit_state_r, +): + """ + Test for :meth:``statsmodels.tsa.holtwinters.HoltWintersResults``. + + The tests are using the implementation in the R package ``forecast`` as + reference, and example data is taken from ``fpp2`` (package and book). + """ + + short_name = {"add": "A", "mul": "M", None: "N"} + model_name = short_name[error] + short_name[trend] + short_name[seasonal] + if model_name in simulate_expected_results_r[damped]: + expected = np.asarray(simulate_expected_results_r[damped][model_name]) + state = simulate_fit_state_r[damped][model_name] + else: + return + + # create HoltWintersResults object with same parameters as in R + fit = ExponentialSmoothing( + austourists, + seasonal_periods=4, + trend=trend, + seasonal=seasonal, + damped_trend=damped, + ).fit( + smoothing_level=state["alpha"], + smoothing_trend=state["beta"], + smoothing_seasonal=state["gamma"], + damping_trend=state["phi"], + optimized=False, + ) + + # set the same final state as in R + fit._level[-1] = state["l"] + fit._trend[-1] = state["b"] + fit._season[-1] = state["s1"] + fit._season[-2] = state["s2"] + fit._season[-3] = state["s3"] + fit._season[-4] = state["s4"] + + # for MMM with damped trend the fit fails + if np.any(np.isnan(fit.fittedvalues)): + return + + innov = np.asarray([[1.76405235, 0.40015721, 0.97873798, 2.2408932]]).T + sim = fit.simulate(4, repetitions=1, error=error, random_errors=innov) + + assert_almost_equal(expected, sim.values, 5) + + +def test_simulate_keywords(austourists): + """ + check whether all keywords are accepted and work without throwing errors. + """ + fit = ExponentialSmoothing( + austourists, + seasonal_periods=4, + trend="add", + seasonal="add", + damped_trend=True, + initialization_method="estimated", + ).fit() + + # test anchor + rs = np.random.RandomState(1232131) + with pytest.warns(FutureWarning, match="After statsmodels 0.15 is released"): + sim_0 = fit.simulate(4, anchor=0, rng=0).values + with pytest.warns(FutureWarning, match="After statsmodels 0.15 is released"): + sim_1 = fit.simulate(4, anchor="start", rng=0).values + assert_almost_equal(sim_0, sim_1) + with pytest.warns(FutureWarning, match="After statsmodels 0.15 is released"): + sim_2 = fit.simulate(4, anchor=-1, rng=0).values + with pytest.warns(FutureWarning, match="After statsmodels 0.15 is released"): + sim_3 = fit.simulate(4, anchor="2015-12-01", rng=0).values + + assert_almost_equal(sim_2, sim_3) + with pytest.warns(FutureWarning, match="After statsmodels 0.15 is released"): + sim_4 = fit.simulate(4, anchor="end", rng=0).values + with pytest.warns(FutureWarning, match="After statsmodels 0.15 is released"): + sim_5 = fit.simulate(4, anchor="2016-03-01", rng=0).values + assert_almost_equal(sim_4, sim_5) + + # test different random error options + with pytest.warns(FutureWarning, match="After statsmodels 0.15 is released"): + fit.simulate(4, repetitions=10, random_errors=scipy.stats.norm, rng=0) + with pytest.warns(FutureWarning, match="After statsmodels 0.15 is released"): + fit.simulate(4, repetitions=10, random_errors=scipy.stats.norm(), rng=0) + + fit.simulate(4, repetitions=10, random_errors=rs.randn(4, 10)) + with pytest.warns(FutureWarning, match="After statsmodels 0.15 is released"): + fit.simulate(4, repetitions=10, random_errors="bootstrap", rng=0) + + # test seeding + with pytest.warns(FutureWarning, match="After statsmodels 0.15 is released"): + res = fit.simulate(4, repetitions=10, rng=10).values + res2 = fit.simulate(4, repetitions=10, rng=np.random.RandomState(10)).values + assert np.all(res == res2) + + +def test_simulate_boxcox(austourists): + """ + check if simulation results with boxcox fits are reasonable + """ + fit = ExponentialSmoothing( + austourists, + seasonal_periods=4, + trend="add", + seasonal="mul", + damped_trend=False, + initialization_method="estimated", + use_boxcox=True, + ).fit() + expected = fit.forecast(4).values + with pytest.warns(FutureWarning, match="After statsmodels 0.15 is released"): + res = fit.simulate(4, repetitions=10, rng=0).values + mean = np.mean(res, axis=1) + + assert np.all(np.abs(mean - expected) < 5) + + +@pytest.mark.parametrize("ix", [10, 100, 1000, 2000]) +def test_forecast_index(ix): + # GH 6549 + ts_1 = pd.Series( + [85601, 89662, 85122, 84400, 78250, 84434, 71072, 70357, 72635, 73210], + index=range(ix, ix + 10), + ) + model = ExponentialSmoothing(ts_1, trend="add", damped_trend=False).fit() + index = model.forecast(steps=10).index + assert index[0] == ix + 10 + assert index[-1] == ix + 19 + + +def test_error_dampen(): + with pytest.raises(ValueError, match="Can only dampen the"): + ExponentialSmoothing(np.ones(100), damped_trend=True) + + +def test_error_boxcox(): + rs = np.random.RandomState(32321830) + y = rs.standard_normal(100) + with pytest.raises(TypeError, match="use_boxcox must be True"): + ExponentialSmoothing(y, use_boxcox="a", initialization_method="known") + + mod = ExponentialSmoothing(y**2, use_boxcox=True) + assert isinstance(mod, ExponentialSmoothing) + + mod = ExponentialSmoothing( + y**2, use_boxcox=True, initialization_method="legacy-heuristic" + ) + with pytest.raises(TypeError, match="unexpected keyword argument 'use_boxcox'"): + mod.fit(use_boxcox=False) + + +def test_error_initialization(ses): + with pytest.raises(ValueError, match="initialization is 'known' but initial_level"): + ExponentialSmoothing(ses, initialization_method="known") + with pytest.raises(ValueError, match="initial_trend set but model"): + ExponentialSmoothing( + ses, + initialization_method="known", + initial_level=1.0, + initial_trend=1.0, + ) + with pytest.raises(ValueError, match="initial_seasonal set but model"): + ExponentialSmoothing( + ses, + initialization_method="known", + initial_level=1.0, + initial_seasonal=[0.2, 0.3, 0.4, 0.5], + ) + with pytest.raises(ValueError): + ExponentialSmoothing(ses, initial_level=1.0) + with pytest.raises(ValueError): + ExponentialSmoothing(ses, initial_trend=1.0) + with pytest.raises(ValueError): + ExponentialSmoothing(ses, initial_seasonal=[1.0, 0.2, 0.05, 4]) + with pytest.raises(ValueError): + ExponentialSmoothing( + ses, + trend="add", + initialization_method="known", + initial_level=1.0, + ) + with pytest.raises(ValueError): + ExponentialSmoothing( + ses, + trend="add", + seasonal="add", + initialization_method="known", + initial_level=1.0, + initial_trend=2.0, + ) + mod = ExponentialSmoothing(ses, initialization_method="known", initial_level=1.0) + with pytest.raises(TypeError, match="unexpected keyword argument 'initial_level'"): + mod.fit(initial_level=2.0) + with pytest.raises( + TypeError, match="unexpected keyword argument 'use_basinhopping'" + ): + mod.fit(use_basinhopping=True, method="least_squares") + + +@pytest.mark.parametrize( + "method", + [ + "least_squares", + "basinhopping", + "L-BFGS-B", + "TNC", + "SLSQP", + "Powell", + "trust-constr", + ], +) +def test_alternative_minimizers(method, ses): + sv = np.array([0.77, 11.00]) + minimize_kwargs = {} + if method == "basinhopping": + rs = np.random.RandomState(32321831) + minimize_kwargs[BASINHOPPING_RNG] = rs + mod = ExponentialSmoothing(ses, initialization_method="estimated") + res = mod.fit(method=method, start_params=sv, minimize_kwargs=minimize_kwargs) + assert_allclose(res.params["smoothing_level"], 0.77232545, rtol=1e-3) + assert_allclose(res.params["initial_level"], 11.00359693, rtol=1e-3) + assert isinstance(res.summary().as_text(), str) + + +def test_minimizer_kwargs_error(ses): + mod = ExponentialSmoothing(ses, initialization_method="estimated") + kwargs = {"args": "anything"} + with pytest.raises(ValueError): + mod.fit(minimize_kwargs=kwargs) + with pytest.raises(ValueError): + mod.fit(method="least_squares", minimize_kwargs=kwargs) + rs = np.random.RandomState(32321837) + kwargs = {"minimizer_kwargs": {"args": "anything"}, BASINHOPPING_RNG: rs} + with pytest.raises(ValueError): + mod.fit(method="basinhopping", minimize_kwargs=kwargs) + kwargs = {"minimizer_kwargs": {"method": "SLSQP"}, BASINHOPPING_RNG: rs} + res = mod.fit(method="basinhopping", minimize_kwargs=kwargs) + assert isinstance(res.params, dict) + assert isinstance(res.summary().as_text(), str) + + +@pytest.mark.parametrize("params", [[0.8, 0.3, 0.9], [0.3, 0.8, 0.2], [0.5, 0.6, 0.6]]) +def test_to_restricted_equiv(params): + params = np.array(params) + sel = np.array([True] * 3) + bounds = np.array([[0.0, 1.0]] * 3) + assert_allclose( + to_restricted(params, sel, bounds), + _test_to_restricted(params, sel.astype(np.int64), bounds), + ) + + +@pytest.mark.parametrize("params", [[0.8, 0.3, 0.1], [0.3, 0.2, 0.6], [0.5, 0.5, 0.5]]) +def test_restricted_round_tip(params): + params = np.array(params) + sel = np.array([True] * 3) + bounds = np.array([[0.0, 1.0]] * 3) + assert_allclose( + params, + to_unrestricted(to_restricted(params, sel, bounds), sel, bounds), + ) + + +def test_bad_bounds(ses): + bounds = {"bad_key": (0.0, 1.0)} + with pytest.raises(KeyError): + ExponentialSmoothing(ses, bounds=bounds) + bounds = {"smoothing_level": [0.0, 1.0]} + with pytest.raises(TypeError): + ExponentialSmoothing(ses, bounds=bounds) + bounds = {"smoothing_level": (0.0, 1.0, 2.0)} + with pytest.raises(ValueError): + ExponentialSmoothing(ses, bounds=bounds) + bounds = {"smoothing_level": (1.0, 0.0)} + with pytest.raises(ValueError): + ExponentialSmoothing(ses, bounds=bounds) + bounds = {"smoothing_level": (-1.0, 2.0)} + with pytest.raises(ValueError): + ExponentialSmoothing(ses, bounds=bounds) + + +def test_valid_bounds(ses): + bounds = {"smoothing_level": (0.1, 1.0)} + res = ExponentialSmoothing( + ses, bounds=bounds, initialization_method="estimated" + ).fit(method="least_squares") + res2 = ExponentialSmoothing(ses, initialization_method="estimated").fit( + method="least_squares" + ) + assert_allclose( + res.params["smoothing_level"], + res2.params["smoothing_level"], + rtol=1e-4, + ) + + +def test_fixed_basic(ses): + mod = ExponentialSmoothing(ses, initialization_method="estimated") + with mod.fix_params({"smoothing_level": 0.3}): + res = mod.fit() + assert res.params["smoothing_level"] == 0.3 + assert isinstance(res.summary().as_text(), str) + + mod = ExponentialSmoothing( + ses, trend="add", damped_trend=True, initialization_method="estimated" + ) + with mod.fix_params({"damping_trend": 0.98}): + res = mod.fit() + assert res.params["damping_trend"] == 0.98 + assert isinstance(res.summary().as_text(), str) + + mod = ExponentialSmoothing( + ses, trend="add", seasonal="add", initialization_method="estimated" + ) + with mod.fix_params({"smoothing_seasonal": 0.1, "smoothing_level": 0.2}): + res = mod.fit() + assert res.params["smoothing_seasonal"] == 0.1 + assert res.params["smoothing_level"] == 0.2 + assert isinstance(res.summary().as_text(), str) + + +def test_fixed_errors(ses): + mod = ExponentialSmoothing(ses, initialization_method="estimated") + with pytest.raises(KeyError): + with mod.fix_params({"smoothing_trend": 0.3}): + pass + with pytest.raises(ValueError): + with mod.fix_params({"smoothing_level": -0.3}): + pass + mod = ExponentialSmoothing(ses, trend="add", initialization_method="estimated") + with pytest.raises(ValueError): + with mod.fix_params({"smoothing_level": 0.3, "smoothing_trend": 0.4}): + pass + mod = ExponentialSmoothing( + ses, trend="add", seasonal="add", initialization_method="estimated" + ) + with pytest.raises(ValueError): + with mod.fix_params({"smoothing_level": 0.3, "smoothing_seasonal": 0.8}): + pass + + bounds = {"smoothing_level": (0.4, 0.8), "smoothing_seasonal": (0.7, 0.9)} + mod = ExponentialSmoothing( + ses, + trend="add", + seasonal="add", + bounds=bounds, + initialization_method="estimated", + ) + with pytest.raises(ValueError, match="After adjusting for user-provided"): + with mod.fix_params({"smoothing_trend": 0.3, "smoothing_seasonal": 0.6}): + mod.fit() + + +@pytest.mark.parametrize("trend", ["add", None]) +@pytest.mark.parametrize("seasonal", ["add", None]) +def test_brute(ses, trend, seasonal): + mod = ExponentialSmoothing( + ses, trend=trend, seasonal=seasonal, initialization_method="estimated" + ) + res = mod.fit(use_brute=True) + assert res.mle_retvals.success + + with mod.fix_params({"smoothing_level": 0.1}): + res = mod.fit(use_brute=True) + assert res.mle_retvals.success + assert isinstance(res.summary().as_text(), str) + + +def test_fix_set_parameters(ses): + with pytest.raises(ValueError): + ExponentialSmoothing(ses, initial_level=1.0, initialization_method="heuristic") + with pytest.raises(ValueError): + ExponentialSmoothing( + ses, + trend="add", + initial_trend=1.0, + initialization_method="legacy-heuristic", + ) + with pytest.raises(ValueError): + ExponentialSmoothing( + ses, + seasonal="add", + initial_seasonal=np.ones(12), + initialization_method="estimated", + ) + + +def test_fix_unfixable(ses): + mod = ExponentialSmoothing(ses, initialization_method="estimated") + with pytest.raises(ValueError, match="Cannot fix a parameter"): + with mod.fix_params({"smoothing_level": 0.25}): + mod.fit(smoothing_level=0.2) + + +def test_infeasible_bounds(ses): + bounds = {"smoothing_level": (0.1, 0.2), "smoothing_trend": (0.3, 0.4)} + with pytest.raises(ValueError, match="The bounds for smoothing_trend"): + ExponentialSmoothing( + ses, trend="add", bounds=bounds, initialization_method="estimated" + ).fit() + bounds = {"smoothing_level": (0.3, 0.5), "smoothing_seasonal": (0.7, 0.8)} + with pytest.raises(ValueError, match="The bounds for smoothing_seasonal"): + ExponentialSmoothing( + ses, + seasonal="add", + bounds=bounds, + initialization_method="estimated", + ).fit() + + +@pytest.mark.parametrize("method", ["estimated", "heuristic", "legacy-heuristic"]) +@pytest.mark.parametrize("trend", [None, "add"]) +@pytest.mark.parametrize("seasonal", [None, "add"]) +def test_initialization_methods(ses, method, trend, seasonal): + mod = ExponentialSmoothing( + ses, trend=trend, seasonal=seasonal, initialization_method=method + ) + res = mod.fit() + assert res.mle_retvals.success + assert isinstance(res.summary().as_text(), str) + + +def test_attributes(ses): + res = ExponentialSmoothing(ses, initialization_method="estimated").fit() + assert res.k > 0 + assert res.resid.shape[0] == ses.shape[0] + assert_allclose(res.fcastvalues, res.fittedfcast[-1:]) + + +def test_summary_boxcox(ses): + mod = ExponentialSmoothing( + ses**2, use_boxcox=True, initialization_method="heuristic" + ) + with pytest.raises(TypeError, match="unexpected keyword argument 'use_boxcox'"): + mod.fit(use_boxcox=True) + res = mod.fit() + summ = str(res.summary()) + assert re.findall(r"Box-Cox:[\s]*True", summ) + assert isinstance(res.summary().as_text(), str) + + +def test_simulate(ses): + mod = ExponentialSmoothing(np.asarray(ses), initialization_method="heuristic") + res = mod.fit() + assert isinstance(res.summary().as_text(), str) + with pytest.raises(ValueError, match="error must be"): + res.simulate(10, error="unknown", rng=0) + with pytest.raises(ValueError, match="If random"): + res.simulate(10, error="additive", random_errors=np.empty((20, 20)), rng=0) + with pytest.warns(FutureWarning, match="After statsmodels 0.15 is released"): + res.simulate(10, error="additive", anchor=100, rng=0) + with pytest.raises(ValueError, match="Cannot anchor"): + res.simulate(10, error="additive", anchor=2000, rng=0) + with pytest.raises( + TypeError, match="When creating a random number generator from a" + ): + res.simulate(10, error="additive", anchor=100, rng="bad_value") + with pytest.raises(ValueError, match="random_errors must be"): + with pytest.warns(FutureWarning, match="After statsmodels 0.15 is released"): + res.simulate(10, error="additive", random_errors="bad_values", rng=0) + + +def test_simulate_error_aliases(ses): + # "additive"/"multiplicative" are documented aliases for "add"/"mul" + mod = ExponentialSmoothing(np.asarray(ses), initialization_method="heuristic") + res = mod.fit() + innov = np.arange(1, 41, dtype=float).reshape(10, 4) + add_sim = res.simulate(10, repetitions=4, error="add", random_errors=innov) + additive_sim = res.simulate( + 10, repetitions=4, error="additive", random_errors=innov + ) + assert_almost_equal(np.asarray(add_sim), np.asarray(additive_sim)) + mul_sim = res.simulate(10, repetitions=4, error="mul", random_errors=innov) + multiplicative_sim = res.simulate( + 10, repetitions=4, error="multiplicative", random_errors=innov + ) + assert_almost_equal(np.asarray(mul_sim), np.asarray(multiplicative_sim)) + + +@pytest.mark.parametrize("index_typ", ["date_range", "period", "range"]) +def test_forecast_index_types(ses, index_typ): + nobs = ses.shape[0] + kwargs = {} + model_warning = None + fcast_index = None + if index_typ == "period": + index = pd.period_range("2000-1-1", periods=nobs + 36, freq="M") + elif index_typ == "date_range": + index = pd.date_range("2000-1-1", periods=nobs + 36, freq=MONTH_END) + elif index_typ == "range": + index = pd.RangeIndex(nobs + 36) + kwargs["seasonal_periods"] = 12 + if fcast_index is None: + fcast_index = index[-36:] + ses = ses.copy() + ses.index = index[:-36] + + with pytest_warns(model_warning): + res = ExponentialSmoothing( + ses, + trend="add", + seasonal="add", + initialization_method="heuristic", + **kwargs, + ).fit() + fcast = res.forecast(36) + assert isinstance(fcast, pd.Series) + pd.testing.assert_index_equal(fcast.index, fcast_index) + + +def test_boxcox_components(ses): + mod = ExponentialSmoothing( + ses + 1 - ses.min(), initialization_method="estimated", use_boxcox=True + ) + res = mod.fit() + assert isinstance(res.summary().as_text(), str) + with pytest.raises(AssertionError): + # Must be different since level is not transformed + assert_allclose(res.level, res.fittedvalues) + assert not hasattr(res, "_untransformed_level") + assert not hasattr(res, "_untransformed_trend") + assert not hasattr(res, "_untransformed_seasonal") + + +@pytest.mark.parametrize("repetitions", [1, 10]) +@pytest.mark.parametrize("random_errors", [None, "bootstrap"]) +def test_forecast_1_simulation(austourists, random_errors, repetitions): + # GH 7053 + fit = ExponentialSmoothing( + austourists, + seasonal_periods=4, + trend="add", + seasonal="add", + damped_trend=True, + initialization_method="estimated", + ).fit() + + with pytest.warns(FutureWarning, match="After statsmodels 0.15 is released"): + sim = fit.simulate( + 1, anchor=0, random_errors=random_errors, repetitions=repetitions, rng=0 + ) + expected_shape = (1,) if repetitions == 1 else (1, repetitions) + assert sim.shape == expected_shape + with pytest.warns(FutureWarning, match="After statsmodels 0.15 is released"): + sim = fit.simulate( + 10, anchor=0, random_errors=random_errors, repetitions=repetitions, rng=0 + ) + expected_shape = (10,) if repetitions == 1 else (10, repetitions) + assert sim.shape == expected_shape + + +@pytest.mark.parametrize("trend", [None, "add"]) +@pytest.mark.parametrize("seasonal", [None, "add"]) +@pytest.mark.parametrize("nobs", [9, 10]) +def test_estimated_initialization_short_data(ses, trend, seasonal, nobs): + # GH 7319 + res = ExponentialSmoothing( + ses[:nobs], + trend=trend, + seasonal=seasonal, + seasonal_periods=4, + initialization_method="estimated", + ).fit() + assert res.mle_retvals.success + + +def test_invalid_index(): + rs = np.random.RandomState(32321830) + y = rs.standard_normal(12 * 200) + df_y = pd.DataFrame(data=y) + # Can't have a freq here + df_y.index.freq = "d" + + model = ExponentialSmoothing( + df_y, + seasonal_periods=12, + trend="add", + seasonal="add", + initialization_method="heuristic", + ) + fitted = model.fit(optimized=True, use_brute=True) + + fcast = fitted.forecast(steps=157200) + assert fcast.shape[0] == 157200 + + index = pd.date_range("2020-01-01", periods=2 * y.shape[0]) + index = rs.choice(index, size=df_y.shape[0], replace=False) + index = sorted(index) + df_y.index = index + assert isinstance(df_y.index, pd.DatetimeIndex) + assert df_y.index.freq is None + assert df_y.index.inferred_freq is None + with pytest.warns(ValueWarning, match="A date index has been provided"): + model = ExponentialSmoothing( + df_y, + seasonal_periods=12, + trend="add", + seasonal="add", + initialization_method="heuristic", + ) + fitted = model.fit(optimized=True, use_brute=True) + with pytest.raises(ValueError, match="No supported index is available"): + fitted.forecast(steps=157200) + + +def test_initial_level(): + # GH 8634 + series = [0.0, 0.0, 0.0, 100.0, 0.0, 0.0, 0.0] + es = ExponentialSmoothing(series, initialization_method="known", initial_level=20.0) + es_fit = es.fit() + assert isinstance(es_fit.params, dict) + assert_allclose(es_fit.params["initial_level"], 20.0) + + +def test_all_initial_values(): + fit1 = ExponentialSmoothing( + aust, + seasonal_periods=4, + trend="add", + seasonal="mul", + initialization_method="estimated", + ).fit() + lvl = np.round(fit1.params["initial_level"]) + trend = np.round(fit1.params["initial_trend"], 1) + seas = np.round(fit1.params["initial_seasons"], 1) + fit2 = ExponentialSmoothing( + aust, + seasonal_periods=4, + trend="add", + seasonal="mul", + initialization_method="known", + initial_level=lvl, + initial_trend=trend, + initial_seasonal=seas, + ).fit() + assert_allclose(fit2.params["initial_level"], lvl) + assert_allclose(fit2.params["initial_trend"], trend) + assert_allclose(fit2.params["initial_seasons"], seas) diff --git a/shared/package-files/73/73724b3e09cdbcb9173ea779f124ec42038d8bb8b57949f4f354e041a18e7a16/utils.pyi b/shared/package-files/73/73724b3e09cdbcb9173ea779f124ec42038d8bb8b57949f4f354e041a18e7a16/utils.pyi new file mode 100644 index 0000000000000000000000000000000000000000..58c49d8926c5fd6633b3ef740493e0135aa7543c --- /dev/null +++ b/shared/package-files/73/73724b3e09cdbcb9173ea779f124ec42038d8bb8b57949f4f354e041a18e7a16/utils.pyi @@ -0,0 +1,5 @@ +from django.db.migrations.state import ProjectState + +from django.db.models.fields import Field + +def is_referenced_by_foreign_key(state: ProjectState, model_name_lower: str, field: Field, field_name: str) -> bool: ... diff --git a/shared/package-files/73/737283b0c48b363653b955cf875a841ce88f3cecd975522af305870bcef639ed/cons25-iso8859 b/shared/package-files/73/737283b0c48b363653b955cf875a841ce88f3cecd975522af305870bcef639ed/cons25-iso8859 new file mode 100644 index 0000000000000000000000000000000000000000..df810962d1951d93c8c85e8452cbaffa46b74e60 Binary files /dev/null and b/shared/package-files/73/737283b0c48b363653b955cf875a841ce88f3cecd975522af305870bcef639ed/cons25-iso8859 differ diff --git a/shared/package-files/73/737283b0c48b363653b955cf875a841ce88f3cecd975522af305870bcef639ed/cons25l1 b/shared/package-files/73/737283b0c48b363653b955cf875a841ce88f3cecd975522af305870bcef639ed/cons25l1 new file mode 100644 index 0000000000000000000000000000000000000000..df810962d1951d93c8c85e8452cbaffa46b74e60 Binary files /dev/null and b/shared/package-files/73/737283b0c48b363653b955cf875a841ce88f3cecd975522af305870bcef639ed/cons25l1 differ diff --git a/shared/package-files/73/737499f8aee1bf2cc663a251019c4983027fb144bd93459892f318d34601605a/hebrewprober.py b/shared/package-files/73/737499f8aee1bf2cc663a251019c4983027fb144bd93459892f318d34601605a/hebrewprober.py new file mode 100644 index 0000000000000000000000000000000000000000..b0e1bf49268203d1f9d14cbe73753d95dc66c8a4 --- /dev/null +++ b/shared/package-files/73/737499f8aee1bf2cc663a251019c4983027fb144bd93459892f318d34601605a/hebrewprober.py @@ -0,0 +1,292 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Universal charset detector code. +# +# The Initial Developer of the Original Code is +# Shy Shalom +# Portions created by the Initial Developer are Copyright (C) 2005 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .charsetprober import CharSetProber +from .enums import ProbingState + +# This prober doesn't actually recognize a language or a charset. +# It is a helper prober for the use of the Hebrew model probers + +### General ideas of the Hebrew charset recognition ### +# +# Four main charsets exist in Hebrew: +# "ISO-8859-8" - Visual Hebrew +# "windows-1255" - Logical Hebrew +# "ISO-8859-8-I" - Logical Hebrew +# "x-mac-hebrew" - ?? Logical Hebrew ?? +# +# Both "ISO" charsets use a completely identical set of code points, whereas +# "windows-1255" and "x-mac-hebrew" are two different proper supersets of +# these code points. windows-1255 defines additional characters in the range +# 0x80-0x9F as some misc punctuation marks as well as some Hebrew-specific +# diacritics and additional 'Yiddish' ligature letters in the range 0xc0-0xd6. +# x-mac-hebrew defines similar additional code points but with a different +# mapping. +# +# As far as an average Hebrew text with no diacritics is concerned, all four +# charsets are identical with respect to code points. Meaning that for the +# main Hebrew alphabet, all four map the same values to all 27 Hebrew letters +# (including final letters). +# +# The dominant difference between these charsets is their directionality. +# "Visual" directionality means that the text is ordered as if the renderer is +# not aware of a BIDI rendering algorithm. The renderer sees the text and +# draws it from left to right. The text itself when ordered naturally is read +# backwards. A buffer of Visual Hebrew generally looks like so: +# "[last word of first line spelled backwards] [whole line ordered backwards +# and spelled backwards] [first word of first line spelled backwards] +# [end of line] [last word of second line] ... etc' " +# adding punctuation marks, numbers and English text to visual text is +# naturally also "visual" and from left to right. +# +# "Logical" directionality means the text is ordered "naturally" according to +# the order it is read. It is the responsibility of the renderer to display +# the text from right to left. A BIDI algorithm is used to place general +# punctuation marks, numbers and English text in the text. +# +# Texts in x-mac-hebrew are almost impossible to find on the Internet. From +# what little evidence I could find, it seems that its general directionality +# is Logical. +# +# To sum up all of the above, the Hebrew probing mechanism knows about two +# charsets: +# Visual Hebrew - "ISO-8859-8" - backwards text - Words and sentences are +# backwards while line order is natural. For charset recognition purposes +# the line order is unimportant (In fact, for this implementation, even +# word order is unimportant). +# Logical Hebrew - "windows-1255" - normal, naturally ordered text. +# +# "ISO-8859-8-I" is a subset of windows-1255 and doesn't need to be +# specifically identified. +# "x-mac-hebrew" is also identified as windows-1255. A text in x-mac-hebrew +# that contain special punctuation marks or diacritics is displayed with +# some unconverted characters showing as question marks. This problem might +# be corrected using another model prober for x-mac-hebrew. Due to the fact +# that x-mac-hebrew texts are so rare, writing another model prober isn't +# worth the effort and performance hit. +# +#### The Prober #### +# +# The prober is divided between two SBCharSetProbers and a HebrewProber, +# all of which are managed, created, fed data, inquired and deleted by the +# SBCSGroupProber. The two SBCharSetProbers identify that the text is in +# fact some kind of Hebrew, Logical or Visual. The final decision about which +# one is it is made by the HebrewProber by combining final-letter scores +# with the scores of the two SBCharSetProbers to produce a final answer. +# +# The SBCSGroupProber is responsible for stripping the original text of HTML +# tags, English characters, numbers, low-ASCII punctuation characters, spaces +# and new lines. It reduces any sequence of such characters to a single space. +# The buffer fed to each prober in the SBCS group prober is pure text in +# high-ASCII. +# The two SBCharSetProbers (model probers) share the same language model: +# Win1255Model. +# The first SBCharSetProber uses the model normally as any other +# SBCharSetProber does, to recognize windows-1255, upon which this model was +# built. The second SBCharSetProber is told to make the pair-of-letter +# lookup in the language model backwards. This in practice exactly simulates +# a visual Hebrew model using the windows-1255 logical Hebrew model. +# +# The HebrewProber is not using any language model. All it does is look for +# final-letter evidence suggesting the text is either logical Hebrew or visual +# Hebrew. Disjointed from the model probers, the results of the HebrewProber +# alone are meaningless. HebrewProber always returns 0.00 as confidence +# since it never identifies a charset by itself. Instead, the pointer to the +# HebrewProber is passed to the model probers as a helper "Name Prober". +# When the Group prober receives a positive identification from any prober, +# it asks for the name of the charset identified. If the prober queried is a +# Hebrew model prober, the model prober forwards the call to the +# HebrewProber to make the final decision. In the HebrewProber, the +# decision is made according to the final-letters scores maintained and Both +# model probers scores. The answer is returned in the form of the name of the +# charset identified, either "windows-1255" or "ISO-8859-8". + +class HebrewProber(CharSetProber): + # windows-1255 / ISO-8859-8 code points of interest + FINAL_KAF = 0xea + NORMAL_KAF = 0xeb + FINAL_MEM = 0xed + NORMAL_MEM = 0xee + FINAL_NUN = 0xef + NORMAL_NUN = 0xf0 + FINAL_PE = 0xf3 + NORMAL_PE = 0xf4 + FINAL_TSADI = 0xf5 + NORMAL_TSADI = 0xf6 + + # Minimum Visual vs Logical final letter score difference. + # If the difference is below this, don't rely solely on the final letter score + # distance. + MIN_FINAL_CHAR_DISTANCE = 5 + + # Minimum Visual vs Logical model score difference. + # If the difference is below this, don't rely at all on the model score + # distance. + MIN_MODEL_DISTANCE = 0.01 + + VISUAL_HEBREW_NAME = "ISO-8859-8" + LOGICAL_HEBREW_NAME = "windows-1255" + + def __init__(self): + super(HebrewProber, self).__init__() + self._final_char_logical_score = None + self._final_char_visual_score = None + self._prev = None + self._before_prev = None + self._logical_prober = None + self._visual_prober = None + self.reset() + + def reset(self): + self._final_char_logical_score = 0 + self._final_char_visual_score = 0 + # The two last characters seen in the previous buffer, + # mPrev and mBeforePrev are initialized to space in order to simulate + # a word delimiter at the beginning of the data + self._prev = ' ' + self._before_prev = ' ' + # These probers are owned by the group prober. + + def set_model_probers(self, logicalProber, visualProber): + self._logical_prober = logicalProber + self._visual_prober = visualProber + + def is_final(self, c): + return c in [self.FINAL_KAF, self.FINAL_MEM, self.FINAL_NUN, + self.FINAL_PE, self.FINAL_TSADI] + + def is_non_final(self, c): + # The normal Tsadi is not a good Non-Final letter due to words like + # 'lechotet' (to chat) containing an apostrophe after the tsadi. This + # apostrophe is converted to a space in FilterWithoutEnglishLetters + # causing the Non-Final tsadi to appear at an end of a word even + # though this is not the case in the original text. + # The letters Pe and Kaf rarely display a related behavior of not being + # a good Non-Final letter. Words like 'Pop', 'Winamp' and 'Mubarak' + # for example legally end with a Non-Final Pe or Kaf. However, the + # benefit of these letters as Non-Final letters outweighs the damage + # since these words are quite rare. + return c in [self.NORMAL_KAF, self.NORMAL_MEM, + self.NORMAL_NUN, self.NORMAL_PE] + + def feed(self, byte_str): + # Final letter analysis for logical-visual decision. + # Look for evidence that the received buffer is either logical Hebrew + # or visual Hebrew. + # The following cases are checked: + # 1) A word longer than 1 letter, ending with a final letter. This is + # an indication that the text is laid out "naturally" since the + # final letter really appears at the end. +1 for logical score. + # 2) A word longer than 1 letter, ending with a Non-Final letter. In + # normal Hebrew, words ending with Kaf, Mem, Nun, Pe or Tsadi, + # should not end with the Non-Final form of that letter. Exceptions + # to this rule are mentioned above in isNonFinal(). This is an + # indication that the text is laid out backwards. +1 for visual + # score + # 3) A word longer than 1 letter, starting with a final letter. Final + # letters should not appear at the beginning of a word. This is an + # indication that the text is laid out backwards. +1 for visual + # score. + # + # The visual score and logical score are accumulated throughout the + # text and are finally checked against each other in GetCharSetName(). + # No checking for final letters in the middle of words is done since + # that case is not an indication for either Logical or Visual text. + # + # We automatically filter out all 7-bit characters (replace them with + # spaces) so the word boundary detection works properly. [MAP] + + if self.state == ProbingState.NOT_ME: + # Both model probers say it's not them. No reason to continue. + return ProbingState.NOT_ME + + byte_str = self.filter_high_byte_only(byte_str) + + for cur in byte_str: + if cur == ' ': + # We stand on a space - a word just ended + if self._before_prev != ' ': + # next-to-last char was not a space so self._prev is not a + # 1 letter word + if self.is_final(self._prev): + # case (1) [-2:not space][-1:final letter][cur:space] + self._final_char_logical_score += 1 + elif self.is_non_final(self._prev): + # case (2) [-2:not space][-1:Non-Final letter][ + # cur:space] + self._final_char_visual_score += 1 + else: + # Not standing on a space + if ((self._before_prev == ' ') and + (self.is_final(self._prev)) and (cur != ' ')): + # case (3) [-2:space][-1:final letter][cur:not space] + self._final_char_visual_score += 1 + self._before_prev = self._prev + self._prev = cur + + # Forever detecting, till the end or until both model probers return + # ProbingState.NOT_ME (handled above) + return ProbingState.DETECTING + + @property + def charset_name(self): + # Make the decision: is it Logical or Visual? + # If the final letter score distance is dominant enough, rely on it. + finalsub = self._final_char_logical_score - self._final_char_visual_score + if finalsub >= self.MIN_FINAL_CHAR_DISTANCE: + return self.LOGICAL_HEBREW_NAME + if finalsub <= -self.MIN_FINAL_CHAR_DISTANCE: + return self.VISUAL_HEBREW_NAME + + # It's not dominant enough, try to rely on the model scores instead. + modelsub = (self._logical_prober.get_confidence() + - self._visual_prober.get_confidence()) + if modelsub > self.MIN_MODEL_DISTANCE: + return self.LOGICAL_HEBREW_NAME + if modelsub < -self.MIN_MODEL_DISTANCE: + return self.VISUAL_HEBREW_NAME + + # Still no good, back to final letter distance, maybe it'll save the + # day. + if finalsub < 0.0: + return self.VISUAL_HEBREW_NAME + + # (finalsub > 0 - Logical) or (don't know what to do) default to + # Logical. + return self.LOGICAL_HEBREW_NAME + + @property + def language(self): + return 'Hebrew' + + @property + def state(self): + # Remain active as long as any of the model probers are active. + if (self._logical_prober.state == ProbingState.NOT_ME) and \ + (self._visual_prober.state == ProbingState.NOT_ME): + return ProbingState.NOT_ME + return ProbingState.DETECTING diff --git a/shared/package-files/73/73749a522cfd58cf03c6ca088c089bfcc98973efbc66ad1d06d49ccf8da9b47f/_model.py b/shared/package-files/73/73749a522cfd58cf03c6ca088c089bfcc98973efbc66ad1d06d49ccf8da9b47f/_model.py new file mode 100644 index 0000000000000000000000000000000000000000..e103064a6802dbe8590f05a1187e4df30d891d8c --- /dev/null +++ b/shared/package-files/73/73749a522cfd58cf03c6ca088c089bfcc98973efbc66ad1d06d49ccf8da9b47f/_model.py @@ -0,0 +1,42 @@ +from typing import Any + +import numpy as np + +from .._serializable import Deserializer, Serializable, Serializer +from ..utils import safe_isinstance + + +class Model(Serializable): + """This is the superclass of all models.""" + + def __init__(self, model=None): + """Wrap a callable model as a SHAP Model object.""" + if isinstance(model, Model): + self.inner_model: Any = model.inner_model + else: + self.inner_model = model + + if hasattr(model, "output_names"): + self.output_names = model.output_names + + def __call__(self, *args): + out = self.inner_model(*args) + is_tensor = safe_isinstance(out, "torch.Tensor") + out = out.cpu().detach().numpy() if is_tensor else np.array(out) + return out + + def save(self, out_file): + """Save the model to the given file stream.""" + super().save(out_file) + with Serializer(out_file, "shap.Model", version=0) as s: + s.save("model", self.inner_model) + + @classmethod + def load(cls, in_file, instantiate=True): + if instantiate: + return cls._instantiated_load(in_file) + + kwargs = super().load(in_file, instantiate=False) + with Deserializer(in_file, "shap.Model", min_version=0, max_version=0) as s: + kwargs["model"] = s.load("model") + return kwargs diff --git a/shared/package-files/73/737801932494767f6403bb299922493d0e6f332dc213d18319d4c59d22109a84/yhat_exact_c.csv b/shared/package-files/73/737801932494767f6403bb299922493d0e6f332dc213d18319d4c59d22109a84/yhat_exact_c.csv new file mode 100644 index 0000000000000000000000000000000000000000..617228ba902332115c7963882c025a5b3a361e46 --- /dev/null +++ b/shared/package-files/73/737801932494767f6403bb299922493d0e6f332dc213d18319d4c59d22109a84/yhat_exact_c.csv @@ -0,0 +1,251 @@ +yhat1,yhat2,yhat3,yhat4,yhat5,yhat6 +4.8564757594,4.7737798231,1.0629802339,4.5077285877,4.5622072362,4.5192778020 +4.3802260168,5.6140133447,3.4640440803,4.6451139813,3.8773321387,4.5438641692 +4.5588418673,5.6225064824,5.3407060303,4.3405011840,5.4600466767,4.2782569409 +3.9507827608,5.3487217610,5.4118204790,4.4096228098,4.3702357145,4.5836303978 +4.5804681490,6.3881841171,4.1502891739,4.7975154783,3.7949197183,4.9718794716 +5.0032409924,3.4106576794,5.4821040681,4.2964182149,4.1528170835,3.8740105400 +6.1439810685,4.7432320834,7.7039949074,4.0943179478,5.1277481550,4.6131286421 +5.3098043569,6.2280284352,5.4650688035,3.8951289718,3.5021875797,3.7720644643 +6.7370040358,4.5769052643,4.0785096637,2.9922651118,3.8554921177,4.0006637112 +8.2794534209,2.8986527047,5.9934467858,6.7863266033,4.7807352842,3.9700512070 +5.3994706147,4.1561554760,8.1640216896,7.4298455092,6.0888272280,3.7754024525 +4.9218045655,5.4072460550,5.7171282128,4.4379132025,5.0405425254,5.1032809723 +4.5809811787,3.3815613729,4.1122940996,2.8103672864,4.0052742863,5.0975296701 +3.2986980116,4.0528408707,7.0812545405,2.8175490692,6.9643606969,5.3282288302 +3.6125257499,4.7123122142,7.2802430740,4.9998742381,6.5195297109,4.0888259706 +4.0789657485,5.8862981771,6.4284934825,4.6063307602,4.1113507949,5.4600237412 +3.5827143922,2.7156701332,3.9263920137,7.6742887717,4.6487630996,4.4507906663 +4.7465347618,4.1929171465,4.1915903715,2.0185734313,5.4112948426,4.6820392038 +3.8127243048,6.8089433136,6.3694834206,2.8142361499,4.1789450524,2.9246777573 +2.6507492591,4.0732023852,4.3113964897,3.3292074089,4.9631906968,4.9470150498 +2.8548980286,4.1067694984,3.6986970613,5.0550056219,4.0370113097,5.3120288563 +3.3159395945,5.3863702796,5.7334881207,5.3434184298,5.4904297697,4.7803059985 +4.8431197809,5.5538298091,6.4783859548,8.3057664495,5.0202593302,4.7801484532 +4.3082119128,4.4230517789,3.8676933770,3.8941721698,6.0173206815,4.6440567890 +4.4165127148,4.3808105249,4.5517660837,3.2898692911,4.7963174021,3.8920677491 +4.7309696514,5.2801924782,7.1540005854,4.8903934701,4.2106121558,4.0817734302 +4.0410886315,4.9585603530,6.2690890362,2.2073876653,5.4001970429,5.7237280604 +4.8332270128,3.5634924463,5.9852363972,4.5417420173,3.7883420643,3.7343618389 +4.5111306180,5.0333269610,5.5439697883,7.8649159665,3.3783377468,4.2256240739 +4.7795160442,4.8885895295,5.1558960118,2.4246478844,2.8723762647,5.0049152206 +4.1634630642,3.0082511574,6.7333312854,1.7577371552,4.9067761467,4.0185751413 +7.4774502912,5.5256888505,6.4253062305,4.5969330228,4.1336608185,3.7435630339 +3.7357425973,3.3978865699,6.3850324197,6.7955618376,3.5374585303,4.3519277114 +3.8136969056,1.4223961614,3.9137300397,4.3787671461,4.1996445120,4.6801971467 +3.4168935420,5.1928940937,4.1313460248,5.3022783788,5.0220531097,5.0231834564 +3.9431774564,5.0539207294,5.7166316517,3.9645588970,3.7344911267,4.7472665236 +5.8769015221,3.4568435077,4.5983046191,4.5476226499,5.1508903972,4.1423306786 +6.3451471244,3.4525233065,3.8923446980,5.3935741113,4.3477370835,4.3221446745 +5.1756374968,6.4372027039,3.6219427792,5.4372556864,3.7588708954,5.4326260847 +5.5770569483,2.8471482674,1.9528836062,4.2697049976,3.7217798152,3.7617662530 +6.3168522717,4.0152314769,1.6965283909,4.8762993376,4.5263133252,4.6945269065 +6.4017152938,4.6879242999,4.1933331002,3.5315279085,3.5152815115,2.3590033197 +5.8043000464,4.0628647407,5.3578122209,4.6217281026,3.7408163831,5.7068734824 +5.5491499549,3.5900272630,1.9076262576,3.7595010920,4.0144473333,6.0648587570 +5.0586337054,4.0577439190,-0.2033612457,2.3925340704,5.1933709218,4.8173241101 +5.0706090032,3.2997132534,2.5787941478,5.8131547100,3.8574885646,4.8777641015 +5.2607840312,4.9485054124,5.4461001297,5.9182842360,3.9711274448,5.2232830270 +4.8688685227,5.4471766809,4.1323447658,4.8544622996,4.6227411767,4.4754849228 +5.6352916186,3.8893758868,0.8326871048,4.3506808570,5.1744439793,5.1377863560 +4.8362453771,5.2120960571,0.8435185540,4.6219865783,4.3982605837,4.1303783461 +5.9360716139,4.6009855369,0.9320453718,4.5894955163,5.1446104974,4.7206233425 +7.2002391355,6.4781161540,2.8379786962,6.3275708285,4.4335990006,4.3336494927 +7.8589048665,6.7603942006,4.2250339511,5.5197677458,3.2453799215,4.4870067920 +7.2880079127,4.1216235213,-0.0568921323,4.0920515138,4.5885026888,5.5531437913 +5.6605978857,4.9893001744,-1.4544737583,3.3192516948,3.3089322709,4.4013827151 +5.9996576521,6.2246279399,2.1629052006,3.1431835658,3.3564521333,4.6034119082 +5.5839811157,6.2030122490,4.6018398852,4.7731816265,3.7989099394,5.3068050470 +3.5999325179,5.7684073507,2.7259948119,5.7192595634,3.0731380327,4.4660071898 +5.4401538781,4.5459108955,0.1333320606,4.1895094201,2.8609833771,3.9746136975 +6.9874270540,6.5774993780,-0.3791701331,3.6788888651,2.1991521821,4.2593156048 +7.0030065424,5.6466682329,1.8589131112,2.5187699145,1.3300193667,5.6218582272 +5.9290930778,3.2147258549,4.2074002314,3.7189410999,2.5774203670,4.3561586046 +6.4719117339,5.6751884826,3.3522646424,4.8391148795,2.5423436095,4.1157435547 +6.9432788786,5.3003261494,-2.1986992167,5.6544382687,1.2520828888,4.0551016887 +3.9058013502,4.9670740876,-2.3785357370,4.2618635503,1.8198346028,4.2300337138 +2.3274874822,4.9332683791,2.2005608972,5.8001104380,2.4927298534,4.6590273147 +1.9782810757,3.0618750432,4.3097362731,5.8544002731,3.0249154799,5.4718072167 +3.3919351286,6.8536873068,2.1982905781,4.6279762364,2.7927026190,4.8585791147 +3.6728791711,4.2580095925,-1.1720611315,3.8239934692,3.4830202934,4.1231045895 +4.0150298486,5.2679069592,-2.7606442537,3.0050313805,4.7362230675,4.4562407086 +4.0936759332,6.3435246151,3.0934721218,3.0473133678,4.2475318785,4.2535252521 +5.2189267343,4.9071082105,6.5755742571,6.7747170150,3.9087825697,3.7839948329 +5.5167441820,4.7603567640,2.6353210273,4.1613171659,4.5774450111,5.0042760365 +4.3493098464,6.6080312279,-2.3363850600,3.3752732310,3.7497202821,4.4612021004 +4.9931132007,5.1208824878,-2.9726618484,4.4417380246,2.9344436368,4.4872541469 +4.6713852933,6.0029299088,4.1021452040,4.3440934596,3.2228513242,5.1884784928 +6.1787618594,5.1745771320,5.7416492012,5.2334424436,3.2508077947,4.3495472054 +7.2968215671,3.8036385547,-0.2381039143,4.2512059998,3.4854256246,3.5891281979 +5.3019815599,5.4234047749,-3.4350762648,4.1250305822,4.0409597160,4.6799152083 +5.6919743584,4.4949496684,-1.6153628173,5.1631451769,2.8790890983,5.6027081261 +6.8455273324,3.9879656085,2.8720877798,5.1119102038,4.7728291303,4.2808615693 +5.6533589575,2.6630513204,3.4378279820,4.4182988889,3.3067630783,3.2271978549 +6.2870734485,5.7527968456,0.5802321899,5.9297928697,3.9866542467,4.7573423130 +6.0565657056,2.3476268043,-4.6153310536,3.1787582624,3.5987337905,4.1562326325 +6.4992350088,3.6521006730,-2.5802817089,3.1251493123,4.3322884862,4.7183434582 +7.3280712146,3.6781654954,3.3313086747,5.5510727677,3.7360679081,4.7379668978 +7.9811338456,4.3861846156,2.3854048002,2.6059423341,4.4712011836,5.1429552448 +6.7833633698,4.3740218160,-1.9538574181,3.9250421993,3.4170601485,4.0505465552 +6.2185606035,3.9566154858,-3.8713701454,4.3685185487,2.7759657937,4.9070885233 +5.2956694987,4.2255769140,-0.2116731766,5.0524457171,4.0911086630,3.1226506162 +4.0365575386,3.3016101817,3.3690117450,4.5822537095,3.6312025332,5.6913656934 +4.6810049068,5.2300614106,2.3111491132,5.3442619448,3.1017103434,4.3083977435 +4.9456666518,4.2695292085,-1.0348726005,5.2771366540,4.1987319966,4.4390656908 +3.6593614820,4.9552024282,-5.3683261795,5.3562294223,3.4428886253,3.4635336323 +5.2827233920,4.6390309766,-1.4726661378,5.8360815201,3.7632889618,4.3292725060 +2.9748761638,4.0804387751,3.3282568897,5.6385260787,3.8887055522,3.5795095867 +1.7555754082,5.6751753356,0.2347093508,5.4691783731,3.0063251114,5.3088506333 +2.4946536258,4.5432705737,-4.6882810045,1.1371210533,3.4052114274,4.0338017891 +4.1837113715,4.5781499465,-4.4598039789,4.7052901780,3.1130957877,4.9866189718 +5.3085210813,5.6339773996,-1.8095666664,6.2784917539,2.4224304377,3.2562181349 +7.5222679253,5.1975586925,0.9696265547,4.1505424843,3.1970476474,5.3466105591 +6.8200590087,5.7023631594,0.0740645056,4.6882898439,3.5015153229,3.7552823674 +6.8480498299,4.8436075323,-3.3225275631,3.8945016948,3.4203501697,4.9441955111 +6.0230358608,6.3444892686,-3.7246481005,7.3985902037,2.2197001661,3.6174909754 +1.6807481593,5.0327737713,-0.6355495512,3.2229962739,2.2200381892,5.7877860305 +0.9954359835,5.0417560243,0.7282770164,4.6773650604,3.4550295425,3.6790900903 +1.5259562726,5.1118066586,-1.8704586819,4.2872456308,1.9203846545,3.3477068258 +1.5630882285,4.3582165014,-1.5830002190,5.2044994046,0.8702085591,5.7481364721 +3.7549736606,4.9417926178,-3.2820793975,4.6843268567,2.3862287825,4.8049943889 +3.1347561478,4.4453204210,-3.6822379437,5.0540212912,3.5792494384,4.7122888702 +4.7551048080,3.9378776629,-2.6490462177,4.2725662973,2.9840379940,4.1364634781 +4.2082698296,3.1409692310,-1.2042524428,5.4501655074,2.8114005656,6.0021858696 +5.6402705812,4.0925686701,-1.7623523648,4.5619001805,4.9603288467,2.6290972338 +7.1993518184,4.4137234260,-4.4965975584,4.3581981090,5.3105678295,4.9273905493 +7.8669020921,5.2331140468,-4.6182735925,6.4797990515,5.6655006210,4.5163625326 +7.8714536976,3.6672964830,-3.8940551133,4.5915388423,4.6426489521,4.5252246208 +6.6620595902,3.0355939785,-1.2723473054,3.0138602942,6.8163321820,5.4045144471 +4.4978161249,5.2521093850,-3.4650064045,5.3429068837,7.2013897016,4.1581061166 +6.1283246576,6.5418530631,-4.5628426333,4.9436949025,6.6375981906,3.9406255118 +6.5220264551,4.2874022968,-5.0425206801,4.9485212918,6.3504543941,5.3494718843 +4.4510895412,4.2834860823,-3.5349617184,3.0321139575,5.8234159081,2.8941415378 +5.4808097984,6.0594754374,-1.9563821489,1.8837131152,6.6862023222,5.2219148626 +4.8043061326,5.5141188355,-2.6263416213,4.2600705765,7.0365091954,3.9318148001 +5.7700669097,4.8610108566,-5.1476926175,4.7265886723,5.4205618362,3.7260588350 +5.7173655586,5.4408507780,-5.1364546621,4.4355440192,6.1584584483,5.4794799277 +3.8925816138,5.0810809362,-2.3068849118,4.2498064428,7.6586496576,3.5653920207 +4.6723601100,4.5857886518,-3.7844271012,3.5984666341,6.3284623050,4.8866883940 +5.1788065263,5.3658831575,-3.3018414389,5.7954666953,4.4919931680,5.3950256386 +5.7213013120,6.6501576761,-4.0601845395,7.5590012131,5.8916731125,4.0632080040 +3.5281308348,3.9745947317,-4.9896851878,2.1772754268,4.7090020514,4.5299321345 +4.8112545959,3.5777349034,-3.6091231986,5.3495585332,5.1315875674,4.9364072796 +4.1046099156,5.9431644946,-2.6105506282,2.5418436307,4.9643847916,4.5440333600 +4.1238367663,6.7856118344,-4.3104945987,3.0309885808,5.3730937799,5.0621723108 +5.4671409847,5.3116757589,-4.5986043694,5.1640171184,4.8281435005,6.0957909547 +4.4613307689,5.9844762021,-4.1307661603,7.7834588913,4.4252395000,3.7986799438 +6.1239080938,4.3681850438,-4.0183666238,5.2702779474,5.5016254226,5.6058704761 +8.1695895936,7.0755914835,-4.1402801866,6.9888930084,5.9117620844,5.0952883614 +6.1553397100,4.0253093238,-3.8123182255,4.0429661280,5.7458947385,5.5943447865 +5.5762879307,5.4272497595,-1.3509815126,2.3628454411,5.7334745066,5.0309046708 +4.6510959827,4.4060563788,-4.0185982913,4.3503406608,7.0383263448,2.7764510697 +4.3937445801,4.2164179089,-5.7752393012,3.3721140006,7.3354890534,5.0298687589 +4.6485046523,5.8003316399,-3.7068433469,6.1864409021,4.8265868072,4.3257498201 +5.5432768763,5.3616256875,-1.4690539579,5.9594715658,6.2113574687,4.1184653273 +4.9730140024,3.9979622530,-1.1349706431,3.3365665189,5.5085115016,5.3790023068 +6.1354492822,5.2689521336,-5.4720260233,2.3000494947,4.8668057001,3.0953995259 +5.5534922764,5.5697732143,-6.0784183683,4.7822332426,5.4202956337,4.8640532445 +5.2701602338,4.8440319254,-2.3497684497,3.4318312617,4.4038921604,5.6247521301 +5.2164315582,4.4585601367,-1.5189016651,3.5816143672,4.5822998363,3.5462491131 +6.2100101494,6.4294568906,-1.8694872463,3.8844018859,5.6762561373,5.3476377449 +6.2038226387,4.6346828728,-5.3046424746,6.6944579861,3.7811032135,3.6481002194 +5.8594613418,5.4361774743,-5.1045811376,5.6684597016,3.5414093939,5.4863699272 +5.1312954448,4.2963380613,-1.8461795794,2.9615017457,4.3934480684,5.1338314336 +5.0707564699,4.8019530509,-1.8754807455,4.2126570200,5.4483140643,3.2186875877 +5.3024642744,6.0227866824,-3.1525505964,3.1728831067,4.7570224997,5.3293573088 +6.7879927759,3.5341819252,-6.2076311366,4.1674001246,3.4233785395,5.0933414819 +6.0959154220,5.6666787812,-3.9985134848,3.1286485921,6.0090104933,3.2355050788 +4.8770092475,5.5071911462,-2.2402244446,4.2458555556,5.3319928535,4.5508172645 +4.6462822076,3.7518689113,-2.6677735581,3.5140694681,3.9302443031,3.4693742748 +4.4493063305,5.3523679747,-4.2833733602,4.4677866226,5.3261432467,4.4750702044 +4.8519104039,3.8704625972,-5.7434472532,4.7589839275,4.7355905046,4.2638381759 +4.1761724219,5.2475077356,-4.5719566477,5.4033924769,4.7243287703,3.1805946558 +3.6216295088,4.5481247568,-2.4212825459,7.3032754131,4.1663012143,4.6330886685 +1.4077245453,4.5433220483,-2.3759544201,4.8974510868,4.9454567083,5.3929741696 +4.0636335345,5.5540880159,-5.0368208549,2.5971037081,5.8474307271,4.0875864261 +3.1755581314,4.8797047351,-5.5786338133,2.0790017788,4.8688312101,4.1328612125 +4.2383507502,4.0432364540,-5.3234953644,5.3476684201,5.0191255136,4.3701405208 +4.8666980186,4.3842779297,-2.7061080702,5.3733806734,6.3115616415,5.7961596186 +3.5006748019,5.0326780821,-2.4626290230,6.1317759485,6.0701470343,4.7742381918 +3.8758838647,4.7620609155,-3.5447255805,2.4007482876,3.9938498188,3.9842301787 +4.5595618905,5.7164547880,-4.9470800659,5.4151564210,5.0136159400,4.1117493504 +6.2023217953,4.6585043199,-3.8157672796,6.1377982947,5.1851163641,5.1680961326 +6.6614906175,4.4862497262,-2.6839089723,6.6469325172,3.0866338668,3.8208368790 +3.9330122023,4.8931946185,-1.8890933487,3.6418136321,3.8294624324,5.5142152207 +3.3624266139,5.7000992690,-3.0593470590,2.4752063660,2.9488767049,4.2701185945 +3.1964625939,4.6574808863,-4.6629639060,2.8498792195,3.9731733634,3.7515961108 +5.9142384115,5.2115779252,-3.5339673537,2.8421070411,4.2028899258,4.5456089182 +4.2795018321,4.1438177734,-3.0497450887,5.3677632986,4.6646717740,5.2503284794 +6.8544789979,4.9168715809,-2.8841045580,4.0102387905,4.7739250489,4.3592520289 +6.5785072521,3.9712129002,-4.0537997178,4.4817181331,5.4048491545,4.1364356484 +6.0225496469,4.8196761345,-4.9419951771,5.0627116887,4.6007970347,4.5203158989 +5.0340614613,5.3113546917,-4.4852476141,4.4424632683,4.4686906053,4.3562024316 +6.8149029635,4.7764049759,-5.0927131551,4.7192587658,4.3400682662,5.1750095538 +5.7572216048,5.0852399903,-4.4719361336,2.3228060531,4.2754642787,4.1667433111 +6.1940809022,5.2030355864,-4.8574647529,4.0975703123,4.3798271060,4.9595683458 +5.5200884428,5.0060145767,-5.9975721396,3.0213633819,3.6806872558,5.2729580918 +4.2745663125,3.8635605519,-6.0675414963,5.9154958287,5.0815281661,3.9769449600 +2.5406332233,5.5287260018,-4.9707983262,6.0247077915,5.5070111460,4.6070789902 +3.3371378536,5.1182959756,-3.0582767542,5.6586511879,5.1252984641,4.6317077025 +3.1891145313,4.1874172320,-4.4072190418,3.7299708526,5.1210920027,4.7838976350 +2.2880847678,4.9543964123,-6.8577933075,3.4404997138,4.3457624987,4.9474460358 +0.8607358563,5.6506140689,-5.9942480303,5.3725082210,3.8214240645,4.8585516794 +1.9090115009,4.1736808673,-2.3648347905,5.0045345282,5.0848408317,5.9477653341 +1.0908043975,4.4115406105,-3.1526538834,4.8691525334,4.1978011210,3.6659718879 +2.5045794681,5.6107177077,-4.8068027320,5.4057595053,4.0101649849,4.5170053684 +4.6660373235,4.5297637335,-7.3279702149,4.2244469007,5.6704477211,6.0418472102 +6.6208094353,4.3177646969,-4.8495994534,4.1942279008,5.7960911223,5.1633893474 +7.9045975935,3.7364557935,-2.7469931299,3.7945467363,4.9378715397,4.2277078776 +6.7112183950,3.9552771862,-3.4322933169,2.9962289039,5.2336807114,3.4118360601 +7.6085801115,3.7984965006,-5.9676742032,4.6716328208,5.6770068511,5.2033915267 +6.5053711455,4.0031176792,-6.8983003181,5.3939807076,6.1822277179,4.6650915721 +6.5392019374,4.6429055517,-6.5390704399,5.2874269484,5.0617439792,3.9017260341 +5.2270108094,4.4630710638,-4.5972120007,4.2644612926,5.0302578587,4.0848685617 +5.5496858310,4.4487542973,-2.8009740648,3.3284628309,6.4133470233,3.4924372586 +7.0371776295,5.1454992863,-4.8038202052,6.5027008055,4.4580512069,5.0688646792 +7.2790384455,3.8305558589,-8.1285657006,4.3740292327,4.4175186905,4.7331314804 +5.3199184459,6.3595515832,-7.2493819308,6.2083486089,5.2600325748,5.6580023585 +4.9934556650,7.1111584018,-4.4671418166,3.9620028681,3.2784158628,4.4464836987 +4.2819567954,3.6290831153,-2.5447505490,2.9033094916,3.5047785669,5.0902289931 +3.0568943057,5.9647541508,-3.4066125502,2.1135453933,5.8188088953,4.4457507456 +2.1304712729,4.5839043211,-6.4217535278,3.2185677448,4.1073127271,4.7816574459 +4.8147659877,6.0868954346,-6.5795439179,7.6120198292,4.6210328822,4.6511473511 +5.8070914019,5.5745830940,-2.8701479375,6.2934298224,5.8679003369,3.0686975933 +3.6115552732,5.6051241927,-0.1565133541,3.0892597963,5.6292173358,4.5247718332 +2.9239742918,5.0645079050,-3.0106595660,2.8086948758,5.6505592764,5.1831295785 +4.3273263869,6.0094500831,-5.5392347499,5.4083365583,5.2901205135,4.5164771585 +3.7841411819,3.9431576374,-5.0346292184,4.1872625796,5.8242205935,3.5092717707 +2.9439589660,5.6025452125,-2.4836601202,4.5822132922,6.1914037917,5.4666134801 +2.9523695391,5.0410134987,-0.7558311054,5.0598205196,5.7990047238,4.5474676004 +2.2194426369,2.8717922780,-3.8104258303,5.0531065528,6.4355422054,4.4086296771 +2.2286583798,5.4099611913,-6.5740490807,4.6269428270,6.2346414362,4.5851645672 +3.0675309699,4.3586276188,-5.5960189493,2.9169547205,6.5151270777,4.6699692987 +4.4460740436,5.2961663528,-2.2639887009,4.3943373517,6.1833794642,3.1948426841 +5.1845831627,5.2075777558,-1.9983201220,2.6474402228,7.0406625177,4.2990464928 +3.5553859823,3.8846966161,-2.9711761962,6.5383306526,6.3769610301,4.5680337551 +5.1368821707,5.6189015736,-5.1948266433,9.3372897936,5.4303467101,4.1543003104 +4.7166452225,3.4762764160,-4.7996852767,3.5709426391,6.0709400596,4.0162537375 +4.0655064696,4.8679798824,-2.5257817203,-0.2397540472,7.4430134883,3.9741481384 +4.8739646478,6.1001218568,0.1309412790,3.9178609675,4.7876906875,5.7503016926 +3.2036693337,4.0978865218,-1.3996139990,6.6508999867,4.6941532361,3.2454641348 +4.7404405197,4.0877490842,-3.7645785945,4.3435381982,6.8122472905,4.0582880196 +3.9524198102,3.0605371217,-2.8759647346,6.5352019477,5.1398339218,5.4600301737 +5.1156643408,3.1298905115,0.1325467265,4.2355351326,4.1474944903,3.6031137112 +6.6783762367,5.0939390625,1.5048033372,4.8953245397,4.4007169152,6.0441346235 +5.1757050832,2.3866379586,0.0443435711,2.9547869931,4.3714863561,3.6838266160 +5.3307733146,5.0024969355,-2.1842578899,2.4141336352,4.2150618862,3.5282264202 +4.9625892048,4.1347588039,-2.6512376363,6.7856744153,4.0409769865,3.5442862768 +5.1941150714,5.4732915830,1.2894533068,5.9372271540,5.2995430730,5.3587242672 +5.7842645137,3.8712216053,3.1499162931,7.4436349050,4.8329832398,4.3608245532 +4.8817417798,5.5837321696,1.0092497588,5.4831170612,5.2140420248,4.9816943324 +3.9102292878,4.5787311311,-2.7490211779,3.9868229598,6.7003222520,4.6231462773 +3.7104173166,6.3020864130,-2.4687305447,2.5978512267,3.9219762100,4.8640467589 +2.6969414480,3.5627605456,1.9264159841,2.9392001484,4.3075157645,4.5246176769 +3.1021142802,4.4852079467,4.9896603230,4.0170818602,4.8452548954,3.6551728846 +1.9498933374,5.1335954089,1.3907402820,3.9319088353,5.2717133432,5.0288914923 +5.3022616650,4.8500804218,-4.3388057198,3.7600673234,4.9716484394,4.3383128810 +2.8381666261,5.5680553555,-2.5366843969,4.7642074766,4.3406980043,4.6799907608 +2.5103293788,3.1495788140,2.7225753380,4.9935148390,5.5794567272,5.5523926628 +4.0647003336,4.5231525968,4.0833849317,3.6763204386,5.9614121030,4.2830503713 +5.3192407560,4.8920386478,0.7357547931,4.5268430470,4.3460743252,4.0771200785 +5.5757491351,1.6517485430,-3.5749591267,6.3889723180,3.6970456936,4.6004392063 diff --git a/shared/package-files/73/737842719bae8623b32be9f3f60ccac6a181eadd7e92eb489ef55870f2e7c263/broadcast_tensors.h b/shared/package-files/73/737842719bae8623b32be9f3f60ccac6a181eadd7e92eb489ef55870f2e7c263/broadcast_tensors.h new file mode 100644 index 0000000000000000000000000000000000000000..1e66a92a9750e5e373832112b026f4ec99dceb69 --- /dev/null +++ b/shared/package-files/73/737842719bae8623b32be9f3f60ccac6a181eadd7e92eb489ef55870f2e7c263/broadcast_tensors.h @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::broadcast_tensors(Tensor[] tensors) -> Tensor[] +inline ::std::vector broadcast_tensors(at::TensorList tensors) { + return at::_ops::broadcast_tensors::call(tensors); +} + +} diff --git a/shared/package-files/73/737bb2b105e38872173451332f42f80ce0a80e65205f225d3ee7fec7b46d9d5f/enums.py b/shared/package-files/73/737bb2b105e38872173451332f42f80ce0a80e65205f225d3ee7fec7b46d9d5f/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..e8d23ea9355619a22ee39780e55bc86fab08bc2a --- /dev/null +++ b/shared/package-files/73/737bb2b105e38872173451332f42f80ce0a80e65205f225d3ee7fec7b46d9d5f/enums.py @@ -0,0 +1,189 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +import sys +from enum import Enum +from platform import machine + +from ..auxlib.decorators import classproperty +from ..auxlib.ish import dals +from ..auxlib.type_coercion import TypeCoercionError, boolify +from ..exceptions import CondaUpgradeError + + +class Arch(Enum): + x86 = "x86" + x86_64 = "x86_64" + # arm64 is for macOS and Windows + arm64 = "arm64" + armv6l = "armv6l" + armv7l = "armv7l" + # aarch64 is for Linux only + aarch64 = "aarch64" + ppc64 = "ppc64" + ppc64le = "ppc64le" + riscv64 = "riscv64" + s390x = "s390x" + z = "z" + + @classmethod + def from_sys(cls): + if sys.platform == "zos": + return cls["z"] + return cls[machine()] + + def __json__(self): + return self.value + + +class Platform(Enum): + linux = "linux" + win = "win32" + openbsd = "openbsd5" + osx = "darwin" + zos = "zos" + + @classmethod + def from_sys(cls): + p = sys.platform + if p.startswith("linux"): + # Changed in version 2.7.3: Since lots of code check for sys.platform == 'linux2', + # and there is no essential change between Linux 2.x and 3.x, sys.platform is always + # set to 'linux2', even on Linux 3.x. In Python 3.3 and later, the value will always + # be set to 'linux' + p = "linux" + return cls(p) + + def __json__(self): + return self.value + + +class FileMode(Enum): + text = "text" + binary = "binary" + + def __str__(self): + return "%s" % self.value + + +class LinkType(Enum): + # directory is not a link type, and copy is not a path type + # LinkType is still probably the best name here + hardlink = 1 + softlink = 2 + copy = 3 + directory = 4 + + def __int__(self): + return self.value + + def __str__(self): + return self.name + + def __json__(self): + return self.name + + +class PathType(Enum): + """ + Refers to if the file in question is hard linked or soft linked. Originally designed to be used + in paths.json + """ + + hardlink = "hardlink" + softlink = "softlink" + directory = "directory" + + # these additional types should not be included by conda-build in packages + linked_package_record = ( + "linked_package_record" # a package's .json file in conda-meta + ) + pyc_file = "pyc_file" + unix_python_entry_point = "unix_python_entry_point" + windows_python_entry_point_script = "windows_python_entry_point_script" + windows_python_entry_point_exe = "windows_python_entry_point_exe" + + @classproperty + def basic_types(self): + return (PathType.hardlink, PathType.softlink, PathType.directory) + + def __str__(self): + return self.name + + def __json__(self): + return self.name + + +class LeasedPathType(Enum): + application_entry_point = "application_entry_point" + application_entry_point_windows_exe = "application_entry_point_windows_exe" + application_softlink = "application_softlink" + + def __str__(self): + return self.name + + def __json__(self): + return self.name + + +class PackageType(Enum): + NOARCH_GENERIC = "noarch_generic" + NOARCH_PYTHON = "noarch_python" + VIRTUAL_PRIVATE_ENV = "virtual_private_env" + VIRTUAL_PYTHON_WHEEL = "virtual_python_wheel" # manageable + VIRTUAL_PYTHON_EGG_MANAGEABLE = "virtual_python_egg_manageable" + VIRTUAL_PYTHON_EGG_UNMANAGEABLE = "virtual_python_egg_unmanageable" + VIRTUAL_PYTHON_EGG_LINK = "virtual_python_egg_link" # unmanageable + VIRTUAL_SYSTEM = "virtual_system" # virtual packages representing system attributes + + @staticmethod + def conda_package_types(): + return { + None, + PackageType.NOARCH_GENERIC, + PackageType.NOARCH_PYTHON, + } + + @staticmethod + def unmanageable_package_types(): + return { + PackageType.VIRTUAL_PYTHON_EGG_UNMANAGEABLE, + PackageType.VIRTUAL_PYTHON_EGG_LINK, + PackageType.VIRTUAL_SYSTEM, + } + + +class NoarchType(Enum): + generic = "generic" + python = "python" + + @staticmethod + def coerce(val): + # what a mess + if isinstance(val, NoarchType): + return val + valtype = getattr(val, "type", None) + if isinstance(valtype, NoarchType): # see issue #8311 + return valtype + if isinstance(val, bool): + val = NoarchType.generic if val else None + if isinstance(val, str): + val = val.lower() + if val == "python": + val = NoarchType.python + elif val == "generic": + val = NoarchType.generic + else: + try: + val = NoarchType.generic if boolify(val) else None + except TypeCoercionError: + raise CondaUpgradeError( + dals( + """ + The noarch type for this package is set to '%s'. + The current version of conda is too old to install this package. + Please update conda. + """ + % val + ) + ) + return val diff --git a/shared/package-files/73/737bfdc14ccb1d41fe7815468fafdbae85611e48a8370a5a680a530c02447e55/test_circuitplot.py b/shared/package-files/73/737bfdc14ccb1d41fe7815468fafdbae85611e48a8370a5a680a530c02447e55/test_circuitplot.py new file mode 100644 index 0000000000000000000000000000000000000000..fcc89f77047450ad3f8663f371f483654dc70ea9 --- /dev/null +++ b/shared/package-files/73/737bfdc14ccb1d41fe7815468fafdbae85611e48a8370a5a680a530c02447e55/test_circuitplot.py @@ -0,0 +1,69 @@ +from sympy.physics.quantum.circuitplot import labeller, render_label, Mz, CreateOneQubitGate,\ + CreateCGate +from sympy.physics.quantum.gate import CNOT, H, SWAP, CGate, S, T +from sympy.external import import_module +from sympy.testing.pytest import skip + +mpl = import_module('matplotlib') + +def test_render_label(): + assert render_label('q0') == r'$\left|q0\right\rangle$' + assert render_label('q0', {'q0': '0'}) == r'$\left|q0\right\rangle=\left|0\right\rangle$' + +def test_Mz(): + assert str(Mz(0)) == 'Mz(0)' + +def test_create1(): + Qgate = CreateOneQubitGate('Q') + assert str(Qgate(0)) == 'Q(0)' + +def test_createc(): + Qgate = CreateCGate('Q') + assert str(Qgate([1],0)) == 'C((1),Q(0))' + +def test_labeller(): + """Test the labeller utility""" + assert labeller(2) == ['q_1', 'q_0'] + assert labeller(3,'j') == ['j_2', 'j_1', 'j_0'] + +def test_cnot(): + """Test a simple cnot circuit. Right now this only makes sure the code doesn't + raise an exception, and some simple properties + """ + if not mpl: + skip("matplotlib not installed") + else: + from sympy.physics.quantum.circuitplot import CircuitPlot + + c = CircuitPlot(CNOT(1,0),2,labels=labeller(2)) + assert c.ngates == 2 + assert c.nqubits == 2 + assert c.labels == ['q_1', 'q_0'] + + c = CircuitPlot(CNOT(1,0),2) + assert c.ngates == 2 + assert c.nqubits == 2 + assert c.labels == [] + +def test_ex1(): + if not mpl: + skip("matplotlib not installed") + else: + from sympy.physics.quantum.circuitplot import CircuitPlot + + c = CircuitPlot(CNOT(1,0)*H(1),2,labels=labeller(2)) + assert c.ngates == 2 + assert c.nqubits == 2 + assert c.labels == ['q_1', 'q_0'] + +def test_ex4(): + if not mpl: + skip("matplotlib not installed") + else: + from sympy.physics.quantum.circuitplot import CircuitPlot + + c = CircuitPlot(SWAP(0,2)*H(0)* CGate((0,),S(1)) *H(1)*CGate((0,),T(2))\ + *CGate((1,),S(2))*H(2),3,labels=labeller(3,'j')) + assert c.ngates == 7 + assert c.nqubits == 3 + assert c.labels == ['j_2', 'j_1', 'j_0'] diff --git a/shared/package-files/73/737d928dc058e44684582d19ccc5aa7c433d05f31af2c31ce275ff5a7b4bddf7/gflags.pyi b/shared/package-files/73/737d928dc058e44684582d19ccc5aa7c433d05f31af2c31ce275ff5a7b4bddf7/gflags.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a4c487d310d47f07906c5ab3667613c4e3918602 --- /dev/null +++ b/shared/package-files/73/737d928dc058e44684582d19ccc5aa7c433d05f31af2c31ce275ff5a7b4bddf7/gflags.pyi @@ -0,0 +1,312 @@ +from types import ModuleType +from typing import IO, Any, Callable, Dict, Iterable, List, Optional, Sequence, Text, Union + +class Error(Exception): ... + +FlagsError = Error + +class DuplicateFlag(FlagsError): ... +class CantOpenFlagFileError(FlagsError): ... +class DuplicateFlagCannotPropagateNoneToSwig(DuplicateFlag): ... + +class DuplicateFlagError(DuplicateFlag): + def __init__(self, flagname: str, flag_values: FlagValues, other_flag_values: FlagValues = ...) -> None: ... + +class IllegalFlagValueError(FlagsError): ... + +IllegalFlagValue = IllegalFlagValueError + +class UnrecognizedFlag(FlagsError): ... + +class UnrecognizedFlagError(UnrecognizedFlag): + def __init__(self, flagname: str, flagvalue: str = ...) -> None: ... + +def get_help_width() -> int: ... + +GetHelpWidth = get_help_width + +def text_wrap(text: str, length: int = ..., indent: str = ..., firstline_indent: str = ..., tabs: str = ...) -> str: ... + +TextWrap = text_wrap + +def doc_to_help(doc: str) -> str: ... + +DocToHelp = doc_to_help + +class FlagValues: + def __init__(self) -> None: ... + def UseGnuGetOpt(self, use_gnu_getopt: bool = ...) -> None: ... + def is_gnu_getopt(self) -> bool: ... + IsGnuGetOpt = is_gnu_getopt + # TODO dict type + def FlagDict(self) -> Dict[Any, Any]: ... + def flags_by_module_dict(self) -> Dict[str, List[Flag]]: ... + FlagsByModuleDict = flags_by_module_dict + def flags_by_module_id_dict(self) -> Dict[int, List[Flag]]: ... + FlagsByModuleIdDict = flags_by_module_id_dict + def key_flags_by_module_dict(self) -> Dict[str, List[Flag]]: ... + KeyFlagsByModuleDict = key_flags_by_module_dict + def find_module_defining_flag(self, flagname: str, default: str = ...) -> str: ... + FindModuleDefiningFlag = find_module_defining_flag + def find_module_id_defining_flag(self, flagname: str, default: int = ...) -> int: ... + FindModuleIdDefiningFlag = find_module_id_defining_flag + def append_flag_values(self, flag_values: FlagValues) -> None: ... + AppendFlagValues = append_flag_values + def remove_flag_values(self, flag_values: FlagValues) -> None: ... + RemoveFlagValues = remove_flag_values + def __setitem__(self, name: str, flag: Flag) -> None: ... + def __getitem__(self, name: str) -> Flag: ... + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __delattr__(self, flag_name: str) -> None: ... + def set_default(self, name: str, value: Any) -> None: ... + SetDefault = set_default + def __contains__(self, name: str) -> bool: ... + has_key = __contains__ + def __iter__(self) -> Iterable[str]: ... + def __call__(self, argv: List[str], known_only: bool = ...) -> List[str]: ... + def reset(self) -> None: ... + Reset = reset + def RegisteredFlags(self) -> List[str]: ... + def flag_values_dict(self) -> Dict[str, Any]: ... + FlagValuesDict = flag_values_dict + def __str__(self) -> str: ... + def GetHelp(self, prefix: str = ...) -> str: ... + def module_help(self, module: Union[ModuleType, str]) -> str: ... + ModuleHelp = module_help + def main_module_help(self) -> str: ... + MainModuleHelp = main_module_help + def get(self, name: str, default: Any) -> Any: ... + def ShortestUniquePrefixes(self, fl: Dict[str, Flag]) -> Dict[str, str]: ... + def ExtractFilename(self, flagfile_str: str) -> str: ... + def read_flags_from_files(self, argv: List[str], force_gnu: bool = ...) -> List[str]: ... + ReadFlagsFromFiles = read_flags_from_files + def flags_into_string(self) -> str: ... + FlagsIntoString = flags_into_string + def append_flags_into_file(self, filename: str) -> None: ... + AppendFlagsIntoFile = append_flags_into_file + def write_help_in_xml_format(self, outfile: IO[str] = ...) -> None: ... + WriteHelpInXMLFormat = write_help_in_xml_format + # TODO validator: gflags_validators.Validator + def AddValidator(self, validator: Any) -> None: ... + def is_parsed(self) -> bool: ... + IsParsed = is_parsed + +FLAGS: FlagValues + +class Flag: + name: str + default: Any + default_as_str: str + value: Any + help: str + short_name: str + boolean = False + present = False + parser: ArgumentParser + serializer: ArgumentSerializer + allow_override = False + def __init__( + self, + parser: ArgumentParser, + serializer: ArgumentSerializer, + name: str, + default: Optional[str], + help_string: str, + short_name: str = ..., + boolean: bool = ..., + allow_override: bool = ..., + ) -> None: ... + def Parse(self, argument: Any) -> Any: ... + def Unparse(self) -> None: ... + def Serialize(self) -> str: ... + def SetDefault(self, value: Any) -> None: ... + def Type(self) -> str: ... + def WriteInfoInXMLFormat(self, outfile: IO[str], module_name: str, is_key: bool = ..., indent: str = ...) -> None: ... + +class ArgumentParser(object): + syntactic_help: str + # TODO what is this + def parse(self, argument: Any) -> Any: ... + Parser = parse + def flag_type(self) -> str: ... + Type = flag_type + def WriteCustomInfoInXMLFormat(self, outfile: IO[str], indent: str) -> None: ... + +class ArgumentSerializer: + def Serialize(self, value: Any) -> Text: ... + +class ListSerializer(ArgumentSerializer): + def __init__(self, list_sep: str) -> None: ... + def Serialize(self, value: List[Any]) -> str: ... + +def register_validator( + flag_name: str, checker: Callable[[Any], bool], message: str = ..., flag_values: FlagValues = ... +) -> None: ... + +RegisterValidator = register_validator + +def mark_flag_as_required(flag_name: str, flag_values: FlagValues = ...) -> None: ... + +MarkFlagAsRequired = mark_flag_as_required + +def mark_flags_as_required(flag_names: Iterable[str], flag_values: FlagValues = ...) -> None: ... + +MarkFlagsAsRequired = mark_flags_as_required + +def mark_flags_as_mutual_exclusive(flag_names: Iterable[str], required: bool = ..., flag_values: FlagValues = ...) -> None: ... + +MarkFlagsAsMutualExclusive = mark_flags_as_mutual_exclusive + +def DEFINE( + parser: ArgumentParser, + name: str, + default: Any, + help: str, + flag_values: FlagValues = ..., + serializer: ArgumentSerializer = ..., + **args: Any, +) -> None: ... +def DEFINE_flag(flag: Flag, flag_values: FlagValues = ...) -> None: ... +def declare_key_flag(flag_name: str, flag_values: FlagValues = ...) -> None: ... + +DECLARE_key_flag = declare_key_flag + +def adopt_module_key_flags(module: ModuleType, flag_values: FlagValues = ...) -> None: ... + +ADOPT_module_key_flags = adopt_module_key_flags + +def DEFINE_string(name: str, default: Optional[str], help: str, flag_values: FlagValues = ..., **args: Any) -> None: ... + +class BooleanParser(ArgumentParser): + def Convert(self, argument: Any) -> bool: ... + def Parse(self, argument: Any) -> bool: ... + +class BooleanFlag(Flag): + def __init__(self, name: str, default: Optional[bool], help: str, short_name: str = ..., **args: Any) -> None: ... + +def DEFINE_boolean(name: str, default: Optional[bool], help: str, flag_values: FlagValues = ..., **args: Any) -> None: ... + +DEFINE_bool = DEFINE_boolean + +class HelpFlag(BooleanFlag): + def __init__(self) -> None: ... + def Parse(self, arg: Any) -> None: ... + +class HelpXMLFlag(BooleanFlag): + def __init__(self) -> None: ... + def Parse(self, arg: Any) -> None: ... + +class HelpshortFlag(BooleanFlag): + def __init__(self) -> None: ... + def Parse(self, arg: Any) -> None: ... + +class NumericParser(ArgumentParser): + def IsOutsideBounds(self, val: float) -> bool: ... + def Parse(self, argument: Any) -> float: ... + def WriteCustomInfoInXMLFormat(self, outfile: IO[str], indent: str) -> None: ... + def Convert(self, argument: Any) -> Any: ... + +class FloatParser(NumericParser): + number_article: str + number_name: str + syntactic_help: str + def __init__(self, lower_bound: float = ..., upper_bound: float = ...) -> None: ... + def Convert(self, argument: Any) -> float: ... + +def DEFINE_float( + name: str, + default: Optional[float], + help: str, + lower_bound: float = ..., + upper_bound: float = ..., + flag_values: FlagValues = ..., + **args: Any, +) -> None: ... + +class IntegerParser(NumericParser): + number_article: str + number_name: str + syntactic_help: str + def __init__(self, lower_bound: int = ..., upper_bound: int = ...) -> None: ... + def Convert(self, argument: Any) -> int: ... + +def DEFINE_integer( + name: str, + default: Optional[int], + help: str, + lower_bound: int = ..., + upper_bound: int = ..., + flag_values: FlagValues = ..., + **args: Any, +) -> None: ... + +class EnumParser(ArgumentParser): + def __init__(self, enum_values: List[str]) -> None: ... + def Parse(self, argument: Any) -> Any: ... + +class EnumFlag(Flag): + def __init__( + self, name: str, default: Optional[str], help: str, enum_values: List[str], short_name: str, **args: Any + ) -> None: ... + +def DEFINE_enum( + name: str, default: Optional[str], enum_values: Iterable[str], help: str, flag_values: FlagValues = ..., **args: Any +) -> None: ... + +class BaseListParser(ArgumentParser): + def __init__(self, token: str = ..., name: str = ...) -> None: ... + def Parse(self, argument: Any) -> List[Any]: ... + +class ListParser(BaseListParser): + def __init__(self) -> None: ... + +class WhitespaceSeparatedListParser(BaseListParser): + def __init__(self) -> None: ... + +def DEFINE_list(name: str, default: Optional[List[str]], help: str, flag_values: FlagValues = ..., **args: Any) -> None: ... +def DEFINE_spaceseplist( + name: str, default: Optional[List[str]], help: str, flag_values: FlagValues = ..., **args: Any +) -> None: ... + +class MultiFlag(Flag): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def Parse(self, arguments: Any) -> None: ... + def Serialize(self) -> str: ... + +def DEFINE_multi_string( + name: str, default: Optional[Union[str, List[str]]], help: str, flag_values: FlagValues = ..., **args: Any +) -> None: ... + +DEFINE_multistring = DEFINE_multi_string + +def DEFINE_multi_integer( + name: str, + default: Optional[Union[int, List[int]]], + help: str, + lower_bound: int = ..., + upper_bound: int = ..., + flag_values: FlagValues = ..., + **args: Any, +) -> None: ... + +DEFINE_multi_int = DEFINE_multi_integer + +def DEFINE_multi_float( + name: str, + default: Optional[Union[float, List[float]]], + help: str, + lower_bound: float = ..., + upper_bound: float = ..., + flag_values: FlagValues = ..., + **args: Any, +) -> None: ... +def DEFINE_multi_enum( + name: str, + default: Optional[Union[Sequence[str], str]], + enum_values: Sequence[str], + help: str, + flag_values: FlagValues = ..., + case_sensitive: bool = ..., + **args: Any, +) -> None: ... diff --git a/shared/package-files/73/737e2cae5914f2191762974a5d5a3312eb623ebc91f1b7ffe6a126886401a06e/test8.arff b/shared/package-files/73/737e2cae5914f2191762974a5d5a3312eb623ebc91f1b7ffe6a126886401a06e/test8.arff new file mode 100644 index 0000000000000000000000000000000000000000..776deb4c9e7550eafdb26d16826f5651da37ef12 --- /dev/null +++ b/shared/package-files/73/737e2cae5914f2191762974a5d5a3312eb623ebc91f1b7ffe6a126886401a06e/test8.arff @@ -0,0 +1,12 @@ +@RELATION test8 + +@ATTRIBUTE attr_datetime_utc DATE "yyyy-MM-dd HH:mm Z" +@ATTRIBUTE attr_datetime_full DATE "yy-MM-dd HH:mm:ss z" + +@DATA +"1999-01-31 00:01 UTC","99-01-31 00:01:08 +0430" +"2004-12-01 23:59 UTC","04-12-01 23:59:59 -0800" +"1817-04-28 13:00 UTC","17-04-28 13:00:33 +1000" +"2100-09-10 12:00 UTC","21-09-10 12:00:21 -0300" +"2013-11-30 04:55 UTC","13-11-30 04:55:48 -1100" +"1631-10-15 20:04 UTC","31-10-15 20:04:10 +0000" \ No newline at end of file diff --git a/shared/package-files/73/737ed4f6da819da51db753b215d199c19a46dca47a217373d1cbde248c7e52e7/matmul.py b/shared/package-files/73/737ed4f6da819da51db753b215d199c19a46dca47a217373d1cbde248c7e52e7/matmul.py new file mode 100644 index 0000000000000000000000000000000000000000..832e52727f092f5f543730b16406c3c9d7f05d80 --- /dev/null +++ b/shared/package-files/73/737ed4f6da819da51db753b215d199c19a46dca47a217373d1cbde248c7e52e7/matmul.py @@ -0,0 +1,204 @@ +import torch + +from .. import Config, autotune, cdiv, heuristics, jit +from .. import language as tl +from .matmul_perf_model import early_config_prune, estimate_matmul_time + +_ordered_datatypes = [torch.float16, torch.bfloat16, torch.float32] + + +def get_higher_dtype(a, b): + if a is b: + return a + + assert a in _ordered_datatypes + assert b in _ordered_datatypes + + for d in _ordered_datatypes: + if a is d: + return b + if b is d: + return a + + +def init_to_zero(name): + return lambda nargs: nargs[name].zero_() + + +def get_configs_io_bound(): + configs = [] + for num_stages in [2, 3, 4, 5, 6]: + for block_m in [16, 32]: + for block_k in [32, 64]: + for block_n in [32, 64, 128, 256]: + num_warps = 2 if block_n <= 64 else 4 + configs.append( + Config({'BLOCK_M': block_m, 'BLOCK_N': block_n, 'BLOCK_K': block_k, 'SPLIT_K': 1}, + num_stages=num_stages, num_warps=num_warps)) + # split_k + for split_k in [2, 4, 8, 16]: + configs.append( + Config({'BLOCK_M': block_m, 'BLOCK_N': block_n, 'BLOCK_K': block_k, 'SPLIT_K': split_k}, + num_stages=num_stages, num_warps=num_warps, pre_hook=init_to_zero('C'))) + return configs + + +@autotune( + configs=[ + # basic configs for compute-bound matmuls + Config({'BLOCK_M': 128, 'BLOCK_N': 256, 'BLOCK_K': 32, 'SPLIT_K': 1}, num_stages=3, num_warps=8), + Config({'BLOCK_M': 256, 'BLOCK_N': 128, 'BLOCK_K': 32, 'SPLIT_K': 1}, num_stages=3, num_warps=8), + Config({'BLOCK_M': 256, 'BLOCK_N': 64, 'BLOCK_K': 32, 'SPLIT_K': 1}, num_stages=4, num_warps=4), + Config({'BLOCK_M': 64, 'BLOCK_N': 256, 'BLOCK_K': 32, 'SPLIT_K': 1}, num_stages=4, num_warps=4), + Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'BLOCK_K': 32, 'SPLIT_K': 1}, num_stages=4, num_warps=4), + Config({'BLOCK_M': 128, 'BLOCK_N': 64, 'BLOCK_K': 32, 'SPLIT_K': 1}, num_stages=4, num_warps=4), + Config({'BLOCK_M': 64, 'BLOCK_N': 128, 'BLOCK_K': 32, 'SPLIT_K': 1}, num_stages=4, num_warps=4), + Config({'BLOCK_M': 128, 'BLOCK_N': 32, 'BLOCK_K': 32, 'SPLIT_K': 1}, num_stages=4, num_warps=4), + Config({'BLOCK_M': 64, 'BLOCK_N': 32, 'BLOCK_K': 32, 'SPLIT_K': 1}, num_stages=5, num_warps=2), + # good for int8 + Config({'BLOCK_M': 128, 'BLOCK_N': 256, 'BLOCK_K': 128, 'SPLIT_K': 1}, num_stages=3, num_warps=8), + Config({'BLOCK_M': 256, 'BLOCK_N': 128, 'BLOCK_K': 128, 'SPLIT_K': 1}, num_stages=3, num_warps=8), + Config({'BLOCK_M': 256, 'BLOCK_N': 64, 'BLOCK_K': 128, 'SPLIT_K': 1}, num_stages=4, num_warps=4), + Config({'BLOCK_M': 64, 'BLOCK_N': 256, 'BLOCK_K': 128, 'SPLIT_K': 1}, num_stages=4, num_warps=4), + Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'BLOCK_K': 128, 'SPLIT_K': 1}, num_stages=4, num_warps=4), + Config({'BLOCK_M': 128, 'BLOCK_N': 64, 'BLOCK_K': 64, 'SPLIT_K': 1}, num_stages=4, num_warps=4), + Config({'BLOCK_M': 64, 'BLOCK_N': 128, 'BLOCK_K': 64, 'SPLIT_K': 1}, num_stages=4, num_warps=4), + Config({'BLOCK_M': 128, 'BLOCK_N': 32, 'BLOCK_K': 64, 'SPLIT_K': 1}, num_stages=4, num_warps=4), + Config({'BLOCK_M': 64, 'BLOCK_N': 32, 'BLOCK_K': 64, 'SPLIT_K': 1}, num_stages=5, num_warps=2), + ] + get_configs_io_bound(), + key=['M', 'N', 'K'], + prune_configs_by={ + 'early_config_prune': early_config_prune, + 'perf_model': estimate_matmul_time, + 'top_k': 10, + }, +) +@heuristics({ + 'EVEN_K': lambda args: args['K'] % (args['BLOCK_K'] * args['SPLIT_K']) == 0, +}) +@jit +def _kernel(A, B, C, M, N, K, # + stride_am, stride_ak, # + stride_bk, stride_bn, # + stride_cm, stride_cn, # + dot_out_dtype: tl.constexpr, # + allow_tf32: tl.constexpr, # + fp8_fast_accum: tl.constexpr, # + BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, # + GROUP_M: tl.constexpr, SPLIT_K: tl.constexpr, EVEN_K: tl.constexpr, AB_DTYPE: tl.constexpr # + ): + # matrix multiplication + pid = tl.program_id(0) + pid_z = tl.program_id(1) + grid_m = tl.cdiv(M, BLOCK_M) + grid_n = tl.cdiv(N, BLOCK_N) + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + # do matrix multiplication + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + rk = pid_z * BLOCK_K + tl.arange(0, BLOCK_K) + # pointers + A = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak) + B = B + (rk[:, None] * stride_bk + rbn[None, :] * stride_bn) + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=dot_out_dtype) + for k in range(0, tl.cdiv(K, BLOCK_K * SPLIT_K)): + if EVEN_K: + a = tl.load(A) + b = tl.load(B) + else: + k_remaining = K - k * (BLOCK_K * SPLIT_K) + _0 = tl.zeros((1, 1), dtype=C.dtype.element_ty) + a = tl.load(A, mask=rk[None, :] < k_remaining, other=_0) + b = tl.load(B, mask=rk[:, None] < k_remaining, other=_0) + if AB_DTYPE: + a = a.to(C.dtype.element_ty) + b = b.to(C.dtype.element_ty) + if fp8_fast_accum: + acc = tl.dot(a, b, acc, out_dtype=dot_out_dtype, allow_tf32=allow_tf32) + else: + acc += tl.dot(a, b, out_dtype=dot_out_dtype, allow_tf32=allow_tf32) + A += BLOCK_K * SPLIT_K * stride_ak + B += BLOCK_K * SPLIT_K * stride_bk + acc = acc.to(C.dtype.element_ty) + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + C = C + (rm[:, None] * stride_cm + rn[None, :] * stride_cn) + mask = (rm < M)[:, None] & (rn < N)[None, :] + # handles write-back with reduction-splitting + if SPLIT_K == 1: + tl.store(C, acc, mask=mask) + else: + tl.atomic_add(C, acc, mask=mask) + + +class _matmul(torch.autograd.Function): + kernel = _kernel + + _locks = {} + + @staticmethod + def _call(a, b, dot_out_dtype, allow_tf32, fp8_fast_accum): + device = a.device + # handle non-contiguous inputs if necessary + if a.stride(0) > 1 and a.stride(1) > 1: + a = a.contiguous() + if b.stride(0) > 1 and b.stride(1) > 1: + b = b.contiguous() + # checks constraints + assert a.shape[1] == b.shape[0], "incompatible dimensions" + M, K = a.shape + _, N = b.shape + # allocates output + if a.dtype in [tl.float8e4nv, tl.float8e4b15, tl.float8e5] or\ + b.dtype in [tl.float8e4nv, tl.float8e4b15, tl.float8e5]: + c_dtype = torch.float16 + elif a.dtype in [torch.int8] or b.dtype in [torch.int8]: + c_dtype = torch.int32 + else: + c_dtype = get_higher_dtype(a.dtype, b.dtype) + c = torch.empty((M, N), device=device, dtype=c_dtype) + if dot_out_dtype is None: + if c_dtype in [torch.float16, torch.float32, torch.bfloat16]: + dot_out_dtype = tl.float32 + else: + dot_out_dtype = tl.int32 + else: + assert isinstance(dot_out_dtype, torch.dtype), "dot_out_dtype must be a torch.dtype" + if dot_out_dtype == torch.float16: + dot_out_dtype = tl.float16 + elif dot_out_dtype in [torch.float32, torch.bfloat16]: + dot_out_dtype = tl.float32 + else: + dot_out_dtype = tl.int32 + ab_dtype = True + if a.dtype in [tl.float8e4nv, tl.float8e5] and b.dtype in [tl.float8e4nv, tl.float8e5]: + ab_dtype = False + if a.dtype in [torch.int8] and b.dtype in [torch.int8]: + ab_dtype = False + # launch kernel + grid = lambda META: (cdiv(M, META['BLOCK_M']) * cdiv(N, META['BLOCK_N']), META['SPLIT_K']) + _kernel[grid]( + a, b, c, M, N, K, # + a.stride(0), a.stride(1), # + b.stride(0), b.stride(1), # + c.stride(0), c.stride(1), # + dot_out_dtype=dot_out_dtype, # + allow_tf32=allow_tf32, # + fp8_fast_accum=fp8_fast_accum, # + GROUP_M=8, AB_DTYPE=ab_dtype) + return c + + @staticmethod + def forward(ctx, a, b, dot_out_dtype=None, allow_tf32=True, fp8_fast_accum=True): + return _matmul._call(a, b, dot_out_dtype=dot_out_dtype, allow_tf32=allow_tf32, fp8_fast_accum=fp8_fast_accum) + + +matmul = _matmul.apply diff --git a/shared/package-files/73/737f40832acb07ec4e0b6fb856c7e4be629e56ea686a9a99d2c079c9d951f1fa/_standard_gamma_grad_cuda_dispatch.h b/shared/package-files/73/737f40832acb07ec4e0b6fb856c7e4be629e56ea686a9a99d2c079c9d951f1fa/_standard_gamma_grad_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1283483fa2b049407686c413d091844c0581cfd3 --- /dev/null +++ b/shared/package-files/73/737f40832acb07ec4e0b6fb856c7e4be629e56ea686a9a99d2c079c9d951f1fa/_standard_gamma_grad_cuda_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor _standard_gamma_grad(const at::Tensor & self, const at::Tensor & output); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/73/7385bacbe8f3adb5d5e20c0c193a7000867b9ebf6f9987a4cb57ad145f3c425b/representation.py b/shared/package-files/73/7385bacbe8f3adb5d5e20c0c193a7000867b9ebf6f9987a4cb57ad145f3c425b/representation.py new file mode 100644 index 0000000000000000000000000000000000000000..11d29f050fd8ecf11012ef4f4ea6c2a5dab19f01 --- /dev/null +++ b/shared/package-files/73/7385bacbe8f3adb5d5e20c0c193a7000867b9ebf6f9987a4cb57ad145f3c425b/representation.py @@ -0,0 +1,1329 @@ +""" +State Space Representation + +Author: Chad Fulton +License: Simplified-BSD +""" +from statsmodels.compat.numpy import inplace_reshape + +import numpy as np + +from . import tools +from .initialization import Initialization +from .tools import find_best_blas_type, validate_matrix_shape, validate_vector_shape + + +class OptionWrapper: + def __init__(self, mask_attribute, mask_value): + # Name of the class-level bitmask attribute + self.mask_attribute = mask_attribute + # Value of this option + self.mask_value = mask_value + + def __get__(self, obj, objtype): + # Return True / False based on whether the bit is set in the bitmask + return bool(getattr(obj, self.mask_attribute, 0) & self.mask_value) + + def __set__(self, obj, value): + mask_attribute_value = getattr(obj, self.mask_attribute, 0) + if bool(value): + value = mask_attribute_value | self.mask_value + else: + value = mask_attribute_value & ~self.mask_value + setattr(obj, self.mask_attribute, value) + + +class MatrixWrapper: + def __init__(self, name, attribute): + self.name = name + self.attribute = attribute + self._attribute = "_" + attribute + + def __get__(self, obj, objtype): + matrix = getattr(obj, self._attribute, None) + # # Remove last dimension if the array is not actually time-varying + # if matrix is not None and matrix.shape[-1] == 1: + # return np.squeeze(matrix, -1) + return matrix + + def __set__(self, obj, value): + value = np.asarray(value, order="F") + shape = obj.shapes[self.attribute] + + if len(shape) == 3: + value = self._set_matrix(obj, value, shape) + else: + value = self._set_vector(obj, value, shape) + + setattr(obj, self._attribute, value) + obj.shapes[self.attribute] = value.shape + + def _set_matrix(self, obj, value, shape): + # Expand 1-dimensional array if possible + if value.ndim == 1 and shape[0] == 1 and value.shape[0] == shape[1]: + value = value[None, :] + + # Enforce that the matrix is appropriate size + validate_matrix_shape(self.name, value.shape, shape[0], shape[1], obj.nobs) + + # Expand time-invariant matrix + if value.ndim == 2: + value = np.array(value[:, :, None], order="F") + + return value + + def _set_vector(self, obj, value, shape): + # Enforce that the vector has appropriate length + validate_vector_shape(self.name, value.shape, shape[0], obj.nobs) + + # Expand the time-invariant vector + if value.ndim == 1: + value = np.array(value[:, None], order="F") + + return value + + +class Representation: + r""" + State space representation of a time series process + + Parameters + ---------- + k_endog : ndarray or int + The observed time-series process :math:`y` if array like or the + number of variables in the process if an integer. + k_states : int + The dimension of the unobserved state process. + k_posdef : int, optional + The dimension of a guaranteed positive definite covariance matrix + describing the shocks in the measurement equation. Must be less than + or equal to `k_states`. Default is `k_states`. + initial_variance : float, optional + Initial variance used when approximate diffuse initialization is + specified. Default is 1e6. + initialization : Initialization or str, optional + Initialization method for the initial state. If a string, must be one + of {'diffuse', 'approximate_diffuse', 'stationary', 'known'}. + initial_state : array_like, optional + If `initialization='known'` is used, the mean of the initial state's + distribution. + initial_state_cov : array_like, optional + If `initialization='known'` is used, the covariance matrix of the + initial state's distribution. + nobs : int, optional + If an endogenous vector is not given (i.e., `k_endog` is an integer), + the number of observations can optionally be specified. If not + specified, they will be set to zero until data is bound to the model. + dtype : np.dtype, optional + If an endogenous vector is not given (i.e., `k_endog` is an integer), + the default datatype of the state space matrices can optionally be + specified. Default is `np.float64`. + design : array_like, optional + The design matrix, :math:`Z`. Default is set to zeros. + obs_intercept : array_like, optional + The intercept for the observation equation, :math:`d`. Default is set + to zeros. + obs_cov : array_like, optional + The covariance matrix for the observation equation :math:`H`. Default + is set to zeros. + transition : array_like, optional + The transition matrix, :math:`T`. Default is set to zeros. + state_intercept : array_like, optional + The intercept for the transition equation, :math:`c`. Default is set to + zeros. + selection : array_like, optional + The selection matrix, :math:`R`. Default is set to zeros. + state_cov : array_like, optional + The covariance matrix for the state equation :math:`Q`. Default is set + to zeros. + **kwargs + Additional keyword arguments. Not used directly. It is present to + improve compatibility with subclasses, so that they can use `**kwargs` + to specify any default state space matrices (e.g., `design`) without + having to clean out any other keyword arguments they might have been + passed. + + Attributes + ---------- + nobs : int + The number of observations. + k_endog : int + The dimension of the observation series. + k_states : int + The dimension of the unobserved state process. + k_posdef : int + The dimension of a guaranteed positive + definite covariance matrix describing + the shocks in the measurement equation. + shapes : dict of str to tuple + A dictionary recording the initial shapes + of each of the representation matrices as + tuples. + initialization : Initialization + Kalman filter initialization method. Default is unset. + initial_variance : float + Initial variance for approximate diffuse + initialization. Default is 1e6. + + Notes + ----- + A general state space model is of the form + + .. math:: + + y_t & = Z_t \alpha_t + d_t + \varepsilon_t \\ + \alpha_{t+1} & = T_t \alpha_t + c_t + R_t \eta_t \\ + + where :math:`y_t` refers to the observation vector at time :math:`t`, + :math:`\alpha_t` refers to the (unobserved) state vector at time + :math:`t`, and where the irregular components are defined as + + .. math:: + + \varepsilon_t \sim N(0, H_t) \\ + \eta_t \sim N(0, Q_t) \\ + + The remaining variables (:math:`Z_t, d_t, H_t, T_t, c_t, R_t, Q_t`) in the + equations are matrices describing the process. Their variable names and + dimensions are as follows + + Z : `design` :math:`(k\_endog \times k\_states \times nobs)` + + d : `obs_intercept` :math:`(k\_endog \times nobs)` + + H : `obs_cov` :math:`(k\_endog \times k\_endog \times nobs)` + + T : `transition` :math:`(k\_states \times k\_states \times nobs)` + + c : `state_intercept` :math:`(k\_states \times nobs)` + + R : `selection` :math:`(k\_states \times k\_posdef \times nobs)` + + Q : `state_cov` :math:`(k\_posdef \times k\_posdef \times nobs)` + + In the case that one of the matrices is time-invariant (so that, for + example, :math:`Z_t = Z_{t+1} ~ \forall ~ t`), its last dimension may + be of size :math:`1` rather than size `nobs`. + + References + ---------- + .. [*] Durbin, James, and Siem Jan Koopman. 2012. + Time Series Analysis by State Space Methods: Second Edition. + Oxford University Press. + """ + + endog = None + r"""(array) The observation vector, alias for `obs`""" + design = MatrixWrapper("design", "design") + r"""(array) Design matrix: :math:`Z~(k\_endog \times k\_states \times nobs)`""" + obs_intercept = MatrixWrapper("observation intercept", "obs_intercept") + r"""(array) Observation intercept: :math:`d~(k\_endog \times nobs)`""" + obs_cov = MatrixWrapper("observation covariance matrix", "obs_cov") + r""" + (array) Observation covariance matrix: + :math:`H~(k\_endog \times k\_endog \times nobs)` + """ + transition = MatrixWrapper("transition", "transition") + r""" + (array) Transition matrix: + :math:`T~(k\_states \times k\_states \times nobs)` + """ + state_intercept = MatrixWrapper("state intercept", "state_intercept") + r"""(array) State intercept: :math:`c~(k\_states \times nobs)`""" + selection = MatrixWrapper("selection", "selection") + r""" + (array) Selection matrix: + :math:`R~(k\_states \times k\_posdef \times nobs)` + """ + state_cov = MatrixWrapper("state covariance matrix", "state_cov") + r""" + (array) State covariance matrix: + :math:`Q~(k\_posdef \times k\_posdef \times nobs)` + """ + + def __init__( + self, + k_endog, + k_states, + k_posdef=None, + initial_variance=1e6, + nobs=0, + dtype=np.float64, + design=None, + obs_intercept=None, + obs_cov=None, + transition=None, + state_intercept=None, + selection=None, + state_cov=None, + statespace_classes=None, + **kwargs, + ): + self.shapes = {} + + # Check if k_endog is actually the endog array + endog = None + if isinstance(k_endog, np.ndarray): + endog = k_endog + # If so, assume that it is either column-ordered and in wide format + # or row-ordered and in long format + if endog.flags["C_CONTIGUOUS"] and (endog.shape[0] > 1 or nobs == 1): + endog = endog.T + k_endog = endog.shape[0] + + # Endogenous array, dimensions, dtype + self.k_endog = k_endog + if k_endog < 1: + raise ValueError( + "Number of endogenous variables in statespace" + " model must be a positive number." + ) + self.nobs = nobs + + # Get dimensions from transition equation + if k_states < 1: + raise ValueError( + "Number of states in statespace model must be a positive number." + ) + self.k_states = k_states + self.k_posdef = k_posdef if k_posdef is not None else k_states + + # Make sure k_posdef <= k_states + # TODO: we could technically allow k_posdef > k_states, but the Cython + # code needs to be more thoroughly checked to avoid seg faults. + if self.k_posdef > self.k_states: + raise ValueError( + "Dimension of state innovation `k_posdef` cannot" + " be larger than the dimension of the state." + ) + + # Bind endog, if it was given + if endog is not None: + self.bind(endog) + + # Record the shapes of all of our matrices + # Note: these are time-invariant shapes; in practice the last dimension + # may also be `self.nobs` for any or all of these. + self.shapes = { + "obs": (self.k_endog, self.nobs), + "design": (self.k_endog, self.k_states, 1), + "obs_intercept": (self.k_endog, 1), + "obs_cov": (self.k_endog, self.k_endog, 1), + "transition": (self.k_states, self.k_states, 1), + "state_intercept": (self.k_states, 1), + "selection": (self.k_states, self.k_posdef, 1), + "state_cov": (self.k_posdef, self.k_posdef, 1), + } + + # Representation matrices + # These matrices are only used in the Python object as containers, + # which will be copied to the appropriate _statespace object if a + # filter is called. + scope = locals() + for name, shape in self.shapes.items(): + if name == "obs": + continue + # Create the initial storage array for each matrix + setattr(self, "_" + name, np.zeros(shape, dtype=dtype, order="F")) + + # If we were given an initial value for the matrix, set it + # (notice it is being set via the descriptor) + if scope[name] is not None: + setattr(self, name, scope[name]) + + # Options + self.initial_variance = initial_variance + self.prefix_statespace_map = ( + statespace_classes + if statespace_classes is not None + else tools.prefix_statespace_map.copy() + ) + + # State-space initialization data + self.initialization = kwargs.pop("initialization", None) + basic_inits = ["diffuse", "approximate_diffuse", "stationary"] + + if self.initialization in basic_inits: + self.initialize(self.initialization) + elif self.initialization == "known": + if "constant" in kwargs: + constant = kwargs.pop("constant") + elif "initial_state" in kwargs: + # TODO deprecation warning + constant = kwargs.pop("initial_state") + else: + raise ValueError( + 'Initial state must be provided when "known"' + " is the specified initialization method." + ) + if "stationary_cov" in kwargs: + stationary_cov = kwargs.pop("stationary_cov") + elif "initial_state_cov" in kwargs: + # TODO deprecation warning + stationary_cov = kwargs.pop("initial_state_cov") + else: + raise ValueError( + "Initial state covariance matrix must be" + ' provided when "known" is the specified' + " initialization method." + ) + self.initialize("known", constant=constant, stationary_cov=stationary_cov) + elif ( + not isinstance(self.initialization, Initialization) + and self.initialization is not None + ): + raise ValueError("Invalid state space initialization method.") + + # Check for unused kwargs + if kwargs: + # raise TypeError(f'{__class__} constructor got unexpected keyword' + # f' argument(s): {kwargs}.') + raise TypeError(f"Unknown keyword arguments: {list(kwargs.keys())}.") + + # Matrix representations storage + self._representations = {} + + # Setup the underlying statespace object storage + self._statespaces = {} + + # Caches + self._time_invariant = None + + def __getitem__(self, key): + _type = type(key) + # If only a string is given then we must be getting an entire matrix + if _type is str: + if key not in self.shapes: + raise IndexError(f'"{key}" is an invalid state space matrix name') + matrix = getattr(self, "_" + key) + + # See note on time-varying arrays, below + if matrix.shape[-1] == 1: + return matrix[(slice(None),) * (matrix.ndim - 1) + (0,)] + else: + return matrix + # Otherwise if we have a tuple, we want a slice of a matrix + elif _type is tuple: + name, slice_ = key[0], key[1:] + if name not in self.shapes: + raise IndexError(f'"{name}" is an invalid state space matrix name') + + matrix = getattr(self, "_" + name) + + # Since the model can support time-varying arrays, but often we + # will instead have time-invariant arrays, we want to allow setting + # a matrix slice like mod['transition',0,:] even though technically + # it should be mod['transition',0,:,0]. Thus if the array in + # question is time-invariant but the last slice was excluded, + # add it in as a zero. + if matrix.shape[-1] == 1 and len(slice_) <= matrix.ndim - 1: + slice_ = slice_ + (0,) + + return matrix[slice_] + # Otherwise, we have only a single slice index, but it is not a string + else: + raise IndexError( + "First index must the name of a valid state space matrix." + ) + + def __setitem__(self, key, value): + _type = type(key) + # If only a string is given then we must be setting an entire matrix + if _type is str: + if key not in self.shapes: + raise IndexError(f'"{key}" is an invalid state space matrix name') + setattr(self, key, value) + # If it's a tuple (with a string as the first element) then we must be + # setting a slice of a matrix + elif _type is tuple: + name, slice_ = key[0], key[1:] + if name not in self.shapes: + raise IndexError(f'"{key[0]}" is an invalid state space matrix name') + + # Change the dtype of the corresponding matrix + dtype = np.array(value).dtype + matrix = getattr(self, "_" + name) + valid_types = ["f", "d", "F", "D"] + if matrix.dtype != dtype and dtype.char in valid_types: + matrix = getattr(self, "_" + name).real.astype(dtype) + + # Since the model can support time-varying arrays, but often we + # will instead have time-invariant arrays, we want to allow setting + # a matrix slice like mod['transition',0,:] even though technically + # it should be mod['transition',0,:,0]. Thus if the array in + # question is time-invariant but the last slice was excluded, + # add it in as a zero. + if matrix.shape[-1] == 1 and len(slice_) == matrix.ndim - 1: + slice_ = slice_ + (0,) + + # Set the new value + matrix[slice_] = value + setattr(self, name, matrix) + # Otherwise we got a single non-string key, (e.g., mod[:]), which is + # invalid + else: + raise IndexError( + "First index must the name of a valid state space matrix." + ) + + def _clone_kwargs(self, endog, **kwargs): + """ + Construct keyword arguments for cloning a state space model + + Parameters + ---------- + endog : array_like + An observed time-series process :math:`y`. + **kwargs + Keyword arguments to pass to the new state space representation + model constructor. Those that are not specified are copied from + the specification of the current state space model. + """ + + # We always need the base dimensions, but they cannot change from + # the base model when cloning (the idea is: if these need to change, + # need to make a new instance manually, since it's not really cloning). + kwargs["nobs"] = len(endog) + kwargs["k_endog"] = self.k_endog + for key in ["k_states", "k_posdef"]: + val = getattr(self, key) + if key not in kwargs or kwargs[key] is None: + kwargs[key] = val + if kwargs[key] != val: + raise ValueError( + f"Cannot change the dimension of {key} when cloning." + ) + + # Get defaults for time-invariant system matrices, if not otherwise + # provided + # Time-varying matrices must be replaced. + for name in self.shapes: + if name == "obs": + continue + + if name not in kwargs: + mat = getattr(self, name) + if mat.shape[-1] != 1: + raise ValueError( + f"The `{name}` matrix is time-varying. Cloning" + " this model requires specifying an" + " updated matrix." + ) + kwargs[name] = mat + + # Default is to use the same initialization + kwargs.setdefault("initialization", self.initialization) + + return kwargs + + def clone(self, endog, **kwargs): + """ + Clone a state space representation while overriding some elements + + Parameters + ---------- + endog : array_like + An observed time-series process :math:`y`. + **kwargs + Keyword arguments to pass to the new state space representation + model constructor. Those that are not specified are copied from + the specification of the current state space model. + + Returns + ------- + Representation + + Notes + ----- + If some system matrices are time-varying, then new time-varying + matrices *must* be provided. + """ + kwargs = self._clone_kwargs(endog, **kwargs) + mod = self.__class__(**kwargs) + mod.bind(endog) + return mod + + def extend(self, endog, start=None, end=None, **kwargs): + """ + Extend the current state space model, or a specific (time) subset + + Parameters + ---------- + endog : array_like + An observed time-series process :math:`y`. + start : int, optional + The first period of a time-varying state space model to include in + the new model. Has no effect if the state space model is + time-invariant. Default is the initial period. + end : int, optional + The last period of a time-varying state space model to include in + the new model. Has no effect if the state space model is + time-invariant. Default is the final period. + **kwargs + Keyword arguments to pass to the new state space representation + model constructor. Those that are not specified are copied from + the specification of the current state space model. + + Returns + ------- + Representation + + Notes + ----- + This method does not allow replacing a time-varying system matrix with + a time-invariant one (or vice-versa). If that is required, use `clone`. + """ + endog = np.atleast_1d(endog) + if endog.ndim == 1: + endog = endog[:, np.newaxis] + nobs = len(endog) + + if start is None: + start = 0 + if end is None: + end = self.nobs + + if start < 0: + start = self.nobs + start + if end < 0: + end = self.nobs + end + if start > self.nobs: + raise ValueError( + "The `start` argument of the extension within the" + " base model cannot be after the end of the" + " base model." + ) + if end > self.nobs: + raise ValueError( + "The `end` argument of the extension within the" + " base model cannot be after the end of the" + " base model." + ) + if start > end: + raise ValueError( + "The `start` argument of the extension within the" + " base model cannot be after the `end` argument." + ) + + # Note: if start == end or if end < self.nobs, then we're just cloning + # (no extension) + endog = tools.concat([self.endog[:, start:end].T, endog]) + + # Extend any time-varying arrays + error_ti = ( + "Model has time-invariant %s matrix, so cannot provide" + " an extended matrix." + ) + error_tv = ( + "Model has time-varying %s matrix, so an updated" + " time-varying matrix for the extension period" + " is required." + ) + for name, shape in self.shapes.items(): + if name == "obs": + continue + + mat = getattr(self, name) + + # If we were *not* given an extended value for this matrix... + if name not in kwargs: + # If this is a time-varying matrix in the existing model + if mat.shape[-1] > 1: + # If we have an extension period, then raise an error + # because we should have been given an extended value + if end + nobs > self.nobs: + raise ValueError(error_tv % name) + # If we do not have an extension period, then set the new + # time-varying matrix to be the portion of the existing + # time-varying matrix that corresponds to the period of + # interest + else: + kwargs[name] = mat[..., start : end + nobs] + elif nobs == 0: + raise ValueError( + "Extension is being performed within-sample" + " so cannot provide an extended matrix" + ) + # If we were given an extended value for this matrix + else: + # TODO: Need to add a check for ndim, and if the matrix has + # one fewer dimensions than the existing matrix, add a new axis + + # If this is a time-invariant matrix in the existing model, + # raise an error + if mat.shape[-1] == 1 and self.nobs > 1: + raise ValueError(error_ti % name) + + # Otherwise, validate the shape of the given extended value + # Note: we do not validate the number of observations here + # (so we pass in updated_mat.shape[-1] as the nobs argument + # in the validate_* calls); instead, we check below that we + # at least `nobs` values were passed in and then only take the + # first of them as required. This can be useful when e.g., the + # end user knows the extension values up to some maximum + # endpoint, but does not know what the calling methods may + # specifically require. + updated_mat = np.asarray(kwargs[name]) + if len(shape) == 2: + validate_vector_shape( + name, updated_mat.shape, shape[0], updated_mat.shape[-1] + ) + else: + validate_matrix_shape( + name, + updated_mat.shape, + shape[0], + shape[1], + updated_mat.shape[-1], + ) + + if updated_mat.shape[-1] < nobs: + raise ValueError(error_tv % name) + else: + updated_mat = updated_mat[..., :nobs] + + # Concatenate to get the new time-varying matrix + kwargs[name] = np.c_[mat[..., start:end], updated_mat] + + return self.clone(endog, **kwargs) + + def diff_endog(self, new_endog, tolerance=1e-10): + """ + Compute indices of revised and newly added observations + + Parameters + ---------- + new_endog : array_like + New observation data to compare against the currently bound + endogenous data. + tolerance : float, optional + Tolerance used when comparing values to determine whether a + change represents a revision. Default is 1e-10. + + Returns + ------- + revision_ix : list of tuple + List of (row, column) indices indicating which values in + `new_endog` represent a revision to a previously observed + (non-missing) value. + new_ix : list of tuple + List of (row, column) indices indicating which values in + `new_endog` represent a newly observed value (i.e., one that + was previously missing). + """ + # TODO: move this function to tools? + endog = self.endog.T + if len(new_endog) < len(endog): + raise ValueError( + f"Given data (length {len(new_endog):d}) is too short to diff" + f" against model data (length {len(endog):d})." + ) + if len(new_endog) > len(endog): + nobs_append = len(new_endog) - len(endog) + endog = np.c_[endog.T, new_endog[-nobs_append:].T * np.nan].T + + new_nan = np.isnan(new_endog) + existing_nan = np.isnan(endog) + diff = np.abs(new_endog - endog) + diff[new_nan ^ existing_nan] = np.inf + diff[new_nan & existing_nan] = 0.0 + + is_revision = diff > tolerance + is_new = existing_nan & ~new_nan + is_revision[is_new] = False + + revision_ix = list(zip(*np.where(is_revision), strict=True)) + new_ix = list(zip(*np.where(is_new), strict=True)) + + return revision_ix, new_ix + + @property + def prefix(self): + """(str) BLAS prefix of currently active representation matrices""" + arrays = ( + self._design, + self._obs_intercept, + self._obs_cov, + self._transition, + self._state_intercept, + self._selection, + self._state_cov, + ) + if self.endog is not None: + arrays = (self.endog,) + arrays + return find_best_blas_type(arrays)[0] + + @property + def dtype(self): + """(dtype) Datatype of currently active representation matrices""" + return tools.prefix_dtype_map[self.prefix] + + @property + def time_invariant(self): + """ + (bool) Whether or not currently active representation matrices are + time-invariant + """ + if self._time_invariant is None: + return ( + self._design.shape[2] + == self._obs_intercept.shape[1] + == self._obs_cov.shape[2] + == self._transition.shape[2] + == self._state_intercept.shape[1] + == self._selection.shape[2] + == self._state_cov.shape[2] + ) + else: + return self._time_invariant + + @property + def _statespace(self): + prefix = self.prefix + if prefix in self._statespaces: + return self._statespaces[prefix] + return None + + @property + def obs(self): + r"""(array) Observation vector: :math:`y~(k\_endog \times nobs)`""" + return self.endog + + def bind(self, endog): + """ + Bind data to the statespace representation + + Parameters + ---------- + endog : ndarray + Endogenous data to bind to the model. Must be column-ordered + ndarray with shape (`k_endog`, `nobs`) or row-ordered ndarray with + shape (`nobs`, `k_endog`). + + Notes + ----- + The strict requirements arise because the underlying statespace and + Kalman filtering classes require Fortran-ordered arrays in the wide + format (shaped (`k_endog`, `nobs`)), and this structure is setup to + prevent copying arrays in memory. + + By default, numpy arrays are row (C)-ordered and most time series are + represented in the long format (with time on the 0-th axis). In this + case, no copying or re-ordering needs to be performed, instead the + array can simply be transposed to get it in the right order and shape. + + Although this class (Representation) has stringent `bind` requirements, + it is assumed that it will rarely be used directly. + """ + if not isinstance(endog, np.ndarray): + raise ValueError("Invalid endogenous array; must be an ndarray.") + + # Make sure we have a 2-dimensional array + # Note: reshaping a 1-dim array into a 2-dim array by changing the + # shape tuple always results in a row (C)-ordered array, so it + # must be shaped (nobs, k_endog) + if endog.ndim == 1: + # In the case of nobs x 0 arrays + if self.k_endog == 1: + endog = inplace_reshape(endog, (endog.shape[0], 1)) + # In the case of k_endog x 0 arrays + else: + endog = inplace_reshape(endog, (1, endog.shape[0])) + if not endog.ndim == 2: + raise ValueError( + "Invalid endogenous array provided; must be 2-dimensional." + ) + + # Check for valid column-ordered arrays + if endog.flags["F_CONTIGUOUS"] and endog.shape[0] == self.k_endog: + pass + # Check for valid row-ordered arrays, and transpose them to be the + # correct column-ordered array + elif endog.flags["C_CONTIGUOUS"] and endog.shape[1] == self.k_endog: + endog = endog.T + # Invalid column-ordered arrays + elif endog.flags["F_CONTIGUOUS"]: + raise ValueError( + "Invalid endogenous array; column-ordered" + " arrays must have first axis shape of" + " `k_endog`." + ) + # Invalid row-ordered arrays + elif endog.flags["C_CONTIGUOUS"]: + raise ValueError( + "Invalid endogenous array; row-ordered" + " arrays must have last axis shape of" + " `k_endog`." + ) + # Non-contiguous arrays + else: + raise ValueError( + "Invalid endogenous array; must be ordered in contiguous memory." + ) + + # We may still have a non-fortran contiguous array, so double-check + if not endog.flags["F_CONTIGUOUS"]: + endog = np.asfortranarray(endog) + + # Set a flag for complex data + self._complex_endog = np.iscomplexobj(endog) + + # Set the data + self.endog = endog + self.nobs = self.endog.shape[1] + + # Reset shapes + if hasattr(self, "shapes"): + self.shapes["obs"] = self.endog.shape + + def initialize( + self, + initialization, + approximate_diffuse_variance=None, + constant=None, + stationary_cov=None, + a=None, + Pstar=None, + Pinf=None, + A=None, + R0=None, + Q0=None, + ): + """ + Create an Initialization object if necessary + + Parameters + ---------- + initialization : str or Initialization + Initialization method for the initial state. If a string, must + be one of {'known', 'components', 'approximate_diffuse', + 'stationary', 'diffuse'}. Otherwise, may be an already-created + Initialization object, which is used directly. + approximate_diffuse_variance : float, optional + Initial variance used when `initialization='approximate_diffuse'` + is specified. Default is `self.initial_variance`. + constant : array_like, optional + Known mean of the initial state vector, used when + `initialization='known'`. + stationary_cov : array_like, optional + Known covariance matrix of the initial state vector, used when + `initialization='known'`. + a : array_like, optional + Vector of constant values describing the mean of the stationary + component of the initial state, used when + `initialization='components'`. + Pstar : array_like, optional + Stationary component of the initial state covariance matrix, + used when `initialization='components'`. + Pinf : array_like, optional + Diffuse component of the initial state covariance matrix, used + when `initialization='components'`. + A : array_like, optional + Diffuse selection matrix, used when `initialization='components'`. + R0 : array_like, optional + Stationary selection matrix, used when + `initialization='components'`. + Q0 : array_like, optional + Covariance matrix associated with stationary initial states, + used when `initialization='components'`. + """ + if initialization == "known": + initialization = Initialization( + self.k_states, "known", constant=constant, stationary_cov=stationary_cov + ) + elif initialization == "components": + initialization = Initialization.from_components( + self.k_states, a=a, Pstar=Pstar, Pinf=Pinf, A=A, R0=R0, Q0=Q0 + ) + elif initialization == "approximate_diffuse": + if approximate_diffuse_variance is None: + approximate_diffuse_variance = self.initial_variance + initialization = Initialization( + self.k_states, + "approximate_diffuse", + approximate_diffuse_variance=approximate_diffuse_variance, + ) + elif initialization == "stationary": + initialization = Initialization(self.k_states, "stationary") + elif initialization == "diffuse": + initialization = Initialization(self.k_states, "diffuse") + + # We must have an initialization object at this point + if not isinstance(initialization, Initialization): + raise ValueError("Invalid state space initialization method.") + + self.initialization = initialization + + def initialize_known(self, constant, stationary_cov): + """ + Initialize the statespace model with a known distribution for the + initial state + + These values are assumed to be known with certainty or else + filled with parameters during, for example, maximum likelihood + estimation. + + Parameters + ---------- + constant : array_like + Known mean of the initial state vector. + stationary_cov : array_like + Known covariance matrix of the initial state vector. + """ + constant = np.asarray(constant, order="F") + stationary_cov = np.asarray(stationary_cov, order="F") + + if not constant.shape == (self.k_states,): + raise ValueError( + "Invalid dimensions for constant state vector." + f" Requires shape ({self.k_states:d},), got {constant.shape!s}" + ) + if not stationary_cov.shape == (self.k_states, self.k_states): + raise ValueError( + "Invalid dimensions for stationary covariance" + f" matrix. Requires shape ({self.k_states:d},{self.k_states:d}), got {stationary_cov.shape!s}" + ) + + self.initialize("known", constant=constant, stationary_cov=stationary_cov) + + def initialize_approximate_diffuse(self, variance=None): + """ + Initialize the statespace model with approximate diffuse values + + Rather than following the exact diffuse treatment (which is developed + for the case that the variance becomes infinitely large), this assigns + an arbitrary large number for the variance. + + Parameters + ---------- + variance : float, optional + The variance for approximating diffuse initial conditions. Default + is `self.initial_variance`. + """ + if variance is None: + variance = self.initial_variance + + self.initialize("approximate_diffuse", approximate_diffuse_variance=variance) + + def initialize_components( + self, a=None, Pstar=None, Pinf=None, A=None, R0=None, Q0=None + ): + """ + Initialize the statespace model with component matrices + + Parameters + ---------- + a : array_like, optional + Vector of constant values describing the mean of the stationary + component of the initial state. + Pstar : array_like, optional + Stationary component of the initial state covariance matrix. If + given, should be a matrix shaped `k_states x k_states`. The + submatrix associated with the diffuse states should contain zeros. + Note that by definition, `Pstar = R0 @ Q0 @ R0.T`, so either + `R0,Q0` or `Pstar` may be given, but not both. + Pinf : array_like, optional + Diffuse component of the initial state covariance matrix. If given, + should be a matrix shaped `k_states x k_states` with ones in the + diagonal positions corresponding to states with diffuse + initialization and zeros otherwise. Note that by definition, + `Pinf = A @ A.T`, so either `A` or `Pinf` may be given, but not + both. + A : array_like, optional + Diffuse selection matrix, used in the definition of the diffuse + initial state covariance matrix. If given, should be a + `k_states x k_diffuse_states` matrix that contains the subset of + the columns of the identity matrix that correspond to states with + diffuse initialization. Note that by definition, `Pinf = A @ A.T`, + so either `A` or `Pinf` may be given, but not both. + R0 : array_like, optional + Stationary selection matrix, used in the definition of the + stationary initial state covariance matrix. If given, should be a + `k_states x k_nondiffuse_states` matrix that contains the subset of + the columns of the identity matrix that correspond to states with a + non-diffuse initialization. Note that by definition, + `Pstar = R0 @ Q0 @ R0.T`, so either `R0,Q0` or `Pstar` may be + given, but not both. + Q0 : array_like, optional + Covariance matrix associated with stationary initial states. If + given, should be a matrix shaped + `k_nondiffuse_states x k_nondiffuse_states`. + Note that by definition, `Pstar = R0 @ Q0 @ R0.T`, so either + `R0,Q0` or `Pstar` may be given, but not both. + + Notes + ----- + The matrices `a, Pstar, Pinf, A, R0, Q0` and the process for + initializing the state space model is as given in Chapter 5 of [1]_. + For the definitions of these matrices, see equation (5.2) and the + subsequent discussion there. + + References + ---------- + .. [1] Durbin, James, and Siem Jan Koopman. 2012. + Time Series Analysis by State Space Methods: Second Edition. + Oxford University Press. + """ + self.initialize("components", a=a, Pstar=Pstar, Pinf=Pinf, A=A, R0=R0, Q0=Q0) + + def initialize_stationary(self): + """Initialize the statespace model as stationary""" + self.initialize("stationary") + + def initialize_diffuse(self): + """Initialize the statespace model as diffuse""" + self.initialize("diffuse") + + def _initialize_representation(self, prefix=None): + if prefix is None: + prefix = self.prefix + dtype = tools.prefix_dtype_map[prefix] + + # If the dtype-specific representation matrices do not exist, create + # them + if prefix not in self._representations: + # Copy the statespace representation matrices + self._representations[prefix] = {} + for matrix in self.shapes: + if matrix == "obs": + self._representations[prefix][matrix] = self.obs.astype(dtype) + else: + # Note: this always makes a copy + self._representations[prefix][matrix] = getattr( + self, "_" + matrix + ).astype(dtype) + # If they do exist, update them + else: + for matrix in self.shapes: + existing = self._representations[prefix][matrix] + if matrix == "obs": + # existing[:] = self.obs.astype(dtype) + pass + else: + new = getattr(self, "_" + matrix).astype(dtype) + if existing.shape == new.shape: + existing[:] = new[:] + else: + self._representations[prefix][matrix] = new + + # Determine if we need to (re-)create the _statespace models + # (if time-varying matrices changed) + if prefix in self._statespaces: + ss = self._statespaces[prefix] + create = ( + ss.obs.shape[1] != self.endog.shape[1] + or ss.design.shape[2] != self.design.shape[2] + or ss.obs_intercept.shape[1] != self.obs_intercept.shape[1] + or ss.obs_cov.shape[2] != self.obs_cov.shape[2] + or ss.transition.shape[2] != self.transition.shape[2] + or ss.state_intercept.shape[1] != self.state_intercept.shape[1] + or ss.selection.shape[2] != self.selection.shape[2] + or ss.state_cov.shape[2] != self.state_cov.shape[2] + ) + else: + create = True + + # (re-)create if necessary + if create: + if prefix in self._statespaces: + del self._statespaces[prefix] + + # Setup the base statespace object + cls = self.prefix_statespace_map[prefix] + self._statespaces[prefix] = cls( + self._representations[prefix]["obs"], + self._representations[prefix]["design"], + self._representations[prefix]["obs_intercept"], + self._representations[prefix]["obs_cov"], + self._representations[prefix]["transition"], + self._representations[prefix]["state_intercept"], + self._representations[prefix]["selection"], + self._representations[prefix]["state_cov"], + ) + + return prefix, dtype, create + + def _initialize_state(self, prefix=None, complex_step=False): + # TODO once the transition to using the Initialization objects is + # complete, this should be moved entirely to the _{{prefix}}Statespace + # object. + if prefix is None: + prefix = self.prefix + + # (Re-)initialize the statespace model + if isinstance(self.initialization, Initialization): + if not self.initialization.initialized: + raise RuntimeError("Initialization is incomplete.") + self._statespaces[prefix].initialize( + self.initialization, complex_step=complex_step + ) + else: + raise RuntimeError("Statespace model not initialized.") + + +class FrozenRepresentation: + """ + Frozen Statespace Model + + Takes a snapshot of a Statespace model. + + Parameters + ---------- + model : Representation + A Statespace representation + + Attributes + ---------- + nobs : int + Number of observations. + k_endog : int + The dimension of the observation series. + k_states : int + The dimension of the unobserved state process. + k_posdef : int + The dimension of a guaranteed positive definite + covariance matrix describing the shocks in the + measurement equation. + dtype : dtype + Datatype of representation matrices + prefix : str + BLAS prefix of representation matrices + shapes : dict of str to tuple + A dictionary recording the shapes of each of + the representation matrices as tuples. + endog : ndarray + The observation vector. + design : ndarray + The design matrix, :math:`Z`. + obs_intercept : ndarray + The intercept for the observation equation, :math:`d`. + obs_cov : ndarray + The covariance matrix for the observation equation :math:`H`. + transition : ndarray + The transition matrix, :math:`T`. + state_intercept : ndarray + The intercept for the transition equation, :math:`c`. + selection : ndarray + The selection matrix, :math:`R`. + state_cov : ndarray + The covariance matrix for the state equation :math:`Q`. + missing : ndarray of bool + An array of the same size as `endog`, filled + with boolean values that are True if the + corresponding entry in `endog` is NaN and False + otherwise. + nmissing : ndarray of int + An array of size `nobs`, where the ith entry + is the number (between 0 and `k_endog`) of NaNs in + the ith row of the `endog` array. + time_invariant : bool + Whether or not the representation matrices are time-invariant + initialization : Initialization + Kalman filter initialization method. + initial_state : ndarray + The state vector used to initialize the Kalman filter. + initial_state_cov : ndarray + The state covariance matrix used to initialize the Kalman filter. + initial_diffuse_state_cov : ndarray + The diffuse part of the state covariance matrix used to initialize + the Kalman filter. + initial_variance : float + Initial variance used for approximate diffuse initialization. + model : Representation + The Statespace representation model from which this snapshot was + taken. + """ + + _model_attributes = [ + "model", + "prefix", + "dtype", + "nobs", + "k_endog", + "k_states", + "k_posdef", + "time_invariant", + "endog", + "design", + "obs_intercept", + "obs_cov", + "transition", + "state_intercept", + "selection", + "state_cov", + "missing", + "nmissing", + "shapes", + "initialization", + "initial_state", + "initial_state_cov", + "initial_variance", + ] + _attributes = _model_attributes + + def __init__(self, model): + # Initialize all attributes to None + for name in self._attributes: + setattr(self, name, None) + + # Update the representation attributes + self.update_representation(model) + + def update_representation(self, model): + """ + Update the snapshot to reflect the current state of the model + + Parameters + ---------- + model : Representation + A Statespace representation + """ + # Model + self.model = model + + # Data type + self.prefix = model.prefix + self.dtype = model.dtype + + # Copy the model dimensions + self.nobs = model.nobs + self.k_endog = model.k_endog + self.k_states = model.k_states + self.k_posdef = model.k_posdef + self.time_invariant = model.time_invariant + + # Save the state space representation at the time + self.endog = model.endog + self.design = model._design.copy() + self.obs_intercept = model._obs_intercept.copy() + self.obs_cov = model._obs_cov.copy() + self.transition = model._transition.copy() + self.state_intercept = model._state_intercept.copy() + self.selection = model._selection.copy() + self.state_cov = model._state_cov.copy() + + self.missing = np.array(model._statespaces[self.prefix].missing, copy=True) + self.nmissing = np.array(model._statespaces[self.prefix].nmissing, copy=True) + + # Save the final shapes of the matrices + self.shapes = dict(model.shapes) + for name in self.shapes: + if name == "obs": + continue + self.shapes[name] = getattr(self, name).shape + self.shapes["obs"] = self.endog.shape + + # Save the state space initialization + self.initialization = model.initialization + + if model.initialization is not None: + model._initialize_state() + self.initial_state = np.array( + model._statespaces[self.prefix].initial_state, copy=True + ) + self.initial_state_cov = np.array( + model._statespaces[self.prefix].initial_state_cov, copy=True + ) + self.initial_diffuse_state_cov = np.array( + model._statespaces[self.prefix].initial_diffuse_state_cov, copy=True + ) diff --git a/shared/package-files/73/738c5027f6c14b8c6b323de97f1d4cb37a02dbf2f0b89b8d617359c6cf9c546f/test_hyperbolic_space.py b/shared/package-files/73/738c5027f6c14b8c6b323de97f1d4cb37a02dbf2f0b89b8d617359c6cf9c546f/test_hyperbolic_space.py new file mode 100644 index 0000000000000000000000000000000000000000..48ddc7f8065f2b69bcd8eca4726a21c5901514ec --- /dev/null +++ b/shared/package-files/73/738c5027f6c14b8c6b323de97f1d4cb37a02dbf2f0b89b8d617359c6cf9c546f/test_hyperbolic_space.py @@ -0,0 +1,91 @@ +r''' +unit test describing the hyperbolic half-plane with the Poincare metric. This +is a basic model of hyperbolic geometry on the (positive) half-space + +{(x,y) \in R^2 | y > 0} + +with the Riemannian metric + +ds^2 = (dx^2 + dy^2)/y^2 + +It has constant negative scalar curvature = -2 + +https://en.wikipedia.org/wiki/Poincare_half-plane_model +''' +from sympy.matrices.dense import diag +from sympy.diffgeom import (twoform_to_matrix, + metric_to_Christoffel_1st, metric_to_Christoffel_2nd, + metric_to_Riemann_components, metric_to_Ricci_components) +import sympy.diffgeom.rn +from sympy.tensor.array import ImmutableDenseNDimArray + + +def test_H2(): + TP = sympy.diffgeom.TensorProduct + R2 = sympy.diffgeom.rn.R2 + y = R2.y + dy = R2.dy + dx = R2.dx + g = (TP(dx, dx) + TP(dy, dy))*y**(-2) + automat = twoform_to_matrix(g) + mat = diag(y**(-2), y**(-2)) + assert mat == automat + + gamma1 = metric_to_Christoffel_1st(g) + assert gamma1[0, 0, 0] == 0 + assert gamma1[0, 0, 1] == -y**(-3) + assert gamma1[0, 1, 0] == -y**(-3) + assert gamma1[0, 1, 1] == 0 + + assert gamma1[1, 1, 1] == -y**(-3) + assert gamma1[1, 1, 0] == 0 + assert gamma1[1, 0, 1] == 0 + assert gamma1[1, 0, 0] == y**(-3) + + gamma2 = metric_to_Christoffel_2nd(g) + assert gamma2[0, 0, 0] == 0 + assert gamma2[0, 0, 1] == -y**(-1) + assert gamma2[0, 1, 0] == -y**(-1) + assert gamma2[0, 1, 1] == 0 + + assert gamma2[1, 1, 1] == -y**(-1) + assert gamma2[1, 1, 0] == 0 + assert gamma2[1, 0, 1] == 0 + assert gamma2[1, 0, 0] == y**(-1) + + Rm = metric_to_Riemann_components(g) + assert Rm[0, 0, 0, 0] == 0 + assert Rm[0, 0, 0, 1] == 0 + assert Rm[0, 0, 1, 0] == 0 + assert Rm[0, 0, 1, 1] == 0 + + assert Rm[0, 1, 0, 0] == 0 + assert Rm[0, 1, 0, 1] == -y**(-2) + assert Rm[0, 1, 1, 0] == y**(-2) + assert Rm[0, 1, 1, 1] == 0 + + assert Rm[1, 0, 0, 0] == 0 + assert Rm[1, 0, 0, 1] == y**(-2) + assert Rm[1, 0, 1, 0] == -y**(-2) + assert Rm[1, 0, 1, 1] == 0 + + assert Rm[1, 1, 0, 0] == 0 + assert Rm[1, 1, 0, 1] == 0 + assert Rm[1, 1, 1, 0] == 0 + assert Rm[1, 1, 1, 1] == 0 + + Ric = metric_to_Ricci_components(g) + assert Ric[0, 0] == -y**(-2) + assert Ric[0, 1] == 0 + assert Ric[1, 0] == 0 + assert Ric[0, 0] == -y**(-2) + + assert Ric == ImmutableDenseNDimArray([-y**(-2), 0, 0, -y**(-2)], (2, 2)) + + ## scalar curvature is -2 + #TODO - it would be nice to have index contraction built-in + R = (Ric[0, 0] + Ric[1, 1])*y**2 + assert R == -2 + + ## Gauss curvature is -1 + assert R/2 == -1 diff --git a/shared/package-files/73/738e7488503a141150a737687aed97f8d89d07365accda57f37e95d1e3f94226/upsample_trilinear3d_backward.h b/shared/package-files/73/738e7488503a141150a737687aed97f8d89d07365accda57f37e95d1e3f94226/upsample_trilinear3d_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..9857a527871c27b90366d30f9857dd061dc2fa8d --- /dev/null +++ b/shared/package-files/73/738e7488503a141150a737687aed97f8d89d07365accda57f37e95d1e3f94226/upsample_trilinear3d_backward.h @@ -0,0 +1,91 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::upsample_trilinear3d_backward.grad_input(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & upsample_trilinear3d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_d=c10::nullopt, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_trilinear3d_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_d, scales_h, scales_w, grad_input); +} +namespace symint { + template ::value>> + at::Tensor & upsample_trilinear3d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_d=c10::nullopt, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_trilinear3d_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_d, scales_h, scales_w, grad_input); + } +} + +// aten::upsample_trilinear3d_backward.grad_input(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & upsample_trilinear3d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_d, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input) { + return at::_ops::upsample_trilinear3d_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_d, scales_h, scales_w, grad_input); +} +namespace symint { + template ::value>> + at::Tensor & upsample_trilinear3d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_d, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input) { + return at::_ops::upsample_trilinear3d_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_d, scales_h, scales_w, grad_input); + } +} + +// aten::upsample_trilinear3d_backward.grad_input(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & upsample_trilinear3d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_d=c10::nullopt, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_trilinear3d_backward_grad_input::call(grad_output, output_size, input_size, align_corners, scales_d, scales_h, scales_w, grad_input); +} +namespace symint { + template ::value>> + at::Tensor & upsample_trilinear3d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_d=c10::nullopt, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_trilinear3d_backward_grad_input::call(grad_output, output_size, input_size, align_corners, scales_d, scales_h, scales_w, grad_input); + } +} + +// aten::upsample_trilinear3d_backward.grad_input(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & upsample_trilinear3d_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_d, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input) { + return at::_ops::upsample_trilinear3d_backward_grad_input::call(grad_output, output_size, input_size, align_corners, scales_d, scales_h, scales_w, grad_input); +} +namespace symint { + template ::value>> + at::Tensor & upsample_trilinear3d_backward_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_d, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input) { + return at::_ops::upsample_trilinear3d_backward_grad_input::call(grad_output, output_size, input_size, align_corners, scales_d, scales_h, scales_w, grad_input); + } +} + +// aten::upsample_trilinear3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor +inline at::Tensor upsample_trilinear3d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_d=c10::nullopt, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_trilinear3d_backward::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_d, scales_h, scales_w); +} +namespace symint { + template ::value>> + at::Tensor upsample_trilinear3d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_d=c10::nullopt, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_trilinear3d_backward::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_d, scales_h, scales_w); + } +} + +// aten::upsample_trilinear3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor +inline at::Tensor upsample_trilinear3d_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_d=c10::nullopt, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_trilinear3d_backward::call(grad_output, output_size, input_size, align_corners, scales_d, scales_h, scales_w); +} +namespace symint { + template ::value>> + at::Tensor upsample_trilinear3d_backward(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_d=c10::nullopt, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_trilinear3d_backward::call(grad_output, output_size, input_size, align_corners, scales_d, scales_h, scales_w); + } +} + +} diff --git a/shared/package-files/73/739469060632e45e8293e45db11c426088a76696432a327201d27d46ca9e3bcb/_regression.py b/shared/package-files/73/739469060632e45e8293e45db11c426088a76696432a327201d27d46ca9e3bcb/_regression.py new file mode 100644 index 0000000000000000000000000000000000000000..0731e00ce3a1ab24adb2e33ed17ac948455586e8 --- /dev/null +++ b/shared/package-files/73/739469060632e45e8293e45db11c426088a76696432a327201d27d46ca9e3bcb/_regression.py @@ -0,0 +1,1930 @@ +"""Metrics to assess performance on regression task. + +Functions named as ``*_score`` return a scalar value to maximize: the higher +the better. + +Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize: +the lower the better. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Real + +import numpy as np + +from ..exceptions import UndefinedMetricWarning +from ..utils._array_api import ( + _average, + _find_matching_floating_dtype, + get_namespace, + get_namespace_and_device, + size, +) +from ..utils._array_api import ( + _xlogy as xlogy, +) +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.stats import _weighted_percentile +from ..utils.validation import ( + _check_sample_weight, + _num_samples, + check_array, + check_consistent_length, + column_or_1d, +) + +__ALL__ = [ + "max_error", + "mean_absolute_error", + "mean_squared_error", + "mean_squared_log_error", + "median_absolute_error", + "mean_absolute_percentage_error", + "mean_pinball_loss", + "r2_score", + "root_mean_squared_log_error", + "root_mean_squared_error", + "explained_variance_score", + "mean_tweedie_deviance", + "mean_poisson_deviance", + "mean_gamma_deviance", + "d2_tweedie_score", + "d2_pinball_score", + "d2_absolute_error_score", +] + + +def _check_reg_targets( + y_true, y_pred, sample_weight, multioutput, dtype="numeric", xp=None +): + """Check that y_true, y_pred and sample_weight belong to the same regression task. + + To reduce redundancy when calling `_find_matching_floating_dtype`, + please use `_check_reg_targets_with_floating_dtype` instead. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,) or None + Sample weights. + + multioutput : array-like or string in ['raw_values', uniform_average', + 'variance_weighted'] or None + None is accepted due to backward compatibility of r2_score(). + + dtype : str or list, default="numeric" + the dtype argument passed to check_array. + + xp : module, default=None + Precomputed array namespace module. When passed, typically from a caller + that has already performed inspection of its own inputs, skips array + namespace inspection. + + Returns + ------- + type_true : one of {'continuous', continuous-multioutput'} + The type of the true target data, as output by + 'utils.multiclass.type_of_target'. + + y_true : array-like of shape (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,) or None + Sample weights. + + multioutput : array-like of shape (n_outputs) or string in ['raw_values', + uniform_average', 'variance_weighted'] or None + Custom output weights if ``multioutput`` is array-like or + just the corresponding argument if ``multioutput`` is a + correct keyword. + """ + xp, _ = get_namespace(y_true, y_pred, multioutput, xp=xp) + + check_consistent_length(y_true, y_pred, sample_weight) + y_true = check_array(y_true, ensure_2d=False, dtype=dtype) + y_pred = check_array(y_pred, ensure_2d=False, dtype=dtype) + if sample_weight is not None: + sample_weight = _check_sample_weight(sample_weight, y_true, dtype=dtype) + + if y_true.ndim == 1: + y_true = xp.reshape(y_true, (-1, 1)) + + if y_pred.ndim == 1: + y_pred = xp.reshape(y_pred, (-1, 1)) + + if y_true.shape[1] != y_pred.shape[1]: + raise ValueError( + "y_true and y_pred have different number of output ({0}!={1})".format( + y_true.shape[1], y_pred.shape[1] + ) + ) + + n_outputs = y_true.shape[1] + allowed_multioutput_str = ("raw_values", "uniform_average", "variance_weighted") + if isinstance(multioutput, str): + if multioutput not in allowed_multioutput_str: + raise ValueError( + "Allowed 'multioutput' string values are {}. " + "You provided multioutput={!r}".format( + allowed_multioutput_str, multioutput + ) + ) + elif multioutput is not None: + multioutput = check_array(multioutput, ensure_2d=False) + if n_outputs == 1: + raise ValueError("Custom weights are useful only in multi-output cases.") + elif n_outputs != multioutput.shape[0]: + raise ValueError( + "There must be equally many custom weights " + f"({multioutput.shape[0]}) as outputs ({n_outputs})." + ) + y_type = "continuous" if n_outputs == 1 else "continuous-multioutput" + + return y_type, y_true, y_pred, sample_weight, multioutput + + +def _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=None +): + """Ensures y_true, y_pred, and sample_weight correspond to same regression task. + + Extends `_check_reg_targets` by automatically selecting a suitable floating-point + data type for inputs using `_find_matching_floating_dtype`. + + Use this private method only when converting inputs to array API-compatibles. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,) + + multioutput : array-like or string in ['raw_values', 'uniform_average', \ + 'variance_weighted'] or None + None is accepted due to backward compatibility of r2_score(). + + xp : module, default=None + Precomputed array namespace module. When passed, typically from a caller + that has already performed inspection of its own inputs, skips array + namespace inspection. + + Returns + ------- + type_true : one of {'continuous', 'continuous-multioutput'} + The type of the true target data, as output by + 'utils.multiclass.type_of_target'. + + y_true : array-like of shape (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : array-like of shape (n_outputs) or string in ['raw_values', \ + 'uniform_average', 'variance_weighted'] or None + Custom output weights if ``multioutput`` is array-like or + just the corresponding argument if ``multioutput`` is a + correct keyword. + """ + dtype_name = _find_matching_floating_dtype(y_true, y_pred, sample_weight, xp=xp) + + y_type, y_true, y_pred, sample_weight, multioutput = _check_reg_targets( + y_true, y_pred, sample_weight, multioutput, dtype=dtype_name, xp=xp + ) + + return y_type, y_true, y_pred, sample_weight, multioutput + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [StrOptions({"raw_values", "uniform_average"}), "array-like"], + }, + prefer_skip_nested_validation=True, +) +def mean_absolute_error( + y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" +): + """Mean absolute error regression loss. + + The mean absolute error is a non-negative floating point value, where best value + is 0.0. Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or array of floats + If multioutput is 'raw_values', then mean absolute error is returned + for each output separately. + If multioutput is 'uniform_average' or an ndarray of weights, then the + weighted average of all output errors is returned. + + MAE output is non-negative floating point. The best value is 0.0. + + Examples + -------- + >>> from sklearn.metrics import mean_absolute_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> mean_absolute_error(y_true, y_pred) + 0.5 + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> mean_absolute_error(y_true, y_pred) + 0.75 + >>> mean_absolute_error(y_true, y_pred, multioutput='raw_values') + array([0.5, 1. ]) + >>> mean_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7]) + 0.85... + """ + xp, _ = get_namespace(y_true, y_pred, sample_weight, multioutput) + + _, y_true, y_pred, sample_weight, multioutput = ( + _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=xp + ) + ) + + output_errors = _average( + xp.abs(y_pred - y_true), weights=sample_weight, axis=0, xp=xp + ) + if isinstance(multioutput, str): + if multioutput == "raw_values": + return output_errors + elif multioutput == "uniform_average": + # pass None as weights to _average: uniform mean + multioutput = None + + # Average across the outputs (if needed). + # The second call to `_average` should always return + # a scalar array that we convert to a Python float to + # consistently return the same eager evaluated value. + # Therefore, `axis=None`. + mean_absolute_error = _average(output_errors, weights=multioutput) + + return float(mean_absolute_error) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "alpha": [Interval(Real, 0, 1, closed="both")], + "multioutput": [StrOptions({"raw_values", "uniform_average"}), "array-like"], + }, + prefer_skip_nested_validation=True, +) +def mean_pinball_loss( + y_true, y_pred, *, sample_weight=None, alpha=0.5, multioutput="uniform_average" +): + """Pinball loss for quantile regression. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + alpha : float, slope of the pinball loss, default=0.5, + This loss is equivalent to :ref:`mean_absolute_error` when `alpha=0.5`, + `alpha=0.95` is minimized by estimators of the 95th percentile. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or ndarray of floats + If multioutput is 'raw_values', then mean absolute error is returned + for each output separately. + If multioutput is 'uniform_average' or an ndarray of weights, then the + weighted average of all output errors is returned. + + The pinball loss output is a non-negative floating point. The best + value is 0.0. + + Examples + -------- + >>> from sklearn.metrics import mean_pinball_loss + >>> y_true = [1, 2, 3] + >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.1) + 0.03... + >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.1) + 0.3... + >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.9) + 0.3... + >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.9) + 0.03... + >>> mean_pinball_loss(y_true, y_true, alpha=0.1) + 0.0 + >>> mean_pinball_loss(y_true, y_true, alpha=0.9) + 0.0 + """ + xp, _ = get_namespace(y_true, y_pred, sample_weight, multioutput) + + _, y_true, y_pred, sample_weight, multioutput = ( + _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=xp + ) + ) + + diff = y_true - y_pred + sign = xp.astype(diff >= 0, diff.dtype) + loss = alpha * sign * diff - (1 - alpha) * (1 - sign) * diff + output_errors = _average(loss, weights=sample_weight, axis=0) + + if isinstance(multioutput, str) and multioutput == "raw_values": + return output_errors + + if isinstance(multioutput, str) and multioutput == "uniform_average": + # pass None as weights to _average: uniform mean + multioutput = None + + # Average across the outputs (if needed). + # The second call to `_average` should always return + # a scalar array that we convert to a Python float to + # consistently return the same eager evaluated value. + # Therefore, `axis=None`. + return float(_average(output_errors, weights=multioutput)) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [StrOptions({"raw_values", "uniform_average"}), "array-like"], + }, + prefer_skip_nested_validation=True, +) +def mean_absolute_percentage_error( + y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" +): + """Mean absolute percentage error (MAPE) regression loss. + + Note that we are not using the common "percentage" definition: the percentage + in the range [0, 100] is converted to a relative value in the range [0, 1] + by dividing by 100. Thus, an error of 200% corresponds to a relative error of 2. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.24 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + If input is list then the shape must be (n_outputs,). + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or ndarray of floats + If multioutput is 'raw_values', then mean absolute percentage error + is returned for each output separately. + If multioutput is 'uniform_average' or an ndarray of weights, then the + weighted average of all output errors is returned. + + MAPE output is non-negative floating point. The best value is 0.0. + But note that bad predictions can lead to arbitrarily large + MAPE values, especially if some `y_true` values are very close to zero. + Note that we return a large value instead of `inf` when `y_true` is zero. + + Examples + -------- + >>> from sklearn.metrics import mean_absolute_percentage_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> mean_absolute_percentage_error(y_true, y_pred) + 0.3273... + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> mean_absolute_percentage_error(y_true, y_pred) + 0.5515... + >>> mean_absolute_percentage_error(y_true, y_pred, multioutput=[0.3, 0.7]) + 0.6198... + >>> # the value when some element of the y_true is zero is arbitrarily high because + >>> # of the division by epsilon + >>> y_true = [1., 0., 2.4, 7.] + >>> y_pred = [1.2, 0.1, 2.4, 8.] + >>> mean_absolute_percentage_error(y_true, y_pred) + 112589990684262.48 + """ + xp, _, device_ = get_namespace_and_device( + y_true, y_pred, sample_weight, multioutput + ) + _, y_true, y_pred, sample_weight, multioutput = ( + _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=xp + ) + ) + epsilon = xp.asarray(xp.finfo(xp.float64).eps, dtype=y_true.dtype, device=device_) + y_true_abs = xp.abs(y_true) + mape = xp.abs(y_pred - y_true) / xp.maximum(y_true_abs, epsilon) + output_errors = _average(mape, weights=sample_weight, axis=0) + if isinstance(multioutput, str): + if multioutput == "raw_values": + return output_errors + elif multioutput == "uniform_average": + # pass None as weights to _average: uniform mean + multioutput = None + + # Average across the outputs (if needed). + # The second call to `_average` should always return + # a scalar array that we convert to a Python float to + # consistently return the same eager evaluated value. + # Therefore, `axis=None`. + mean_absolute_percentage_error = _average(output_errors, weights=multioutput) + + return float(mean_absolute_percentage_error) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [StrOptions({"raw_values", "uniform_average"}), "array-like"], + }, + prefer_skip_nested_validation=True, +) +def mean_squared_error( + y_true, + y_pred, + *, + sample_weight=None, + multioutput="uniform_average", +): + """Mean squared error regression loss. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or array of floats + A non-negative floating point value (the best value is 0.0), or an + array of floating point values, one for each individual target. + + Examples + -------- + >>> from sklearn.metrics import mean_squared_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> mean_squared_error(y_true, y_pred) + 0.375 + >>> y_true = [[0.5, 1],[-1, 1],[7, -6]] + >>> y_pred = [[0, 2],[-1, 2],[8, -5]] + >>> mean_squared_error(y_true, y_pred) + 0.708... + >>> mean_squared_error(y_true, y_pred, multioutput='raw_values') + array([0.41666667, 1. ]) + >>> mean_squared_error(y_true, y_pred, multioutput=[0.3, 0.7]) + 0.825... + """ + xp, _ = get_namespace(y_true, y_pred, sample_weight, multioutput) + _, y_true, y_pred, sample_weight, multioutput = ( + _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=xp + ) + ) + output_errors = _average((y_true - y_pred) ** 2, axis=0, weights=sample_weight) + + if isinstance(multioutput, str): + if multioutput == "raw_values": + return output_errors + elif multioutput == "uniform_average": + # pass None as weights to _average: uniform mean + multioutput = None + + # Average across the outputs (if needed). + # The second call to `_average` should always return + # a scalar array that we convert to a Python float to + # consistently return the same eager evaluated value. + # Therefore, `axis=None`. + mean_squared_error = _average(output_errors, weights=multioutput) + + return float(mean_squared_error) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [StrOptions({"raw_values", "uniform_average"}), "array-like"], + }, + prefer_skip_nested_validation=True, +) +def root_mean_squared_error( + y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" +): + """Root mean squared error regression loss. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.4 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or ndarray of floats + A non-negative floating point value (the best value is 0.0), or an + array of floating point values, one for each individual target. + + Examples + -------- + >>> from sklearn.metrics import root_mean_squared_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> root_mean_squared_error(y_true, y_pred) + 0.612... + >>> y_true = [[0.5, 1],[-1, 1],[7, -6]] + >>> y_pred = [[0, 2],[-1, 2],[8, -5]] + >>> root_mean_squared_error(y_true, y_pred) + 0.822... + """ + + xp, _ = get_namespace(y_true, y_pred, sample_weight, multioutput) + + output_errors = xp.sqrt( + mean_squared_error( + y_true, y_pred, sample_weight=sample_weight, multioutput="raw_values" + ) + ) + + if isinstance(multioutput, str): + if multioutput == "raw_values": + return output_errors + elif multioutput == "uniform_average": + # pass None as weights to _average: uniform mean + multioutput = None + + # Average across the outputs (if needed). + # The second call to `_average` should always return + # a scalar array that we convert to a Python float to + # consistently return the same eager evaluated value. + # Therefore, `axis=None`. + root_mean_squared_error = _average(output_errors, weights=multioutput) + + return float(root_mean_squared_error) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [StrOptions({"raw_values", "uniform_average"}), "array-like"], + }, + prefer_skip_nested_validation=True, +) +def mean_squared_log_error( + y_true, + y_pred, + *, + sample_weight=None, + multioutput="uniform_average", +): + """Mean squared logarithmic error regression loss. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors when the input is of multioutput + format. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or ndarray of floats + A non-negative floating point value (the best value is 0.0), or an + array of floating point values, one for each individual target. + + Examples + -------- + >>> from sklearn.metrics import mean_squared_log_error + >>> y_true = [3, 5, 2.5, 7] + >>> y_pred = [2.5, 5, 4, 8] + >>> mean_squared_log_error(y_true, y_pred) + 0.039... + >>> y_true = [[0.5, 1], [1, 2], [7, 6]] + >>> y_pred = [[0.5, 2], [1, 2.5], [8, 8]] + >>> mean_squared_log_error(y_true, y_pred) + 0.044... + >>> mean_squared_log_error(y_true, y_pred, multioutput='raw_values') + array([0.00462428, 0.08377444]) + >>> mean_squared_log_error(y_true, y_pred, multioutput=[0.3, 0.7]) + 0.060... + """ + xp, _ = get_namespace(y_true, y_pred) + + _, y_true, y_pred, sample_weight, multioutput = ( + _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=xp + ) + ) + + if xp.any(y_true <= -1) or xp.any(y_pred <= -1): + raise ValueError( + "Mean Squared Logarithmic Error cannot be used when " + "targets contain values less than or equal to -1." + ) + + return mean_squared_error( + xp.log1p(y_true), + xp.log1p(y_pred), + sample_weight=sample_weight, + multioutput=multioutput, + ) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [StrOptions({"raw_values", "uniform_average"}), "array-like"], + }, + prefer_skip_nested_validation=True, +) +def root_mean_squared_log_error( + y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" +): + """Root mean squared logarithmic error regression loss. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.4 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors when the input is of multioutput + format. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or ndarray of floats + A non-negative floating point value (the best value is 0.0), or an + array of floating point values, one for each individual target. + + Examples + -------- + >>> from sklearn.metrics import root_mean_squared_log_error + >>> y_true = [3, 5, 2.5, 7] + >>> y_pred = [2.5, 5, 4, 8] + >>> root_mean_squared_log_error(y_true, y_pred) + 0.199... + """ + xp, _ = get_namespace(y_true, y_pred) + + _, y_true, y_pred, sample_weight, multioutput = ( + _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=xp + ) + ) + + if xp.any(y_true <= -1) or xp.any(y_pred <= -1): + raise ValueError( + "Root Mean Squared Logarithmic Error cannot be used when " + "targets contain values less than or equal to -1." + ) + + return root_mean_squared_error( + xp.log1p(y_true), + xp.log1p(y_pred), + sample_weight=sample_weight, + multioutput=multioutput, + ) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "multioutput": [StrOptions({"raw_values", "uniform_average"}), "array-like"], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def median_absolute_error( + y_true, y_pred, *, multioutput="uniform_average", sample_weight=None +): + """Median absolute error regression loss. + + Median absolute error output is non-negative floating point. The best value + is 0.0. Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. Array-like value defines + weights used to average errors. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + .. versionadded:: 0.24 + + Returns + ------- + loss : float or ndarray of floats + If multioutput is 'raw_values', then mean absolute error is returned + for each output separately. + If multioutput is 'uniform_average' or an ndarray of weights, then the + weighted average of all output errors is returned. + + Examples + -------- + >>> from sklearn.metrics import median_absolute_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> median_absolute_error(y_true, y_pred) + 0.5 + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> median_absolute_error(y_true, y_pred) + 0.75 + >>> median_absolute_error(y_true, y_pred, multioutput='raw_values') + array([0.5, 1. ]) + >>> median_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7]) + 0.85 + """ + _, y_true, y_pred, sample_weight, multioutput = _check_reg_targets( + y_true, y_pred, sample_weight, multioutput + ) + if sample_weight is None: + output_errors = np.median(np.abs(y_pred - y_true), axis=0) + else: + output_errors = _weighted_percentile( + np.abs(y_pred - y_true), sample_weight=sample_weight + ) + if isinstance(multioutput, str): + if multioutput == "raw_values": + return output_errors + elif multioutput == "uniform_average": + # pass None as weights to np.average: uniform mean + multioutput = None + + return float(np.average(output_errors, weights=multioutput)) + + +def _assemble_r2_explained_variance( + numerator, denominator, n_outputs, multioutput, force_finite, xp, device +): + """Common part used by explained variance score and :math:`R^2` score.""" + dtype = numerator.dtype + + nonzero_denominator = denominator != 0 + + if not force_finite: + # Standard formula, that may lead to NaN or -Inf + output_scores = 1 - (numerator / denominator) + else: + nonzero_numerator = numerator != 0 + # Default = Zero Numerator = perfect predictions. Set to 1.0 + # (note: even if denominator is zero, thus avoiding NaN scores) + output_scores = xp.ones([n_outputs], device=device, dtype=dtype) + # Non-zero Numerator and Non-zero Denominator: use the formula + valid_score = nonzero_denominator & nonzero_numerator + + output_scores[valid_score] = 1 - ( + numerator[valid_score] / denominator[valid_score] + ) + + # Non-zero Numerator and Zero Denominator: + # arbitrary set to 0.0 to avoid -inf scores + output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0 + + if isinstance(multioutput, str): + if multioutput == "raw_values": + # return scores individually + return output_scores + elif multioutput == "uniform_average": + # pass None as weights to _average: uniform mean + avg_weights = None + elif multioutput == "variance_weighted": + avg_weights = denominator + if not xp.any(nonzero_denominator): + # All weights are zero, _average would raise a ZeroDiv error. + # This only happens when all y are constant (or 1-element long) + # Since weights are all equal, fall back to uniform weights. + avg_weights = None + else: + avg_weights = multioutput + + result = _average(output_scores, weights=avg_weights) + if size(result) == 1: + return float(result) + return result + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [ + StrOptions({"raw_values", "uniform_average", "variance_weighted"}), + "array-like", + ], + "force_finite": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def explained_variance_score( + y_true, + y_pred, + *, + sample_weight=None, + multioutput="uniform_average", + force_finite=True, +): + """Explained variance regression score function. + + Best possible score is 1.0, lower values are worse. + + In the particular case when ``y_true`` is constant, the explained variance + score is not finite: it is either ``NaN`` (perfect predictions) or + ``-Inf`` (imperfect predictions). To prevent such non-finite numbers to + pollute higher-level experiments such as a grid search cross-validation, + by default these cases are replaced with 1.0 (perfect predictions) or 0.0 + (imperfect predictions) respectively. If ``force_finite`` + is set to ``False``, this score falls back on the original :math:`R^2` + definition. + + .. note:: + The Explained Variance score is similar to the + :func:`R^2 score `, with the notable difference that it + does not account for systematic offsets in the prediction. Most often + the :func:`R^2 score ` should be preferred. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average', 'variance_weighted'} or \ + array-like of shape (n_outputs,), default='uniform_average' + Defines aggregating of multiple output scores. + Array-like value defines weights used to average scores. + + 'raw_values' : + Returns a full set of scores in case of multioutput input. + + 'uniform_average' : + Scores of all outputs are averaged with uniform weight. + + 'variance_weighted' : + Scores of all outputs are averaged, weighted by the variances + of each individual output. + + force_finite : bool, default=True + Flag indicating if ``NaN`` and ``-Inf`` scores resulting from constant + data should be replaced with real numbers (``1.0`` if prediction is + perfect, ``0.0`` otherwise). Default is ``True``, a convenient setting + for hyperparameters' search procedures (e.g. grid search + cross-validation). + + .. versionadded:: 1.1 + + Returns + ------- + score : float or ndarray of floats + The explained variance or ndarray if 'multioutput' is 'raw_values'. + + See Also + -------- + r2_score : + Similar metric, but accounting for systematic offsets in + prediction. + + Notes + ----- + This is not a symmetric function. + + Examples + -------- + >>> from sklearn.metrics import explained_variance_score + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> explained_variance_score(y_true, y_pred) + 0.957... + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> explained_variance_score(y_true, y_pred, multioutput='uniform_average') + 0.983... + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2] + >>> explained_variance_score(y_true, y_pred) + 1.0 + >>> explained_variance_score(y_true, y_pred, force_finite=False) + nan + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2 + 1e-8] + >>> explained_variance_score(y_true, y_pred) + 0.0 + >>> explained_variance_score(y_true, y_pred, force_finite=False) + -inf + """ + xp, _, device = get_namespace_and_device(y_true, y_pred, sample_weight, multioutput) + + _, y_true, y_pred, sample_weight, multioutput = ( + _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=xp + ) + ) + + y_diff_avg = _average(y_true - y_pred, weights=sample_weight, axis=0) + numerator = _average( + (y_true - y_pred - y_diff_avg) ** 2, weights=sample_weight, axis=0 + ) + + y_true_avg = _average(y_true, weights=sample_weight, axis=0) + denominator = _average((y_true - y_true_avg) ** 2, weights=sample_weight, axis=0) + + return _assemble_r2_explained_variance( + numerator=numerator, + denominator=denominator, + n_outputs=y_true.shape[1], + multioutput=multioutput, + force_finite=force_finite, + xp=xp, + device=device, + ) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [ + StrOptions({"raw_values", "uniform_average", "variance_weighted"}), + "array-like", + None, + ], + "force_finite": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def r2_score( + y_true, + y_pred, + *, + sample_weight=None, + multioutput="uniform_average", + force_finite=True, +): + """:math:`R^2` (coefficient of determination) regression score function. + + Best possible score is 1.0 and it can be negative (because the + model can be arbitrarily worse). In the general case when the true y is + non-constant, a constant model that always predicts the average y + disregarding the input features would get a :math:`R^2` score of 0.0. + + In the particular case when ``y_true`` is constant, the :math:`R^2` score + is not finite: it is either ``NaN`` (perfect predictions) or ``-Inf`` + (imperfect predictions). To prevent such non-finite numbers to pollute + higher-level experiments such as a grid search cross-validation, by default + these cases are replaced with 1.0 (perfect predictions) or 0.0 (imperfect + predictions) respectively. You can set ``force_finite`` to ``False`` to + prevent this fix from happening. + + Note: when the prediction residuals have zero mean, the :math:`R^2` score + is identical to the + :func:`Explained Variance score `. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average', 'variance_weighted'}, \ + array-like of shape (n_outputs,) or None, default='uniform_average' + + Defines aggregating of multiple output scores. + Array-like value defines weights used to average scores. + Default is "uniform_average". + + 'raw_values' : + Returns a full set of scores in case of multioutput input. + + 'uniform_average' : + Scores of all outputs are averaged with uniform weight. + + 'variance_weighted' : + Scores of all outputs are averaged, weighted by the variances + of each individual output. + + .. versionchanged:: 0.19 + Default value of multioutput is 'uniform_average'. + + force_finite : bool, default=True + Flag indicating if ``NaN`` and ``-Inf`` scores resulting from constant + data should be replaced with real numbers (``1.0`` if prediction is + perfect, ``0.0`` otherwise). Default is ``True``, a convenient setting + for hyperparameters' search procedures (e.g. grid search + cross-validation). + + .. versionadded:: 1.1 + + Returns + ------- + z : float or ndarray of floats + The :math:`R^2` score or ndarray of scores if 'multioutput' is + 'raw_values'. + + Notes + ----- + This is not a symmetric function. + + Unlike most other scores, :math:`R^2` score may be negative (it need not + actually be the square of a quantity R). + + This metric is not well-defined for single samples and will return a NaN + value if n_samples is less than two. + + References + ---------- + .. [1] `Wikipedia entry on the Coefficient of determination + `_ + + Examples + -------- + >>> from sklearn.metrics import r2_score + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> r2_score(y_true, y_pred) + 0.948... + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> r2_score(y_true, y_pred, + ... multioutput='variance_weighted') + 0.938... + >>> y_true = [1, 2, 3] + >>> y_pred = [1, 2, 3] + >>> r2_score(y_true, y_pred) + 1.0 + >>> y_true = [1, 2, 3] + >>> y_pred = [2, 2, 2] + >>> r2_score(y_true, y_pred) + 0.0 + >>> y_true = [1, 2, 3] + >>> y_pred = [3, 2, 1] + >>> r2_score(y_true, y_pred) + -3.0 + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2] + >>> r2_score(y_true, y_pred) + 1.0 + >>> r2_score(y_true, y_pred, force_finite=False) + nan + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2 + 1e-8] + >>> r2_score(y_true, y_pred) + 0.0 + >>> r2_score(y_true, y_pred, force_finite=False) + -inf + """ + xp, _, device_ = get_namespace_and_device( + y_true, y_pred, sample_weight, multioutput + ) + + _, y_true, y_pred, sample_weight, multioutput = ( + _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=xp + ) + ) + + if _num_samples(y_pred) < 2: + msg = "R^2 score is not well-defined with less than two samples." + warnings.warn(msg, UndefinedMetricWarning) + return float("nan") + + if sample_weight is not None: + sample_weight = column_or_1d(sample_weight) + weight = sample_weight[:, None] + else: + weight = 1.0 + + numerator = xp.sum(weight * (y_true - y_pred) ** 2, axis=0) + denominator = xp.sum( + weight * (y_true - _average(y_true, axis=0, weights=sample_weight, xp=xp)) ** 2, + axis=0, + ) + + return _assemble_r2_explained_variance( + numerator=numerator, + denominator=denominator, + n_outputs=y_true.shape[1], + multioutput=multioutput, + force_finite=force_finite, + xp=xp, + device=device_, + ) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + }, + prefer_skip_nested_validation=True, +) +def max_error(y_true, y_pred): + """ + The max_error metric calculates the maximum residual error. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) + Estimated target values. + + Returns + ------- + max_error : float + A positive floating point value (the best value is 0.0). + + Examples + -------- + >>> from sklearn.metrics import max_error + >>> y_true = [3, 2, 7, 1] + >>> y_pred = [4, 2, 7, 1] + >>> max_error(y_true, y_pred) + 1.0 + """ + xp, _ = get_namespace(y_true, y_pred) + y_type, y_true, y_pred, _, _ = _check_reg_targets( + y_true, y_pred, sample_weight=None, multioutput=None, xp=xp + ) + if y_type == "continuous-multioutput": + raise ValueError("Multioutput not supported in max_error") + return float(xp.max(xp.abs(y_true - y_pred))) + + +def _mean_tweedie_deviance(y_true, y_pred, sample_weight, power): + """Mean Tweedie deviance regression loss.""" + xp, _, device_ = get_namespace_and_device(y_true, y_pred) + p = power + if p < 0: + # 'Extreme stable', y any real number, y_pred > 0 + dev = 2 * ( + xp.pow( + xp.where(y_true > 0, y_true, 0.0), + 2 - p, + ) + / ((1 - p) * (2 - p)) + - y_true * xp.pow(y_pred, 1 - p) / (1 - p) + + xp.pow(y_pred, 2 - p) / (2 - p) + ) + elif p == 0: + # Normal distribution, y and y_pred any real number + dev = (y_true - y_pred) ** 2 + elif p == 1: + # Poisson distribution + dev = 2 * (xlogy(y_true, y_true / y_pred) - y_true + y_pred) + elif p == 2: + # Gamma distribution + dev = 2 * (xp.log(y_pred / y_true) + y_true / y_pred - 1) + else: + dev = 2 * ( + xp.pow(y_true, 2 - p) / ((1 - p) * (2 - p)) + - y_true * xp.pow(y_pred, 1 - p) / (1 - p) + + xp.pow(y_pred, 2 - p) / (2 - p) + ) + return float(_average(dev, weights=sample_weight)) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "power": [ + Interval(Real, None, 0, closed="right"), + Interval(Real, 1, None, closed="left"), + ], + }, + prefer_skip_nested_validation=True, +) +def mean_tweedie_deviance(y_true, y_pred, *, sample_weight=None, power=0): + """Mean Tweedie deviance regression loss. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + power : float, default=0 + Tweedie power parameter. Either power <= 0 or power >= 1. + + The higher `p` the less weight is given to extreme + deviations between true and predicted targets. + + - power < 0: Extreme stable distribution. Requires: y_pred > 0. + - power = 0 : Normal distribution, output corresponds to + mean_squared_error. y_true and y_pred can be any real numbers. + - power = 1 : Poisson distribution. Requires: y_true >= 0 and + y_pred > 0. + - 1 < p < 2 : Compound Poisson distribution. Requires: y_true >= 0 + and y_pred > 0. + - power = 2 : Gamma distribution. Requires: y_true > 0 and y_pred > 0. + - power = 3 : Inverse Gaussian distribution. Requires: y_true > 0 + and y_pred > 0. + - otherwise : Positive stable distribution. Requires: y_true > 0 + and y_pred > 0. + + Returns + ------- + loss : float + A non-negative floating point value (the best value is 0.0). + + Examples + -------- + >>> from sklearn.metrics import mean_tweedie_deviance + >>> y_true = [2, 0, 1, 4] + >>> y_pred = [0.5, 0.5, 2., 2.] + >>> mean_tweedie_deviance(y_true, y_pred, power=1) + 1.4260... + """ + xp, _ = get_namespace(y_true, y_pred) + y_type, y_true, y_pred, sample_weight, _ = _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput=None, xp=xp + ) + if y_type == "continuous-multioutput": + raise ValueError("Multioutput not supported in mean_tweedie_deviance") + + if sample_weight is not None: + sample_weight = column_or_1d(sample_weight) + sample_weight = sample_weight[:, np.newaxis] + + message = f"Mean Tweedie deviance error with power={power} can only be used on " + if power < 0: + # 'Extreme stable', y any real number, y_pred > 0 + if xp.any(y_pred <= 0): + raise ValueError(message + "strictly positive y_pred.") + elif power == 0: + # Normal, y and y_pred can be any real number + pass + elif 1 <= power < 2: + # Poisson and compound Poisson distribution, y >= 0, y_pred > 0 + if xp.any(y_true < 0) or xp.any(y_pred <= 0): + raise ValueError(message + "non-negative y and strictly positive y_pred.") + elif power >= 2: + # Gamma and Extreme stable distribution, y and y_pred > 0 + if xp.any(y_true <= 0) or xp.any(y_pred <= 0): + raise ValueError(message + "strictly positive y and y_pred.") + else: # pragma: nocover + # Unreachable statement + raise ValueError + + return _mean_tweedie_deviance( + y_true, y_pred, sample_weight=sample_weight, power=power + ) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def mean_poisson_deviance(y_true, y_pred, *, sample_weight=None): + """Mean Poisson deviance regression loss. + + Poisson deviance is equivalent to the Tweedie deviance with + the power parameter `power=1`. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. Requires y_true >= 0. + + y_pred : array-like of shape (n_samples,) + Estimated target values. Requires y_pred > 0. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + loss : float + A non-negative floating point value (the best value is 0.0). + + Examples + -------- + >>> from sklearn.metrics import mean_poisson_deviance + >>> y_true = [2, 0, 1, 4] + >>> y_pred = [0.5, 0.5, 2., 2.] + >>> mean_poisson_deviance(y_true, y_pred) + 1.4260... + """ + return mean_tweedie_deviance(y_true, y_pred, sample_weight=sample_weight, power=1) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def mean_gamma_deviance(y_true, y_pred, *, sample_weight=None): + """Mean Gamma deviance regression loss. + + Gamma deviance is equivalent to the Tweedie deviance with + the power parameter `power=2`. It is invariant to scaling of + the target variable, and measures relative errors. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. Requires y_true > 0. + + y_pred : array-like of shape (n_samples,) + Estimated target values. Requires y_pred > 0. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + loss : float + A non-negative floating point value (the best value is 0.0). + + Examples + -------- + >>> from sklearn.metrics import mean_gamma_deviance + >>> y_true = [2, 0.5, 1, 4] + >>> y_pred = [0.5, 0.5, 2., 2.] + >>> mean_gamma_deviance(y_true, y_pred) + 1.0568... + """ + return mean_tweedie_deviance(y_true, y_pred, sample_weight=sample_weight, power=2) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "power": [ + Interval(Real, None, 0, closed="right"), + Interval(Real, 1, None, closed="left"), + ], + }, + prefer_skip_nested_validation=True, +) +def d2_tweedie_score(y_true, y_pred, *, sample_weight=None, power=0): + """ + :math:`D^2` regression score function, fraction of Tweedie deviance explained. + + Best possible score is 1.0 and it can be negative (because the model can be + arbitrarily worse). A model that always uses the empirical mean of `y_true` as + constant prediction, disregarding the input features, gets a D^2 score of 0.0. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + power : float, default=0 + Tweedie power parameter. Either power <= 0 or power >= 1. + + The higher `p` the less weight is given to extreme + deviations between true and predicted targets. + + - power < 0: Extreme stable distribution. Requires: y_pred > 0. + - power = 0 : Normal distribution, output corresponds to r2_score. + y_true and y_pred can be any real numbers. + - power = 1 : Poisson distribution. Requires: y_true >= 0 and + y_pred > 0. + - 1 < p < 2 : Compound Poisson distribution. Requires: y_true >= 0 + and y_pred > 0. + - power = 2 : Gamma distribution. Requires: y_true > 0 and y_pred > 0. + - power = 3 : Inverse Gaussian distribution. Requires: y_true > 0 + and y_pred > 0. + - otherwise : Positive stable distribution. Requires: y_true > 0 + and y_pred > 0. + + Returns + ------- + z : float + The D^2 score. + + Notes + ----- + This is not a symmetric function. + + Like R^2, D^2 score may be negative (it need not actually be the square of + a quantity D). + + This metric is not well-defined for single samples and will return a NaN + value if n_samples is less than two. + + References + ---------- + .. [1] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. + Wainwright. "Statistical Learning with Sparsity: The Lasso and + Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/ + + Examples + -------- + >>> from sklearn.metrics import d2_tweedie_score + >>> y_true = [0.5, 1, 2.5, 7] + >>> y_pred = [1, 1, 5, 3.5] + >>> d2_tweedie_score(y_true, y_pred) + 0.285... + >>> d2_tweedie_score(y_true, y_pred, power=1) + 0.487... + >>> d2_tweedie_score(y_true, y_pred, power=2) + 0.630... + >>> d2_tweedie_score(y_true, y_true, power=2) + 1.0 + """ + xp, _ = get_namespace(y_true, y_pred) + + y_type, y_true, y_pred, sample_weight, _ = _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput=None, xp=xp + ) + if y_type == "continuous-multioutput": + raise ValueError("Multioutput not supported in d2_tweedie_score") + + if _num_samples(y_pred) < 2: + msg = "D^2 score is not well-defined with less than two samples." + warnings.warn(msg, UndefinedMetricWarning) + return float("nan") + + y_true, y_pred = xp.squeeze(y_true, axis=1), xp.squeeze(y_pred, axis=1) + numerator = mean_tweedie_deviance( + y_true, y_pred, sample_weight=sample_weight, power=power + ) + + y_avg = _average(y_true, weights=sample_weight, xp=xp) + denominator = _mean_tweedie_deviance( + y_true, y_avg, sample_weight=sample_weight, power=power + ) + + return 1 - numerator / denominator + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "alpha": [Interval(Real, 0, 1, closed="both")], + "multioutput": [ + StrOptions({"raw_values", "uniform_average"}), + "array-like", + ], + }, + prefer_skip_nested_validation=True, +) +def d2_pinball_score( + y_true, y_pred, *, sample_weight=None, alpha=0.5, multioutput="uniform_average" +): + """ + :math:`D^2` regression score function, fraction of pinball loss explained. + + Best possible score is 1.0 and it can be negative (because the model can be + arbitrarily worse). A model that always uses the empirical alpha-quantile of + `y_true` as constant prediction, disregarding the input features, + gets a :math:`D^2` score of 0.0. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.1 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + alpha : float, default=0.5 + Slope of the pinball deviance. It determines the quantile level alpha + for which the pinball deviance and also D2 are optimal. + The default `alpha=0.5` is equivalent to `d2_absolute_error_score`. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average scores. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Scores of all outputs are averaged with uniform weight. + + Returns + ------- + score : float or ndarray of floats + The :math:`D^2` score with a pinball deviance + or ndarray of scores if `multioutput='raw_values'`. + + Notes + ----- + Like :math:`R^2`, :math:`D^2` score may be negative + (it need not actually be the square of a quantity D). + + This metric is not well-defined for a single point and will return a NaN + value if n_samples is less than two. + + References + ---------- + .. [1] Eq. (7) of `Koenker, Roger; Machado, José A. F. (1999). + "Goodness of Fit and Related Inference Processes for Quantile Regression" + `_ + .. [2] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. + Wainwright. "Statistical Learning with Sparsity: The Lasso and + Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/ + + Examples + -------- + >>> from sklearn.metrics import d2_pinball_score + >>> y_true = [1, 2, 3] + >>> y_pred = [1, 3, 3] + >>> d2_pinball_score(y_true, y_pred) + 0.5 + >>> d2_pinball_score(y_true, y_pred, alpha=0.9) + 0.772... + >>> d2_pinball_score(y_true, y_pred, alpha=0.1) + -1.045... + >>> d2_pinball_score(y_true, y_true, alpha=0.1) + 1.0 + """ + _, y_true, y_pred, sample_weight, multioutput = _check_reg_targets( + y_true, y_pred, sample_weight, multioutput + ) + + if _num_samples(y_pred) < 2: + msg = "D^2 score is not well-defined with less than two samples." + warnings.warn(msg, UndefinedMetricWarning) + return float("nan") + + numerator = mean_pinball_loss( + y_true, + y_pred, + sample_weight=sample_weight, + alpha=alpha, + multioutput="raw_values", + ) + + if sample_weight is None: + y_quantile = np.tile( + np.percentile(y_true, q=alpha * 100, axis=0), (len(y_true), 1) + ) + else: + y_quantile = np.tile( + _weighted_percentile( + y_true, sample_weight=sample_weight, percentile_rank=alpha * 100 + ), + (len(y_true), 1), + ) + + denominator = mean_pinball_loss( + y_true, + y_quantile, + sample_weight=sample_weight, + alpha=alpha, + multioutput="raw_values", + ) + + nonzero_numerator = numerator != 0 + nonzero_denominator = denominator != 0 + valid_score = nonzero_numerator & nonzero_denominator + output_scores = np.ones(y_true.shape[1]) + + output_scores[valid_score] = 1 - (numerator[valid_score] / denominator[valid_score]) + output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0 + + if isinstance(multioutput, str): + if multioutput == "raw_values": + # return scores individually + return output_scores + else: # multioutput == "uniform_average" + # passing None as weights to np.average results in uniform mean + avg_weights = None + else: + avg_weights = multioutput + + return float(np.average(output_scores, weights=avg_weights)) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [ + StrOptions({"raw_values", "uniform_average"}), + "array-like", + ], + }, + prefer_skip_nested_validation=True, +) +def d2_absolute_error_score( + y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" +): + """ + :math:`D^2` regression score function, fraction of absolute error explained. + + Best possible score is 1.0 and it can be negative (because the model can be + arbitrarily worse). A model that always uses the empirical median of `y_true` + as constant prediction, disregarding the input features, + gets a :math:`D^2` score of 0.0. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.1 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average scores. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Scores of all outputs are averaged with uniform weight. + + Returns + ------- + score : float or ndarray of floats + The :math:`D^2` score with an absolute error deviance + or ndarray of scores if 'multioutput' is 'raw_values'. + + Notes + ----- + Like :math:`R^2`, :math:`D^2` score may be negative + (it need not actually be the square of a quantity D). + + This metric is not well-defined for single samples and will return a NaN + value if n_samples is less than two. + + References + ---------- + .. [1] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. + Wainwright. "Statistical Learning with Sparsity: The Lasso and + Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/ + + Examples + -------- + >>> from sklearn.metrics import d2_absolute_error_score + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> d2_absolute_error_score(y_true, y_pred) + 0.764... + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> d2_absolute_error_score(y_true, y_pred, multioutput='uniform_average') + 0.691... + >>> d2_absolute_error_score(y_true, y_pred, multioutput='raw_values') + array([0.8125 , 0.57142857]) + >>> y_true = [1, 2, 3] + >>> y_pred = [1, 2, 3] + >>> d2_absolute_error_score(y_true, y_pred) + 1.0 + >>> y_true = [1, 2, 3] + >>> y_pred = [2, 2, 2] + >>> d2_absolute_error_score(y_true, y_pred) + 0.0 + >>> y_true = [1, 2, 3] + >>> y_pred = [3, 2, 1] + >>> d2_absolute_error_score(y_true, y_pred) + -1.0 + """ + return d2_pinball_score( + y_true, y_pred, sample_weight=sample_weight, alpha=0.5, multioutput=multioutput + ) diff --git a/shared/package-files/73/7395953d62eec7abab783ae9603ff82f091d04a4689780e455c239f0f5509f64/stackloss.csv b/shared/package-files/73/7395953d62eec7abab783ae9603ff82f091d04a4689780e455c239f0f5509f64/stackloss.csv new file mode 100644 index 0000000000000000000000000000000000000000..3eb60f57f1bace1c9a3effd7fdb5034fd7e8256f --- /dev/null +++ b/shared/package-files/73/7395953d62eec7abab783ae9603ff82f091d04a4689780e455c239f0f5509f64/stackloss.csv @@ -0,0 +1,22 @@ +"STACKLOSS","AIRFLOW","WATERTEMP","ACIDCONC" +42,80,27,89 +37,80,27,88 +37,75,25,90 +28,62,24,87 +18,62,22,87 +18,62,23,87 +19,62,24,93 +20,62,24,93 +15,58,23,87 +14,58,18,80 +14,58,18,89 +13,58,17,88 +11,58,18,82 +12,58,19,93 +8,50,18,89 +7,50,18,86 +8,50,19,72 +8,50,19,79 +9,50,20,80 +15,56,20,82 +15,70,20,91 diff --git a/shared/package-files/73/73961d514f48c671ccff2a69a790122a14fc5b64d9b686af800417873c587a7f/_transformer_encoder_layer_fwd_ops.h b/shared/package-files/73/73961d514f48c671ccff2a69a790122a14fc5b64d9b686af800417873c587a7f/_transformer_encoder_layer_fwd_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..4762e40a77d0ed5490ed08d5f0cee02944f318cc --- /dev/null +++ b/shared/package-files/73/73961d514f48c671ccff2a69a790122a14fc5b64d9b686af800417873c587a7f/_transformer_encoder_layer_fwd_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _transformer_encoder_layer_fwd { + using schema = at::Tensor (const at::Tensor &, int64_t, int64_t, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, bool, bool, double, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const c10::optional &, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_transformer_encoder_layer_fwd") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_transformer_encoder_layer_fwd(Tensor src, int embed_dim, int num_heads, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, bool use_gelu, bool norm_first, float eps, Tensor norm_weight_1, Tensor norm_bias_1, Tensor norm_weight_2, Tensor norm_bias_2, Tensor ffn_weight_1, Tensor ffn_bias_1, Tensor ffn_weight_2, Tensor ffn_bias_2, Tensor? mask=None, int? mask_type=None) -> Tensor") + static at::Tensor call(const at::Tensor & src, int64_t embed_dim, int64_t num_heads, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, bool use_gelu, bool norm_first, double eps, const at::Tensor & norm_weight_1, const at::Tensor & norm_bias_1, const at::Tensor & norm_weight_2, const at::Tensor & norm_bias_2, const at::Tensor & ffn_weight_1, const at::Tensor & ffn_bias_1, const at::Tensor & ffn_weight_2, const at::Tensor & ffn_bias_2, const c10::optional & mask, c10::optional mask_type); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & src, int64_t embed_dim, int64_t num_heads, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, bool use_gelu, bool norm_first, double eps, const at::Tensor & norm_weight_1, const at::Tensor & norm_bias_1, const at::Tensor & norm_weight_2, const at::Tensor & norm_bias_2, const at::Tensor & ffn_weight_1, const at::Tensor & ffn_bias_1, const at::Tensor & ffn_weight_2, const at::Tensor & ffn_bias_2, const c10::optional & mask, c10::optional mask_type); +}; + +struct TORCH_API _transformer_encoder_layer_fwd_out { + using schema = at::Tensor & (const at::Tensor &, int64_t, int64_t, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, bool, bool, double, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const c10::optional &, c10::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_transformer_encoder_layer_fwd") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_transformer_encoder_layer_fwd.out(Tensor src, int embed_dim, int num_heads, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, bool use_gelu, bool norm_first, float eps, Tensor norm_weight_1, Tensor norm_bias_1, Tensor norm_weight_2, Tensor norm_bias_2, Tensor ffn_weight_1, Tensor ffn_bias_1, Tensor ffn_weight_2, Tensor ffn_bias_2, Tensor? mask=None, int? mask_type=None, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & src, int64_t embed_dim, int64_t num_heads, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, bool use_gelu, bool norm_first, double eps, const at::Tensor & norm_weight_1, const at::Tensor & norm_bias_1, const at::Tensor & norm_weight_2, const at::Tensor & norm_bias_2, const at::Tensor & ffn_weight_1, const at::Tensor & ffn_bias_1, const at::Tensor & ffn_weight_2, const at::Tensor & ffn_bias_2, const c10::optional & mask, c10::optional mask_type, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & src, int64_t embed_dim, int64_t num_heads, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, bool use_gelu, bool norm_first, double eps, const at::Tensor & norm_weight_1, const at::Tensor & norm_bias_1, const at::Tensor & norm_weight_2, const at::Tensor & norm_bias_2, const at::Tensor & ffn_weight_1, const at::Tensor & ffn_bias_1, const at::Tensor & ffn_weight_2, const at::Tensor & ffn_bias_2, const c10::optional & mask, c10::optional mask_type, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/73/739847c1f7efa86afca711882010b022f134bf965d5d6b539dfa6c2798007b18/tanh_backward_meta_dispatch.h b/shared/package-files/73/739847c1f7efa86afca711882010b022f134bf965d5d6b539dfa6c2798007b18/tanh_backward_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..e278ce95589d108c109e31000961a2fd57ceeeb1 --- /dev/null +++ b/shared/package-files/73/739847c1f7efa86afca711882010b022f134bf965d5d6b539dfa6c2798007b18/tanh_backward_meta_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor tanh_backward(const at::Tensor & grad_output, const at::Tensor & output); +TORCH_API at::Tensor & tanh_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & output); +TORCH_API at::Tensor & tanh_backward_outf(const at::Tensor & grad_output, const at::Tensor & output, at::Tensor & grad_input); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/73/739b81615340c21b97b68f31430b92b6497f6abe561b33842f0bc4b93f6804ec/unique_dim.h b/shared/package-files/73/739b81615340c21b97b68f31430b92b6497f6abe561b33842f0bc4b93f6804ec/unique_dim.h new file mode 100644 index 0000000000000000000000000000000000000000..fddfb249b720b043cd5006869606b6ff0b3b325d --- /dev/null +++ b/shared/package-files/73/739b81615340c21b97b68f31430b92b6497f6abe561b33842f0bc4b93f6804ec/unique_dim.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::unique_dim(Tensor self, int dim, bool sorted=True, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor) +inline ::std::tuple unique_dim(const at::Tensor & self, int64_t dim, bool sorted=true, bool return_inverse=false, bool return_counts=false) { + return at::_ops::unique_dim::call(self, dim, sorted, return_inverse, return_counts); +} + +// aten::unique_dim.out(Tensor self, int dim, bool sorted=True, bool return_inverse=False, bool return_counts=False, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple unique_dim_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & self, int64_t dim, bool sorted=true, bool return_inverse=false, bool return_counts=false) { + return at::_ops::unique_dim_out::call(self, dim, sorted, return_inverse, return_counts, out0, out1, out2); +} +// aten::unique_dim.out(Tensor self, int dim, bool sorted=True, bool return_inverse=False, bool return_counts=False, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple unique_dim_outf(const at::Tensor & self, int64_t dim, bool sorted, bool return_inverse, bool return_counts, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) { + return at::_ops::unique_dim_out::call(self, dim, sorted, return_inverse, return_counts, out0, out1, out2); +} + +} diff --git a/shared/package-files/73/73a0bb64da343b90c7f52a30b005e9e23fd217ec2c923ad494db5f0c9a268f14/test_cumulative.py b/shared/package-files/73/73a0bb64da343b90c7f52a30b005e9e23fd217ec2c923ad494db5f0c9a268f14/test_cumulative.py new file mode 100644 index 0000000000000000000000000000000000000000..1bdbef6d50c4c23db86060493dcd4f6df4bc4728 --- /dev/null +++ b/shared/package-files/73/73a0bb64da343b90c7f52a30b005e9e23fd217ec2c923ad494db5f0c9a268f14/test_cumulative.py @@ -0,0 +1,319 @@ +import numpy as np +import pytest + +from pandas.errors import UnsupportedFunctionCall +import pandas.util._test_decorators as td + +import pandas as pd +from pandas import ( + DataFrame, + Series, +) +import pandas._testing as tm + + +@pytest.fixture( + params=[np.int32, np.int64, np.float32, np.float64, "Int64", "Float64"], + ids=["np.int32", "np.int64", "np.float32", "np.float64", "Int64", "Float64"], +) +def dtypes_for_minmax(request): + """ + Fixture of dtypes with min and max values used for testing + cummin and cummax + """ + dtype = request.param + + np_type = dtype + if dtype == "Int64": + np_type = np.int64 + elif dtype == "Float64": + np_type = np.float64 + + min_val = ( + np.iinfo(np_type).min + if np.dtype(np_type).kind == "i" + else np.finfo(np_type).min + ) + max_val = ( + np.iinfo(np_type).max + if np.dtype(np_type).kind == "i" + else np.finfo(np_type).max + ) + + return (dtype, min_val, max_val) + + +def test_groupby_cumprod(): + # GH 4095 + df = DataFrame({"key": ["b"] * 10, "value": 2}) + + actual = df.groupby("key")["value"].cumprod() + expected = df.groupby("key", group_keys=False)["value"].apply(lambda x: x.cumprod()) + expected.name = "value" + tm.assert_series_equal(actual, expected) + + df = DataFrame({"key": ["b"] * 100, "value": 2}) + df["value"] = df["value"].astype(float) + actual = df.groupby("key")["value"].cumprod() + expected = df.groupby("key", group_keys=False)["value"].apply(lambda x: x.cumprod()) + expected.name = "value" + tm.assert_series_equal(actual, expected) + + +@pytest.mark.skip_ubsan +def test_groupby_cumprod_overflow(): + # GH#37493 if we overflow we return garbage consistent with numpy + df = DataFrame({"key": ["b"] * 4, "value": 100_000}) + actual = df.groupby("key")["value"].cumprod() + expected = Series( + [100_000, 10_000_000_000, 1_000_000_000_000_000, 7766279631452241920], + name="value", + ) + tm.assert_series_equal(actual, expected) + + numpy_result = df.groupby("key", group_keys=False)["value"].apply( + lambda x: x.cumprod() + ) + numpy_result.name = "value" + tm.assert_series_equal(actual, numpy_result) + + +def test_groupby_cumprod_nan_influences_other_columns(): + # GH#48064 + df = DataFrame( + { + "a": 1, + "b": [1, np.nan, 2], + "c": [1, 2, 3.0], + } + ) + result = df.groupby("a").cumprod(numeric_only=True, skipna=False) + expected = DataFrame({"b": [1, np.nan, np.nan], "c": [1, 2, 6.0]}) + tm.assert_frame_equal(result, expected) + + +def test_cummin(dtypes_for_minmax): + dtype = dtypes_for_minmax[0] + min_val = dtypes_for_minmax[1] + + # GH 15048 + base_df = DataFrame({"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [3, 4, 3, 2, 2, 3, 2, 1]}) + expected_mins = [3, 3, 3, 2, 2, 2, 2, 1] + + df = base_df.astype(dtype) + + expected = DataFrame({"B": expected_mins}).astype(dtype) + result = df.groupby("A").cummin() + tm.assert_frame_equal(result, expected) + result = df.groupby("A", group_keys=False).B.apply(lambda x: x.cummin()).to_frame() + tm.assert_frame_equal(result, expected) + + # Test w/ min value for dtype + df.loc[[2, 6], "B"] = min_val + df.loc[[1, 5], "B"] = min_val + 1 + expected.loc[[2, 3, 6, 7], "B"] = min_val + expected.loc[[1, 5], "B"] = min_val + 1 # should not be rounded to min_val + result = df.groupby("A").cummin() + tm.assert_frame_equal(result, expected, check_exact=True) + expected = ( + df.groupby("A", group_keys=False).B.apply(lambda x: x.cummin()).to_frame() + ) + tm.assert_frame_equal(result, expected, check_exact=True) + + # Test nan in some values + # Explicit cast to float to avoid implicit cast when setting nan + base_df = base_df.astype({"B": "float"}) + base_df.loc[[0, 2, 4, 6], "B"] = np.nan + expected = DataFrame({"B": [np.nan, 4, np.nan, 2, np.nan, 3, np.nan, 1]}) + result = base_df.groupby("A").cummin() + tm.assert_frame_equal(result, expected) + expected = ( + base_df.groupby("A", group_keys=False).B.apply(lambda x: x.cummin()).to_frame() + ) + tm.assert_frame_equal(result, expected) + + # GH 15561 + df = DataFrame({"a": [1], "b": pd.to_datetime(["2001"])}) + expected = Series(pd.to_datetime("2001"), index=[0], name="b") + + result = df.groupby("a")["b"].cummin() + tm.assert_series_equal(expected, result) + + # GH 15635 + df = DataFrame({"a": [1, 2, 1], "b": [1, 2, 2]}) + result = df.groupby("a").b.cummin() + expected = Series([1, 2, 1], name="b") + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("method", ["cummin", "cummax"]) +@pytest.mark.parametrize("dtype", ["UInt64", "Int64", "Float64", "float", "boolean"]) +def test_cummin_max_all_nan_column(method, dtype): + base_df = DataFrame({"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [np.nan] * 8}) + base_df["B"] = base_df["B"].astype(dtype) + grouped = base_df.groupby("A") + + expected = DataFrame({"B": [np.nan] * 8}, dtype=dtype) + result = getattr(grouped, method)() + tm.assert_frame_equal(expected, result) + + result = getattr(grouped["B"], method)().to_frame() + tm.assert_frame_equal(expected, result) + + +def test_cummax(dtypes_for_minmax): + dtype = dtypes_for_minmax[0] + max_val = dtypes_for_minmax[2] + + # GH 15048 + base_df = DataFrame({"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [3, 4, 3, 2, 2, 3, 2, 1]}) + expected_maxs = [3, 4, 4, 4, 2, 3, 3, 3] + + df = base_df.astype(dtype) + + expected = DataFrame({"B": expected_maxs}).astype(dtype) + result = df.groupby("A").cummax() + tm.assert_frame_equal(result, expected) + result = df.groupby("A", group_keys=False).B.apply(lambda x: x.cummax()).to_frame() + tm.assert_frame_equal(result, expected) + + # Test w/ max value for dtype + df.loc[[2, 6], "B"] = max_val + expected.loc[[2, 3, 6, 7], "B"] = max_val + result = df.groupby("A").cummax() + tm.assert_frame_equal(result, expected) + expected = ( + df.groupby("A", group_keys=False).B.apply(lambda x: x.cummax()).to_frame() + ) + tm.assert_frame_equal(result, expected) + + # Test nan in some values + # Explicit cast to float to avoid implicit cast when setting nan + base_df = base_df.astype({"B": "float"}) + base_df.loc[[0, 2, 4, 6], "B"] = np.nan + expected = DataFrame({"B": [np.nan, 4, np.nan, 4, np.nan, 3, np.nan, 3]}) + result = base_df.groupby("A").cummax() + tm.assert_frame_equal(result, expected) + expected = ( + base_df.groupby("A", group_keys=False).B.apply(lambda x: x.cummax()).to_frame() + ) + tm.assert_frame_equal(result, expected) + + # GH 15561 + df = DataFrame({"a": [1], "b": pd.to_datetime(["2001"])}) + expected = Series(pd.to_datetime("2001"), index=[0], name="b") + + result = df.groupby("a")["b"].cummax() + tm.assert_series_equal(expected, result) + + # GH 15635 + df = DataFrame({"a": [1, 2, 1], "b": [2, 1, 1]}) + result = df.groupby("a").b.cummax() + expected = Series([2, 1, 2], name="b") + tm.assert_series_equal(result, expected) + + +def test_cummax_i8_at_implementation_bound(): + # the minimum value used to be treated as NPY_NAT+1 instead of NPY_NAT + # for int64 dtype GH#46382 + ser = Series([pd.NaT._value + n for n in range(5)]) + df = DataFrame({"A": 1, "B": ser, "C": ser._values.view("M8[ns]")}) + gb = df.groupby("A") + + res = gb.cummax() + exp = df[["B", "C"]] + tm.assert_frame_equal(res, exp) + + +@pytest.mark.parametrize("method", ["cummin", "cummax"]) +@pytest.mark.parametrize("dtype", ["float", "Int64", "Float64"]) +@pytest.mark.parametrize( + "groups,expected_data", + [ + ([1, 1, 1], [1, None, None]), + ([1, 2, 3], [1, None, 2]), + ([1, 3, 3], [1, None, None]), + ], +) +def test_cummin_max_skipna(method, dtype, groups, expected_data): + # GH-34047 + df = DataFrame({"a": Series([1, None, 2], dtype=dtype)}) + orig = df.copy() + gb = df.groupby(groups)["a"] + + result = getattr(gb, method)(skipna=False) + expected = Series(expected_data, dtype=dtype, name="a") + + # check we didn't accidentally alter df + tm.assert_frame_equal(df, orig) + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("method", ["cummin", "cummax"]) +def test_cummin_max_skipna_multiple_cols(method): + # Ensure missing value in "a" doesn't cause "b" to be nan-filled + df = DataFrame({"a": [np.nan, 2.0, 2.0], "b": [2.0, 2.0, 2.0]}) + gb = df.groupby([1, 1, 1])[["a", "b"]] + + result = getattr(gb, method)(skipna=False) + expected = DataFrame({"a": [np.nan, np.nan, np.nan], "b": [2.0, 2.0, 2.0]}) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", ["cumprod", "cumsum"]) +def test_numpy_compat(func): + # see gh-12811 + df = DataFrame({"A": [1, 2, 1], "B": [1, 2, 3]}) + g = df.groupby("A") + + msg = "numpy operations are not valid with groupby" + + with pytest.raises(UnsupportedFunctionCall, match=msg): + getattr(g, func)(1, 2, 3) + with pytest.raises(UnsupportedFunctionCall, match=msg): + getattr(g, func)(foo=1) + + +@td.skip_if_32bit +@pytest.mark.parametrize("method", ["cummin", "cummax"]) +@pytest.mark.parametrize( + "dtype,val", [("UInt64", np.iinfo("uint64").max), ("Int64", 2**53 + 1)] +) +def test_nullable_int_not_cast_as_float(method, dtype, val): + data = [val, pd.NA] + df = DataFrame({"grp": [1, 1], "b": data}, dtype=dtype) + grouped = df.groupby("grp") + + result = grouped.transform(method) + expected = DataFrame({"b": data}, dtype=dtype) + + tm.assert_frame_equal(result, expected) + + +def test_cython_api2(): + # this takes the fast apply path + + # cumsum (GH5614) + df = DataFrame([[1, 2, np.nan], [1, np.nan, 9], [3, 4, 9]], columns=["A", "B", "C"]) + expected = DataFrame([[2, np.nan], [np.nan, 9], [4, 9]], columns=["B", "C"]) + result = df.groupby("A").cumsum() + tm.assert_frame_equal(result, expected) + + # GH 5755 - cumsum is a transformer and should ignore as_index + result = df.groupby("A", as_index=False).cumsum() + tm.assert_frame_equal(result, expected) + + # GH 13994 + msg = "DataFrameGroupBy.cumsum with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A").cumsum(axis=1) + expected = df.cumsum(axis=1) + tm.assert_frame_equal(result, expected) + + msg = "DataFrameGroupBy.cumprod with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A").cumprod(axis=1) + expected = df.cumprod(axis=1) + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/73/73a180f9e39b5d0b42b737a160aaf8b863298ed2d1516d02e55210424f04ca73/test_in_memory_kms.h b/shared/package-files/73/73a180f9e39b5d0b42b737a160aaf8b863298ed2d1516d02e55210424f04ca73/test_in_memory_kms.h new file mode 100644 index 0000000000000000000000000000000000000000..b9d4169c6345f9f1d565615919830d94f107479c --- /dev/null +++ b/shared/package-files/73/73a180f9e39b5d0b42b737a160aaf8b863298ed2d1516d02e55210424f04ca73/test_in_memory_kms.h @@ -0,0 +1,101 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include "arrow/util/base64.h" + +#include "parquet/encryption/kms_client_factory.h" +#include "parquet/encryption/local_wrap_kms_client.h" +#include "parquet/platform.h" + +namespace parquet::encryption { + +// This is a mock class, built for testing only. Don't use it as an example of +// LocalWrapKmsClient implementation. +class TestOnlyLocalWrapInMemoryKms : public LocalWrapKmsClient { + public: + explicit TestOnlyLocalWrapInMemoryKms(const KmsConnectionConfig& kms_connection_config); + + static void InitializeMasterKeys( + const std::unordered_map& + master_keys_map); + + protected: + const ::arrow::util::SecureString& GetMasterKeyFromServer( + const std::string& master_key_identifier) override; + + private: + static std::unordered_map master_key_map_; +}; + +// This is a mock class, built for testing only. Don't use it as an example of KmsClient +// implementation. +class TestOnlyInServerWrapKms : public KmsClient { + public: + static void InitializeMasterKeys( + const std::unordered_map& + master_keys_map); + + std::string WrapKey(const ::arrow::util::SecureString& key_bytes, + const std::string& master_key_identifier) override; + + ::arrow::util::SecureString UnwrapKey( + const std::string& wrapped_key, const std::string& master_key_identifier) override; + + static void StartKeyRotation( + const std::unordered_map& + new_master_keys_map); + static void FinishKeyRotation(); + + private: + ::arrow::util::SecureString GetMasterKeyFromServer( + const std::string& master_key_identifier); + + // Different wrapping and unwrapping key maps to imitate versioning + // and support key rotation. + static std::unordered_map + unwrapping_master_key_map_; + static std::unordered_map + wrapping_master_key_map_; +}; + +// This is a mock class, built for testing only. Don't use it as an example of +// KmsClientFactory implementation. +class TestOnlyInMemoryKmsClientFactory : public KmsClientFactory { + public: + TestOnlyInMemoryKmsClientFactory( + bool wrap_locally, + const std::unordered_map& master_keys_map) + : KmsClientFactory(wrap_locally) { + TestOnlyLocalWrapInMemoryKms::InitializeMasterKeys(master_keys_map); + TestOnlyInServerWrapKms::InitializeMasterKeys(master_keys_map); + } + + std::shared_ptr CreateKmsClient( + const KmsConnectionConfig& kms_connection_config) { + if (wrap_locally_) { + return std::make_shared(kms_connection_config); + } else { + return std::make_shared(); + } + } +}; + +} // namespace parquet::encryption diff --git a/shared/package-files/73/73a1ad9cd778c63e01084e7618c6979e7f809d99bbca7f5885af08c1be71842a/dtd.py b/shared/package-files/73/73a1ad9cd778c63e01084e7618c6979e7f809d99bbca7f5885af08c1be71842a/dtd.py new file mode 100644 index 0000000000000000000000000000000000000000..71c556bd201b37b0622df050e8c9dadd5f32f4e0 --- /dev/null +++ b/shared/package-files/73/73a1ad9cd778c63e01084e7618c6979e7f809d99bbca7f5885af08c1be71842a/dtd.py @@ -0,0 +1,100 @@ +import os +import pathlib +from typing import Any, Callable, Optional, Tuple, Union + +import PIL.Image + +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class DTD(VisionDataset): + """`Describable Textures Dataset (DTD) `_. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default), ``"val"``, or ``"test"``. + partition (int, optional): The dataset partition. Should be ``1 <= partition <= 10``. Defaults to ``1``. + + .. note:: + + The partition only changes which split each image belongs to. Thus, regardless of the selected + partition, combining all splits will result in all images. + + transform (callable, optional): A function/transform that takes in a PIL image and returns a transformed + version. E.g, ``transforms.RandomCrop``. + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. Default is False. + """ + + _URL = "https://www.robots.ox.ac.uk/~vgg/data/dtd/download/dtd-r1.0.1.tar.gz" + _MD5 = "fff73e5086ae6bdbea199a49dfb8a4c1" + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "train", + partition: int = 1, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + self._split = verify_str_arg(split, "split", ("train", "val", "test")) + if not isinstance(partition, int) and not (1 <= partition <= 10): + raise ValueError( + f"Parameter 'partition' should be an integer with `1 <= partition <= 10`, " + f"but got {partition} instead" + ) + self._partition = partition + + super().__init__(root, transform=transform, target_transform=target_transform) + self._base_folder = pathlib.Path(self.root) / type(self).__name__.lower() + self._data_folder = self._base_folder / "dtd" + self._meta_folder = self._data_folder / "labels" + self._images_folder = self._data_folder / "images" + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + self._image_files = [] + classes = [] + with open(self._meta_folder / f"{self._split}{self._partition}.txt") as file: + for line in file: + cls, name = line.strip().split("/") + self._image_files.append(self._images_folder.joinpath(cls, name)) + classes.append(cls) + + self.classes = sorted(set(classes)) + self.class_to_idx = dict(zip(self.classes, range(len(self.classes)))) + self._labels = [self.class_to_idx[cls] for cls in classes] + + def __len__(self) -> int: + return len(self._image_files) + + def __getitem__(self, idx: int) -> Tuple[Any, Any]: + image_file, label = self._image_files[idx], self._labels[idx] + image = PIL.Image.open(image_file).convert("RGB") + + if self.transform: + image = self.transform(image) + + if self.target_transform: + label = self.target_transform(label) + + return image, label + + def extra_repr(self) -> str: + return f"split={self._split}, partition={self._partition}" + + def _check_exists(self) -> bool: + return os.path.exists(self._data_folder) and os.path.isdir(self._data_folder) + + def _download(self) -> None: + if self._check_exists(): + return + download_and_extract_archive(self._URL, download_root=str(self._base_folder), md5=self._MD5) diff --git a/shared/package-files/73/73a2b1defe3519192bbe4cbc93bd5d6ff5096e9cb2a763990ac8c34af8e4afab/GMT-4 b/shared/package-files/73/73a2b1defe3519192bbe4cbc93bd5d6ff5096e9cb2a763990ac8c34af8e4afab/GMT-4 new file mode 100644 index 0000000000000000000000000000000000000000..13aef80cbbcf0c938b8d11d92b0755e146a501d2 Binary files /dev/null and b/shared/package-files/73/73a2b1defe3519192bbe4cbc93bd5d6ff5096e9cb2a763990ac8c34af8e4afab/GMT-4 differ diff --git a/shared/package-files/73/73a2f772cf4362e94c3544e39d9268ed5511b9c8e15072d8cc6d8469113d3757/test_chi2.py b/shared/package-files/73/73a2f772cf4362e94c3544e39d9268ed5511b9c8e15072d8cc6d8469113d3757/test_chi2.py new file mode 100644 index 0000000000000000000000000000000000000000..c50def36f1b6c281e6c96019355b901bf4326a38 --- /dev/null +++ b/shared/package-files/73/73a2f772cf4362e94c3544e39d9268ed5511b9c8e15072d8cc6d8469113d3757/test_chi2.py @@ -0,0 +1,93 @@ +""" +Tests for chi2, currently the only feature selection function designed +specifically to work with sparse matrices. +""" + +import warnings + +import numpy as np +import pytest +import scipy.stats + +from sklearn.feature_selection import SelectKBest, chi2 +from sklearn.feature_selection._univariate_selection import _chisquare +from sklearn.utils._testing import assert_array_almost_equal, assert_array_equal +from sklearn.utils.fixes import COO_CONTAINERS, CSR_CONTAINERS + +# Feature 0 is highly informative for class 1; +# feature 1 is the same everywhere; +# feature 2 is a bit informative for class 2. +X = [[2, 1, 2], [9, 1, 1], [6, 1, 2], [0, 1, 2]] +y = [0, 1, 2, 2] + + +def mkchi2(k): + """Make k-best chi2 selector""" + return SelectKBest(chi2, k=k) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_chi2(csr_container): + # Test Chi2 feature extraction + + chi2 = mkchi2(k=1).fit(X, y) + chi2 = mkchi2(k=1).fit(X, y) + assert_array_equal(chi2.get_support(indices=True), [0]) + assert_array_equal(chi2.transform(X), np.array(X)[:, [0]]) + + chi2 = mkchi2(k=2).fit(X, y) + assert_array_equal(sorted(chi2.get_support(indices=True)), [0, 2]) + + Xsp = csr_container(X, dtype=np.float64) + chi2 = mkchi2(k=2).fit(Xsp, y) + assert_array_equal(sorted(chi2.get_support(indices=True)), [0, 2]) + Xtrans = chi2.transform(Xsp) + assert_array_equal(Xtrans.shape, [Xsp.shape[0], 2]) + + # == doesn't work on scipy.sparse matrices + Xtrans = Xtrans.toarray() + Xtrans2 = mkchi2(k=2).fit_transform(Xsp, y).toarray() + assert_array_almost_equal(Xtrans, Xtrans2) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +def test_chi2_coo(coo_container): + # Check that chi2 works with a COO matrix + # (as returned by CountVectorizer, DictVectorizer) + Xcoo = coo_container(X) + mkchi2(k=2).fit_transform(Xcoo, y) + # if we got here without an exception, we're safe + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_chi2_negative(csr_container): + # Check for proper error on negative numbers in the input X. + X, y = [[0, 1], [-1e-20, 1]], [0, 1] + for X in (X, np.array(X), csr_container(X)): + with pytest.raises(ValueError): + chi2(X, y) + + +def test_chi2_unused_feature(): + # Unused feature should evaluate to NaN + # and should issue no runtime warning + with warnings.catch_warnings(record=True) as warned: + warnings.simplefilter("always") + chi, p = chi2([[1, 0], [0, 0]], [1, 0]) + for w in warned: + if "divide by zero" in repr(w): + raise AssertionError("Found unexpected warning %s" % w) + assert_array_equal(chi, [1, np.nan]) + assert_array_equal(p[1], np.nan) + + +def test_chisquare(): + # Test replacement for scipy.stats.chisquare against the original. + obs = np.array([[2.0, 2.0], [1.0, 1.0]]) + exp = np.array([[1.5, 1.5], [1.5, 1.5]]) + # call SciPy first because our version overwrites obs + chi_scp, p_scp = scipy.stats.chisquare(obs, exp) + chi_our, p_our = _chisquare(obs, exp) + + assert_array_almost_equal(chi_scp, chi_our) + assert_array_almost_equal(p_scp, p_our) diff --git a/shared/package-files/73/73a76294f20704a3820184c66164964a0e1594212cc57ae0d8c60c3bb0df45a4/_sequential.py b/shared/package-files/73/73a76294f20704a3820184c66164964a0e1594212cc57ae0d8c60c3bb0df45a4/_sequential.py new file mode 100644 index 0000000000000000000000000000000000000000..c6d6ed9e2e72e278bee29638945bc9a2456826f6 --- /dev/null +++ b/shared/package-files/73/73a76294f20704a3820184c66164964a0e1594212cc57ae0d8c60c3bb0df45a4/_sequential.py @@ -0,0 +1,363 @@ +""" +Sequential feature selection +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from numbers import Integral, Real + +import numpy as np + +from ..base import BaseEstimator, MetaEstimatorMixin, _fit_context, clone, is_classifier +from ..metrics import check_scoring, get_scorer_names +from ..model_selection import check_cv, cross_val_score +from ..utils._metadata_requests import ( + MetadataRouter, + MethodMapping, + _raise_for_params, + _routing_enabled, + process_routing, +) +from ..utils._param_validation import HasMethods, Interval, RealNotInt, StrOptions +from ..utils._tags import get_tags +from ..utils.validation import check_is_fitted, validate_data +from ._base import SelectorMixin + + +class SequentialFeatureSelector(SelectorMixin, MetaEstimatorMixin, BaseEstimator): + """Transformer that performs Sequential Feature Selection. + + This Sequential Feature Selector adds (forward selection) or + removes (backward selection) features to form a feature subset in a + greedy fashion. At each stage, this estimator chooses the best feature to + add or remove based on the cross-validation score of an estimator. In + the case of unsupervised learning, this Sequential Feature Selector + looks only at the features (X), not the desired outputs (y). + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.24 + + Parameters + ---------- + estimator : estimator instance + An unfitted estimator. + + n_features_to_select : "auto", int or float, default="auto" + If `"auto"`, the behaviour depends on the `tol` parameter: + + - if `tol` is not `None`, then features are selected while the score + change does not exceed `tol`. + - otherwise, half of the features are selected. + + If integer, the parameter is the absolute number of features to select. + If float between 0 and 1, it is the fraction of features to select. + + .. versionadded:: 1.1 + The option `"auto"` was added in version 1.1. + + .. versionchanged:: 1.3 + The default changed from `"warn"` to `"auto"` in 1.3. + + tol : float, default=None + If the score is not incremented by at least `tol` between two + consecutive feature additions or removals, stop adding or removing. + + `tol` can be negative when removing features using `direction="backward"`. + `tol` is required to be strictly positive when doing forward selection. + It can be useful to reduce the number of features at the cost of a small + decrease in the score. + + `tol` is enabled only when `n_features_to_select` is `"auto"`. + + .. versionadded:: 1.1 + + direction : {'forward', 'backward'}, default='forward' + Whether to perform forward selection or backward selection. + + scoring : str or callable, default=None + Scoring method to use for cross-validation. Options: + + - str: see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)`` that returns a single value. + See :ref:`scoring_callable` for details. + - `None`: the `estimator`'s + :ref:`default evaluation criterion ` is used. + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross validation, + - integer, to specify the number of folds in a `(Stratified)KFold`, + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For integer/None inputs, if the estimator is a classifier and ``y`` is + either binary or multiclass, + :class:`~sklearn.model_selection.StratifiedKFold` is used. In all other + cases, :class:`~sklearn.model_selection.KFold` is used. These splitters + are instantiated with `shuffle=False` so the splits will be the same + across calls. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + n_jobs : int, default=None + Number of jobs to run in parallel. When evaluating a new feature to + add or remove, the cross-validation procedure is parallel over the + folds. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Attributes + ---------- + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if the + underlying estimator exposes such an attribute when fit. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_features_to_select_ : int + The number of features that were selected. + + support_ : ndarray of shape (n_features,), dtype=bool + The mask of selected features. + + See Also + -------- + GenericUnivariateSelect : Univariate feature selector with configurable + strategy. + RFE : Recursive feature elimination based on importance weights. + RFECV : Recursive feature elimination based on importance weights, with + automatic selection of the number of features. + SelectFromModel : Feature selection based on thresholds of importance + weights. + + Examples + -------- + >>> from sklearn.feature_selection import SequentialFeatureSelector + >>> from sklearn.neighbors import KNeighborsClassifier + >>> from sklearn.datasets import load_iris + >>> X, y = load_iris(return_X_y=True) + >>> knn = KNeighborsClassifier(n_neighbors=3) + >>> sfs = SequentialFeatureSelector(knn, n_features_to_select=3) + >>> sfs.fit(X, y) + SequentialFeatureSelector(estimator=KNeighborsClassifier(n_neighbors=3), + n_features_to_select=3) + >>> sfs.get_support() + array([ True, False, True, True]) + >>> sfs.transform(X).shape + (150, 3) + """ + + _parameter_constraints: dict = { + "estimator": [HasMethods(["fit"])], + "n_features_to_select": [ + StrOptions({"auto"}), + Interval(RealNotInt, 0, 1, closed="right"), + Interval(Integral, 0, None, closed="neither"), + ], + "tol": [None, Interval(Real, None, None, closed="neither")], + "direction": [StrOptions({"forward", "backward"})], + "scoring": [None, StrOptions(set(get_scorer_names())), callable], + "cv": ["cv_object"], + "n_jobs": [None, Integral], + } + + def __init__( + self, + estimator, + *, + n_features_to_select="auto", + tol=None, + direction="forward", + scoring=None, + cv=5, + n_jobs=None, + ): + self.estimator = estimator + self.n_features_to_select = n_features_to_select + self.tol = tol + self.direction = direction + self.scoring = scoring + self.cv = cv + self.n_jobs = n_jobs + + @_fit_context( + # SequentialFeatureSelector.estimator is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y=None, **params): + """Learn the features to select from X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training vectors, where `n_samples` is the number of samples and + `n_features` is the number of predictors. + + y : array-like of shape (n_samples,), default=None + Target values. This parameter may be ignored for + unsupervised learning. + + **params : dict, default=None + Parameters to be passed to the underlying `estimator`, `cv` + and `scorer` objects. + + .. versionadded:: 1.6 + + Only available if `enable_metadata_routing=True`, + which can be set by using + ``sklearn.set_config(enable_metadata_routing=True)``. + See :ref:`Metadata Routing User Guide ` for + more details. + + Returns + ------- + self : object + Returns the instance itself. + """ + _raise_for_params(params, self, "fit") + tags = self.__sklearn_tags__() + X = validate_data( + self, + X, + accept_sparse="csc", + ensure_min_features=2, + ensure_all_finite=not tags.input_tags.allow_nan, + ) + n_features = X.shape[1] + + if self.n_features_to_select == "auto": + if self.tol is not None: + # With auto feature selection, `n_features_to_select_` will be updated + # to `support_.sum()` after features are selected. + self.n_features_to_select_ = n_features - 1 + else: + self.n_features_to_select_ = n_features // 2 + elif isinstance(self.n_features_to_select, Integral): + if self.n_features_to_select >= n_features: + raise ValueError("n_features_to_select must be < n_features.") + self.n_features_to_select_ = self.n_features_to_select + elif isinstance(self.n_features_to_select, Real): + self.n_features_to_select_ = int(n_features * self.n_features_to_select) + + if self.tol is not None and self.tol < 0 and self.direction == "forward": + raise ValueError( + "tol must be strictly positive when doing forward selection" + ) + + cv = check_cv(self.cv, y, classifier=is_classifier(self.estimator)) + + cloned_estimator = clone(self.estimator) + + # the current mask corresponds to the set of features: + # - that we have already *selected* if we do forward selection + # - that we have already *excluded* if we do backward selection + current_mask = np.zeros(shape=n_features, dtype=bool) + n_iterations = ( + self.n_features_to_select_ + if self.n_features_to_select == "auto" or self.direction == "forward" + else n_features - self.n_features_to_select_ + ) + + old_score = -np.inf + is_auto_select = self.tol is not None and self.n_features_to_select == "auto" + + # We only need to verify the routing here and not use the routed params + # because internally the actual routing will also take place inside the + # `cross_val_score` function. + if _routing_enabled(): + process_routing(self, "fit", **params) + for _ in range(n_iterations): + new_feature_idx, new_score = self._get_best_new_feature_score( + cloned_estimator, X, y, cv, current_mask, **params + ) + if is_auto_select and ((new_score - old_score) < self.tol): + break + + old_score = new_score + current_mask[new_feature_idx] = True + + if self.direction == "backward": + current_mask = ~current_mask + + self.support_ = current_mask + self.n_features_to_select_ = self.support_.sum() + + return self + + def _get_best_new_feature_score(self, estimator, X, y, cv, current_mask, **params): + # Return the best new feature and its score to add to the current_mask, + # i.e. return the best new feature and its score to add (resp. remove) + # when doing forward selection (resp. backward selection). + # Feature will be added if the current score and past score are greater + # than tol when n_feature is auto, + candidate_feature_indices = np.flatnonzero(~current_mask) + scores = {} + for feature_idx in candidate_feature_indices: + candidate_mask = current_mask.copy() + candidate_mask[feature_idx] = True + if self.direction == "backward": + candidate_mask = ~candidate_mask + X_new = X[:, candidate_mask] + scores[feature_idx] = cross_val_score( + estimator, + X_new, + y, + cv=cv, + scoring=self.scoring, + n_jobs=self.n_jobs, + params=params, + ).mean() + new_feature_idx = max(scores, key=lambda feature_idx: scores[feature_idx]) + return new_feature_idx, scores[new_feature_idx] + + def _get_support_mask(self): + check_is_fitted(self) + return self.support_ + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.allow_nan = get_tags(self.estimator).input_tags.allow_nan + tags.input_tags.sparse = get_tags(self.estimator).input_tags.sparse + return tags + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + .. versionadded:: 1.6 + + Returns + ------- + routing : MetadataRouter + A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + router = MetadataRouter(owner=self.__class__.__name__) + router.add( + estimator=self.estimator, + method_mapping=MethodMapping().add(caller="fit", callee="fit"), + ) + router.add( + splitter=check_cv(self.cv, classifier=is_classifier(self.estimator)), + method_mapping=MethodMapping().add(caller="fit", callee="split"), + ) + router.add( + scorer=check_scoring(self.estimator, scoring=self.scoring), + method_mapping=MethodMapping().add(caller="fit", callee="score"), + ) + return router diff --git a/shared/package-files/73/73aaca71ec8f6975dbfbf51004eced4f45f7d7595558376267ab44e865524e9a/_fused_adamw.h b/shared/package-files/73/73aaca71ec8f6975dbfbf51004eced4f45f7d7595558376267ab44e865524e9a/_fused_adamw.h new file mode 100644 index 0000000000000000000000000000000000000000..0cea3dd9adb641eca3c7a3a9dcff60a44b0b5e67 --- /dev/null +++ b/shared/package-files/73/73aaca71ec8f6975dbfbf51004eced4f45f7d7595558376267ab44e865524e9a/_fused_adamw.h @@ -0,0 +1,63 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_fused_adamw_(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, float lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> () +inline void _fused_adamw_(at::TensorList self, at::TensorList grads, at::TensorList exp_avgs, at::TensorList exp_avg_sqs, at::TensorList max_exp_avg_sqs, at::TensorList state_steps, double lr, double beta1, double beta2, double weight_decay, double eps, bool amsgrad, bool maximize, const c10::optional & grad_scale={}, const c10::optional & found_inf={}) { + return at::_ops::_fused_adamw_::call(self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf); +} + +// aten::_fused_adamw_.tensor_lr(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, Tensor lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> () +inline void _fused_adamw_(at::TensorList self, at::TensorList grads, at::TensorList exp_avgs, at::TensorList exp_avg_sqs, at::TensorList max_exp_avg_sqs, at::TensorList state_steps, const at::Tensor & lr, double beta1, double beta2, double weight_decay, double eps, bool amsgrad, bool maximize, const c10::optional & grad_scale={}, const c10::optional & found_inf={}) { + return at::_ops::_fused_adamw__tensor_lr::call(self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf); +} + +// aten::_fused_adamw.out(Tensor[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, float lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None, Tensor(a!)[] out) -> () +inline void _fused_adamw_out(at::TensorList out, at::TensorList self, at::TensorList grads, at::TensorList exp_avgs, at::TensorList exp_avg_sqs, at::TensorList max_exp_avg_sqs, at::TensorList state_steps, double lr, double beta1, double beta2, double weight_decay, double eps, bool amsgrad, bool maximize, const c10::optional & grad_scale={}, const c10::optional & found_inf={}) { + return at::_ops::_fused_adamw_out::call(self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf, out); +} +// aten::_fused_adamw.out(Tensor[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, float lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None, Tensor(a!)[] out) -> () +inline void _fused_adamw_outf(at::TensorList self, at::TensorList grads, at::TensorList exp_avgs, at::TensorList exp_avg_sqs, at::TensorList max_exp_avg_sqs, at::TensorList state_steps, double lr, double beta1, double beta2, double weight_decay, double eps, bool amsgrad, bool maximize, const c10::optional & grad_scale, const c10::optional & found_inf, at::TensorList out) { + return at::_ops::_fused_adamw_out::call(self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf, out); +} + +// aten::_fused_adamw(Tensor[] self, Tensor[] grads, Tensor[] exp_avgs, Tensor[] exp_avg_sqs, Tensor[] max_exp_avg_sqs, Tensor[] state_steps, *, float lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> (Tensor[] self_out, Tensor[] grads_out, Tensor[] exp_avgs_out, Tensor[] exp_avg_sqs_out, Tensor[] max_exp_avg_sqs_out) +inline ::std::tuple<::std::vector,::std::vector,::std::vector,::std::vector,::std::vector> _fused_adamw(at::TensorList self, at::TensorList grads, at::TensorList exp_avgs, at::TensorList exp_avg_sqs, at::TensorList max_exp_avg_sqs, at::TensorList state_steps, double lr, double beta1, double beta2, double weight_decay, double eps, bool amsgrad, bool maximize, const c10::optional & grad_scale={}, const c10::optional & found_inf={}) { + return at::_ops::_fused_adamw::call(self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf); +} + +// aten::_fused_adamw.tensor_lr_out(Tensor[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, Tensor lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None, Tensor(a!)[] out) -> () +inline void _fused_adamw_out(at::TensorList out, at::TensorList self, at::TensorList grads, at::TensorList exp_avgs, at::TensorList exp_avg_sqs, at::TensorList max_exp_avg_sqs, at::TensorList state_steps, const at::Tensor & lr, double beta1, double beta2, double weight_decay, double eps, bool amsgrad, bool maximize, const c10::optional & grad_scale={}, const c10::optional & found_inf={}) { + return at::_ops::_fused_adamw_tensor_lr_out::call(self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf, out); +} +// aten::_fused_adamw.tensor_lr_out(Tensor[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, Tensor lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None, Tensor(a!)[] out) -> () +inline void _fused_adamw_outf(at::TensorList self, at::TensorList grads, at::TensorList exp_avgs, at::TensorList exp_avg_sqs, at::TensorList max_exp_avg_sqs, at::TensorList state_steps, const at::Tensor & lr, double beta1, double beta2, double weight_decay, double eps, bool amsgrad, bool maximize, const c10::optional & grad_scale, const c10::optional & found_inf, at::TensorList out) { + return at::_ops::_fused_adamw_tensor_lr_out::call(self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf, out); +} + +// aten::_fused_adamw.tensor_lr(Tensor[] self, Tensor[] grads, Tensor[] exp_avgs, Tensor[] exp_avg_sqs, Tensor[] max_exp_avg_sqs, Tensor[] state_steps, *, Tensor lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> (Tensor[] self_out, Tensor[] grads_out, Tensor[] exp_avgs_out, Tensor[] exp_avg_sqs_out, Tensor[] max_exp_avg_sqs_out) +inline ::std::tuple<::std::vector,::std::vector,::std::vector,::std::vector,::std::vector> _fused_adamw(at::TensorList self, at::TensorList grads, at::TensorList exp_avgs, at::TensorList exp_avg_sqs, at::TensorList max_exp_avg_sqs, at::TensorList state_steps, const at::Tensor & lr, double beta1, double beta2, double weight_decay, double eps, bool amsgrad, bool maximize, const c10::optional & grad_scale={}, const c10::optional & found_inf={}) { + return at::_ops::_fused_adamw_tensor_lr::call(self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf); +} + +} diff --git a/shared/package-files/73/73ae46ff5e8cc139ec148693537a24af6cf76bd0f48b56b98cbdd4e371473e66/elu_cuda_dispatch.h b/shared/package-files/73/73ae46ff5e8cc139ec148693537a24af6cf76bd0f48b56b98cbdd4e371473e66/elu_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..04a76e25109ac742777b3b46fe2d475f8d503b3d --- /dev/null +++ b/shared/package-files/73/73ae46ff5e8cc139ec148693537a24af6cf76bd0f48b56b98cbdd4e371473e66/elu_cuda_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor elu(const at::Tensor & self, const at::Scalar & alpha=1, const at::Scalar & scale=1, const at::Scalar & input_scale=1); +TORCH_API at::Tensor & elu_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & alpha=1, const at::Scalar & scale=1, const at::Scalar & input_scale=1); +TORCH_API at::Tensor & elu_outf(const at::Tensor & self, const at::Scalar & alpha, const at::Scalar & scale, const at::Scalar & input_scale, at::Tensor & out); +TORCH_API at::Tensor & elu_(at::Tensor & self, const at::Scalar & alpha=1, const at::Scalar & scale=1, const at::Scalar & input_scale=1); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/73/73af505309ddc6ef4129682936b7440570cd0c9d52c8de16bc9a61300ad3f4c2/init.py b/shared/package-files/73/73af505309ddc6ef4129682936b7440570cd0c9d52c8de16bc9a61300ad3f4c2/init.py new file mode 100644 index 0000000000000000000000000000000000000000..426069d780c0b350c60a3bf92331fbfc52b5bf23 --- /dev/null +++ b/shared/package-files/73/73af505309ddc6ef4129682936b7440570cd0c9d52c8de16bc9a61300ad3f4c2/init.py @@ -0,0 +1,626 @@ +"""This file contains utilities for initializing neural network parameters.""" +import math +import warnings + +from torch import Tensor +import torch +from typing import Optional as _Optional + +# These no_grad_* functions are necessary as wrappers around the parts of these +# functions that use `with torch.no_grad()`. The JIT doesn't support context +# managers, so these need to be implemented as builtins. Using these wrappers +# lets us keep those builtins small and re-usable. +def _no_grad_uniform_(tensor, a, b, generator=None): + with torch.no_grad(): + return tensor.uniform_(a, b, generator=generator) + + +def _no_grad_normal_(tensor, mean, std, generator=None): + with torch.no_grad(): + return tensor.normal_(mean, std, generator=generator) + + +def _no_grad_trunc_normal_(tensor, mean, std, a, b, generator=None): + # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf + def norm_cdf(x): + # Computes standard normal cumulative distribution function + return (1. + math.erf(x / math.sqrt(2.))) / 2. + + if (mean < a - 2 * std) or (mean > b + 2 * std): + warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " + "The distribution of values may be incorrect.", + stacklevel=2) + + with torch.no_grad(): + # Values are generated by using a truncated uniform distribution and + # then using the inverse CDF for the normal distribution. + # Get upper and lower cdf values + l = norm_cdf((a - mean) / std) + u = norm_cdf((b - mean) / std) + + # Uniformly fill tensor with values from [l, u], then translate to + # [2l-1, 2u-1]. + tensor.uniform_(2 * l - 1, 2 * u - 1, generator=generator) + + # Use inverse cdf transform for normal distribution to get truncated + # standard normal + tensor.erfinv_() + + # Transform to proper mean, std + tensor.mul_(std * math.sqrt(2.)) + tensor.add_(mean) + + # Clamp to ensure it's in the proper range + tensor.clamp_(min=a, max=b) + return tensor + + +def _no_grad_fill_(tensor, val): + with torch.no_grad(): + return tensor.fill_(val) + + +def _no_grad_zero_(tensor): + with torch.no_grad(): + return tensor.zero_() + + +def calculate_gain(nonlinearity, param=None): + r"""Return the recommended gain value for the given nonlinearity function. + + The values are as follows: + + ================= ==================================================== + nonlinearity gain + ================= ==================================================== + Linear / Identity :math:`1` + Conv{1,2,3}D :math:`1` + Sigmoid :math:`1` + Tanh :math:`\frac{5}{3}` + ReLU :math:`\sqrt{2}` + Leaky Relu :math:`\sqrt{\frac{2}{1 + \text{negative\_slope}^2}}` + SELU :math:`\frac{3}{4}` + ================= ==================================================== + + .. warning:: + In order to implement `Self-Normalizing Neural Networks`_ , + you should use ``nonlinearity='linear'`` instead of ``nonlinearity='selu'``. + This gives the initial weights a variance of ``1 / N``, + which is necessary to induce a stable fixed point in the forward pass. + In contrast, the default gain for ``SELU`` sacrifices the normalization + effect for more stable gradient flow in rectangular layers. + + Args: + nonlinearity: the non-linear function (`nn.functional` name) + param: optional parameter for the non-linear function + + Examples: + >>> gain = nn.init.calculate_gain('leaky_relu', 0.2) # leaky_relu with negative_slope=0.2 + + .. _Self-Normalizing Neural Networks: https://papers.nips.cc/paper/2017/hash/5d44ee6f2c3f71b73125876103c8f6c4-Abstract.html + """ + linear_fns = ['linear', 'conv1d', 'conv2d', 'conv3d', 'conv_transpose1d', 'conv_transpose2d', 'conv_transpose3d'] + if nonlinearity in linear_fns or nonlinearity == 'sigmoid': + return 1 + elif nonlinearity == 'tanh': + return 5.0 / 3 + elif nonlinearity == 'relu': + return math.sqrt(2.0) + elif nonlinearity == 'leaky_relu': + if param is None: + negative_slope = 0.01 + elif not isinstance(param, bool) and isinstance(param, int) or isinstance(param, float): + # True/False are instances of int, hence check above + negative_slope = param + else: + raise ValueError(f"negative_slope {param} not a valid number") + return math.sqrt(2.0 / (1 + negative_slope ** 2)) + elif nonlinearity == 'selu': + return 3.0 / 4 # Value found empirically (https://github.com/pytorch/pytorch/pull/50664) + else: + raise ValueError(f"Unsupported nonlinearity {nonlinearity}") + + +def uniform_( + tensor: Tensor, + a: float = 0.0, + b: float = 1.0, + generator: _Optional[torch.Generator] = None, +) -> Tensor: + r"""Fill the input Tensor with values drawn from the uniform distribution. + + :math:`\mathcal{U}(a, b)`. + + Args: + tensor: an n-dimensional `torch.Tensor` + a: the lower bound of the uniform distribution + b: the upper bound of the uniform distribution + generator: the torch Generator to sample from (default: None) + + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.uniform_(w) + """ + if torch.overrides.has_torch_function_variadic(tensor): + return torch.overrides.handle_torch_function( + uniform_, (tensor,), tensor=tensor, a=a, b=b, generator=generator + ) + return _no_grad_uniform_(tensor, a, b, generator) + + +def normal_( + tensor: Tensor, + mean: float = 0.0, + std: float = 1.0, + generator: _Optional[torch.Generator] = None, +) -> Tensor: + r"""Fill the input Tensor with values drawn from the normal distribution. + + :math:`\mathcal{N}(\text{mean}, \text{std}^2)`. + + Args: + tensor: an n-dimensional `torch.Tensor` + mean: the mean of the normal distribution + std: the standard deviation of the normal distribution + generator: the torch Generator to sample from (default: None) + + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.normal_(w) + """ + if torch.overrides.has_torch_function_variadic(tensor): + return torch.overrides.handle_torch_function( + normal_, (tensor,), tensor=tensor, mean=mean, std=std, generator=generator + ) + return _no_grad_normal_(tensor, mean, std, generator) + +def trunc_normal_( + tensor: Tensor, + mean: float = 0., + std: float = 1., + a: float = -2., + b: float = 2., + generator: _Optional[torch.Generator] = None +) -> Tensor: + r"""Fill the input Tensor with values drawn from a truncated normal distribution. + + The values are effectively drawn from the + normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` + with values outside :math:`[a, b]` redrawn until they are within + the bounds. The method used for generating the random values works + best when :math:`a \leq \text{mean} \leq b`. + + Args: + tensor: an n-dimensional `torch.Tensor` + mean: the mean of the normal distribution + std: the standard deviation of the normal distribution + a: the minimum cutoff value + b: the maximum cutoff value + generator: the torch Generator to sample from (default: None) + + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.trunc_normal_(w) + """ + return _no_grad_trunc_normal_(tensor, mean, std, a, b, generator=generator) + + +def constant_(tensor: Tensor, val: float) -> Tensor: + r"""Fill the input Tensor with the value :math:`\text{val}`. + + Args: + tensor: an n-dimensional `torch.Tensor` + val: the value to fill the tensor with + + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.constant_(w, 0.3) + """ + if torch.overrides.has_torch_function_variadic(tensor): + return torch.overrides.handle_torch_function(constant_, (tensor,), tensor=tensor, val=val) + return _no_grad_fill_(tensor, val) + + +def ones_(tensor: Tensor) -> Tensor: + r"""Fill the input Tensor with the scalar value `1`. + + Args: + tensor: an n-dimensional `torch.Tensor` + + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.ones_(w) + """ + return _no_grad_fill_(tensor, 1.) + + +def zeros_(tensor: Tensor) -> Tensor: + r"""Fill the input Tensor with the scalar value `0`. + + Args: + tensor: an n-dimensional `torch.Tensor` + + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.zeros_(w) + """ + return _no_grad_zero_(tensor) + + +def eye_(tensor): + r"""Fill the 2-dimensional input `Tensor` with the identity matrix. + + Preserves the identity of the inputs in `Linear` layers, where as + many inputs are preserved as possible. + + Args: + tensor: a 2-dimensional `torch.Tensor` + + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.eye_(w) + """ + if tensor.ndimension() != 2: + raise ValueError("Only tensors with 2 dimensions are supported") + + with torch.no_grad(): + torch.eye(*tensor.shape, out=tensor, requires_grad=tensor.requires_grad) + return tensor + + +def dirac_(tensor, groups=1): + r"""Fill the {3, 4, 5}-dimensional input `Tensor` with the Dirac delta function. + + Preserves the identity of the inputs in `Convolutional` + layers, where as many input channels are preserved as possible. In case + of groups>1, each group of channels preserves identity + + Args: + tensor: a {3, 4, 5}-dimensional `torch.Tensor` + groups (int, optional): number of groups in the conv layer (default: 1) + Examples: + >>> w = torch.empty(3, 16, 5, 5) + >>> nn.init.dirac_(w) + >>> w = torch.empty(3, 24, 5, 5) + >>> nn.init.dirac_(w, 3) + """ + dimensions = tensor.ndimension() + if dimensions not in [3, 4, 5]: + raise ValueError("Only tensors with 3, 4, or 5 dimensions are supported") + + sizes = tensor.size() + + if sizes[0] % groups != 0: + raise ValueError('dim 0 must be divisible by groups') + + out_chans_per_grp = sizes[0] // groups + min_dim = min(out_chans_per_grp, sizes[1]) + + with torch.no_grad(): + tensor.zero_() + + for g in range(groups): + for d in range(min_dim): + if dimensions == 3: # Temporal convolution + tensor[g * out_chans_per_grp + d, d, tensor.size(2) // 2] = 1 + elif dimensions == 4: # Spatial convolution + tensor[g * out_chans_per_grp + d, d, tensor.size(2) // 2, + tensor.size(3) // 2] = 1 + else: # Volumetric convolution + tensor[g * out_chans_per_grp + d, d, tensor.size(2) // 2, + tensor.size(3) // 2, tensor.size(4) // 2] = 1 + return tensor + + +def _calculate_fan_in_and_fan_out(tensor): + dimensions = tensor.dim() + if dimensions < 2: + raise ValueError("Fan in and fan out can not be computed for tensor with fewer than 2 dimensions") + + num_input_fmaps = tensor.size(1) + num_output_fmaps = tensor.size(0) + receptive_field_size = 1 + if tensor.dim() > 2: + # math.prod is not always available, accumulate the product manually + # we could use functools.reduce but that is not supported by TorchScript + for s in tensor.shape[2:]: + receptive_field_size *= s + fan_in = num_input_fmaps * receptive_field_size + fan_out = num_output_fmaps * receptive_field_size + + return fan_in, fan_out + + +def xavier_uniform_( + tensor: Tensor, gain: float = 1.0, generator: _Optional[torch.Generator] = None +) -> Tensor: + r"""Fill the input `Tensor` with values using a Xavier uniform distribution. + + The method is described in `Understanding the difficulty of training + deep feedforward neural networks` - Glorot, X. & Bengio, Y. (2010). + The resulting tensor will have values sampled from + :math:`\mathcal{U}(-a, a)` where + + .. math:: + a = \text{gain} \times \sqrt{\frac{6}{\text{fan\_in} + \text{fan\_out}}} + + Also known as Glorot initialization. + + Args: + tensor: an n-dimensional `torch.Tensor` + gain: an optional scaling factor + generator: the torch Generator to sample from (default: None) + + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.xavier_uniform_(w, gain=nn.init.calculate_gain('relu')) + """ + fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor) + std = gain * math.sqrt(2.0 / float(fan_in + fan_out)) + a = math.sqrt(3.0) * std # Calculate uniform bounds from standard deviation + + return _no_grad_uniform_(tensor, -a, a, generator) + + +def xavier_normal_( + tensor: Tensor, + gain: float = 1.0, + generator: _Optional[torch.Generator] = None, +) -> Tensor: + r"""Fill the input `Tensor` with values using a Xavier normal distribution. + + The method is described in `Understanding the difficulty of training deep feedforward + neural networks` - Glorot, X. & Bengio, Y. (2010). The resulting tensor + will have values sampled from :math:`\mathcal{N}(0, \text{std}^2)` where + + .. math:: + \text{std} = \text{gain} \times \sqrt{\frac{2}{\text{fan\_in} + \text{fan\_out}}} + + Also known as Glorot initialization. + + Args: + tensor: an n-dimensional `torch.Tensor` + gain: an optional scaling factor + generator: the torch Generator to sample from (default: None) + + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.xavier_normal_(w) + """ + fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor) + std = gain * math.sqrt(2.0 / float(fan_in + fan_out)) + + return _no_grad_normal_(tensor, 0., std, generator) + + +def _calculate_correct_fan(tensor, mode): + mode = mode.lower() + valid_modes = ['fan_in', 'fan_out'] + if mode not in valid_modes: + raise ValueError(f"Mode {mode} not supported, please use one of {valid_modes}") + + fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor) + return fan_in if mode == 'fan_in' else fan_out + + +def kaiming_uniform_( + tensor: Tensor, + a: float = 0, + mode: str = "fan_in", + nonlinearity: str = "leaky_relu", + generator: _Optional[torch.Generator] = None, +): + r"""Fill the input `Tensor` with values using a Kaiming uniform distribution. + + The method is described in `Delving deep into rectifiers: Surpassing + human-level performance on ImageNet classification` - He, K. et al. (2015). + The resulting tensor will have values sampled from + :math:`\mathcal{U}(-\text{bound}, \text{bound})` where + + .. math:: + \text{bound} = \text{gain} \times \sqrt{\frac{3}{\text{fan\_mode}}} + + Also known as He initialization. + + Args: + tensor: an n-dimensional `torch.Tensor` + a: the negative slope of the rectifier used after this layer (only + used with ``'leaky_relu'``) + mode: either ``'fan_in'`` (default) or ``'fan_out'``. Choosing ``'fan_in'`` + preserves the magnitude of the variance of the weights in the + forward pass. Choosing ``'fan_out'`` preserves the magnitudes in the + backwards pass. + nonlinearity: the non-linear function (`nn.functional` name), + recommended to use only with ``'relu'`` or ``'leaky_relu'`` (default). + generator: the torch Generator to sample from (default: None) + + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.kaiming_uniform_(w, mode='fan_in', nonlinearity='relu') + """ + if torch.overrides.has_torch_function_variadic(tensor): + return torch.overrides.handle_torch_function( + kaiming_uniform_, + (tensor,), + tensor=tensor, + a=a, + mode=mode, + nonlinearity=nonlinearity, + generator=generator) + + if 0 in tensor.shape: + warnings.warn("Initializing zero-element tensors is a no-op") + return tensor + fan = _calculate_correct_fan(tensor, mode) + gain = calculate_gain(nonlinearity, a) + std = gain / math.sqrt(fan) + bound = math.sqrt(3.0) * std # Calculate uniform bounds from standard deviation + with torch.no_grad(): + return tensor.uniform_(-bound, bound, generator=generator) + + +def kaiming_normal_( + tensor: Tensor, + a: float = 0, + mode: str = "fan_in", + nonlinearity: str = "leaky_relu", + generator: _Optional[torch.Generator] = None, +): + r"""Fill the input `Tensor` with values using a Kaiming normal distribution. + + The method is described in `Delving deep into rectifiers: Surpassing + human-level performance on ImageNet classification` - He, K. et al. (2015). + The resulting tensor will have values sampled from + :math:`\mathcal{N}(0, \text{std}^2)` where + + .. math:: + \text{std} = \frac{\text{gain}}{\sqrt{\text{fan\_mode}}} + + Also known as He initialization. + + Args: + tensor: an n-dimensional `torch.Tensor` + a: the negative slope of the rectifier used after this layer (only + used with ``'leaky_relu'``) + mode: either ``'fan_in'`` (default) or ``'fan_out'``. Choosing ``'fan_in'`` + preserves the magnitude of the variance of the weights in the + forward pass. Choosing ``'fan_out'`` preserves the magnitudes in the + backwards pass. + nonlinearity: the non-linear function (`nn.functional` name), + recommended to use only with ``'relu'`` or ``'leaky_relu'`` (default). + generator: the torch Generator to sample from (default: None) + + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.kaiming_normal_(w, mode='fan_out', nonlinearity='relu') + """ + if 0 in tensor.shape: + warnings.warn("Initializing zero-element tensors is a no-op") + return tensor + fan = _calculate_correct_fan(tensor, mode) + gain = calculate_gain(nonlinearity, a) + std = gain / math.sqrt(fan) + with torch.no_grad(): + return tensor.normal_(0, std, generator=generator) + + +def orthogonal_( + tensor, + gain=1, + generator: _Optional[torch.Generator] = None, +): + r"""Fill the input `Tensor` with a (semi) orthogonal matrix. + + Described in `Exact solutions to the nonlinear dynamics of learning in deep + linear neural networks` - Saxe, A. et al. (2013). The input tensor must have + at least 2 dimensions, and for tensors with more than 2 dimensions the + trailing dimensions are flattened. + + Args: + tensor: an n-dimensional `torch.Tensor`, where :math:`n \geq 2` + gain: optional scaling factor + generator: the torch Generator to sample from (default: None) + + Examples: + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_LAPACK) + >>> w = torch.empty(3, 5) + >>> nn.init.orthogonal_(w) + """ + if tensor.ndimension() < 2: + raise ValueError("Only tensors with 2 or more dimensions are supported") + + if tensor.numel() == 0: + # no-op + return tensor + rows = tensor.size(0) + cols = tensor.numel() // rows + flattened = tensor.new(rows, cols).normal_(0, 1, generator=generator) + + if rows < cols: + flattened.t_() + + # Compute the qr factorization + q, r = torch.linalg.qr(flattened) + # Make Q uniform according to https://arxiv.org/pdf/math-ph/0609050.pdf + d = torch.diag(r, 0) + ph = d.sign() + q *= ph + + if rows < cols: + q.t_() + + with torch.no_grad(): + tensor.view_as(q).copy_(q) + tensor.mul_(gain) + return tensor + + +def sparse_( + tensor, + sparsity, + std=0.01, + generator: _Optional[torch.Generator] = None, +): + r"""Fill the 2D input `Tensor` as a sparse matrix. + + The non-zero elements will be drawn from the normal distribution + :math:`\mathcal{N}(0, 0.01)`, as described in `Deep learning via + Hessian-free optimization` - Martens, J. (2010). + + Args: + tensor: an n-dimensional `torch.Tensor` + sparsity: The fraction of elements in each column to be set to zero + std: the standard deviation of the normal distribution used to generate + the non-zero values + generator: the torch Generator to sample from (default: None) + + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.sparse_(w, sparsity=0.1) + """ + if tensor.ndimension() != 2: + raise ValueError("Only tensors with 2 dimensions are supported") + + rows, cols = tensor.shape + num_zeros = int(math.ceil(sparsity * rows)) + + with torch.no_grad(): + tensor.normal_(0, std, generator=generator) + for col_idx in range(cols): + row_indices = torch.randperm(rows) + zero_indices = row_indices[:num_zeros] + tensor[zero_indices, col_idx] = 0 + return tensor + + +# for backward compatibility +def _make_deprecate(meth): + new_name = meth.__name__ + old_name = new_name[:-1] + + def deprecated_init(*args, **kwargs): + warnings.warn(f"nn.init.{old_name} is now deprecated in favor of nn.init.{new_name}.", stacklevel=2) + return meth(*args, **kwargs) + + deprecated_init.__doc__ = fr""" + {old_name}(...) + + .. warning:: + This method is now deprecated in favor of :func:`torch.nn.init.{new_name}`. + + See :func:`~torch.nn.init.{new_name}` for details.""" + deprecated_init.__name__ = old_name + return deprecated_init + + +uniform = _make_deprecate(uniform_) +normal = _make_deprecate(normal_) +constant = _make_deprecate(constant_) +eye = _make_deprecate(eye_) +dirac = _make_deprecate(dirac_) +xavier_uniform = _make_deprecate(xavier_uniform_) +xavier_normal = _make_deprecate(xavier_normal_) +kaiming_uniform = _make_deprecate(kaiming_uniform_) +kaiming_normal = _make_deprecate(kaiming_normal_) +orthogonal = _make_deprecate(orthogonal_) +sparse = _make_deprecate(sparse_) diff --git a/shared/package-files/73/73b44d9aa54370b291a628a2466cf65426abc4113e6d9337e55f1d39e851f247/empty_permuted_native.h b/shared/package-files/73/73b44d9aa54370b291a628a2466cf65426abc4113e6d9337e55f1d39e851f247/empty_permuted_native.h new file mode 100644 index 0000000000000000000000000000000000000000..2c11d323806b0b4f4afe8428c345682c740e9fd7 --- /dev/null +++ b/shared/package-files/73/73b44d9aa54370b291a628a2466cf65426abc4113e6d9337e55f1d39e851f247/empty_permuted_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor empty_permuted_symint(c10::SymIntArrayRef size, at::IntArrayRef physical_layout, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}); +TORCH_API at::Tensor & empty_permuted_out_symint(c10::SymIntArrayRef size, at::IntArrayRef physical_layout, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/73/73b8e798a154f432f14c95b451bc17b7a67d149a9b06556c580d50afdc5203fc/python.py b/shared/package-files/73/73b8e798a154f432f14c95b451bc17b7a67d149a9b06556c580d50afdc5203fc/python.py new file mode 100644 index 0000000000000000000000000000000000000000..e9bf2d3372797eedd6abe967e2e260b4c63a61dc --- /dev/null +++ b/shared/package-files/73/73b8e798a154f432f14c95b451bc17b7a67d149a9b06556c580d50afdc5203fc/python.py @@ -0,0 +1,1198 @@ +""" + pygments.lexers.python + ~~~~~~~~~~~~~~~~~~~~~~ + + Lexers for Python and related languages. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import re +import keyword + +from pip._vendor.pygments.lexer import DelegatingLexer, Lexer, RegexLexer, include, \ + bygroups, using, default, words, combined, do_insertions, this, line_re +from pip._vendor.pygments.util import get_bool_opt, shebang_matches +from pip._vendor.pygments.token import Text, Comment, Operator, Keyword, Name, String, \ + Number, Punctuation, Generic, Other, Error, Whitespace +from pip._vendor.pygments import unistring as uni + +__all__ = ['PythonLexer', 'PythonConsoleLexer', 'PythonTracebackLexer', + 'Python2Lexer', 'Python2TracebackLexer', + 'CythonLexer', 'DgLexer', 'NumPyLexer'] + + +class PythonLexer(RegexLexer): + """ + For Python source code (version 3.x). + + .. versionadded:: 0.10 + + .. versionchanged:: 2.5 + This is now the default ``PythonLexer``. It is still available as the + alias ``Python3Lexer``. + """ + + name = 'Python' + url = 'http://www.python.org' + aliases = ['python', 'py', 'sage', 'python3', 'py3'] + filenames = [ + '*.py', + '*.pyw', + # Type stubs + '*.pyi', + # Jython + '*.jy', + # Sage + '*.sage', + # SCons + '*.sc', + 'SConstruct', + 'SConscript', + # Skylark/Starlark (used by Bazel, Buck, and Pants) + '*.bzl', + 'BUCK', + 'BUILD', + 'BUILD.bazel', + 'WORKSPACE', + # Twisted Application infrastructure + '*.tac', + ] + mimetypes = ['text/x-python', 'application/x-python', + 'text/x-python3', 'application/x-python3'] + + uni_name = "[%s][%s]*" % (uni.xid_start, uni.xid_continue) + + def innerstring_rules(ttype): + return [ + # the old style '%s' % (...) string formatting (still valid in Py3) + (r'%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?' + '[hlL]?[E-GXc-giorsaux%]', String.Interpol), + # the new style '{}'.format(...) string formatting + (r'\{' + r'((\w+)((\.\w+)|(\[[^\]]+\]))*)?' # field name + r'(\![sra])?' # conversion + r'(\:(.?[<>=\^])?[-+ ]?#?0?(\d+)?,?(\.\d+)?[E-GXb-gnosx%]?)?' + r'\}', String.Interpol), + + # backslashes, quotes and formatting signs must be parsed one at a time + (r'[^\\\'"%{\n]+', ttype), + (r'[\'"\\]', ttype), + # unhandled string formatting sign + (r'%|(\{{1,2})', ttype) + # newlines are an error (use "nl" state) + ] + + def fstring_rules(ttype): + return [ + # Assuming that a '}' is the closing brace after format specifier. + # Sadly, this means that we won't detect syntax error. But it's + # more important to parse correct syntax correctly, than to + # highlight invalid syntax. + (r'\}', String.Interpol), + (r'\{', String.Interpol, 'expr-inside-fstring'), + # backslashes, quotes and formatting signs must be parsed one at a time + (r'[^\\\'"{}\n]+', ttype), + (r'[\'"\\]', ttype), + # newlines are an error (use "nl" state) + ] + + tokens = { + 'root': [ + (r'\n', Whitespace), + (r'^(\s*)([rRuUbB]{,2})("""(?:.|\n)*?""")', + bygroups(Whitespace, String.Affix, String.Doc)), + (r"^(\s*)([rRuUbB]{,2})('''(?:.|\n)*?''')", + bygroups(Whitespace, String.Affix, String.Doc)), + (r'\A#!.+$', Comment.Hashbang), + (r'#.*$', Comment.Single), + (r'\\\n', Text), + (r'\\', Text), + include('keywords'), + include('soft-keywords'), + (r'(def)((?:\s|\\\s)+)', bygroups(Keyword, Text), 'funcname'), + (r'(class)((?:\s|\\\s)+)', bygroups(Keyword, Text), 'classname'), + (r'(from)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Text), + 'fromimport'), + (r'(import)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Text), + 'import'), + include('expr'), + ], + 'expr': [ + # raw f-strings + ('(?i)(rf|fr)(""")', + bygroups(String.Affix, String.Double), + combined('rfstringescape', 'tdqf')), + ("(?i)(rf|fr)(''')", + bygroups(String.Affix, String.Single), + combined('rfstringescape', 'tsqf')), + ('(?i)(rf|fr)(")', + bygroups(String.Affix, String.Double), + combined('rfstringescape', 'dqf')), + ("(?i)(rf|fr)(')", + bygroups(String.Affix, String.Single), + combined('rfstringescape', 'sqf')), + # non-raw f-strings + ('([fF])(""")', bygroups(String.Affix, String.Double), + combined('fstringescape', 'tdqf')), + ("([fF])(''')", bygroups(String.Affix, String.Single), + combined('fstringescape', 'tsqf')), + ('([fF])(")', bygroups(String.Affix, String.Double), + combined('fstringescape', 'dqf')), + ("([fF])(')", bygroups(String.Affix, String.Single), + combined('fstringescape', 'sqf')), + # raw bytes and strings + ('(?i)(rb|br|r)(""")', + bygroups(String.Affix, String.Double), 'tdqs'), + ("(?i)(rb|br|r)(''')", + bygroups(String.Affix, String.Single), 'tsqs'), + ('(?i)(rb|br|r)(")', + bygroups(String.Affix, String.Double), 'dqs'), + ("(?i)(rb|br|r)(')", + bygroups(String.Affix, String.Single), 'sqs'), + # non-raw strings + ('([uU]?)(""")', bygroups(String.Affix, String.Double), + combined('stringescape', 'tdqs')), + ("([uU]?)(''')", bygroups(String.Affix, String.Single), + combined('stringescape', 'tsqs')), + ('([uU]?)(")', bygroups(String.Affix, String.Double), + combined('stringescape', 'dqs')), + ("([uU]?)(')", bygroups(String.Affix, String.Single), + combined('stringescape', 'sqs')), + # non-raw bytes + ('([bB])(""")', bygroups(String.Affix, String.Double), + combined('bytesescape', 'tdqs')), + ("([bB])(''')", bygroups(String.Affix, String.Single), + combined('bytesescape', 'tsqs')), + ('([bB])(")', bygroups(String.Affix, String.Double), + combined('bytesescape', 'dqs')), + ("([bB])(')", bygroups(String.Affix, String.Single), + combined('bytesescape', 'sqs')), + + (r'[^\S\n]+', Text), + include('numbers'), + (r'!=|==|<<|>>|:=|[-~+/*%=<>&^|.]', Operator), + (r'[]{}:(),;[]', Punctuation), + (r'(in|is|and|or|not)\b', Operator.Word), + include('expr-keywords'), + include('builtins'), + include('magicfuncs'), + include('magicvars'), + include('name'), + ], + 'expr-inside-fstring': [ + (r'[{([]', Punctuation, 'expr-inside-fstring-inner'), + # without format specifier + (r'(=\s*)?' # debug (https://bugs.python.org/issue36817) + r'(\![sraf])?' # conversion + r'\}', String.Interpol, '#pop'), + # with format specifier + # we'll catch the remaining '}' in the outer scope + (r'(=\s*)?' # debug (https://bugs.python.org/issue36817) + r'(\![sraf])?' # conversion + r':', String.Interpol, '#pop'), + (r'\s+', Whitespace), # allow new lines + include('expr'), + ], + 'expr-inside-fstring-inner': [ + (r'[{([]', Punctuation, 'expr-inside-fstring-inner'), + (r'[])}]', Punctuation, '#pop'), + (r'\s+', Whitespace), # allow new lines + include('expr'), + ], + 'expr-keywords': [ + # Based on https://docs.python.org/3/reference/expressions.html + (words(( + 'async for', 'await', 'else', 'for', 'if', 'lambda', + 'yield', 'yield from'), suffix=r'\b'), + Keyword), + (words(('True', 'False', 'None'), suffix=r'\b'), Keyword.Constant), + ], + 'keywords': [ + (words(( + 'assert', 'async', 'await', 'break', 'continue', 'del', 'elif', + 'else', 'except', 'finally', 'for', 'global', 'if', 'lambda', + 'pass', 'raise', 'nonlocal', 'return', 'try', 'while', 'yield', + 'yield from', 'as', 'with'), suffix=r'\b'), + Keyword), + (words(('True', 'False', 'None'), suffix=r'\b'), Keyword.Constant), + ], + 'soft-keywords': [ + # `match`, `case` and `_` soft keywords + (r'(^[ \t]*)' # at beginning of line + possible indentation + r'(match|case)\b' # a possible keyword + r'(?![ \t]*(?:' # not followed by... + r'[:,;=^&|@~)\]}]|(?:' + # characters and keywords that mean this isn't + r'|'.join(keyword.kwlist) + r')\b))', # pattern matching + bygroups(Text, Keyword), 'soft-keywords-inner'), + ], + 'soft-keywords-inner': [ + # optional `_` keyword + (r'(\s+)([^\n_]*)(_\b)', bygroups(Whitespace, using(this), Keyword)), + default('#pop') + ], + 'builtins': [ + (words(( + '__import__', 'abs', 'aiter', 'all', 'any', 'bin', 'bool', 'bytearray', + 'breakpoint', 'bytes', 'callable', 'chr', 'classmethod', 'compile', + 'complex', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', + 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', + 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'isinstance', + 'issubclass', 'iter', 'len', 'list', 'locals', 'map', 'max', + 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', + 'print', 'property', 'range', 'repr', 'reversed', 'round', 'set', + 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', + 'tuple', 'type', 'vars', 'zip'), prefix=r'(?>|[-~+/*%=<>&^|.]', Operator), + include('keywords'), + (r'(def)((?:\s|\\\s)+)', bygroups(Keyword, Text), 'funcname'), + (r'(class)((?:\s|\\\s)+)', bygroups(Keyword, Text), 'classname'), + (r'(from)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Text), + 'fromimport'), + (r'(import)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Text), + 'import'), + include('builtins'), + include('magicfuncs'), + include('magicvars'), + include('backtick'), + ('([rR]|[uUbB][rR]|[rR][uUbB])(""")', + bygroups(String.Affix, String.Double), 'tdqs'), + ("([rR]|[uUbB][rR]|[rR][uUbB])(''')", + bygroups(String.Affix, String.Single), 'tsqs'), + ('([rR]|[uUbB][rR]|[rR][uUbB])(")', + bygroups(String.Affix, String.Double), 'dqs'), + ("([rR]|[uUbB][rR]|[rR][uUbB])(')", + bygroups(String.Affix, String.Single), 'sqs'), + ('([uUbB]?)(""")', bygroups(String.Affix, String.Double), + combined('stringescape', 'tdqs')), + ("([uUbB]?)(''')", bygroups(String.Affix, String.Single), + combined('stringescape', 'tsqs')), + ('([uUbB]?)(")', bygroups(String.Affix, String.Double), + combined('stringescape', 'dqs')), + ("([uUbB]?)(')", bygroups(String.Affix, String.Single), + combined('stringescape', 'sqs')), + include('name'), + include('numbers'), + ], + 'keywords': [ + (words(( + 'assert', 'break', 'continue', 'del', 'elif', 'else', 'except', + 'exec', 'finally', 'for', 'global', 'if', 'lambda', 'pass', + 'print', 'raise', 'return', 'try', 'while', 'yield', + 'yield from', 'as', 'with'), suffix=r'\b'), + Keyword), + ], + 'builtins': [ + (words(( + '__import__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', + 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', + 'cmp', 'coerce', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod', + 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', + 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id', + 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', + 'list', 'locals', 'long', 'map', 'max', 'min', 'next', 'object', + 'oct', 'open', 'ord', 'pow', 'property', 'range', 'raw_input', 'reduce', + 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', + 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', + 'unichr', 'unicode', 'vars', 'xrange', 'zip'), + prefix=r'(?>> )(.*\n)', bygroups(Generic.Prompt, Other.Code), 'continuations'), + # This happens, e.g., when tracebacks are embedded in documentation; + # trailing whitespaces are often stripped in such contexts. + (r'(>>>)(\n)', bygroups(Generic.Prompt, Whitespace)), + (r'(\^C)?Traceback \(most recent call last\):\n', Other.Traceback, 'traceback'), + # SyntaxError starts with this + (r' File "[^"]+", line \d+', Other.Traceback, 'traceback'), + (r'.*\n', Generic.Output), + ], + 'continuations': [ + (r'(\.\.\. )(.*\n)', bygroups(Generic.Prompt, Other.Code)), + # See above. + (r'(\.\.\.)(\n)', bygroups(Generic.Prompt, Whitespace)), + default('#pop'), + ], + 'traceback': [ + # As soon as we see a traceback, consume everything until the next + # >>> prompt. + (r'(?=>>>( |$))', Text, '#pop'), + (r'(KeyboardInterrupt)(\n)', bygroups(Name.Class, Whitespace)), + (r'.*\n', Other.Traceback), + ], + } + +class PythonConsoleLexer(DelegatingLexer): + """ + For Python console output or doctests, such as: + + .. sourcecode:: pycon + + >>> a = 'foo' + >>> print(a) + foo + >>> 1 / 0 + Traceback (most recent call last): + File "", line 1, in + ZeroDivisionError: integer division or modulo by zero + + Additional options: + + `python3` + Use Python 3 lexer for code. Default is ``True``. + + .. versionadded:: 1.0 + .. versionchanged:: 2.5 + Now defaults to ``True``. + """ + + name = 'Python console session' + aliases = ['pycon'] + mimetypes = ['text/x-python-doctest'] + + def __init__(self, **options): + python3 = get_bool_opt(options, 'python3', True) + if python3: + pylexer = PythonLexer + tblexer = PythonTracebackLexer + else: + pylexer = Python2Lexer + tblexer = Python2TracebackLexer + # We have two auxiliary lexers. Use DelegatingLexer twice with + # different tokens. TODO: DelegatingLexer should support this + # directly, by accepting a tuplet of auxiliary lexers and a tuple of + # distinguishing tokens. Then we wouldn't need this intermediary + # class. + class _ReplaceInnerCode(DelegatingLexer): + def __init__(self, **options): + super().__init__(pylexer, _PythonConsoleLexerBase, Other.Code, **options) + super().__init__(tblexer, _ReplaceInnerCode, Other.Traceback, **options) + +class PythonTracebackLexer(RegexLexer): + """ + For Python 3.x tracebacks, with support for chained exceptions. + + .. versionadded:: 1.0 + + .. versionchanged:: 2.5 + This is now the default ``PythonTracebackLexer``. It is still available + as the alias ``Python3TracebackLexer``. + """ + + name = 'Python Traceback' + aliases = ['pytb', 'py3tb'] + filenames = ['*.pytb', '*.py3tb'] + mimetypes = ['text/x-python-traceback', 'text/x-python3-traceback'] + + tokens = { + 'root': [ + (r'\n', Whitespace), + (r'^(\^C)?Traceback \(most recent call last\):\n', Generic.Traceback, 'intb'), + (r'^During handling of the above exception, another ' + r'exception occurred:\n\n', Generic.Traceback), + (r'^The above exception was the direct cause of the ' + r'following exception:\n\n', Generic.Traceback), + (r'^(?= File "[^"]+", line \d+)', Generic.Traceback, 'intb'), + (r'^.*\n', Other), + ], + 'intb': [ + (r'^( File )("[^"]+")(, line )(\d+)(, in )(.+)(\n)', + bygroups(Text, Name.Builtin, Text, Number, Text, Name, Whitespace)), + (r'^( File )("[^"]+")(, line )(\d+)(\n)', + bygroups(Text, Name.Builtin, Text, Number, Whitespace)), + (r'^( )(.+)(\n)', + bygroups(Whitespace, using(PythonLexer), Whitespace), 'markers'), + (r'^([ \t]*)(\.\.\.)(\n)', + bygroups(Whitespace, Comment, Whitespace)), # for doctests... + (r'^([^:]+)(: )(.+)(\n)', + bygroups(Generic.Error, Text, Name, Whitespace), '#pop'), + (r'^([a-zA-Z_][\w.]*)(:?\n)', + bygroups(Generic.Error, Whitespace), '#pop'), + default('#pop'), + ], + 'markers': [ + # Either `PEP 657 ` + # error locations in Python 3.11+, or single-caret markers + # for syntax errors before that. + (r'^( {4,})([~^]+)(\n)', + bygroups(Whitespace, Punctuation.Marker, Whitespace), + '#pop'), + default('#pop'), + ], + } + + +Python3TracebackLexer = PythonTracebackLexer + + +class Python2TracebackLexer(RegexLexer): + """ + For Python tracebacks. + + .. versionadded:: 0.7 + + .. versionchanged:: 2.5 + This class has been renamed from ``PythonTracebackLexer``. + ``PythonTracebackLexer`` now refers to the Python 3 variant. + """ + + name = 'Python 2.x Traceback' + aliases = ['py2tb'] + filenames = ['*.py2tb'] + mimetypes = ['text/x-python2-traceback'] + + tokens = { + 'root': [ + # Cover both (most recent call last) and (innermost last) + # The optional ^C allows us to catch keyboard interrupt signals. + (r'^(\^C)?(Traceback.*\n)', + bygroups(Text, Generic.Traceback), 'intb'), + # SyntaxError starts with this. + (r'^(?= File "[^"]+", line \d+)', Generic.Traceback, 'intb'), + (r'^.*\n', Other), + ], + 'intb': [ + (r'^( File )("[^"]+")(, line )(\d+)(, in )(.+)(\n)', + bygroups(Text, Name.Builtin, Text, Number, Text, Name, Whitespace)), + (r'^( File )("[^"]+")(, line )(\d+)(\n)', + bygroups(Text, Name.Builtin, Text, Number, Whitespace)), + (r'^( )(.+)(\n)', + bygroups(Text, using(Python2Lexer), Whitespace), 'marker'), + (r'^([ \t]*)(\.\.\.)(\n)', + bygroups(Text, Comment, Whitespace)), # for doctests... + (r'^([^:]+)(: )(.+)(\n)', + bygroups(Generic.Error, Text, Name, Whitespace), '#pop'), + (r'^([a-zA-Z_]\w*)(:?\n)', + bygroups(Generic.Error, Whitespace), '#pop') + ], + 'marker': [ + # For syntax errors. + (r'( {4,})(\^)', bygroups(Text, Punctuation.Marker), '#pop'), + default('#pop'), + ], + } + + +class CythonLexer(RegexLexer): + """ + For Pyrex and Cython source code. + + .. versionadded:: 1.1 + """ + + name = 'Cython' + url = 'http://cython.org' + aliases = ['cython', 'pyx', 'pyrex'] + filenames = ['*.pyx', '*.pxd', '*.pxi'] + mimetypes = ['text/x-cython', 'application/x-cython'] + + tokens = { + 'root': [ + (r'\n', Whitespace), + (r'^(\s*)("""(?:.|\n)*?""")', bygroups(Whitespace, String.Doc)), + (r"^(\s*)('''(?:.|\n)*?''')", bygroups(Whitespace, String.Doc)), + (r'[^\S\n]+', Text), + (r'#.*$', Comment), + (r'[]{}:(),;[]', Punctuation), + (r'\\\n', Whitespace), + (r'\\', Text), + (r'(in|is|and|or|not)\b', Operator.Word), + (r'(<)([a-zA-Z0-9.?]+)(>)', + bygroups(Punctuation, Keyword.Type, Punctuation)), + (r'!=|==|<<|>>|[-~+/*%=<>&^|.?]', Operator), + (r'(from)(\d+)(<=)(\s+)(<)(\d+)(:)', + bygroups(Keyword, Number.Integer, Operator, Name, Operator, + Name, Punctuation)), + include('keywords'), + (r'(def|property)(\s+)', bygroups(Keyword, Text), 'funcname'), + (r'(cp?def)(\s+)', bygroups(Keyword, Text), 'cdef'), + # (should actually start a block with only cdefs) + (r'(cdef)(:)', bygroups(Keyword, Punctuation)), + (r'(class|struct)(\s+)', bygroups(Keyword, Text), 'classname'), + (r'(from)(\s+)', bygroups(Keyword, Text), 'fromimport'), + (r'(c?import)(\s+)', bygroups(Keyword, Text), 'import'), + include('builtins'), + include('backtick'), + ('(?:[rR]|[uU][rR]|[rR][uU])"""', String, 'tdqs'), + ("(?:[rR]|[uU][rR]|[rR][uU])'''", String, 'tsqs'), + ('(?:[rR]|[uU][rR]|[rR][uU])"', String, 'dqs'), + ("(?:[rR]|[uU][rR]|[rR][uU])'", String, 'sqs'), + ('[uU]?"""', String, combined('stringescape', 'tdqs')), + ("[uU]?'''", String, combined('stringescape', 'tsqs')), + ('[uU]?"', String, combined('stringescape', 'dqs')), + ("[uU]?'", String, combined('stringescape', 'sqs')), + include('name'), + include('numbers'), + ], + 'keywords': [ + (words(( + 'assert', 'async', 'await', 'break', 'by', 'continue', 'ctypedef', 'del', 'elif', + 'else', 'except', 'except?', 'exec', 'finally', 'for', 'fused', 'gil', + 'global', 'if', 'include', 'lambda', 'nogil', 'pass', 'print', + 'raise', 'return', 'try', 'while', 'yield', 'as', 'with'), suffix=r'\b'), + Keyword), + (r'(DEF|IF|ELIF|ELSE)\b', Comment.Preproc), + ], + 'builtins': [ + (words(( + '__import__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bint', + 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', + 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'delattr', + 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', + 'file', 'filter', 'float', 'frozenset', 'getattr', 'globals', + 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', + 'issubclass', 'iter', 'len', 'list', 'locals', 'long', 'map', 'max', + 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'Py_ssize_t', + 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', + 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', + 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'unsigned', + 'vars', 'xrange', 'zip'), prefix=r'(? 1: + print("checking %r ..." % file) + + try: + process_tokens(tokenize.generate_tokens(f.readline)) + + except tokenize.TokenError as msg: + errprint("%r: Token Error: %s" % (file, msg)) + return + + except IndentationError as msg: + errprint("%r: Indentation Error: %s" % (file, msg)) + return + + except NannyNag as nag: + badline = nag.get_lineno() + line = nag.get_line() + if verbose: + print("%r: *** Line %d: trouble in tab city! ***" % (file, badline)) + print("offending line: %r" % (line,)) + print(nag.get_msg()) + else: + if ' ' in file: file = '"' + file + '"' + if filename_only: print(file) + else: print(file, badline, repr(line)) + return + + finally: + f.close() + + if verbose: + print("%r: Clean bill of health." % (file,)) + +class Whitespace: + # the characters used for space and tab + S, T = ' \t' + + # members: + # raw + # the original string + # n + # the number of leading whitespace characters in raw + # nt + # the number of tabs in raw[:n] + # norm + # the normal form as a pair (count, trailing), where: + # count + # a tuple such that raw[:n] contains count[i] + # instances of S * i + T + # trailing + # the number of trailing spaces in raw[:n] + # It's A Theorem that m.indent_level(t) == + # n.indent_level(t) for all t >= 1 iff m.norm == n.norm. + # is_simple + # true iff raw[:n] is of the form (T*)(S*) + + def __init__(self, ws): + self.raw = ws + S, T = Whitespace.S, Whitespace.T + count = [] + b = n = nt = 0 + for ch in self.raw: + if ch == S: + n = n + 1 + b = b + 1 + elif ch == T: + n = n + 1 + nt = nt + 1 + if b >= len(count): + count = count + [0] * (b - len(count) + 1) + count[b] = count[b] + 1 + b = 0 + else: + break + self.n = n + self.nt = nt + self.norm = tuple(count), b + self.is_simple = len(count) <= 1 + + # return length of longest contiguous run of spaces (whether or not + # preceding a tab) + def longest_run_of_spaces(self): + count, trailing = self.norm + return max(len(count)-1, trailing) + + def indent_level(self, tabsize): + # count, il = self.norm + # for i in range(len(count)): + # if count[i]: + # il = il + (i//tabsize + 1)*tabsize * count[i] + # return il + + # quicker: + # il = trailing + sum (i//ts + 1)*ts*count[i] = + # trailing + ts * sum (i//ts + 1)*count[i] = + # trailing + ts * sum i//ts*count[i] + count[i] = + # trailing + ts * [(sum i//ts*count[i]) + (sum count[i])] = + # trailing + ts * [(sum i//ts*count[i]) + num_tabs] + # and note that i//ts*count[i] is 0 when i < ts + + count, trailing = self.norm + il = 0 + for i in range(tabsize, len(count)): + il = il + i//tabsize * count[i] + return trailing + tabsize * (il + self.nt) + + # return true iff self.indent_level(t) == other.indent_level(t) + # for all t >= 1 + def equal(self, other): + return self.norm == other.norm + + # return a list of tuples (ts, i1, i2) such that + # i1 == self.indent_level(ts) != other.indent_level(ts) == i2. + # Intended to be used after not self.equal(other) is known, in which + # case it will return at least one witnessing tab size. + def not_equal_witness(self, other): + n = max(self.longest_run_of_spaces(), + other.longest_run_of_spaces()) + 1 + a = [] + for ts in range(1, n+1): + if self.indent_level(ts) != other.indent_level(ts): + a.append( (ts, + self.indent_level(ts), + other.indent_level(ts)) ) + return a + + # Return True iff self.indent_level(t) < other.indent_level(t) + # for all t >= 1. + # The algorithm is due to Vincent Broman. + # Easy to prove it's correct. + # XXXpost that. + # Trivial to prove n is sharp (consider T vs ST). + # Unknown whether there's a faster general way. I suspected so at + # first, but no longer. + # For the special (but common!) case where M and N are both of the + # form (T*)(S*), M.less(N) iff M.len() < N.len() and + # M.num_tabs() <= N.num_tabs(). Proof is easy but kinda long-winded. + # XXXwrite that up. + # Note that M is of the form (T*)(S*) iff len(M.norm[0]) <= 1. + def less(self, other): + if self.n >= other.n: + return False + if self.is_simple and other.is_simple: + return self.nt <= other.nt + n = max(self.longest_run_of_spaces(), + other.longest_run_of_spaces()) + 1 + # the self.n >= other.n test already did it for ts=1 + for ts in range(2, n+1): + if self.indent_level(ts) >= other.indent_level(ts): + return False + return True + + # return a list of tuples (ts, i1, i2) such that + # i1 == self.indent_level(ts) >= other.indent_level(ts) == i2. + # Intended to be used after not self.less(other) is known, in which + # case it will return at least one witnessing tab size. + def not_less_witness(self, other): + n = max(self.longest_run_of_spaces(), + other.longest_run_of_spaces()) + 1 + a = [] + for ts in range(1, n+1): + if self.indent_level(ts) >= other.indent_level(ts): + a.append( (ts, + self.indent_level(ts), + other.indent_level(ts)) ) + return a + +def format_witnesses(w): + firsts = (str(tup[0]) for tup in w) + prefix = "at tab size" + if len(w) > 1: + prefix = prefix + "s" + return prefix + " " + ', '.join(firsts) + +def process_tokens(tokens): + INDENT = tokenize.INDENT + DEDENT = tokenize.DEDENT + NEWLINE = tokenize.NEWLINE + JUNK = tokenize.COMMENT, tokenize.NL + indents = [Whitespace("")] + check_equal = 0 + + for (type, token, start, end, line) in tokens: + if type == NEWLINE: + # a program statement, or ENDMARKER, will eventually follow, + # after some (possibly empty) run of tokens of the form + # (NL | COMMENT)* (INDENT | DEDENT+)? + # If an INDENT appears, setting check_equal is wrong, and will + # be undone when we see the INDENT. + check_equal = 1 + + elif type == INDENT: + check_equal = 0 + thisguy = Whitespace(token) + if not indents[-1].less(thisguy): + witness = indents[-1].not_less_witness(thisguy) + msg = "indent not greater e.g. " + format_witnesses(witness) + raise NannyNag(start[0], msg, line) + indents.append(thisguy) + + elif type == DEDENT: + # there's nothing we need to check here! what's important is + # that when the run of DEDENTs ends, the indentation of the + # program statement (or ENDMARKER) that triggered the run is + # equal to what's left at the top of the indents stack + + # Ouch! This assert triggers if the last line of the source + # is indented *and* lacks a newline -- then DEDENTs pop out + # of thin air. + # assert check_equal # else no earlier NEWLINE, or an earlier INDENT + check_equal = 1 + + del indents[-1] + + elif check_equal and type not in JUNK: + # this is the first "real token" following a NEWLINE, so it + # must be the first token of the next program statement, or an + # ENDMARKER; the "line" argument exposes the leading whitespace + # for this statement; in the case of ENDMARKER, line is an empty + # string, so will properly match the empty string with which the + # "indents" stack was seeded + check_equal = 0 + thisguy = Whitespace(line) + if not indents[-1].equal(thisguy): + witness = indents[-1].not_equal_witness(thisguy) + msg = "indent not equal e.g. " + format_witnesses(witness) + raise NannyNag(start[0], msg, line) + + +if __name__ == '__main__': + main() diff --git a/shared/package-files/73/73bdb035a2190cb584c33b5768c071e105ea47d6d5bbfb231c4ad6e9e66bc881/sign.h b/shared/package-files/73/73bdb035a2190cb584c33b5768c071e105ea47d6d5bbfb231c4ad6e9e66bc881/sign.h new file mode 100644 index 0000000000000000000000000000000000000000..168409595a20648b94fe2d0d25d1d2d2dd4c1576 --- /dev/null +++ b/shared/package-files/73/73bdb035a2190cb584c33b5768c071e105ea47d6d5bbfb231c4ad6e9e66bc881/sign.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::sign(Tensor self) -> Tensor +inline at::Tensor sign(const at::Tensor & self) { + return at::_ops::sign::call(self); +} + +// aten::sign.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & sign_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::sign_out::call(self, out); +} +// aten::sign.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & sign_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::sign_out::call(self, out); +} + +} diff --git a/shared/package-files/73/73bfd71c00675e60f7fea94af7eaf7ecaa9d28101c82654abd0d96713acd2df7/req_command.py b/shared/package-files/73/73bfd71c00675e60f7fea94af7eaf7ecaa9d28101c82654abd0d96713acd2df7/req_command.py new file mode 100644 index 0000000000000000000000000000000000000000..6f2f79c6b3f50f6bf5626df6418d733612776d46 --- /dev/null +++ b/shared/package-files/73/73bfd71c00675e60f7fea94af7eaf7ecaa9d28101c82654abd0d96713acd2df7/req_command.py @@ -0,0 +1,505 @@ +"""Contains the Command base classes that depend on PipSession. + +The classes in this module are in a separate module so the commands not +needing download / PackageFinder capability don't unnecessarily import the +PackageFinder machinery and all its vendored dependencies, etc. +""" + +import logging +import os +import sys +from functools import partial +from optparse import Values +from typing import TYPE_CHECKING, Any, List, Optional, Tuple + +from pip._internal.cache import WheelCache +from pip._internal.cli import cmdoptions +from pip._internal.cli.base_command import Command +from pip._internal.cli.command_context import CommandContextMixIn +from pip._internal.exceptions import CommandError, PreviousBuildDirError +from pip._internal.index.collector import LinkCollector +from pip._internal.index.package_finder import PackageFinder +from pip._internal.models.selection_prefs import SelectionPreferences +from pip._internal.models.target_python import TargetPython +from pip._internal.network.session import PipSession +from pip._internal.operations.build.build_tracker import BuildTracker +from pip._internal.operations.prepare import RequirementPreparer +from pip._internal.req.constructors import ( + install_req_from_editable, + install_req_from_line, + install_req_from_parsed_requirement, + install_req_from_req_string, +) +from pip._internal.req.req_file import parse_requirements +from pip._internal.req.req_install import InstallRequirement +from pip._internal.resolution.base import BaseResolver +from pip._internal.self_outdated_check import pip_self_version_check +from pip._internal.utils.temp_dir import ( + TempDirectory, + TempDirectoryTypeRegistry, + tempdir_kinds, +) +from pip._internal.utils.virtualenv import running_under_virtualenv + +if TYPE_CHECKING: + from ssl import SSLContext + +logger = logging.getLogger(__name__) + + +def _create_truststore_ssl_context() -> Optional["SSLContext"]: + if sys.version_info < (3, 10): + raise CommandError("The truststore feature is only available for Python 3.10+") + + try: + import ssl + except ImportError: + logger.warning("Disabling truststore since ssl support is missing") + return None + + try: + from pip._vendor import truststore + except ImportError as e: + raise CommandError(f"The truststore feature is unavailable: {e}") + + return truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + + +class SessionCommandMixin(CommandContextMixIn): + + """ + A class mixin for command classes needing _build_session(). + """ + + def __init__(self) -> None: + super().__init__() + self._session: Optional[PipSession] = None + + @classmethod + def _get_index_urls(cls, options: Values) -> Optional[List[str]]: + """Return a list of index urls from user-provided options.""" + index_urls = [] + if not getattr(options, "no_index", False): + url = getattr(options, "index_url", None) + if url: + index_urls.append(url) + urls = getattr(options, "extra_index_urls", None) + if urls: + index_urls.extend(urls) + # Return None rather than an empty list + return index_urls or None + + def get_default_session(self, options: Values) -> PipSession: + """Get a default-managed session.""" + if self._session is None: + self._session = self.enter_context(self._build_session(options)) + # there's no type annotation on requests.Session, so it's + # automatically ContextManager[Any] and self._session becomes Any, + # then https://github.com/python/mypy/issues/7696 kicks in + assert self._session is not None + return self._session + + def _build_session( + self, + options: Values, + retries: Optional[int] = None, + timeout: Optional[int] = None, + fallback_to_certifi: bool = False, + ) -> PipSession: + cache_dir = options.cache_dir + assert not cache_dir or os.path.isabs(cache_dir) + + if "truststore" in options.features_enabled: + try: + ssl_context = _create_truststore_ssl_context() + except Exception: + if not fallback_to_certifi: + raise + ssl_context = None + else: + ssl_context = None + + session = PipSession( + cache=os.path.join(cache_dir, "http-v2") if cache_dir else None, + retries=retries if retries is not None else options.retries, + trusted_hosts=options.trusted_hosts, + index_urls=self._get_index_urls(options), + ssl_context=ssl_context, + ) + + # Handle custom ca-bundles from the user + if options.cert: + session.verify = options.cert + + # Handle SSL client certificate + if options.client_cert: + session.cert = options.client_cert + + # Handle timeouts + if options.timeout or timeout: + session.timeout = timeout if timeout is not None else options.timeout + + # Handle configured proxies + if options.proxy: + session.proxies = { + "http": options.proxy, + "https": options.proxy, + } + + # Determine if we can prompt the user for authentication or not + session.auth.prompting = not options.no_input + session.auth.keyring_provider = options.keyring_provider + + return session + + +class IndexGroupCommand(Command, SessionCommandMixin): + + """ + Abstract base class for commands with the index_group options. + + This also corresponds to the commands that permit the pip version check. + """ + + def handle_pip_version_check(self, options: Values) -> None: + """ + Do the pip version check if not disabled. + + This overrides the default behavior of not doing the check. + """ + # Make sure the index_group options are present. + assert hasattr(options, "no_index") + + if options.disable_pip_version_check or options.no_index: + return + + # Otherwise, check if we're using the latest version of pip available. + session = self._build_session( + options, + retries=0, + timeout=min(5, options.timeout), + # This is set to ensure the function does not fail when truststore is + # specified in use-feature but cannot be loaded. This usually raises a + # CommandError and shows a nice user-facing error, but this function is not + # called in that try-except block. + fallback_to_certifi=True, + ) + with session: + pip_self_version_check(session, options) + + +KEEPABLE_TEMPDIR_TYPES = [ + tempdir_kinds.BUILD_ENV, + tempdir_kinds.EPHEM_WHEEL_CACHE, + tempdir_kinds.REQ_BUILD, +] + + +def warn_if_run_as_root() -> None: + """Output a warning for sudo users on Unix. + + In a virtual environment, sudo pip still writes to virtualenv. + On Windows, users may run pip as Administrator without issues. + This warning only applies to Unix root users outside of virtualenv. + """ + if running_under_virtualenv(): + return + if not hasattr(os, "getuid"): + return + # On Windows, there are no "system managed" Python packages. Installing as + # Administrator via pip is the correct way of updating system environments. + # + # We choose sys.platform over utils.compat.WINDOWS here to enable Mypy platform + # checks: https://mypy.readthedocs.io/en/stable/common_issues.html + if sys.platform == "win32" or sys.platform == "cygwin": + return + + if os.getuid() != 0: + return + + logger.warning( + "Running pip as the 'root' user can result in broken permissions and " + "conflicting behaviour with the system package manager. " + "It is recommended to use a virtual environment instead: " + "https://pip.pypa.io/warnings/venv" + ) + + +def with_cleanup(func: Any) -> Any: + """Decorator for common logic related to managing temporary + directories. + """ + + def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None: + for t in KEEPABLE_TEMPDIR_TYPES: + registry.set_delete(t, False) + + def wrapper( + self: RequirementCommand, options: Values, args: List[Any] + ) -> Optional[int]: + assert self.tempdir_registry is not None + if options.no_clean: + configure_tempdir_registry(self.tempdir_registry) + + try: + return func(self, options, args) + except PreviousBuildDirError: + # This kind of conflict can occur when the user passes an explicit + # build directory with a pre-existing folder. In that case we do + # not want to accidentally remove it. + configure_tempdir_registry(self.tempdir_registry) + raise + + return wrapper + + +class RequirementCommand(IndexGroupCommand): + def __init__(self, *args: Any, **kw: Any) -> None: + super().__init__(*args, **kw) + + self.cmd_opts.add_option(cmdoptions.no_clean()) + + @staticmethod + def determine_resolver_variant(options: Values) -> str: + """Determines which resolver should be used, based on the given options.""" + if "legacy-resolver" in options.deprecated_features_enabled: + return "legacy" + + return "resolvelib" + + @classmethod + def make_requirement_preparer( + cls, + temp_build_dir: TempDirectory, + options: Values, + build_tracker: BuildTracker, + session: PipSession, + finder: PackageFinder, + use_user_site: bool, + download_dir: Optional[str] = None, + verbosity: int = 0, + ) -> RequirementPreparer: + """ + Create a RequirementPreparer instance for the given parameters. + """ + temp_build_dir_path = temp_build_dir.path + assert temp_build_dir_path is not None + legacy_resolver = False + + resolver_variant = cls.determine_resolver_variant(options) + if resolver_variant == "resolvelib": + lazy_wheel = "fast-deps" in options.features_enabled + if lazy_wheel: + logger.warning( + "pip is using lazily downloaded wheels using HTTP " + "range requests to obtain dependency information. " + "This experimental feature is enabled through " + "--use-feature=fast-deps and it is not ready for " + "production." + ) + else: + legacy_resolver = True + lazy_wheel = False + if "fast-deps" in options.features_enabled: + logger.warning( + "fast-deps has no effect when used with the legacy resolver." + ) + + return RequirementPreparer( + build_dir=temp_build_dir_path, + src_dir=options.src_dir, + download_dir=download_dir, + build_isolation=options.build_isolation, + check_build_deps=options.check_build_deps, + build_tracker=build_tracker, + session=session, + progress_bar=options.progress_bar, + finder=finder, + require_hashes=options.require_hashes, + use_user_site=use_user_site, + lazy_wheel=lazy_wheel, + verbosity=verbosity, + legacy_resolver=legacy_resolver, + ) + + @classmethod + def make_resolver( + cls, + preparer: RequirementPreparer, + finder: PackageFinder, + options: Values, + wheel_cache: Optional[WheelCache] = None, + use_user_site: bool = False, + ignore_installed: bool = True, + ignore_requires_python: bool = False, + force_reinstall: bool = False, + upgrade_strategy: str = "to-satisfy-only", + use_pep517: Optional[bool] = None, + py_version_info: Optional[Tuple[int, ...]] = None, + ) -> BaseResolver: + """ + Create a Resolver instance for the given parameters. + """ + make_install_req = partial( + install_req_from_req_string, + isolated=options.isolated_mode, + use_pep517=use_pep517, + ) + resolver_variant = cls.determine_resolver_variant(options) + # The long import name and duplicated invocation is needed to convince + # Mypy into correctly typechecking. Otherwise it would complain the + # "Resolver" class being redefined. + if resolver_variant == "resolvelib": + import pip._internal.resolution.resolvelib.resolver + + return pip._internal.resolution.resolvelib.resolver.Resolver( + preparer=preparer, + finder=finder, + wheel_cache=wheel_cache, + make_install_req=make_install_req, + use_user_site=use_user_site, + ignore_dependencies=options.ignore_dependencies, + ignore_installed=ignore_installed, + ignore_requires_python=ignore_requires_python, + force_reinstall=force_reinstall, + upgrade_strategy=upgrade_strategy, + py_version_info=py_version_info, + ) + import pip._internal.resolution.legacy.resolver + + return pip._internal.resolution.legacy.resolver.Resolver( + preparer=preparer, + finder=finder, + wheel_cache=wheel_cache, + make_install_req=make_install_req, + use_user_site=use_user_site, + ignore_dependencies=options.ignore_dependencies, + ignore_installed=ignore_installed, + ignore_requires_python=ignore_requires_python, + force_reinstall=force_reinstall, + upgrade_strategy=upgrade_strategy, + py_version_info=py_version_info, + ) + + def get_requirements( + self, + args: List[str], + options: Values, + finder: PackageFinder, + session: PipSession, + ) -> List[InstallRequirement]: + """ + Parse command-line arguments into the corresponding requirements. + """ + requirements: List[InstallRequirement] = [] + for filename in options.constraints: + for parsed_req in parse_requirements( + filename, + constraint=True, + finder=finder, + options=options, + session=session, + ): + req_to_add = install_req_from_parsed_requirement( + parsed_req, + isolated=options.isolated_mode, + user_supplied=False, + ) + requirements.append(req_to_add) + + for req in args: + req_to_add = install_req_from_line( + req, + comes_from=None, + isolated=options.isolated_mode, + use_pep517=options.use_pep517, + user_supplied=True, + config_settings=getattr(options, "config_settings", None), + ) + requirements.append(req_to_add) + + for req in options.editables: + req_to_add = install_req_from_editable( + req, + user_supplied=True, + isolated=options.isolated_mode, + use_pep517=options.use_pep517, + config_settings=getattr(options, "config_settings", None), + ) + requirements.append(req_to_add) + + # NOTE: options.require_hashes may be set if --require-hashes is True + for filename in options.requirements: + for parsed_req in parse_requirements( + filename, finder=finder, options=options, session=session + ): + req_to_add = install_req_from_parsed_requirement( + parsed_req, + isolated=options.isolated_mode, + use_pep517=options.use_pep517, + user_supplied=True, + config_settings=parsed_req.options.get("config_settings") + if parsed_req.options + else None, + ) + requirements.append(req_to_add) + + # If any requirement has hash options, enable hash checking. + if any(req.has_hash_options for req in requirements): + options.require_hashes = True + + if not (args or options.editables or options.requirements): + opts = {"name": self.name} + if options.find_links: + raise CommandError( + "You must give at least one requirement to {name} " + '(maybe you meant "pip {name} {links}"?)'.format( + **dict(opts, links=" ".join(options.find_links)) + ) + ) + else: + raise CommandError( + "You must give at least one requirement to {name} " + '(see "pip help {name}")'.format(**opts) + ) + + return requirements + + @staticmethod + def trace_basic_info(finder: PackageFinder) -> None: + """ + Trace basic information about the provided objects. + """ + # Display where finder is looking for packages + search_scope = finder.search_scope + locations = search_scope.get_formatted_locations() + if locations: + logger.info(locations) + + def _build_package_finder( + self, + options: Values, + session: PipSession, + target_python: Optional[TargetPython] = None, + ignore_requires_python: Optional[bool] = None, + ) -> PackageFinder: + """ + Create a package finder appropriate to this requirement command. + + :param ignore_requires_python: Whether to ignore incompatible + "Requires-Python" values in links. Defaults to False. + """ + link_collector = LinkCollector.create(session, options=options) + selection_prefs = SelectionPreferences( + allow_yanked=True, + format_control=options.format_control, + allow_all_prereleases=options.pre, + prefer_binary=options.prefer_binary, + ignore_requires_python=ignore_requires_python, + ) + + return PackageFinder.create( + link_collector=link_collector, + selection_prefs=selection_prefs, + target_python=target_python, + ) diff --git a/shared/package-files/73/73c01de69ec22a3ff570203b95546970fa9b417198697f3772ebbab88171f818/Ulyanovsk b/shared/package-files/73/73c01de69ec22a3ff570203b95546970fa9b417198697f3772ebbab88171f818/Ulyanovsk new file mode 100644 index 0000000000000000000000000000000000000000..d668233b37f268a745e995177195b06ffab1e69b Binary files /dev/null and b/shared/package-files/73/73c01de69ec22a3ff570203b95546970fa9b417198697f3772ebbab88171f818/Ulyanovsk differ diff --git a/shared/package-files/73/73c276c1819066bf56a4b213e331383148048f860d6c711661862c166c407972/__init__.py b/shared/package-files/73/73c276c1819066bf56a4b213e331383148048f860d6c711661862c166c407972/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..549cfb9760dda474cb858b7b36d236af48111067 --- /dev/null +++ b/shared/package-files/73/73c276c1819066bf56a4b213e331383148048f860d6c711661862c166c407972/__init__.py @@ -0,0 +1,6 @@ +"""This module contains the equality constrained SQP solver.""" + + +from .minimize_trustregion_constr import _minimize_trustregion_constr + +__all__ = ['_minimize_trustregion_constr'] diff --git a/shared/package-files/73/73c50984635c37d0ff0c8347144b2291bb8c0f8000ab1469c07a836379860da7/lisaterm b/shared/package-files/73/73c50984635c37d0ff0c8347144b2291bb8c0f8000ab1469c07a836379860da7/lisaterm new file mode 100644 index 0000000000000000000000000000000000000000..34a362e10c6d997d3123dadd7fba8261f9c0ca4e Binary files /dev/null and b/shared/package-files/73/73c50984635c37d0ff0c8347144b2291bb8c0f8000ab1469c07a836379860da7/lisaterm differ diff --git a/shared/package-files/73/73c57df1182979b823f5947570e6617b9b186b59aff4b5bd6e4e08ac73edf703/npm.yaml b/shared/package-files/73/73c57df1182979b823f5947570e6617b9b186b59aff4b5bd6e4e08ac73edf703/npm.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2c3fb791a7ddf6ee29af3c769e3fa33d1d7818fc --- /dev/null +++ b/shared/package-files/73/73c57df1182979b823f5947570e6617b9b186b59aff4b5bd6e4e08ac73edf703/npm.yaml @@ -0,0 +1,34 @@ +#Automaticly generating npm conda package +{% set data = load_npm()%} +{% block body -%} +{% block package -%} +package: + name: {{data.get('name').lower()}} + version: {{data.get('version')}} +{%- endblock %} +{% block build -%} +build: + number: {% block build_number -%}1{%- endblock %} + script: + - cd $RECIPE_DIR + - npm --prefix $PREFIX install . -g --production +{%- endblock %} +{% block requirements -%} +requirements: + build: + - nodejs + + run: + - nodejs + +{%- endblock %} +{% block about -%} +about: + home: {{data.get('url')}} + license: {{data.get('license')}} +{%- endblock %} +{%- endblock %} + +# See +# https://docs.conda.io/projects/conda-build for +# more information about meta.yaml diff --git a/shared/package-files/73/73c704055cce2f0ca22d7261a78960383eb6f987a746c0719dcfcb5974e44378/icl6402 b/shared/package-files/73/73c704055cce2f0ca22d7261a78960383eb6f987a746c0719dcfcb5974e44378/icl6402 new file mode 100644 index 0000000000000000000000000000000000000000..4b824b4215afbab225fb788673676a2c5b671026 Binary files /dev/null and b/shared/package-files/73/73c704055cce2f0ca22d7261a78960383eb6f987a746c0719dcfcb5974e44378/icl6402 differ diff --git a/shared/package-files/73/73c704055cce2f0ca22d7261a78960383eb6f987a746c0719dcfcb5974e44378/icl6404 b/shared/package-files/73/73c704055cce2f0ca22d7261a78960383eb6f987a746c0719dcfcb5974e44378/icl6404 new file mode 100644 index 0000000000000000000000000000000000000000..4b824b4215afbab225fb788673676a2c5b671026 Binary files /dev/null and b/shared/package-files/73/73c704055cce2f0ca22d7261a78960383eb6f987a746c0719dcfcb5974e44378/icl6404 differ diff --git a/shared/package-files/73/73c704055cce2f0ca22d7261a78960383eb6f987a746c0719dcfcb5974e44378/kds6402 b/shared/package-files/73/73c704055cce2f0ca22d7261a78960383eb6f987a746c0719dcfcb5974e44378/kds6402 new file mode 100644 index 0000000000000000000000000000000000000000..4b824b4215afbab225fb788673676a2c5b671026 Binary files /dev/null and b/shared/package-files/73/73c704055cce2f0ca22d7261a78960383eb6f987a746c0719dcfcb5974e44378/kds6402 differ diff --git a/shared/package-files/73/73c704055cce2f0ca22d7261a78960383eb6f987a746c0719dcfcb5974e44378/kds7372 b/shared/package-files/73/73c704055cce2f0ca22d7261a78960383eb6f987a746c0719dcfcb5974e44378/kds7372 new file mode 100644 index 0000000000000000000000000000000000000000..4b824b4215afbab225fb788673676a2c5b671026 Binary files /dev/null and b/shared/package-files/73/73c704055cce2f0ca22d7261a78960383eb6f987a746c0719dcfcb5974e44378/kds7372 differ diff --git a/shared/package-files/73/73c825a802db366beedc038bbe944f61f8bbe540bab8720cb568306e4cee5195/letters.xbm b/shared/package-files/73/73c825a802db366beedc038bbe944f61f8bbe540bab8720cb568306e4cee5195/letters.xbm new file mode 100644 index 0000000000000000000000000000000000000000..0f12568d1a0609f5f2a8a00eae3aca46f317ab87 --- /dev/null +++ b/shared/package-files/73/73c825a802db366beedc038bbe944f61f8bbe540bab8720cb568306e4cee5195/letters.xbm @@ -0,0 +1,27 @@ +#define letters_width 48 +#define letters_height 48 +static char letters_bits[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0xfe, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x02, 0x00, 0x00, 0x00, 0x20, + 0x00, 0xfa, 0x00, 0x00, 0x00, 0x2e, 0x00, 0x02, 0x00, 0x00, 0x00, 0x2a, + 0x00, 0x3a, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x02, 0x00, 0x00, 0x00, 0x2e, + 0xe0, 0xff, 0xff, 0xff, 0xff, 0x21, 0x20, 0x00, 0x00, 0x00, 0x00, 0x21, + 0xa0, 0x03, 0x00, 0x00, 0x70, 0x21, 0x20, 0x00, 0x00, 0x00, 0x50, 0x21, + 0xa0, 0x1f, 0x00, 0x00, 0x50, 0x21, 0x20, 0x00, 0x00, 0x00, 0x70, 0x21, + 0xfe, 0xff, 0xff, 0xff, 0x0f, 0x21, 0x02, 0x00, 0x00, 0x00, 0x08, 0x21, + 0xfa, 0x01, 0x00, 0x80, 0x0b, 0x21, 0x02, 0x00, 0x00, 0x80, 0x0a, 0x21, + 0xba, 0x01, 0x00, 0x80, 0x0a, 0x21, 0x02, 0x00, 0x00, 0x80, 0x0b, 0x21, + 0x3a, 0x00, 0x00, 0x00, 0x08, 0x21, 0x02, 0x00, 0x00, 0x00, 0x08, 0x21, + 0x02, 0xc0, 0xfb, 0x03, 0x08, 0x21, 0x02, 0x00, 0x00, 0x00, 0x08, 0x3f, + 0x02, 0xc0, 0xbd, 0x0f, 0x08, 0x01, 0x02, 0x00, 0x00, 0x00, 0x08, 0x01, + 0x02, 0xc0, 0x7f, 0x7b, 0x08, 0x01, 0x02, 0x00, 0x00, 0x00, 0x08, 0x01, + 0x02, 0x00, 0x00, 0x00, 0xf8, 0x01, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, + 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, + 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, + 0xfe, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; diff --git a/shared/package-files/73/73c8aaa12272cbd33a09d0ffcda01a835f2f0916a16aaed54732efa312430688/statecrime.csv b/shared/package-files/73/73c8aaa12272cbd33a09d0ffcda01a835f2f0916a16aaed54732efa312430688/statecrime.csv new file mode 100644 index 0000000000000000000000000000000000000000..4610e85df22bd246f62a143c6e3bf09655eeccbd --- /dev/null +++ b/shared/package-files/73/73c8aaa12272cbd33a09d0ffcda01a835f2f0916a16aaed54732efa312430688/statecrime.csv @@ -0,0 +1,52 @@ +state,violent,murder,hs_grad,poverty,single,white,urban +Alabama,459.9,7.1,82.1,17.5,29.0,70,48.65 +Alaska,632.6,3.2,91.4,9.0,25.5,68.3,44.46 +Arizona,423.2,5.5,84.2,16.5,25.7,80,80.07 +Arkansas,530.3,6.3,82.4,18.8,26.3,78.4,39.54 +California,473.4,5.4,80.6,14.2,27.8,62.7,89.73 +Colorado,340.9,3.2,89.3,12.9,21.4,84.6,76.86 +Connecticut,300.5,3.0,88.6,9.4,25.0,79.1,84.83 +Delaware,645.1,4.6,87.4,10.8,27.6,71.9,68.71 +District of Columbia,1348.9,24.2,87.1,18.4,48.0,38.7,100 +Florida,612.6,5.5,85.3,14.9,26.6,76.9,87.44 +Georgia,432.6,6.0,83.9,16.5,29.3,61.9,65.38 +Hawaii,274.1,1.8,90.4,10.4,26.3,26.9,71.46 +Idaho,238.5,1.5,88.4,14.3,19.0,92.3,50.51 +Illinois,618.2,8.4,86.4,13.3,26.0,72.5,79.97 +Indiana,366.4,5.3,86.6,14.4,24.5,85.7,59.17 +Iowa,294.5,1.3,90.5,11.8,20.3,92.3,41.66 +Kansas ,412.0,4.7,89.7,13.4,22.8,86.3,50.17 +Kentucky ,265.5,4.3,81.7,18.6,25.4,88.8,40.99 +Louisiana,628.4,12.3,82.2,17.3,31.4,63.7,61.33 +Maine,119.9,2.0,90.2,12.3,22.0,94.9,26.21 +Maryland,590.0,7.7,88.2,9.1,27.3,60.2,83.53 +Massachusetts,465.6,2.7,89.0,10.3,25.0,82.4,90.3 +Michigan,504.4,6.3,87.9,16.2,25.6,79.9,66.37 +Minnesota,214.2,1.5,91.5,11.0,20.2,87.4,58 +Mississippi,306.7,6.9,80.4,21.9,32.8,59.6,27.62 +Missouri,500.3,6.6,86.8,14.6,25.3,83.9,56.61 +Montana ,283.9,3.2,90.8,15.1,20.3,89.4,26.49 +Nebraska,305.5,2.5,89.8,12.3,20.9,88.1,53.78 +Nevada,704.6,5.9,83.9,12.4,28.5,76.2,86.51 +New Hampshire,169.5,0.9,91.3,8.5,19.5,94.5,47.34 +New Jersey,311.3,3.7,87.4,9.4,25.8,70.7,92.24 +New Mexico,652.8,10.0,82.8,18.0,29.1,72.5,53.75 +New York,385.5,4.0,84.7,14.2,30.2,67.4,82.66 +North Carolina,414.0,5.4,84.3,16.3,26.3,70.5,54.88 +North Dakota,223.6,2.0,90.1,11.7,18.2,90.2,40 +Ohio,358.1,5.0,87.6,15.2,26.3,84,65.31 +Oklahoma,510.4,6.5,85.6,16.2,25.9,75.4,45.79 +Oregon,261.2,2.3,89.1,14.3,22.7,85.6,62.47 +Pennsylvania,388.9,5.4,87.9,12.5,24.5,83.5,70.68 +Rhode Island,254.3,3.0,84.7,11.5,27.3,82.6,90.46 +South Carolina,675.1,6.7,83.6,17.1,28.4,67.6,55.78 +South Dakota,201.0,3.6,89.9,14.2,20.8,86.3,29.92 +Tennessee,666.0,7.4,83.1,17.1,26.3,79.1,54.38 +Texas,491.4,5.4,79.9,17.2,27.6,73.8,75.35 +Utah,216.2,1.4,90.4,11.5,17.9,89.3,81.17 +Vermont,135.1,1.3,91.0,11.4,21.3,95.8,17.38 +Virginia,230.0,4.7,86.6,10.5,24.0,70.4,69.79 +Washington,338.3,2.8,89.7,12.3,22.2,80.2,74.97 +West Virginia,331.2,4.9,82.8,17.7,23.3,94.3,33.2 +Wisconsin,259.7,2.6,89.8,12.4,22.2,88.4,55.8 +Wyoming,219.3,2.0,91.8,9.8,18.9,91.3,24.51 diff --git a/shared/package-files/73/73ca4b2255b96d8ddead8da8246c831ca19071ae9bcc80259dcda2fda7a6fccb/mkldnn_linear_backward_weights_ops.h b/shared/package-files/73/73ca4b2255b96d8ddead8da8246c831ca19071ae9bcc80259dcda2fda7a6fccb/mkldnn_linear_backward_weights_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..ce9ae3041d664f991cc4f62a4a6697c5595f5d3f --- /dev/null +++ b/shared/package-files/73/73ca4b2255b96d8ddead8da8246c831ca19071ae9bcc80259dcda2fda7a6fccb/mkldnn_linear_backward_weights_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API mkldnn_linear_backward_weights { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::mkldnn_linear_backward_weights") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "mkldnn_linear_backward_weights(Tensor grad_output, Tensor input, Tensor weight, bool bias_defined) -> (Tensor, Tensor)") + static ::std::tuple call(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, bool bias_defined); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, bool bias_defined); +}; + +struct TORCH_API mkldnn_linear_backward_weights_out { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, bool, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::mkldnn_linear_backward_weights") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "mkldnn_linear_backward_weights.out(Tensor grad_output, Tensor input, Tensor weight, bool bias_defined, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!))") + static ::std::tuple call(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, bool bias_defined, at::Tensor & out0, at::Tensor & out1); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, bool bias_defined, at::Tensor & out0, at::Tensor & out1); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/73/73caabde698f5cb8b8d0de0d08b7291ef41e508ba836d6ecce4b23b6bb82d798/functional.py b/shared/package-files/73/73caabde698f5cb8b8d0de0d08b7291ef41e508ba836d6ecce4b23b6bb82d798/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..af34e707e552d6eae403278743b406988e16e9db --- /dev/null +++ b/shared/package-files/73/73caabde698f5cb8b8d0de0d08b7291ef41e508ba836d6ecce4b23b6bb82d798/functional.py @@ -0,0 +1,2535 @@ +# -*- coding: utf-8 -*- + +import math +import tempfile +import warnings +from collections.abc import Sequence +from typing import List, Optional, Tuple, Union + +import torch +import torchaudio +from torch import Tensor +from torchaudio._internal.module_utils import deprecated + +from .filtering import highpass_biquad, treble_biquad + +__all__ = [ + "spectrogram", + "inverse_spectrogram", + "griffinlim", + "amplitude_to_DB", + "DB_to_amplitude", + "compute_deltas", + "melscale_fbanks", + "linear_fbanks", + "create_dct", + "compute_deltas", + "detect_pitch_frequency", + "DB_to_amplitude", + "mu_law_encoding", + "mu_law_decoding", + "phase_vocoder", + "mask_along_axis", + "mask_along_axis_iid", + "sliding_window_cmn", + "spectral_centroid", + "apply_codec", + "resample", + "edit_distance", + "loudness", + "pitch_shift", + "rnnt_loss", + "psd", + "mvdr_weights_souden", + "mvdr_weights_rtf", + "rtf_evd", + "rtf_power", + "apply_beamforming", + "fftconvolve", + "convolve", + "add_noise", + "speed", + "preemphasis", + "deemphasis", +] + + +def spectrogram( + waveform: Tensor, + pad: int, + window: Tensor, + n_fft: int, + hop_length: int, + win_length: int, + power: Optional[float], + normalized: Union[bool, str], + center: bool = True, + pad_mode: str = "reflect", + onesided: bool = True, + return_complex: Optional[bool] = None, +) -> Tensor: + r"""Create a spectrogram or a batch of spectrograms from a raw audio signal. + The spectrogram can be either magnitude-only or complex. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Args: + waveform (Tensor): Tensor of audio of dimension `(..., time)` + pad (int): Two sided padding of signal + window (Tensor): Window tensor that is applied/multiplied to each frame/window + n_fft (int): Size of FFT + hop_length (int): Length of hop between STFT windows + win_length (int): Window size + power (float or None): Exponent for the magnitude spectrogram, + (must be > 0) e.g., 1 for magnitude, 2 for power, etc. + If None, then the complex spectrum is returned instead. + normalized (bool or str): Whether to normalize by magnitude after stft. If input is str, choices are + ``"window"`` and ``"frame_length"``, if specific normalization type is desirable. ``True`` maps to + ``"window"``. When normalized on ``"window"``, waveform is normalized upon the window's L2 energy. If + normalized on ``"frame_length"``, waveform is normalized by dividing by + :math:`(\text{frame\_length})^{0.5}`. + center (bool, optional): whether to pad :attr:`waveform` on both sides so + that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`. + Default: ``True`` + pad_mode (string, optional): controls the padding method used when + :attr:`center` is ``True``. Default: ``"reflect"`` + onesided (bool, optional): controls whether to return half of results to + avoid redundancy. Default: ``True`` + return_complex (bool, optional): + Deprecated and not used. + + Returns: + Tensor: Dimension `(..., freq, time)`, freq is + ``n_fft // 2 + 1`` and ``n_fft`` is the number of + Fourier bins, and time is the number of window hops (n_frame). + """ + if return_complex is not None: + warnings.warn( + "`return_complex` argument is now deprecated and is not effective." + "`torchaudio.functional.spectrogram(power=None)` always returns a tensor with " + "complex dtype. Please remove the argument in the function call." + ) + + if pad > 0: + # TODO add "with torch.no_grad():" back when JIT supports it + waveform = torch.nn.functional.pad(waveform, (pad, pad), "constant") + + frame_length_norm, window_norm = _get_spec_norms(normalized) + + # pack batch + shape = waveform.size() + waveform = waveform.reshape(-1, shape[-1]) + + # default values are consistent with librosa.core.spectrum._spectrogram + spec_f = torch.stft( + input=waveform, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=center, + pad_mode=pad_mode, + normalized=frame_length_norm, + onesided=onesided, + return_complex=True, + ) + + # unpack batch + spec_f = spec_f.reshape(shape[:-1] + spec_f.shape[-2:]) + + if window_norm: + spec_f /= window.pow(2.0).sum().sqrt() + if power is not None: + if power == 1.0: + return spec_f.abs() + return spec_f.abs().pow(power) + return spec_f + + +def inverse_spectrogram( + spectrogram: Tensor, + length: Optional[int], + pad: int, + window: Tensor, + n_fft: int, + hop_length: int, + win_length: int, + normalized: Union[bool, str], + center: bool = True, + pad_mode: str = "reflect", + onesided: bool = True, +) -> Tensor: + r"""Create an inverse spectrogram or a batch of inverse spectrograms from the provided + complex-valued spectrogram. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Args: + spectrogram (Tensor): Complex tensor of audio of dimension (..., freq, time). + length (int or None): The output length of the waveform. + pad (int): Two sided padding of signal. It is only effective when ``length`` is provided. + window (Tensor): Window tensor that is applied/multiplied to each frame/window + n_fft (int): Size of FFT + hop_length (int): Length of hop between STFT windows + win_length (int): Window size + normalized (bool or str): Whether the stft output was normalized by magnitude. If input is str, choices are + ``"window"`` and ``"frame_length"``, dependent on normalization mode. ``True`` maps to + ``"window"``. + center (bool, optional): whether the waveform was padded on both sides so + that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`. + Default: ``True`` + pad_mode (string, optional): controls the padding method used when + :attr:`center` is ``True``. This parameter is provided for compatibility with the + spectrogram function and is not used. Default: ``"reflect"`` + onesided (bool, optional): controls whether spectrogram was done in onesided mode. + Default: ``True`` + + Returns: + Tensor: Dimension `(..., time)`. Least squares estimation of the original signal. + """ + + frame_length_norm, window_norm = _get_spec_norms(normalized) + + if not spectrogram.is_complex(): + raise ValueError("Expected `spectrogram` to be complex dtype.") + + if window_norm: + spectrogram = spectrogram * window.pow(2.0).sum().sqrt() + + # pack batch + shape = spectrogram.size() + spectrogram = spectrogram.reshape(-1, shape[-2], shape[-1]) + + # default values are consistent with librosa.core.spectrum._spectrogram + waveform = torch.istft( + input=spectrogram, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=center, + normalized=frame_length_norm, + onesided=onesided, + length=length + 2 * pad if length is not None else None, + return_complex=False, + ) + + if length is not None and pad > 0: + # remove padding from front and back + waveform = waveform[:, pad:-pad] + + # unpack batch + waveform = waveform.reshape(shape[:-2] + waveform.shape[-1:]) + + return waveform + + +def _get_spec_norms(normalized: Union[str, bool]): + frame_length_norm, window_norm = False, False + if torch.jit.isinstance(normalized, str): + if normalized not in ["frame_length", "window"]: + raise ValueError("Invalid normalized parameter: {}".format(normalized)) + if normalized == "frame_length": + frame_length_norm = True + elif normalized == "window": + window_norm = True + elif torch.jit.isinstance(normalized, bool): + if normalized: + window_norm = True + else: + raise TypeError("Input type not supported") + return frame_length_norm, window_norm + + +def _get_complex_dtype(real_dtype: torch.dtype): + if real_dtype == torch.double: + return torch.cdouble + if real_dtype == torch.float: + return torch.cfloat + if real_dtype == torch.half: + return torch.complex32 + raise ValueError(f"Unexpected dtype {real_dtype}") + + +def griffinlim( + specgram: Tensor, + window: Tensor, + n_fft: int, + hop_length: int, + win_length: int, + power: float, + n_iter: int, + momentum: float, + length: Optional[int], + rand_init: bool, +) -> Tensor: + r"""Compute waveform from a linear scale magnitude spectrogram using the Griffin-Lim transformation. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Implementation ported from + *librosa* :cite:`brian_mcfee-proc-scipy-2015`, *A fast Griffin-Lim algorithm* :cite:`6701851` + and *Signal estimation from modified short-time Fourier transform* :cite:`1172092`. + + Args: + specgram (Tensor): A magnitude-only STFT spectrogram of dimension `(..., freq, frames)` + where freq is ``n_fft // 2 + 1``. + window (Tensor): Window tensor that is applied/multiplied to each frame/window + n_fft (int): Size of FFT, creates ``n_fft // 2 + 1`` bins + hop_length (int): Length of hop between STFT windows. ( + Default: ``win_length // 2``) + win_length (int): Window size. (Default: ``n_fft``) + power (float): Exponent for the magnitude spectrogram, + (must be > 0) e.g., 1 for magnitude, 2 for power, etc. + n_iter (int): Number of iteration for phase recovery process. + momentum (float): The momentum parameter for fast Griffin-Lim. + Setting this to 0 recovers the original Griffin-Lim method. + Values near 1 can lead to faster convergence, but above 1 may not converge. + length (int or None): Array length of the expected output. + rand_init (bool): Initializes phase randomly if True, to zero otherwise. + + Returns: + Tensor: waveform of `(..., time)`, where time equals the ``length`` parameter if given. + """ + if not 0 <= momentum < 1: + raise ValueError("momentum must be in range [0, 1). Found: {}".format(momentum)) + + momentum = momentum / (1 + momentum) + + # pack batch + shape = specgram.size() + specgram = specgram.reshape([-1] + list(shape[-2:])) + + specgram = specgram.pow(1 / power) + + # initialize the phase + if rand_init: + angles = torch.rand(specgram.size(), dtype=_get_complex_dtype(specgram.dtype), device=specgram.device) + else: + angles = torch.full(specgram.size(), 1, dtype=_get_complex_dtype(specgram.dtype), device=specgram.device) + + # And initialize the previous iterate to 0 + tprev = torch.tensor(0.0, dtype=specgram.dtype, device=specgram.device) + for _ in range(n_iter): + # Invert with our current estimate of the phases + inverse = torch.istft( + specgram * angles, n_fft=n_fft, hop_length=hop_length, win_length=win_length, window=window, length=length + ) + + # Rebuild the spectrogram + rebuilt = torch.stft( + input=inverse, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=True, + pad_mode="reflect", + normalized=False, + onesided=True, + return_complex=True, + ) + + # Update our phase estimates + angles = rebuilt + if momentum: + angles = angles - tprev.mul_(momentum) + angles = angles.div(angles.abs().add(1e-16)) + + # Store the previous iterate + tprev = rebuilt + + # Return the final phase estimates + waveform = torch.istft( + specgram * angles, n_fft=n_fft, hop_length=hop_length, win_length=win_length, window=window, length=length + ) + + # unpack batch + waveform = waveform.reshape(shape[:-2] + waveform.shape[-1:]) + + return waveform + + +def amplitude_to_DB( + x: Tensor, multiplier: float, amin: float, db_multiplier: float, top_db: Optional[float] = None +) -> Tensor: + r"""Turn a spectrogram from the power/amplitude scale to the decibel scale. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + The output of each tensor in a batch depends on the maximum value of that tensor, + and so may return different values for an audio clip split into snippets vs. a full clip. + + Args: + + x (Tensor): Input spectrogram(s) before being converted to decibel scale. + The expected shapes are ``(freq, time)``, ``(channel, freq, time)`` or + ``(..., batch, channel, freq, time)``. + + .. note:: + + When ``top_db`` is specified, cut-off values are computed for each audio + in the batch. Therefore if the input shape is 4D (or larger), different + cut-off values are used for audio data in the batch. + If the input shape is 2D or 3D, a single cutoff value is used. + + multiplier (float): Use 10. for power and 20. for amplitude + amin (float): Number to clamp ``x`` + db_multiplier (float): Log10(max(reference value and amin)) + top_db (float or None, optional): Minimum negative cut-off in decibels. A reasonable number + is 80. (Default: ``None``) + + Returns: + Tensor: Output tensor in decibel scale + """ + x_db = multiplier * torch.log10(torch.clamp(x, min=amin)) + x_db -= multiplier * db_multiplier + + if top_db is not None: + # Expand batch + shape = x_db.size() + packed_channels = shape[-3] if x_db.dim() > 2 else 1 + x_db = x_db.reshape(-1, packed_channels, shape[-2], shape[-1]) + + x_db = torch.max(x_db, (x_db.amax(dim=(-3, -2, -1)) - top_db).view(-1, 1, 1, 1)) + + # Repack batch + x_db = x_db.reshape(shape) + + return x_db + + +def DB_to_amplitude(x: Tensor, ref: float, power: float) -> Tensor: + r"""Turn a tensor from the decibel scale to the power/amplitude scale. + + .. devices:: CPU CUDA + + .. properties:: TorchScript + + Args: + x (Tensor): Input tensor before being converted to power/amplitude scale. + ref (float): Reference which the output will be scaled by. + power (float): If power equals 1, will compute DB to power. If 0.5, will compute DB to amplitude. + + Returns: + Tensor: Output tensor in power/amplitude scale. + """ + return ref * torch.pow(torch.pow(10.0, 0.1 * x), power) + + +def _hz_to_mel(freq: float, mel_scale: str = "htk") -> float: + r"""Convert Hz to Mels. + + Args: + freqs (float): Frequencies in Hz + mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``) + + Returns: + mels (float): Frequency in Mels + """ + + if mel_scale not in ["slaney", "htk"]: + raise ValueError('mel_scale should be one of "htk" or "slaney".') + + if mel_scale == "htk": + return 2595.0 * math.log10(1.0 + (freq / 700.0)) + + # Fill in the linear part + f_min = 0.0 + f_sp = 200.0 / 3 + + mels = (freq - f_min) / f_sp + + # Fill in the log-scale part + min_log_hz = 1000.0 + min_log_mel = (min_log_hz - f_min) / f_sp + logstep = math.log(6.4) / 27.0 + + if freq >= min_log_hz: + mels = min_log_mel + math.log(freq / min_log_hz) / logstep + + return mels + + +def _mel_to_hz(mels: Tensor, mel_scale: str = "htk") -> Tensor: + """Convert mel bin numbers to frequencies. + + Args: + mels (Tensor): Mel frequencies + mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``) + + Returns: + freqs (Tensor): Mels converted in Hz + """ + + if mel_scale not in ["slaney", "htk"]: + raise ValueError('mel_scale should be one of "htk" or "slaney".') + + if mel_scale == "htk": + return 700.0 * (10.0 ** (mels / 2595.0) - 1.0) + + # Fill in the linear scale + f_min = 0.0 + f_sp = 200.0 / 3 + freqs = f_min + f_sp * mels + + # And now the nonlinear scale + min_log_hz = 1000.0 + min_log_mel = (min_log_hz - f_min) / f_sp + logstep = math.log(6.4) / 27.0 + + log_t = mels >= min_log_mel + freqs[log_t] = min_log_hz * torch.exp(logstep * (mels[log_t] - min_log_mel)) + + return freqs + + +def _create_triangular_filterbank( + all_freqs: Tensor, + f_pts: Tensor, +) -> Tensor: + """Create a triangular filter bank. + + Args: + all_freqs (Tensor): STFT freq points of size (`n_freqs`). + f_pts (Tensor): Filter mid points of size (`n_filter`). + + Returns: + fb (Tensor): The filter bank of size (`n_freqs`, `n_filter`). + """ + # Adopted from Librosa + # calculate the difference between each filter mid point and each stft freq point in hertz + f_diff = f_pts[1:] - f_pts[:-1] # (n_filter + 1) + slopes = f_pts.unsqueeze(0) - all_freqs.unsqueeze(1) # (n_freqs, n_filter + 2) + # create overlapping triangles + zero = torch.zeros(1) + down_slopes = (-1.0 * slopes[:, :-2]) / f_diff[:-1] # (n_freqs, n_filter) + up_slopes = slopes[:, 2:] / f_diff[1:] # (n_freqs, n_filter) + fb = torch.max(zero, torch.min(down_slopes, up_slopes)) + + return fb + + +def melscale_fbanks( + n_freqs: int, + f_min: float, + f_max: float, + n_mels: int, + sample_rate: int, + norm: Optional[str] = None, + mel_scale: str = "htk", +) -> Tensor: + r"""Create a frequency bin conversion matrix. + + .. devices:: CPU + + .. properties:: TorchScript + + Note: + For the sake of the numerical compatibility with librosa, not all the coefficients + in the resulting filter bank has magnitude of 1. + + .. image:: https://download.pytorch.org/torchaudio/doc-assets/mel_fbanks.png + :alt: Visualization of generated filter bank + + Args: + n_freqs (int): Number of frequencies to highlight/apply + f_min (float): Minimum frequency (Hz) + f_max (float): Maximum frequency (Hz) + n_mels (int): Number of mel filterbanks + sample_rate (int): Sample rate of the audio waveform + norm (str or None, optional): If "slaney", divide the triangular mel weights by the width of the mel band + (area normalization). (Default: ``None``) + mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``) + + Returns: + Tensor: Triangular filter banks (fb matrix) of size (``n_freqs``, ``n_mels``) + meaning number of frequencies to highlight/apply to x the number of filterbanks. + Each column is a filterbank so that assuming there is a matrix A of + size (..., ``n_freqs``), the applied result would be + ``A @ melscale_fbanks(A.size(-1), ...)``. + + """ + + if norm is not None and norm != "slaney": + raise ValueError('norm must be one of None or "slaney"') + + # freq bins + all_freqs = torch.linspace(0, sample_rate // 2, n_freqs) + + # calculate mel freq bins + m_min = _hz_to_mel(f_min, mel_scale=mel_scale) + m_max = _hz_to_mel(f_max, mel_scale=mel_scale) + + m_pts = torch.linspace(m_min, m_max, n_mels + 2) + f_pts = _mel_to_hz(m_pts, mel_scale=mel_scale) + + # create filterbank + fb = _create_triangular_filterbank(all_freqs, f_pts) + + if norm is not None and norm == "slaney": + # Slaney-style mel is scaled to be approx constant energy per channel + enorm = 2.0 / (f_pts[2 : n_mels + 2] - f_pts[:n_mels]) + fb *= enorm.unsqueeze(0) + + if (fb.max(dim=0).values == 0.0).any(): + warnings.warn( + "At least one mel filterbank has all zero values. " + f"The value for `n_mels` ({n_mels}) may be set too high. " + f"Or, the value for `n_freqs` ({n_freqs}) may be set too low." + ) + + return fb + + +def linear_fbanks( + n_freqs: int, + f_min: float, + f_max: float, + n_filter: int, + sample_rate: int, +) -> Tensor: + r"""Creates a linear triangular filterbank. + + .. devices:: CPU + + .. properties:: TorchScript + + Note: + For the sake of the numerical compatibility with librosa, not all the coefficients + in the resulting filter bank has magnitude of 1. + + .. image:: https://download.pytorch.org/torchaudio/doc-assets/lin_fbanks.png + :alt: Visualization of generated filter bank + + Args: + n_freqs (int): Number of frequencies to highlight/apply + f_min (float): Minimum frequency (Hz) + f_max (float): Maximum frequency (Hz) + n_filter (int): Number of (linear) triangular filter + sample_rate (int): Sample rate of the audio waveform + + Returns: + Tensor: Triangular filter banks (fb matrix) of size (``n_freqs``, ``n_filter``) + meaning number of frequencies to highlight/apply to x the number of filterbanks. + Each column is a filterbank so that assuming there is a matrix A of + size (..., ``n_freqs``), the applied result would be + ``A * linear_fbanks(A.size(-1), ...)``. + """ + # freq bins + all_freqs = torch.linspace(0, sample_rate // 2, n_freqs) + + # filter mid-points + f_pts = torch.linspace(f_min, f_max, n_filter + 2) + + # create filterbank + fb = _create_triangular_filterbank(all_freqs, f_pts) + + return fb + + +def create_dct(n_mfcc: int, n_mels: int, norm: Optional[str]) -> Tensor: + r"""Create a DCT transformation matrix with shape (``n_mels``, ``n_mfcc``), + normalized depending on norm. + + .. devices:: CPU + + .. properties:: TorchScript + + Args: + n_mfcc (int): Number of mfc coefficients to retain + n_mels (int): Number of mel filterbanks + norm (str or None): Norm to use (either "ortho" or None) + + Returns: + Tensor: The transformation matrix, to be right-multiplied to + row-wise data of size (``n_mels``, ``n_mfcc``). + """ + + if norm is not None and norm != "ortho": + raise ValueError('norm must be either "ortho" or None') + + # http://en.wikipedia.org/wiki/Discrete_cosine_transform#DCT-II + n = torch.arange(float(n_mels)) + k = torch.arange(float(n_mfcc)).unsqueeze(1) + dct = torch.cos(math.pi / float(n_mels) * (n + 0.5) * k) # size (n_mfcc, n_mels) + + if norm is None: + dct *= 2.0 + else: + dct[0] *= 1.0 / math.sqrt(2.0) + dct *= math.sqrt(2.0 / float(n_mels)) + return dct.t() + + +def mu_law_encoding(x: Tensor, quantization_channels: int) -> Tensor: + r"""Encode signal based on mu-law companding. + + .. devices:: CPU CUDA + + .. properties:: TorchScript + + For more info see the + `Wikipedia Entry `_ + + This algorithm expects the signal has been scaled to between -1 and 1 and + returns a signal encoded with values from 0 to quantization_channels - 1. + + Args: + x (Tensor): Input tensor + quantization_channels (int): Number of channels + + Returns: + Tensor: Input after mu-law encoding + """ + mu = quantization_channels - 1.0 + if not x.is_floating_point(): + warnings.warn( + "The input Tensor must be of floating type. \ + This will be an error in the v0.12 release." + ) + x = x.to(torch.float) + mu = torch.tensor(mu, dtype=x.dtype) + x_mu = torch.sign(x) * torch.log1p(mu * torch.abs(x)) / torch.log1p(mu) + x_mu = ((x_mu + 1) / 2 * mu + 0.5).to(torch.int64) + return x_mu + + +def mu_law_decoding(x_mu: Tensor, quantization_channels: int) -> Tensor: + r"""Decode mu-law encoded signal. + + .. devices:: CPU CUDA + + .. properties:: TorchScript + + For more info see the + `Wikipedia Entry `_ + + This expects an input with values between 0 and quantization_channels - 1 + and returns a signal scaled between -1 and 1. + + Args: + x_mu (Tensor): Input tensor + quantization_channels (int): Number of channels + + Returns: + Tensor: Input after mu-law decoding + """ + mu = quantization_channels - 1.0 + if not x_mu.is_floating_point(): + x_mu = x_mu.to(torch.float) + mu = torch.tensor(mu, dtype=x_mu.dtype) + x = ((x_mu) / mu) * 2 - 1.0 + x = torch.sign(x) * (torch.exp(torch.abs(x) * torch.log1p(mu)) - 1.0) / mu + return x + + +def phase_vocoder(complex_specgrams: Tensor, rate: float, phase_advance: Tensor) -> Tensor: + r"""Given a STFT tensor, speed up in time without modifying pitch by a factor of ``rate``. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Args: + complex_specgrams (Tensor): + A tensor of dimension `(..., freq, num_frame)` with complex dtype. + rate (float): Speed-up factor + phase_advance (Tensor): Expected phase advance in each bin. Dimension of `(freq, 1)` + + Returns: + Tensor: + Stretched spectrogram. The resulting tensor is of the same dtype as the input + spectrogram, but the number of frames is changed to ``ceil(num_frame / rate)``. + + Example + >>> freq, hop_length = 1025, 512 + >>> # (channel, freq, time) + >>> complex_specgrams = torch.randn(2, freq, 300, dtype=torch.cfloat) + >>> rate = 1.3 # Speed up by 30% + >>> phase_advance = torch.linspace( + >>> 0, math.pi * hop_length, freq)[..., None] + >>> x = phase_vocoder(complex_specgrams, rate, phase_advance) + >>> x.shape # with 231 == ceil(300 / 1.3) + torch.Size([2, 1025, 231]) + """ + if rate == 1.0: + return complex_specgrams + + # pack batch + shape = complex_specgrams.size() + complex_specgrams = complex_specgrams.reshape([-1] + list(shape[-2:])) + + # Figures out the corresponding real dtype, i.e. complex128 -> float64, complex64 -> float32 + # Note torch.real is a view so it does not incur any memory copy. + real_dtype = torch.real(complex_specgrams).dtype + time_steps = torch.arange(0, complex_specgrams.size(-1), rate, device=complex_specgrams.device, dtype=real_dtype) + + alphas = time_steps % 1.0 + phase_0 = complex_specgrams[..., :1].angle() + + # Time Padding + complex_specgrams = torch.nn.functional.pad(complex_specgrams, [0, 2]) + + # (new_bins, freq, 2) + complex_specgrams_0 = complex_specgrams.index_select(-1, time_steps.long()) + complex_specgrams_1 = complex_specgrams.index_select(-1, (time_steps + 1).long()) + + angle_0 = complex_specgrams_0.angle() + angle_1 = complex_specgrams_1.angle() + + norm_0 = complex_specgrams_0.abs() + norm_1 = complex_specgrams_1.abs() + + phase = angle_1 - angle_0 - phase_advance + phase = phase - 2 * math.pi * torch.round(phase / (2 * math.pi)) + + # Compute Phase Accum + phase = phase + phase_advance + phase = torch.cat([phase_0, phase[..., :-1]], dim=-1) + phase_acc = torch.cumsum(phase, -1) + + mag = alphas * norm_1 + (1 - alphas) * norm_0 + + complex_specgrams_stretch = torch.polar(mag, phase_acc) + + # unpack batch + complex_specgrams_stretch = complex_specgrams_stretch.reshape(shape[:-2] + complex_specgrams_stretch.shape[1:]) + return complex_specgrams_stretch + + +def _get_mask_param(mask_param: int, p: float, axis_length: int) -> int: + if p == 1.0: + return mask_param + else: + return min(mask_param, int(axis_length * p)) + + +def mask_along_axis_iid( + specgrams: Tensor, + mask_param: int, + mask_value: float, + axis: int, + p: float = 1.0, +) -> Tensor: + r"""Apply a mask along ``axis``. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Mask will be applied from indices ``[v_0, v_0 + v)``, + where ``v`` is sampled from ``uniform(0, max_v)`` and + ``v_0`` from ``uniform(0, specgrams.size(axis) - v)``, + with ``max_v = mask_param`` when ``p = 1.0`` and + ``max_v = min(mask_param, floor(specgrams.size(axis) * p))`` otherwise. + + Args: + specgrams (Tensor): Real spectrograms `(..., freq, time)`, with at least 3 dimensions. + mask_param (int): Number of columns to be masked will be uniformly sampled from [0, mask_param] + mask_value (float): Value to assign to the masked columns + axis (int): Axis to apply masking on, which should be the one of the last two dimensions. + p (float, optional): maximum proportion of columns that can be masked. (Default: 1.0) + + Returns: + Tensor: Masked spectrograms with the same dimensions as input specgrams Tensor` + """ + + dim = specgrams.dim() + + if dim < 3: + raise ValueError(f"Spectrogram must have at least three dimensions ({dim} given).") + + if axis not in [dim - 2, dim - 1]: + raise ValueError( + f"Only Frequency and Time masking are supported (axis {dim-2} and axis {dim-1} supported; {axis} given)." + ) + + if not 0.0 <= p <= 1.0: + raise ValueError(f"The value of p must be between 0.0 and 1.0 ({p} given).") + + mask_param = _get_mask_param(mask_param, p, specgrams.shape[axis]) + if mask_param < 1: + return specgrams + + device = specgrams.device + dtype = specgrams.dtype + + value = torch.rand(specgrams.shape[: (dim - 2)], device=device, dtype=dtype) * mask_param + min_value = torch.rand(specgrams.shape[: (dim - 2)], device=device, dtype=dtype) * (specgrams.size(axis) - value) + + # Create broadcastable mask + mask_start = min_value.long()[..., None, None] + mask_end = (min_value.long() + value.long())[..., None, None] + mask = torch.arange(0, specgrams.size(axis), device=device, dtype=dtype) + + # Per batch example masking + specgrams = specgrams.transpose(axis, -1) + specgrams = specgrams.masked_fill((mask >= mask_start) & (mask < mask_end), mask_value) + specgrams = specgrams.transpose(axis, -1) + + return specgrams + + +def mask_along_axis( + specgram: Tensor, + mask_param: int, + mask_value: float, + axis: int, + p: float = 1.0, +) -> Tensor: + r"""Apply a mask along ``axis``. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Mask will be applied from indices ``[v_0, v_0 + v)``, + where ``v`` is sampled from ``uniform(0, max_v)`` and + ``v_0`` from ``uniform(0, specgram.size(axis) - v)``, with + ``max_v = mask_param`` when ``p = 1.0`` and + ``max_v = min(mask_param, floor(specgram.size(axis) * p))`` + otherwise. + All examples will have the same mask interval. + + Args: + specgram (Tensor): Real spectrograms `(..., freq, time)`, with at least 2 dimensions. + mask_param (int): Number of columns to be masked will be uniformly sampled from [0, mask_param] + mask_value (float): Value to assign to the masked columns + axis (int): Axis to apply masking on, which should be the one of the last two dimensions. + p (float, optional): maximum proportion of columns that can be masked. (Default: 1.0) + + Returns: + Tensor: Masked spectrograms with the same dimensions as input specgram Tensor + """ + dim = specgram.dim() + + if dim < 2: + raise ValueError(f"Spectrogram must have at least two dimensions (time and frequency) ({dim} given).") + + if axis not in [dim - 2, dim - 1]: + raise ValueError( + f"Only Frequency and Time masking are supported (axis {dim-2} and axis {dim-1} supported; {axis} given)." + ) + + if not 0.0 <= p <= 1.0: + raise ValueError(f"The value of p must be between 0.0 and 1.0 ({p} given).") + + mask_param = _get_mask_param(mask_param, p, specgram.shape[axis]) + if mask_param < 1: + return specgram + + # pack batch + shape = specgram.size() + specgram = specgram.reshape([-1] + list(shape[-2:])) + # After packing, specgram is a 3D tensor, and the axis corresponding to the to-be-masked dimension + # is now (axis - dim + 3), e.g. a tensor of shape (10, 2, 50, 10, 2) becomes a tensor of shape (1000, 10, 2). + value = torch.rand(1) * mask_param + min_value = torch.rand(1) * (specgram.size(axis - dim + 3) - value) + + mask_start = (min_value.long()).squeeze() + mask_end = (min_value.long() + value.long()).squeeze() + mask = torch.arange(0, specgram.shape[axis - dim + 3], device=specgram.device, dtype=specgram.dtype) + mask = (mask >= mask_start) & (mask < mask_end) + # unsqueeze the mask if the axis is frequency + if axis == dim - 2: + mask = mask.unsqueeze(-1) + + if mask_end - mask_start >= mask_param: + raise ValueError("Number of columns to be masked should be less than mask_param") + + specgram = specgram.masked_fill(mask, mask_value) + + # unpack batch + specgram = specgram.reshape(shape[:-2] + specgram.shape[-2:]) + + return specgram + + +def compute_deltas(specgram: Tensor, win_length: int = 5, mode: str = "replicate") -> Tensor: + r"""Compute delta coefficients of a tensor, usually a spectrogram: + + .. devices:: CPU CUDA + + .. properties:: TorchScript + + .. math:: + d_t = \frac{\sum_{n=1}^{\text{N}} n (c_{t+n} - c_{t-n})}{2 \sum_{n=1}^{\text{N}} n^2} + + where :math:`d_t` is the deltas at time :math:`t`, + :math:`c_t` is the spectrogram coeffcients at time :math:`t`, + :math:`N` is ``(win_length-1)//2``. + + Args: + specgram (Tensor): Tensor of audio of dimension `(..., freq, time)` + win_length (int, optional): The window length used for computing delta (Default: ``5``) + mode (str, optional): Mode parameter passed to padding (Default: ``"replicate"``) + + Returns: + Tensor: Tensor of deltas of dimension `(..., freq, time)` + + Example + >>> specgram = torch.randn(1, 40, 1000) + >>> delta = compute_deltas(specgram) + >>> delta2 = compute_deltas(delta) + """ + device = specgram.device + dtype = specgram.dtype + + # pack batch + shape = specgram.size() + specgram = specgram.reshape(1, -1, shape[-1]) + + if win_length < 3: + raise ValueError(f"Window length should be greater than or equal to 3. Found win_length {win_length}") + + n = (win_length - 1) // 2 + + # twice sum of integer squared + denom = n * (n + 1) * (2 * n + 1) / 3 + + specgram = torch.nn.functional.pad(specgram, (n, n), mode=mode) + + kernel = torch.arange(-n, n + 1, 1, device=device, dtype=dtype).repeat(specgram.shape[1], 1, 1) + + output = torch.nn.functional.conv1d(specgram, kernel, groups=specgram.shape[1]) / denom + + # unpack batch + output = output.reshape(shape) + + return output + + +def _compute_nccf(waveform: Tensor, sample_rate: int, frame_time: float, freq_low: int) -> Tensor: + r""" + Compute Normalized Cross-Correlation Function (NCCF). + + .. math:: + \phi_i(m) = \frac{\sum_{n=b_i}^{b_i + N-1} w(n) w(m+n)}{\sqrt{E(b_i) E(m+b_i)}}, + + where + :math:`\phi_i(m)` is the NCCF at frame :math:`i` with lag :math:`m`, + :math:`w` is the waveform, + :math:`N` is the length of a frame, + :math:`b_i` is the beginning of frame :math:`i`, + :math:`E(j)` is the energy :math:`\sum_{n=j}^{j+N-1} w^2(n)`. + """ + + EPSILON = 10 ** (-9) + + # Number of lags to check + lags = int(math.ceil(sample_rate / freq_low)) + + frame_size = int(math.ceil(sample_rate * frame_time)) + + waveform_length = waveform.size()[-1] + num_of_frames = int(math.ceil(waveform_length / frame_size)) + + p = lags + num_of_frames * frame_size - waveform_length + waveform = torch.nn.functional.pad(waveform, (0, p)) + + # Compute lags + output_lag = [] + for lag in range(1, lags + 1): + s1 = waveform[..., :-lag].unfold(-1, frame_size, frame_size)[..., :num_of_frames, :] + s2 = waveform[..., lag:].unfold(-1, frame_size, frame_size)[..., :num_of_frames, :] + + output_frames = ( + (s1 * s2).sum(-1) + / (EPSILON + torch.linalg.vector_norm(s1, ord=2, dim=-1)).pow(2) + / (EPSILON + torch.linalg.vector_norm(s2, ord=2, dim=-1)).pow(2) + ) + + output_lag.append(output_frames.unsqueeze(-1)) + + nccf = torch.cat(output_lag, -1) + + return nccf + + +def _combine_max(a: Tuple[Tensor, Tensor], b: Tuple[Tensor, Tensor], thresh: float = 0.99) -> Tuple[Tensor, Tensor]: + """ + Take value from first if bigger than a multiplicative factor of the second, elementwise. + """ + mask = a[0] > thresh * b[0] + values = mask * a[0] + ~mask * b[0] + indices = mask * a[1] + ~mask * b[1] + return values, indices + + +def _find_max_per_frame(nccf: Tensor, sample_rate: int, freq_high: int) -> Tensor: + r""" + For each frame, take the highest value of NCCF, + apply centered median smoothing, and convert to frequency. + + Note: If the max among all the lags is very close + to the first half of lags, then the latter is taken. + """ + + lag_min = int(math.ceil(sample_rate / freq_high)) + + # Find near enough max that is smallest + + best = torch.max(nccf[..., lag_min:], -1) + + half_size = nccf.shape[-1] // 2 + half = torch.max(nccf[..., lag_min:half_size], -1) + + best = _combine_max(half, best) + indices = best[1] + + # Add back minimal lag + indices += lag_min + # Add 1 empirical calibration offset + indices += 1 + + return indices + + +def _median_smoothing(indices: Tensor, win_length: int) -> Tensor: + r""" + Apply median smoothing to the 1D tensor over the given window. + """ + + # Centered windowed + pad_length = (win_length - 1) // 2 + + # "replicate" padding in any dimension + indices = torch.nn.functional.pad(indices, (pad_length, 0), mode="constant", value=0.0) + + indices[..., :pad_length] = torch.cat(pad_length * [indices[..., pad_length].unsqueeze(-1)], dim=-1) + roll = indices.unfold(-1, win_length, 1) + + values, _ = torch.median(roll, -1) + return values + + +def detect_pitch_frequency( + waveform: Tensor, + sample_rate: int, + frame_time: float = 10 ** (-2), + win_length: int = 30, + freq_low: int = 85, + freq_high: int = 3400, +) -> Tensor: + r"""Detect pitch frequency. + + .. devices:: CPU CUDA + + .. properties:: TorchScript + + It is implemented using normalized cross-correlation function and median smoothing. + + Args: + waveform (Tensor): Tensor of audio of dimension `(..., freq, time)` + sample_rate (int): The sample rate of the waveform (Hz) + frame_time (float, optional): Duration of a frame (Default: ``10 ** (-2)``). + win_length (int, optional): The window length for median smoothing (in number of frames) (Default: ``30``). + freq_low (int, optional): Lowest frequency that can be detected (Hz) (Default: ``85``). + freq_high (int, optional): Highest frequency that can be detected (Hz) (Default: ``3400``). + + Returns: + Tensor: Tensor of freq of dimension `(..., frame)` + """ + # pack batch + shape = list(waveform.size()) + waveform = waveform.reshape([-1] + shape[-1:]) + + nccf = _compute_nccf(waveform, sample_rate, frame_time, freq_low) + indices = _find_max_per_frame(nccf, sample_rate, freq_high) + indices = _median_smoothing(indices, win_length) + + # Convert indices to frequency + EPSILON = 10 ** (-9) + freq = sample_rate / (EPSILON + indices.to(torch.float)) + + # unpack batch + freq = freq.reshape(shape[:-1] + list(freq.shape[-1:])) + + return freq + + +def sliding_window_cmn( + specgram: Tensor, + cmn_window: int = 600, + min_cmn_window: int = 100, + center: bool = False, + norm_vars: bool = False, +) -> Tensor: + r""" + Apply sliding-window cepstral mean (and optionally variance) normalization per utterance. + + .. devices:: CPU CUDA + + .. properties:: TorchScript + + Args: + specgram (Tensor): Tensor of spectrogram of dimension `(..., time, freq)` + cmn_window (int, optional): Window in frames for running average CMN computation (int, default = 600) + min_cmn_window (int, optional): Minimum CMN window used at start of decoding (adds latency only at start). + Only applicable if center == false, ignored if center==true (int, default = 100) + center (bool, optional): If true, use a window centered on the current frame + (to the extent possible, modulo end effects). If false, window is to the left. (bool, default = false) + norm_vars (bool, optional): If true, normalize variance to one. (bool, default = false) + + Returns: + Tensor: Tensor matching input shape `(..., freq, time)` + """ + input_shape = specgram.shape + num_frames, num_feats = input_shape[-2:] + specgram = specgram.view(-1, num_frames, num_feats) + num_channels = specgram.shape[0] + + dtype = specgram.dtype + device = specgram.device + last_window_start = last_window_end = -1 + cur_sum = torch.zeros(num_channels, num_feats, dtype=dtype, device=device) + cur_sumsq = torch.zeros(num_channels, num_feats, dtype=dtype, device=device) + cmn_specgram = torch.zeros(num_channels, num_frames, num_feats, dtype=dtype, device=device) + for t in range(num_frames): + window_start = 0 + window_end = 0 + if center: + window_start = t - cmn_window // 2 + window_end = window_start + cmn_window + else: + window_start = t - cmn_window + window_end = t + 1 + if window_start < 0: + window_end -= window_start + window_start = 0 + if not center: + if window_end > t: + window_end = max(t + 1, min_cmn_window) + if window_end > num_frames: + window_start -= window_end - num_frames + window_end = num_frames + if window_start < 0: + window_start = 0 + if last_window_start == -1: + input_part = specgram[:, window_start : window_end - window_start, :] + cur_sum += torch.sum(input_part, 1) + if norm_vars: + cur_sumsq += torch.cumsum(input_part**2, 1)[:, -1, :] + else: + if window_start > last_window_start: + frame_to_remove = specgram[:, last_window_start, :] + cur_sum -= frame_to_remove + if norm_vars: + cur_sumsq -= frame_to_remove**2 + if window_end > last_window_end: + frame_to_add = specgram[:, last_window_end, :] + cur_sum += frame_to_add + if norm_vars: + cur_sumsq += frame_to_add**2 + window_frames = window_end - window_start + last_window_start = window_start + last_window_end = window_end + cmn_specgram[:, t, :] = specgram[:, t, :] - cur_sum / window_frames + if norm_vars: + if window_frames == 1: + cmn_specgram[:, t, :] = torch.zeros(num_channels, num_feats, dtype=dtype, device=device) + else: + variance = cur_sumsq + variance = variance / window_frames + variance -= (cur_sum**2) / (window_frames**2) + variance = torch.pow(variance, -0.5) + cmn_specgram[:, t, :] *= variance + + cmn_specgram = cmn_specgram.view(input_shape[:-2] + (num_frames, num_feats)) + if len(input_shape) == 2: + cmn_specgram = cmn_specgram.squeeze(0) + return cmn_specgram + + +def spectral_centroid( + waveform: Tensor, + sample_rate: int, + pad: int, + window: Tensor, + n_fft: int, + hop_length: int, + win_length: int, +) -> Tensor: + r"""Compute the spectral centroid for each channel along the time axis. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + The spectral centroid is defined as the weighted average of the + frequency values, weighted by their magnitude. + + Args: + waveform (Tensor): Tensor of audio of dimension `(..., time)` + sample_rate (int): Sample rate of the audio waveform + pad (int): Two sided padding of signal + window (Tensor): Window tensor that is applied/multiplied to each frame/window + n_fft (int): Size of FFT + hop_length (int): Length of hop between STFT windows + win_length (int): Window size + + Returns: + Tensor: Dimension `(..., time)` + """ + specgram = spectrogram( + waveform, + pad=pad, + window=window, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + power=1.0, + normalized=False, + ) + freqs = torch.linspace(0, sample_rate // 2, steps=1 + n_fft // 2, device=specgram.device).reshape((-1, 1)) + freq_dim = -2 + return (freqs * specgram).sum(dim=freq_dim) / specgram.sum(dim=freq_dim) + + +@deprecated("Please migrate to :py:class:`torchaudio.io.AudioEffector`.", remove=False) +def apply_codec( + waveform: Tensor, + sample_rate: int, + format: str, + channels_first: bool = True, + compression: Optional[float] = None, + encoding: Optional[str] = None, + bits_per_sample: Optional[int] = None, +) -> Tensor: + r""" + Apply codecs as a form of augmentation. + + .. devices:: CPU + + Args: + waveform (Tensor): Audio data. Must be 2 dimensional. See also ```channels_first```. + sample_rate (int): Sample rate of the audio waveform. + format (str): File format. + channels_first (bool, optional): + When True, both the input and output Tensor have dimension `(channel, time)`. + Otherwise, they have dimension `(time, channel)`. + compression (float or None, optional): Used for formats other than WAV. + For more details see :py:func:`torchaudio.backend.sox_io_backend.save`. + encoding (str or None, optional): Changes the encoding for the supported formats. + For more details see :py:func:`torchaudio.backend.sox_io_backend.save`. + bits_per_sample (int or None, optional): Changes the bit depth for the supported formats. + For more details see :py:func:`torchaudio.backend.sox_io_backend.save`. + + Returns: + Tensor: Resulting Tensor. + If ``channels_first=True``, it has `(channel, time)` else `(time, channel)`. + """ + from torchaudio.backend import _sox_io_backend + + with tempfile.NamedTemporaryFile() as f: + torchaudio.backend._sox_io_backend.save( + f.name, waveform, sample_rate, channels_first, compression, format, encoding, bits_per_sample + ) + augmented, sr = _sox_io_backend.load(f.name, channels_first=channels_first, format=format) + if sr != sample_rate: + augmented = resample(augmented, sr, sample_rate) + return augmented + + +_CPU = torch.device("cpu") + + +def _get_sinc_resample_kernel( + orig_freq: int, + new_freq: int, + gcd: int, + lowpass_filter_width: int = 6, + rolloff: float = 0.99, + resampling_method: str = "sinc_interp_hann", + beta: Optional[float] = None, + device: torch.device = _CPU, + dtype: Optional[torch.dtype] = None, +): + if not (int(orig_freq) == orig_freq and int(new_freq) == new_freq): + raise Exception( + "Frequencies must be of integer type to ensure quality resampling computation. " + "To work around this, manually convert both frequencies to integer values " + "that maintain their resampling rate ratio before passing them into the function. " + "Example: To downsample a 44100 hz waveform by a factor of 8, use " + "`orig_freq=8` and `new_freq=1` instead of `orig_freq=44100` and `new_freq=5512.5`. " + "For more information, please refer to https://github.com/pytorch/audio/issues/1487." + ) + + if resampling_method in ["sinc_interpolation", "kaiser_window"]: + method_map = { + "sinc_interpolation": "sinc_interp_hann", + "kaiser_window": "sinc_interp_kaiser", + } + warnings.warn( + f'"{resampling_method}" resampling method name is being deprecated and replaced by ' + f'"{method_map[resampling_method]}" in the next release. ' + "The default behavior remains unchanged.", + stacklevel=3, + ) + elif resampling_method not in ["sinc_interp_hann", "sinc_interp_kaiser"]: + raise ValueError("Invalid resampling method: {}".format(resampling_method)) + + orig_freq = int(orig_freq) // gcd + new_freq = int(new_freq) // gcd + + if lowpass_filter_width <= 0: + raise ValueError("Low pass filter width should be positive.") + base_freq = min(orig_freq, new_freq) + # This will perform antialiasing filtering by removing the highest frequencies. + # At first I thought I only needed this when downsampling, but when upsampling + # you will get edge artifacts without this, as the edge is equivalent to zero padding, + # which will add high freq artifacts. + base_freq *= rolloff + + # The key idea of the algorithm is that x(t) can be exactly reconstructed from x[i] (tensor) + # using the sinc interpolation formula: + # x(t) = sum_i x[i] sinc(pi * orig_freq * (i / orig_freq - t)) + # We can then sample the function x(t) with a different sample rate: + # y[j] = x(j / new_freq) + # or, + # y[j] = sum_i x[i] sinc(pi * orig_freq * (i / orig_freq - j / new_freq)) + + # We see here that y[j] is the convolution of x[i] with a specific filter, for which + # we take an FIR approximation, stopping when we see at least `lowpass_filter_width` zeros crossing. + # But y[j+1] is going to have a different set of weights and so on, until y[j + new_freq]. + # Indeed: + # y[j + new_freq] = sum_i x[i] sinc(pi * orig_freq * ((i / orig_freq - (j + new_freq) / new_freq)) + # = sum_i x[i] sinc(pi * orig_freq * ((i - orig_freq) / orig_freq - j / new_freq)) + # = sum_i x[i + orig_freq] sinc(pi * orig_freq * (i / orig_freq - j / new_freq)) + # so y[j+new_freq] uses the same filter as y[j], but on a shifted version of x by `orig_freq`. + # This will explain the F.conv1d after, with a stride of orig_freq. + width = math.ceil(lowpass_filter_width * orig_freq / base_freq) + # If orig_freq is still big after GCD reduction, most filters will be very unbalanced, i.e., + # they will have a lot of almost zero values to the left or to the right... + # There is probably a way to evaluate those filters more efficiently, but this is kept for + # future work. + idx_dtype = dtype if dtype is not None else torch.float64 + + idx = torch.arange(-width, width + orig_freq, dtype=idx_dtype, device=device)[None, None] / orig_freq + + t = torch.arange(0, -new_freq, -1, dtype=dtype, device=device)[:, None, None] / new_freq + idx + t *= base_freq + t = t.clamp_(-lowpass_filter_width, lowpass_filter_width) + + # we do not use built in torch windows here as we need to evaluate the window + # at specific positions, not over a regular grid. + if resampling_method == "sinc_interp_hann": + window = torch.cos(t * math.pi / lowpass_filter_width / 2) ** 2 + else: + # sinc_interp_kaiser + if beta is None: + beta = 14.769656459379492 + beta_tensor = torch.tensor(float(beta)) + window = torch.i0(beta_tensor * torch.sqrt(1 - (t / lowpass_filter_width) ** 2)) / torch.i0(beta_tensor) + + t *= math.pi + + scale = base_freq / orig_freq + kernels = torch.where(t == 0, torch.tensor(1.0).to(t), t.sin() / t) + kernels *= window * scale + + if dtype is None: + kernels = kernels.to(dtype=torch.float32) + + return kernels, width + + +def _apply_sinc_resample_kernel( + waveform: Tensor, + orig_freq: int, + new_freq: int, + gcd: int, + kernel: Tensor, + width: int, +): + if not waveform.is_floating_point(): + raise TypeError(f"Expected floating point type for waveform tensor, but received {waveform.dtype}.") + + orig_freq = int(orig_freq) // gcd + new_freq = int(new_freq) // gcd + + # pack batch + shape = waveform.size() + waveform = waveform.view(-1, shape[-1]) + + num_wavs, length = waveform.shape + waveform = torch.nn.functional.pad(waveform, (width, width + orig_freq)) + resampled = torch.nn.functional.conv1d(waveform[:, None], kernel, stride=orig_freq) + resampled = resampled.transpose(1, 2).reshape(num_wavs, -1) + target_length = torch.ceil(torch.as_tensor(new_freq * length / orig_freq)).long() + resampled = resampled[..., :target_length] + + # unpack batch + resampled = resampled.view(shape[:-1] + resampled.shape[-1:]) + return resampled + + +def resample( + waveform: Tensor, + orig_freq: int, + new_freq: int, + lowpass_filter_width: int = 6, + rolloff: float = 0.99, + resampling_method: str = "sinc_interp_hann", + beta: Optional[float] = None, +) -> Tensor: + r"""Resamples the waveform at the new frequency using bandlimited interpolation. :cite:`RESAMPLE`. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Note: + ``transforms.Resample`` precomputes and reuses the resampling kernel, so using it will result in + more efficient computation if resampling multiple waveforms with the same resampling parameters. + + Args: + waveform (Tensor): The input signal of dimension `(..., time)` + orig_freq (int): The original frequency of the signal + new_freq (int): The desired frequency + lowpass_filter_width (int, optional): Controls the sharpness of the filter, more == sharper + but less efficient. (Default: ``6``) + rolloff (float, optional): The roll-off frequency of the filter, as a fraction of the Nyquist. + Lower values reduce anti-aliasing, but also reduce some of the highest frequencies. (Default: ``0.99``) + resampling_method (str, optional): The resampling method to use. + Options: [``"sinc_interp_hann"``, ``"sinc_interp_kaiser"``] (Default: ``"sinc_interp_hann"``) + beta (float or None, optional): The shape parameter used for kaiser window. + + Returns: + Tensor: The waveform at the new frequency of dimension `(..., time).` + """ + + if orig_freq <= 0.0 or new_freq <= 0.0: + raise ValueError("Original frequency and desired frequecy should be positive") + + if orig_freq == new_freq: + return waveform + + gcd = math.gcd(int(orig_freq), int(new_freq)) + + kernel, width = _get_sinc_resample_kernel( + orig_freq, + new_freq, + gcd, + lowpass_filter_width, + rolloff, + resampling_method, + beta, + waveform.device, + waveform.dtype, + ) + resampled = _apply_sinc_resample_kernel(waveform, orig_freq, new_freq, gcd, kernel, width) + return resampled + + +@torch.jit.unused +def edit_distance(seq1: Sequence, seq2: Sequence) -> int: + """ + Calculate the word level edit (Levenshtein) distance between two sequences. + + .. devices:: CPU + + The function computes an edit distance allowing deletion, insertion and + substitution. The result is an integer. + + For most applications, the two input sequences should be the same type. If + two strings are given, the output is the edit distance between the two + strings (character edit distance). If two lists of strings are given, the + output is the edit distance between sentences (word edit distance). Users + may want to normalize the output by the length of the reference sequence. + + Args: + seq1 (Sequence): the first sequence to compare. + seq2 (Sequence): the second sequence to compare. + Returns: + int: The distance between the first and second sequences. + """ + len_sent2 = len(seq2) + dold = list(range(len_sent2 + 1)) + dnew = [0 for _ in range(len_sent2 + 1)] + + for i in range(1, len(seq1) + 1): + dnew[0] = i + for j in range(1, len_sent2 + 1): + if seq1[i - 1] == seq2[j - 1]: + dnew[j] = dold[j - 1] + else: + substitution = dold[j - 1] + 1 + insertion = dnew[j - 1] + 1 + deletion = dold[j] + 1 + dnew[j] = min(substitution, insertion, deletion) + + dnew, dold = dold, dnew + + return int(dold[-1]) + + +def loudness(waveform: Tensor, sample_rate: int): + r"""Measure audio loudness according to the ITU-R BS.1770-4 recommendation. + + .. devices:: CPU CUDA + + .. properties:: TorchScript + + Args: + waveform(torch.Tensor): audio waveform of dimension `(..., channels, time)` + sample_rate (int): sampling rate of the waveform + + Returns: + Tensor: loudness estimates (LKFS) + + Reference: + - https://www.itu.int/rec/R-REC-BS.1770-4-201510-I/en + """ + + if waveform.size(-2) > 5: + raise ValueError("Only up to 5 channels are supported.") + + gate_duration = 0.4 + overlap = 0.75 + gamma_abs = -70.0 + kweight_bias = -0.691 + gate_samples = int(round(gate_duration * sample_rate)) + step = int(round(gate_samples * (1 - overlap))) + + # Apply K-weighting + waveform = treble_biquad(waveform, sample_rate, 4.0, 1500.0, 1 / math.sqrt(2)) + waveform = highpass_biquad(waveform, sample_rate, 38.0, 0.5) + + # Compute the energy for each block + energy = torch.square(waveform).unfold(-1, gate_samples, step) + energy = torch.mean(energy, dim=-1) + + # Compute channel-weighted summation + g = torch.tensor([1.0, 1.0, 1.0, 1.41, 1.41], dtype=waveform.dtype, device=waveform.device) + g = g[: energy.size(-2)] + + energy_weighted = torch.sum(g.unsqueeze(-1) * energy, dim=-2) + loudness = -0.691 + 10 * torch.log10(energy_weighted) + + # Apply absolute gating of the blocks + gated_blocks = loudness > gamma_abs + gated_blocks = gated_blocks.unsqueeze(-2) + + energy_filtered = torch.sum(gated_blocks * energy, dim=-1) / torch.count_nonzero(gated_blocks, dim=-1) + energy_weighted = torch.sum(g * energy_filtered, dim=-1) + gamma_rel = kweight_bias + 10 * torch.log10(energy_weighted) - 10 + + # Apply relative gating of the blocks + gated_blocks = torch.logical_and(gated_blocks.squeeze(-2), loudness > gamma_rel.unsqueeze(-1)) + gated_blocks = gated_blocks.unsqueeze(-2) + + energy_filtered = torch.sum(gated_blocks * energy, dim=-1) / torch.count_nonzero(gated_blocks, dim=-1) + energy_weighted = torch.sum(g * energy_filtered, dim=-1) + LKFS = kweight_bias + 10 * torch.log10(energy_weighted) + return LKFS + + +def pitch_shift( + waveform: Tensor, + sample_rate: int, + n_steps: int, + bins_per_octave: int = 12, + n_fft: int = 512, + win_length: Optional[int] = None, + hop_length: Optional[int] = None, + window: Optional[Tensor] = None, +) -> Tensor: + """ + Shift the pitch of a waveform by ``n_steps`` steps. + + .. devices:: CPU CUDA + + .. properties:: TorchScript + + Args: + waveform (Tensor): The input waveform of shape `(..., time)`. + sample_rate (int): Sample rate of `waveform`. + n_steps (int): The (fractional) steps to shift `waveform`. + bins_per_octave (int, optional): The number of steps per octave (Default: ``12``). + n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins (Default: ``512``). + win_length (int or None, optional): Window size. If None, then ``n_fft`` is used. (Default: ``None``). + hop_length (int or None, optional): Length of hop between STFT windows. If None, then + ``win_length // 4`` is used (Default: ``None``). + window (Tensor or None, optional): Window tensor that is applied/multiplied to each frame/window. + If None, then ``torch.hann_window(win_length)`` is used (Default: ``None``). + + + Returns: + Tensor: The pitch-shifted audio waveform of shape `(..., time)`. + """ + waveform_stretch = _stretch_waveform( + waveform, + n_steps, + bins_per_octave, + n_fft, + win_length, + hop_length, + window, + ) + rate = 2.0 ** (-float(n_steps) / bins_per_octave) + waveform_shift = resample(waveform_stretch, int(sample_rate / rate), sample_rate) + + return _fix_waveform_shape(waveform_shift, waveform.size()) + + +def _stretch_waveform( + waveform: Tensor, + n_steps: int, + bins_per_octave: int = 12, + n_fft: int = 512, + win_length: Optional[int] = None, + hop_length: Optional[int] = None, + window: Optional[Tensor] = None, +) -> Tensor: + """ + Pitch shift helper function to preprocess and stretch waveform before resampling step. + + Args: + See pitch_shift arg descriptions. + + Returns: + Tensor: The preprocessed waveform stretched prior to resampling. + """ + if hop_length is None: + hop_length = n_fft // 4 + if win_length is None: + win_length = n_fft + if window is None: + window = torch.hann_window(window_length=win_length, device=waveform.device) + + # pack batch + shape = waveform.size() + waveform = waveform.reshape(-1, shape[-1]) + + ori_len = shape[-1] + rate = 2.0 ** (-float(n_steps) / bins_per_octave) + spec_f = torch.stft( + input=waveform, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=True, + pad_mode="reflect", + normalized=False, + onesided=True, + return_complex=True, + ) + phase_advance = torch.linspace(0, math.pi * hop_length, spec_f.shape[-2], device=spec_f.device)[..., None] + spec_stretch = phase_vocoder(spec_f, rate, phase_advance) + len_stretch = int(round(ori_len / rate)) + waveform_stretch = torch.istft( + spec_stretch, n_fft=n_fft, hop_length=hop_length, win_length=win_length, window=window, length=len_stretch + ) + return waveform_stretch + + +def _fix_waveform_shape( + waveform_shift: Tensor, + shape: List[int], +) -> Tensor: + """ + PitchShift helper function to process after resampling step to fix the shape back. + + Args: + waveform_shift(Tensor): The waveform after stretch and resample + shape (List[int]): The shape of initial waveform + + Returns: + Tensor: The pitch-shifted audio waveform of shape `(..., time)`. + """ + ori_len = shape[-1] + shift_len = waveform_shift.size()[-1] + if shift_len > ori_len: + waveform_shift = waveform_shift[..., :ori_len] + else: + waveform_shift = torch.nn.functional.pad(waveform_shift, [0, ori_len - shift_len]) + + # unpack batch + waveform_shift = waveform_shift.view(shape[:-1] + waveform_shift.shape[-1:]) + return waveform_shift + + +def rnnt_loss( + logits: Tensor, + targets: Tensor, + logit_lengths: Tensor, + target_lengths: Tensor, + blank: int = -1, + clamp: float = -1, + reduction: str = "mean", + fused_log_softmax: bool = True, +): + """Compute the RNN Transducer loss from *Sequence Transduction with Recurrent Neural Networks* + :cite:`graves2012sequence`. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + The RNN Transducer loss extends the CTC loss by defining a distribution over output + sequences of all lengths, and by jointly modelling both input-output and output-output + dependencies. + + Args: + logits (Tensor): Tensor of dimension `(batch, max seq length, max target length + 1, class)` + containing output from joiner + targets (Tensor): Tensor of dimension `(batch, max target length)` containing targets with zero padded + logit_lengths (Tensor): Tensor of dimension `(batch)` containing lengths of each sequence from encoder + target_lengths (Tensor): Tensor of dimension `(batch)` containing lengths of targets for each sequence + blank (int, optional): blank label (Default: ``-1``) + clamp (float, optional): clamp for gradients (Default: ``-1``) + reduction (string, optional): Specifies the reduction to apply to the output: + ``"none"`` | ``"mean"`` | ``"sum"``. (Default: ``"mean"``) + fused_log_softmax (bool): set to False if calling log_softmax outside of loss (Default: ``True``) + Returns: + Tensor: Loss with the reduction option applied. If ``reduction`` is ``"none"``, then size `(batch)`, + otherwise scalar. + """ + if reduction not in ["none", "mean", "sum"]: + raise ValueError('reduction should be one of "none", "mean", or "sum"') + + if blank < 0: # reinterpret blank index if blank < 0. + blank = logits.shape[-1] + blank + + costs, _ = torch.ops.torchaudio.rnnt_loss( + logits=logits, + targets=targets, + logit_lengths=logit_lengths, + target_lengths=target_lengths, + blank=blank, + clamp=clamp, + fused_log_softmax=fused_log_softmax, + ) + + if reduction == "mean": + return costs.mean() + elif reduction == "sum": + return costs.sum() + + return costs + + +def psd( + specgram: Tensor, + mask: Optional[Tensor] = None, + normalize: bool = True, + eps: float = 1e-10, +) -> Tensor: + """Compute cross-channel power spectral density (PSD) matrix. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Args: + specgram (torch.Tensor): Multi-channel complex-valued spectrum. + Tensor with dimensions `(..., channel, freq, time)`. + mask (torch.Tensor or None, optional): Time-Frequency mask for normalization. + Tensor with dimensions `(..., freq, time)`. (Default: ``None``) + normalize (bool, optional): If ``True``, normalize the mask along the time dimension. (Default: ``True``) + eps (float, optional): Value to add to the denominator in mask normalization. (Default: ``1e-15``) + + Returns: + torch.Tensor: The complex-valued PSD matrix of the input spectrum. + Tensor with dimensions `(..., freq, channel, channel)` + """ + specgram = specgram.transpose(-3, -2) # shape (freq, channel, time) + # outer product: + # (..., ch_1, time) x (..., ch_2, time) -> (..., time, ch_1, ch_2) + psd = torch.einsum("...ct,...et->...tce", [specgram, specgram.conj()]) + + if mask is not None: + if mask.shape[:-1] != specgram.shape[:-2] or mask.shape[-1] != specgram.shape[-1]: + raise ValueError( + "The dimensions of mask except the channel dimension should be the same as specgram." + f"Found {mask.shape} for mask and {specgram.shape} for specgram." + ) + # Normalized mask along time dimension: + if normalize: + mask = mask / (mask.sum(dim=-1, keepdim=True) + eps) + + psd = psd * mask[..., None, None] + + psd = psd.sum(dim=-3) + return psd + + +def _compute_mat_trace(input: torch.Tensor, dim1: int = -1, dim2: int = -2) -> torch.Tensor: + r"""Compute the trace of a Tensor along ``dim1`` and ``dim2`` dimensions. + + Args: + input (torch.Tensor): Tensor with dimensions `(..., channel, channel)`. + dim1 (int, optional): The first dimension of the diagonal matrix. + (Default: ``-1``) + dim2 (int, optional): The second dimension of the diagonal matrix. + (Default: ``-2``) + + Returns: + Tensor: The trace of the input Tensor. + """ + if input.ndim < 2: + raise ValueError("The dimension of the tensor must be at least 2.") + if input.shape[dim1] != input.shape[dim2]: + raise ValueError("The size of ``dim1`` and ``dim2`` must be the same.") + input = torch.diagonal(input, 0, dim1=dim1, dim2=dim2) + return input.sum(dim=-1) + + +def _tik_reg(mat: torch.Tensor, reg: float = 1e-7, eps: float = 1e-8) -> torch.Tensor: + """Perform Tikhonov regularization (only modifying real part). + + Args: + mat (torch.Tensor): Input matrix with dimensions `(..., channel, channel)`. + reg (float, optional): Regularization factor. (Default: 1e-8) + eps (float, optional): Value to avoid the correlation matrix is all-zero. (Default: ``1e-8``) + + Returns: + Tensor: Regularized matrix with dimensions `(..., channel, channel)`. + """ + # Add eps + C = mat.size(-1) + eye = torch.eye(C, dtype=mat.dtype, device=mat.device) + epsilon = _compute_mat_trace(mat).real[..., None, None] * reg + # in case that correlation_matrix is all-zero + epsilon = epsilon + eps + mat = mat + epsilon * eye[..., :, :] + return mat + + +def _assert_psd_matrices(psd_s: torch.Tensor, psd_n: torch.Tensor) -> None: + """Assertion checks of the PSD matrices of target speech and noise. + + Args: + psd_s (torch.Tensor): The complex-valued power spectral density (PSD) matrix of target speech. + Tensor with dimensions `(..., freq, channel, channel)`. + psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise. + Tensor with dimensions `(..., freq, channel, channel)`. + """ + if psd_s.ndim < 3 or psd_n.ndim < 3: + raise ValueError( + "Expected at least 3D Tensor (..., freq, channel, channel) for psd_s and psd_n. " + f"Found {psd_s.shape} for psd_s and {psd_n.shape} for psd_n." + ) + if not (psd_s.is_complex() and psd_n.is_complex()): + raise TypeError( + "The type of psd_s and psd_n must be ``torch.cfloat`` or ``torch.cdouble``. " + f"Found {psd_s.dtype} for psd_s and {psd_n.dtype} for psd_n." + ) + if psd_s.shape != psd_n.shape: + raise ValueError( + f"The dimensions of psd_s and psd_n should be the same. Found {psd_s.shape} and {psd_n.shape}." + ) + if psd_s.shape[-1] != psd_s.shape[-2]: + raise ValueError(f"The last two dimensions of psd_s should be the same. Found {psd_s.shape}.") + + +def mvdr_weights_souden( + psd_s: Tensor, + psd_n: Tensor, + reference_channel: Union[int, Tensor], + diagonal_loading: bool = True, + diag_eps: float = 1e-7, + eps: float = 1e-8, +) -> Tensor: + r"""Compute the Minimum Variance Distortionless Response (*MVDR* :cite:`capon1969high`) beamforming weights + by the method proposed by *Souden et, al.* :cite:`souden2009optimal`. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Given the power spectral density (PSD) matrix of target speech :math:`\bf{\Phi}_{\textbf{SS}}`, + the PSD matrix of noise :math:`\bf{\Phi}_{\textbf{NN}}`, and a one-hot vector that represents the + reference channel :math:`\bf{u}`, the method computes the MVDR beamforming weight martrix + :math:`\textbf{w}_{\text{MVDR}}`. The formula is defined as: + + .. math:: + \textbf{w}_{\text{MVDR}}(f) = + \frac{{{\bf{\Phi}_{\textbf{NN}}^{-1}}(f){\bf{\Phi}_{\textbf{SS}}}}(f)} + {\text{Trace}({{{\bf{\Phi}_{\textbf{NN}}^{-1}}(f) \bf{\Phi}_{\textbf{SS}}}(f))}}\bm{u} + + Args: + psd_s (torch.Tensor): The complex-valued power spectral density (PSD) matrix of target speech. + Tensor with dimensions `(..., freq, channel, channel)`. + psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise. + Tensor with dimensions `(..., freq, channel, channel)`. + reference_channel (int or torch.Tensor): Specifies the reference channel. + If the dtype is ``int``, it represents the reference channel index. + If the dtype is ``torch.Tensor``, its shape is `(..., channel)`, where the ``channel`` dimension + is one-hot. + diagonal_loading (bool, optional): If ``True``, enables applying diagonal loading to ``psd_n``. + (Default: ``True``) + diag_eps (float, optional): The coefficient multiplied to the identity matrix for diagonal loading. + It is only effective when ``diagonal_loading`` is set to ``True``. (Default: ``1e-7``) + eps (float, optional): Value to add to the denominator in the beamforming weight formula. + (Default: ``1e-8``) + + Returns: + torch.Tensor: The complex-valued MVDR beamforming weight matrix with dimensions `(..., freq, channel)`. + """ + _assert_psd_matrices(psd_s, psd_n) + + if diagonal_loading: + psd_n = _tik_reg(psd_n, reg=diag_eps) + numerator = torch.linalg.solve(psd_n, psd_s) # psd_n.inv() @ psd_s + # ws: (..., C, C) / (...,) -> (..., C, C) + ws = numerator / (_compute_mat_trace(numerator)[..., None, None] + eps) + if torch.jit.isinstance(reference_channel, int): + beamform_weights = ws[..., :, reference_channel] + elif torch.jit.isinstance(reference_channel, Tensor): + reference_channel = reference_channel.to(psd_n.dtype) + # h: (..., F, C_1, C_2) x (..., C_2) -> (..., F, C_1) + beamform_weights = torch.einsum("...c,...c->...", [ws, reference_channel[..., None, None, :]]) + else: + raise TypeError(f'Expected "int" or "Tensor" for reference_channel. Found: {type(reference_channel)}.') + + return beamform_weights + + +def mvdr_weights_rtf( + rtf: Tensor, + psd_n: Tensor, + reference_channel: Optional[Union[int, Tensor]] = None, + diagonal_loading: bool = True, + diag_eps: float = 1e-7, + eps: float = 1e-8, +) -> Tensor: + r"""Compute the Minimum Variance Distortionless Response (*MVDR* :cite:`capon1969high`) beamforming weights + based on the relative transfer function (RTF) and power spectral density (PSD) matrix of noise. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Given the relative transfer function (RTF) matrix or the steering vector of target speech :math:`\bm{v}`, + the PSD matrix of noise :math:`\bf{\Phi}_{\textbf{NN}}`, and a one-hot vector that represents the + reference channel :math:`\bf{u}`, the method computes the MVDR beamforming weight martrix + :math:`\textbf{w}_{\text{MVDR}}`. The formula is defined as: + + .. math:: + \textbf{w}_{\text{MVDR}}(f) = + \frac{{{\bf{\Phi}_{\textbf{NN}}^{-1}}(f){\bm{v}}(f)}} + {{\bm{v}^{\mathsf{H}}}(f){\bf{\Phi}_{\textbf{NN}}^{-1}}(f){\bm{v}}(f)} + + where :math:`(.)^{\mathsf{H}}` denotes the Hermitian Conjugate operation. + + Args: + rtf (torch.Tensor): The complex-valued RTF vector of target speech. + Tensor with dimensions `(..., freq, channel)`. + psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise. + Tensor with dimensions `(..., freq, channel, channel)`. + reference_channel (int or torch.Tensor): Specifies the reference channel. + If the dtype is ``int``, it represents the reference channel index. + If the dtype is ``torch.Tensor``, its shape is `(..., channel)`, where the ``channel`` dimension + is one-hot. + diagonal_loading (bool, optional): If ``True``, enables applying diagonal loading to ``psd_n``. + (Default: ``True``) + diag_eps (float, optional): The coefficient multiplied to the identity matrix for diagonal loading. + It is only effective when ``diagonal_loading`` is set to ``True``. (Default: ``1e-7``) + eps (float, optional): Value to add to the denominator in the beamforming weight formula. + (Default: ``1e-8``) + + Returns: + torch.Tensor: The complex-valued MVDR beamforming weight matrix with dimensions `(..., freq, channel)`. + """ + if rtf.ndim < 2: + raise ValueError(f"Expected at least 2D Tensor (..., freq, channel) for rtf. Found {rtf.shape}.") + if psd_n.ndim < 3: + raise ValueError(f"Expected at least 3D Tensor (..., freq, channel, channel) for psd_n. Found {psd_n.shape}.") + if not (rtf.is_complex() and psd_n.is_complex()): + raise TypeError( + "The type of rtf and psd_n must be ``torch.cfloat`` or ``torch.cdouble``. " + f"Found {rtf.dtype} for rtf and {psd_n.dtype} for psd_n." + ) + if rtf.shape != psd_n.shape[:-1]: + raise ValueError( + "The dimensions of rtf and the dimensions withou the last dimension of psd_n should be the same. " + f"Found {rtf.shape} for rtf and {psd_n.shape} for psd_n." + ) + if psd_n.shape[-1] != psd_n.shape[-2]: + raise ValueError(f"The last two dimensions of psd_n should be the same. Found {psd_n.shape}.") + + if diagonal_loading: + psd_n = _tik_reg(psd_n, reg=diag_eps) + # numerator = psd_n.inv() @ stv + numerator = torch.linalg.solve(psd_n, rtf.unsqueeze(-1)).squeeze(-1) # (..., freq, channel) + # denominator = stv^H @ psd_n.inv() @ stv + denominator = torch.einsum("...d,...d->...", [rtf.conj(), numerator]) + beamform_weights = numerator / (denominator.real.unsqueeze(-1) + eps) + # normalize the numerator + if reference_channel is not None: + if torch.jit.isinstance(reference_channel, int): + scale = rtf[..., reference_channel].conj() + elif torch.jit.isinstance(reference_channel, Tensor): + reference_channel = reference_channel.to(psd_n.dtype) + scale = torch.einsum("...c,...c->...", [rtf.conj(), reference_channel[..., None, :]]) + else: + raise TypeError(f'Expected "int" or "Tensor" for reference_channel. Found: {type(reference_channel)}.') + + beamform_weights = beamform_weights * scale[..., None] + + return beamform_weights + + +def rtf_evd(psd_s: Tensor) -> Tensor: + r"""Estimate the relative transfer function (RTF) or the steering vector by eigenvalue decomposition. + + .. devices:: CPU CUDA + + .. properties:: TorchScript + + Args: + psd_s (Tensor): The complex-valued power spectral density (PSD) matrix of target speech. + Tensor of dimension `(..., freq, channel, channel)` + + Returns: + Tensor: The estimated complex-valued RTF of target speech. + Tensor of dimension `(..., freq, channel)` + """ + if not psd_s.is_complex(): + raise TypeError(f"The type of psd_s must be ``torch.cfloat`` or ``torch.cdouble``. Found {psd_s.dtype}.") + if psd_s.shape[-1] != psd_s.shape[-2]: + raise ValueError(f"The last two dimensions of psd_s should be the same. Found {psd_s.shape}.") + _, v = torch.linalg.eigh(psd_s) # v is sorted along with eigenvalues in ascending order + rtf = v[..., -1] # choose the eigenvector with max eigenvalue + return rtf + + +def rtf_power( + psd_s: Tensor, + psd_n: Tensor, + reference_channel: Union[int, Tensor], + n_iter: int = 3, + diagonal_loading: bool = True, + diag_eps: float = 1e-7, +) -> Tensor: + r"""Estimate the relative transfer function (RTF) or the steering vector by the power method. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Args: + psd_s (torch.Tensor): The complex-valued power spectral density (PSD) matrix of target speech. + Tensor with dimensions `(..., freq, channel, channel)`. + psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise. + Tensor with dimensions `(..., freq, channel, channel)`. + reference_channel (int or torch.Tensor): Specifies the reference channel. + If the dtype is ``int``, it represents the reference channel index. + If the dtype is ``torch.Tensor``, its shape is `(..., channel)`, where the ``channel`` dimension + is one-hot. + diagonal_loading (bool, optional): If ``True``, enables applying diagonal loading to ``psd_n``. + (Default: ``True``) + diag_eps (float, optional): The coefficient multiplied to the identity matrix for diagonal loading. + It is only effective when ``diagonal_loading`` is set to ``True``. (Default: ``1e-7``) + + Returns: + torch.Tensor: The estimated complex-valued RTF of target speech. + Tensor of dimension `(..., freq, channel)`. + """ + _assert_psd_matrices(psd_s, psd_n) + if n_iter <= 0: + raise ValueError("The number of iteration must be greater than 0.") + + # Apply diagonal loading to psd_n to improve robustness. + if diagonal_loading: + psd_n = _tik_reg(psd_n, reg=diag_eps) + # phi is regarded as the first iteration + phi = torch.linalg.solve(psd_n, psd_s) # psd_n.inv() @ psd_s + if torch.jit.isinstance(reference_channel, int): + rtf = phi[..., reference_channel] + elif torch.jit.isinstance(reference_channel, Tensor): + reference_channel = reference_channel.to(psd_n.dtype) + rtf = torch.einsum("...c,...c->...", [phi, reference_channel[..., None, None, :]]) + else: + raise TypeError(f'Expected "int" or "Tensor" for reference_channel. Found: {type(reference_channel)}.') + rtf = rtf.unsqueeze(-1) # (..., freq, channel, 1) + if n_iter >= 2: + # The number of iterations in the for loop is `n_iter - 2` + # because the `phi` above and `torch.matmul(psd_s, rtf)` are regarded as + # two iterations. + for _ in range(n_iter - 2): + rtf = torch.matmul(phi, rtf) + rtf = torch.matmul(psd_s, rtf) + else: + # if there is only one iteration, the rtf is the psd_s[..., referenc_channel] + # which is psd_n @ phi @ ref_channel + rtf = torch.matmul(psd_n, rtf) + return rtf.squeeze(-1) + + +def apply_beamforming(beamform_weights: Tensor, specgram: Tensor) -> Tensor: + r"""Apply the beamforming weight to the multi-channel noisy spectrum to obtain the single-channel enhanced spectrum. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + .. math:: + \hat{\textbf{S}}(f) = \textbf{w}_{\text{bf}}(f)^{\mathsf{H}} \textbf{Y}(f) + + where :math:`\textbf{w}_{\text{bf}}(f)` is the beamforming weight for the :math:`f`-th frequency bin, + :math:`\textbf{Y}` is the multi-channel spectrum for the :math:`f`-th frequency bin. + + Args: + beamform_weights (Tensor): The complex-valued beamforming weight matrix. + Tensor of dimension `(..., freq, channel)` + specgram (Tensor): The multi-channel complex-valued noisy spectrum. + Tensor of dimension `(..., channel, freq, time)` + + Returns: + Tensor: The single-channel complex-valued enhanced spectrum. + Tensor of dimension `(..., freq, time)` + """ + if beamform_weights.shape[:-2] != specgram.shape[:-3]: + raise ValueError( + "The dimensions except the last two dimensions of beamform_weights should be the same " + "as the dimensions except the last three dimensions of specgram. " + f"Found {beamform_weights.shape} for beamform_weights and {specgram.shape} for specgram." + ) + + if not (beamform_weights.is_complex() and specgram.is_complex()): + raise TypeError( + "The type of beamform_weights and specgram must be ``torch.cfloat`` or ``torch.cdouble``. " + f"Found {beamform_weights.dtype} for beamform_weights and {specgram.dtype} for specgram." + ) + + # (..., freq, channel) x (..., channel, freq, time) -> (..., freq, time) + specgram_enhanced = torch.einsum("...fc,...cft->...ft", [beamform_weights.conj(), specgram]) + return specgram_enhanced + + +def _check_shape_compatible(x: torch.Tensor, y: torch.Tensor) -> None: + if x.ndim != y.ndim: + raise ValueError(f"The operands must be the same dimension (got {x.ndim} and {y.ndim}).") + + for i in range(x.ndim - 1): + xi = x.size(i) + yi = y.size(i) + if xi == yi or xi == 1 or yi == 1: + continue + raise ValueError(f"Leading dimensions of x and y are not broadcastable (got {x.shape} and {y.shape}).") + + +def _check_convolve_mode(mode: str) -> None: + valid_convolve_modes = ["full", "valid", "same"] + if mode not in valid_convolve_modes: + raise ValueError(f"Unrecognized mode value '{mode}'. Please specify one of {valid_convolve_modes}.") + + +def _apply_convolve_mode(conv_result: torch.Tensor, x_length: int, y_length: int, mode: str) -> torch.Tensor: + valid_convolve_modes = ["full", "valid", "same"] + if mode == "full": + return conv_result + elif mode == "valid": + target_length = max(x_length, y_length) - min(x_length, y_length) + 1 + start_idx = (conv_result.size(-1) - target_length) // 2 + return conv_result[..., start_idx : start_idx + target_length] + elif mode == "same": + start_idx = (conv_result.size(-1) - x_length) // 2 + return conv_result[..., start_idx : start_idx + x_length] + else: + raise ValueError(f"Unrecognized mode value '{mode}'. Please specify one of {valid_convolve_modes}.") + + +def fftconvolve(x: torch.Tensor, y: torch.Tensor, mode: str = "full") -> torch.Tensor: + r""" + Convolves inputs along their last dimension using FFT. For inputs with large last dimensions, this function + is generally much faster than :meth:`convolve`. + Note that, in contrast to :meth:`torch.nn.functional.conv1d`, which actually applies the valid cross-correlation + operator, this function applies the true `convolution`_ operator. + Also note that this function can only output float tensors (int tensor inputs will be cast to float). + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Args: + x (torch.Tensor): First convolution operand, with shape `(..., N)`. + y (torch.Tensor): Second convolution operand, with shape `(..., M)` + (leading dimensions must be broadcast-able with those of ``x``). + mode (str, optional): Must be one of ("full", "valid", "same"). + + * "full": Returns the full convolution result, with shape `(..., N + M - 1)`. (Default) + * "valid": Returns the segment of the full convolution result corresponding to where + the two inputs overlap completely, with shape `(..., max(N, M) - min(N, M) + 1)`. + * "same": Returns the center segment of the full convolution result, with shape `(..., N)`. + + Returns: + torch.Tensor: Result of convolving ``x`` and ``y``, with shape `(..., L)`, where + the leading dimensions match those of ``x`` and `L` is dictated by ``mode``. + + .. _convolution: + https://en.wikipedia.org/wiki/Convolution + """ + _check_shape_compatible(x, y) + _check_convolve_mode(mode) + + n = x.size(-1) + y.size(-1) - 1 + fresult = torch.fft.rfft(x, n=n) * torch.fft.rfft(y, n=n) + result = torch.fft.irfft(fresult, n=n) + return _apply_convolve_mode(result, x.size(-1), y.size(-1), mode) + + +def convolve(x: torch.Tensor, y: torch.Tensor, mode: str = "full") -> torch.Tensor: + r""" + Convolves inputs along their last dimension using the direct method. + Note that, in contrast to :meth:`torch.nn.functional.conv1d`, which actually applies the valid cross-correlation + operator, this function applies the true `convolution`_ operator. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Args: + x (torch.Tensor): First convolution operand, with shape `(..., N)`. + y (torch.Tensor): Second convolution operand, with shape `(..., M)` + (leading dimensions must be broadcast-able with those of ``x``). + mode (str, optional): Must be one of ("full", "valid", "same"). + + * "full": Returns the full convolution result, with shape `(..., N + M - 1)`. (Default) + * "valid": Returns the segment of the full convolution result corresponding to where + the two inputs overlap completely, with shape `(..., max(N, M) - min(N, M) + 1)`. + * "same": Returns the center segment of the full convolution result, with shape `(..., N)`. + + Returns: + torch.Tensor: Result of convolving ``x`` and ``y``, with shape `(..., L)`, where + the leading dimensions match those of ``x`` and `L` is dictated by ``mode``. + + .. _convolution: + https://en.wikipedia.org/wiki/Convolution + """ + _check_shape_compatible(x, y) + _check_convolve_mode(mode) + + x_size, y_size = x.size(-1), y.size(-1) + + if x.size(-1) < y.size(-1): + x, y = y, x + + if x.shape[:-1] != y.shape[:-1]: + new_shape = [max(i, j) for i, j in zip(x.shape[:-1], y.shape[:-1])] + x = x.broadcast_to(new_shape + [x.shape[-1]]) + y = y.broadcast_to(new_shape + [y.shape[-1]]) + + num_signals = torch.tensor(x.shape[:-1]).prod() + reshaped_x = x.reshape((int(num_signals), x.size(-1))) + reshaped_y = y.reshape((int(num_signals), y.size(-1))) + output = torch.nn.functional.conv1d( + input=reshaped_x, + weight=reshaped_y.flip(-1).unsqueeze(1), + stride=1, + groups=reshaped_x.size(0), + padding=reshaped_y.size(-1) - 1, + ) + output_shape = x.shape[:-1] + (-1,) + result = output.reshape(output_shape) + return _apply_convolve_mode(result, x_size, y_size, mode) + + +def add_noise( + waveform: torch.Tensor, noise: torch.Tensor, snr: torch.Tensor, lengths: Optional[torch.Tensor] = None +) -> torch.Tensor: + r"""Scales and adds noise to waveform per signal-to-noise ratio. + + Specifically, for each pair of waveform vector :math:`x \in \mathbb{R}^L` and noise vector + :math:`n \in \mathbb{R}^L`, the function computes output :math:`y` as + + .. math:: + y = x + a n \, \text{,} + + where + + .. math:: + a = \sqrt{ \frac{ ||x||_{2}^{2} }{ ||n||_{2}^{2} } \cdot 10^{-\frac{\text{SNR}}{10}} } \, \text{,} + + with :math:`\text{SNR}` being the desired signal-to-noise ratio between :math:`x` and :math:`n`, in dB. + + Note that this function broadcasts singleton leading dimensions in its inputs in a manner that is + consistent with the above formulae and PyTorch's broadcasting semantics. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Args: + waveform (torch.Tensor): Input waveform, with shape `(..., L)`. + noise (torch.Tensor): Noise, with shape `(..., L)` (same shape as ``waveform``). + snr (torch.Tensor): Signal-to-noise ratios in dB, with shape `(...,)`. + lengths (torch.Tensor or None, optional): Valid lengths of signals in ``waveform`` and ``noise``, with shape + `(...,)` (leading dimensions must match those of ``waveform``). If ``None``, all elements in ``waveform`` + and ``noise`` are treated as valid. (Default: ``None``) + + Returns: + torch.Tensor: Result of scaling and adding ``noise`` to ``waveform``, with shape `(..., L)` + (same shape as ``waveform``). + """ + + if not (waveform.ndim - 1 == noise.ndim - 1 == snr.ndim and (lengths is None or lengths.ndim == snr.ndim)): + raise ValueError("Input leading dimensions don't match.") + + L = waveform.size(-1) + + if L != noise.size(-1): + raise ValueError(f"Length dimensions of waveform and noise don't match (got {L} and {noise.size(-1)}).") + + # compute scale + if lengths is not None: + mask = torch.arange(0, L, device=lengths.device).expand(waveform.shape) < lengths.unsqueeze( + -1 + ) # (*, L) < (*, 1) = (*, L) + masked_waveform = waveform * mask + masked_noise = noise * mask + else: + masked_waveform = waveform + masked_noise = noise + + energy_signal = torch.linalg.vector_norm(masked_waveform, ord=2, dim=-1) ** 2 # (*,) + energy_noise = torch.linalg.vector_norm(masked_noise, ord=2, dim=-1) ** 2 # (*,) + original_snr_db = 10 * (torch.log10(energy_signal) - torch.log10(energy_noise)) + scale = 10 ** ((original_snr_db - snr) / 20.0) # (*,) + + # scale noise + scaled_noise = scale.unsqueeze(-1) * noise # (*, 1) * (*, L) = (*, L) + + return waveform + scaled_noise # (*, L) + + +def speed( + waveform: torch.Tensor, orig_freq: int, factor: float, lengths: Optional[torch.Tensor] = None +) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: + r"""Adjusts waveform speed. + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Args: + waveform (torch.Tensor): Input signals, with shape `(..., time)`. + orig_freq (int): Original frequency of the signals in ``waveform``. + factor (float): Factor by which to adjust speed of input. Values greater than 1.0 + compress ``waveform`` in time, whereas values less than 1.0 stretch ``waveform`` in time. + lengths (torch.Tensor or None, optional): Valid lengths of signals in ``waveform``, with shape `(...)`. + If ``None``, all elements in ``waveform`` are treated as valid. (Default: ``None``) + + Returns: + (torch.Tensor, torch.Tensor or None): + torch.Tensor + Speed-adjusted waveform, with shape `(..., new_time).` + torch.Tensor or None + If ``lengths`` is not ``None``, valid lengths of signals in speed-adjusted waveform, + with shape `(...)`; otherwise, ``None``. + """ + + source_sample_rate = int(factor * orig_freq) + target_sample_rate = int(orig_freq) + + gcd = math.gcd(source_sample_rate, target_sample_rate) + source_sample_rate = source_sample_rate // gcd + target_sample_rate = target_sample_rate // gcd + + if lengths is None: + out_lengths = None + else: + out_lengths = torch.ceil(lengths * target_sample_rate / source_sample_rate).to(lengths.dtype) + + return resample(waveform, source_sample_rate, target_sample_rate), out_lengths + + +def preemphasis(waveform, coeff: float = 0.97) -> torch.Tensor: + r"""Pre-emphasizes a waveform along its last dimension, i.e. + for each signal :math:`x` in ``waveform``, computes + output :math:`y` as + + .. math:: + y[i] = x[i] - \text{coeff} \cdot x[i - 1] + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Args: + waveform (torch.Tensor): Waveform, with shape `(..., N)`. + coeff (float, optional): Pre-emphasis coefficient. Typically between 0.0 and 1.0. + (Default: 0.97) + + Returns: + torch.Tensor: Pre-emphasized waveform, with shape `(..., N)`. + """ + waveform = waveform.clone() + waveform[..., 1:] -= coeff * waveform[..., :-1] + return waveform + + +def deemphasis(waveform, coeff: float = 0.97) -> torch.Tensor: + r"""De-emphasizes a waveform along its last dimension. + Inverse of :meth:`preemphasis`. Concretely, for each signal + :math:`x` in ``waveform``, computes output :math:`y` as + + .. math:: + y[i] = x[i] + \text{coeff} \cdot y[i - 1] + + .. devices:: CPU CUDA + + .. properties:: Autograd TorchScript + + Args: + waveform (torch.Tensor): Waveform, with shape `(..., N)`. + coeff (float, optional): De-emphasis coefficient. Typically between 0.0 and 1.0. + (Default: 0.97) + + Returns: + torch.Tensor: De-emphasized waveform, with shape `(..., N)`. + """ + a_coeffs = torch.tensor([1.0, -coeff], dtype=waveform.dtype, device=waveform.device) + b_coeffs = torch.tensor([1.0, 0.0], dtype=waveform.dtype, device=waveform.device) + return torchaudio.functional.lfilter(waveform, a_coeffs=a_coeffs, b_coeffs=b_coeffs) + + +def frechet_distance(mu_x, sigma_x, mu_y, sigma_y): + r"""Computes the Fréchet distance between two multivariate normal distributions :cite:`dowson1982frechet`. + + Concretely, for multivariate Gaussians :math:`X(\mu_X, \Sigma_X)` + and :math:`Y(\mu_Y, \Sigma_Y)`, the function computes and returns :math:`F` as + + .. math:: + F(X, Y) = || \mu_X - \mu_Y ||_2^2 + + \text{Tr}\left( \Sigma_X + \Sigma_Y - 2 \sqrt{\Sigma_X \Sigma_Y} \right) + + Args: + mu_x (torch.Tensor): mean :math:`\mu_X` of multivariate Gaussian :math:`X`, with shape `(N,)`. + sigma_x (torch.Tensor): covariance matrix :math:`\Sigma_X` of :math:`X`, with shape `(N, N)`. + mu_y (torch.Tensor): mean :math:`\mu_Y` of multivariate Gaussian :math:`Y`, with shape `(N,)`. + sigma_y (torch.Tensor): covariance matrix :math:`\Sigma_Y` of :math:`Y`, with shape `(N, N)`. + + Returns: + torch.Tensor: the Fréchet distance between :math:`X` and :math:`Y`. + """ + if len(mu_x.size()) != 1: + raise ValueError(f"Input mu_x must be one-dimensional; got dimension {len(mu_x.size())}.") + if len(sigma_x.size()) != 2: + raise ValueError(f"Input sigma_x must be two-dimensional; got dimension {len(sigma_x.size())}.") + if sigma_x.size(0) != sigma_x.size(1) != mu_x.size(0): + raise ValueError("Each of sigma_x's dimensions must match mu_x's size.") + if mu_x.size() != mu_y.size(): + raise ValueError(f"Inputs mu_x and mu_y must have the same shape; got {mu_x.size()} and {mu_y.size()}.") + if sigma_x.size() != sigma_y.size(): + raise ValueError( + f"Inputs sigma_x and sigma_y must have the same shape; got {sigma_x.size()} and {sigma_y.size()}." + ) + + a = (mu_x - mu_y).square().sum() + b = sigma_x.trace() + sigma_y.trace() + c = torch.linalg.eigvals(sigma_x @ sigma_y).sqrt().real.sum() + return a + b - 2 * c diff --git a/shared/package-files/73/73cd251a91a814862401d82be1fcdbc7374d0b2258acb76cb3ae1bc1ad0c73ac/libdevicefuncs.py b/shared/package-files/73/73cd251a91a814862401d82be1fcdbc7374d0b2258acb76cb3ae1bc1ad0c73ac/libdevicefuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..ba3bb5accaa55cb96bb369350eaf80bf356ddd89 --- /dev/null +++ b/shared/package-files/73/73cd251a91a814862401d82be1fcdbc7374d0b2258acb76cb3ae1bc1ad0c73ac/libdevicefuncs.py @@ -0,0 +1,1057 @@ +from collections import namedtuple +from textwrap import indent + +from numba.types import float32, float64, int16, int32, int64, void, Tuple +from numba.core.typing.templates import signature + +arg = namedtuple("arg", ("name", "ty", "is_ptr")) + +functions = { + "__nv_abs": (int32, [arg(name="x", ty=int32, is_ptr=False)]), + "__nv_acos": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_acosf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_acosh": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_acoshf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_asin": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_asinf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_asinh": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_asinhf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_atan": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_atan2": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_atan2f": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_atanf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_atanh": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_atanhf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_brev": (int32, [arg(name="x", ty=int32, is_ptr=False)]), + "__nv_brevll": (int64, [arg(name="x", ty=int64, is_ptr=False)]), + "__nv_byte_perm": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + arg(name="z", ty=int32, is_ptr=False), + ], + ), + "__nv_cbrt": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_cbrtf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_ceil": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_ceilf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_clz": (int32, [arg(name="x", ty=int32, is_ptr=False)]), + "__nv_clzll": (int32, [arg(name="x", ty=int64, is_ptr=False)]), + "__nv_copysign": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_copysignf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_cos": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_cosf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_cosh": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_coshf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_cospi": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_cospif": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_dadd_rd": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_dadd_rn": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_dadd_ru": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_dadd_rz": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_ddiv_rd": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_ddiv_rn": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_ddiv_ru": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_ddiv_rz": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_dmul_rd": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_dmul_rn": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_dmul_ru": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_dmul_rz": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_double2float_rd": ( + float32, + [arg(name="d", ty=float64, is_ptr=False)], + ), + "__nv_double2float_rn": ( + float32, + [arg(name="d", ty=float64, is_ptr=False)], + ), + "__nv_double2float_ru": ( + float32, + [arg(name="d", ty=float64, is_ptr=False)], + ), + "__nv_double2float_rz": ( + float32, + [arg(name="d", ty=float64, is_ptr=False)], + ), + "__nv_double2hiint": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2int_rd": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2int_rn": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2int_ru": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2int_rz": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2ll_rd": (int64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_double2ll_rn": (int64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_double2ll_ru": (int64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_double2ll_rz": (int64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_double2loint": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2uint_rd": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2uint_rn": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2uint_ru": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2uint_rz": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2ull_rd": (int64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_double2ull_rn": (int64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_double2ull_ru": (int64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_double2ull_rz": (int64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_double_as_longlong": ( + int64, + [arg(name="x", ty=float64, is_ptr=False)], + ), + "__nv_drcp_rd": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_drcp_rn": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_drcp_ru": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_drcp_rz": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_dsqrt_rd": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_dsqrt_rn": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_dsqrt_ru": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_dsqrt_rz": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_erf": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_erfc": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_erfcf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_erfcinv": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_erfcinvf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_erfcx": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_erfcxf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_erff": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_erfinv": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_erfinvf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_exp": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_exp10": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_exp10f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_exp2": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_exp2f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_expf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_expm1": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_expm1f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fabs": (float64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_fabsf": (float32, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_fadd_rd": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fadd_rn": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fadd_ru": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fadd_rz": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fast_cosf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fast_exp10f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fast_expf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fast_fdividef": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fast_log10f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fast_log2f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fast_logf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fast_powf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fast_sincosf": ( + void, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="sptr", ty=float32, is_ptr=True), + arg(name="cptr", ty=float32, is_ptr=True), + ], + ), + "__nv_fast_sinf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fast_tanf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fdim": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_fdimf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fdiv_rd": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fdiv_rn": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fdiv_ru": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fdiv_rz": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_ffs": (int32, [arg(name="x", ty=int32, is_ptr=False)]), + "__nv_ffsll": (int32, [arg(name="x", ty=int64, is_ptr=False)]), + "__nv_finitef": (int32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_float2half_rn": (int16, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float2int_rd": (int32, [arg(name="in", ty=float32, is_ptr=False)]), + "__nv_float2int_rn": (int32, [arg(name="in", ty=float32, is_ptr=False)]), + "__nv_float2int_ru": (int32, [arg(name="in", ty=float32, is_ptr=False)]), + "__nv_float2int_rz": (int32, [arg(name="in", ty=float32, is_ptr=False)]), + "__nv_float2ll_rd": (int64, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float2ll_rn": (int64, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float2ll_ru": (int64, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float2ll_rz": (int64, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float2uint_rd": (int32, [arg(name="in", ty=float32, is_ptr=False)]), + "__nv_float2uint_rn": (int32, [arg(name="in", ty=float32, is_ptr=False)]), + "__nv_float2uint_ru": (int32, [arg(name="in", ty=float32, is_ptr=False)]), + "__nv_float2uint_rz": (int32, [arg(name="in", ty=float32, is_ptr=False)]), + "__nv_float2ull_rd": (int64, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float2ull_rn": (int64, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float2ull_ru": (int64, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float2ull_rz": (int64, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float_as_int": (int32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_floor": (float64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_floorf": (float32, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_fma": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + arg(name="z", ty=float64, is_ptr=False), + ], + ), + "__nv_fma_rd": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + arg(name="z", ty=float64, is_ptr=False), + ], + ), + "__nv_fma_rn": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + arg(name="z", ty=float64, is_ptr=False), + ], + ), + "__nv_fma_ru": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + arg(name="z", ty=float64, is_ptr=False), + ], + ), + "__nv_fma_rz": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + arg(name="z", ty=float64, is_ptr=False), + ], + ), + "__nv_fmaf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + arg(name="z", ty=float32, is_ptr=False), + ], + ), + "__nv_fmaf_rd": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + arg(name="z", ty=float32, is_ptr=False), + ], + ), + "__nv_fmaf_rn": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + arg(name="z", ty=float32, is_ptr=False), + ], + ), + "__nv_fmaf_ru": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + arg(name="z", ty=float32, is_ptr=False), + ], + ), + "__nv_fmaf_rz": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + arg(name="z", ty=float32, is_ptr=False), + ], + ), + "__nv_fmax": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_fmaxf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fmin": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_fminf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fmod": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_fmodf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fmul_rd": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fmul_rn": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fmul_ru": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fmul_rz": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_frcp_rd": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_frcp_rn": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_frcp_ru": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_frcp_rz": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_frexp": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="b", ty=int32, is_ptr=True), + ], + ), + "__nv_frexpf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="b", ty=int32, is_ptr=True), + ], + ), + "__nv_frsqrt_rn": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fsqrt_rd": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fsqrt_rn": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fsqrt_ru": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fsqrt_rz": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fsub_rd": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fsub_rn": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fsub_ru": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fsub_rz": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_hadd": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_half2float": (float32, [arg(name="h", ty=int16, is_ptr=False)]), + "__nv_hiloint2double": ( + float64, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_hypot": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_hypotf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_ilogb": (int32, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_ilogbf": (int32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_int2double_rn": (float64, [arg(name="i", ty=int32, is_ptr=False)]), + "__nv_int2float_rd": (float32, [arg(name="in", ty=int32, is_ptr=False)]), + "__nv_int2float_rn": (float32, [arg(name="in", ty=int32, is_ptr=False)]), + "__nv_int2float_ru": (float32, [arg(name="in", ty=int32, is_ptr=False)]), + "__nv_int2float_rz": (float32, [arg(name="in", ty=int32, is_ptr=False)]), + "__nv_int_as_float": (float32, [arg(name="x", ty=int32, is_ptr=False)]), + "__nv_isfinited": (int32, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_isinfd": (int32, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_isinff": (int32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_isnand": (int32, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_isnanf": (int32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_j0": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_j0f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_j1": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_j1f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_jn": ( + float64, + [ + arg(name="n", ty=int32, is_ptr=False), + arg(name="x", ty=float64, is_ptr=False), + ], + ), + "__nv_jnf": ( + float32, + [ + arg(name="n", ty=int32, is_ptr=False), + arg(name="x", ty=float32, is_ptr=False), + ], + ), + "__nv_ldexp": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_ldexpf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_lgamma": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_lgammaf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_ll2double_rd": (float64, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ll2double_rn": (float64, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ll2double_ru": (float64, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ll2double_rz": (float64, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ll2float_rd": (float32, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ll2float_rn": (float32, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ll2float_ru": (float32, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ll2float_rz": (float32, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_llabs": (int64, [arg(name="x", ty=int64, is_ptr=False)]), + "__nv_llmax": ( + int64, + [ + arg(name="x", ty=int64, is_ptr=False), + arg(name="y", ty=int64, is_ptr=False), + ], + ), + "__nv_llmin": ( + int64, + [ + arg(name="x", ty=int64, is_ptr=False), + arg(name="y", ty=int64, is_ptr=False), + ], + ), + "__nv_llrint": (int64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_llrintf": (int64, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_llround": (int64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_llroundf": (int64, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_log": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_log10": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_log10f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_log1p": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_log1pf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_log2": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_log2f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_logb": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_logbf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_logf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_longlong_as_double": ( + float64, + [arg(name="x", ty=int64, is_ptr=False)], + ), + "__nv_max": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_min": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_modf": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="b", ty=float64, is_ptr=True), + ], + ), + "__nv_modff": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="b", ty=float32, is_ptr=True), + ], + ), + "__nv_mul24": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_mul64hi": ( + int64, + [ + arg(name="x", ty=int64, is_ptr=False), + arg(name="y", ty=int64, is_ptr=False), + ], + ), + "__nv_mulhi": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + # __nv_nan and __nv_nanf are excluded - they return a representation of a + # quiet NaN, but the argument they take seems to be undocumented, and + # follows a strange form - it is not an output like every other pointer + # argument. If a NaN is required, one can be obtained in CUDA Python by + # other means, e.g. `math.nan`. They are left in this list for completeness + # / reference. + # "__nv_nan": (float64, [arg(name="tagp", ty=int8, is_ptr=True)]), + # "__nv_nanf": (float32, [arg(name="tagp", ty=int8, is_ptr=True)]), + "__nv_nearbyint": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_nearbyintf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_nextafter": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_nextafterf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_normcdf": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_normcdff": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_normcdfinv": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_normcdfinvf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_popc": (int32, [arg(name="x", ty=int32, is_ptr=False)]), + "__nv_popcll": (int32, [arg(name="x", ty=int64, is_ptr=False)]), + "__nv_pow": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_powf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_powi": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_powif": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_rcbrt": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_rcbrtf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_remainder": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_remainderf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_remquo": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + arg(name="c", ty=int32, is_ptr=True), + ], + ), + "__nv_remquof": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + arg(name="quo", ty=int32, is_ptr=True), + ], + ), + "__nv_rhadd": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_rint": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_rintf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_round": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_roundf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_rsqrt": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_rsqrtf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_sad": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + arg(name="z", ty=int32, is_ptr=False), + ], + ), + "__nv_saturatef": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_scalbn": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_scalbnf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_signbitd": (int32, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_signbitf": (int32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_sin": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_sincos": ( + void, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="sptr", ty=float64, is_ptr=True), + arg(name="cptr", ty=float64, is_ptr=True), + ], + ), + "__nv_sincosf": ( + void, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="sptr", ty=float32, is_ptr=True), + arg(name="cptr", ty=float32, is_ptr=True), + ], + ), + "__nv_sincospi": ( + void, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="sptr", ty=float64, is_ptr=True), + arg(name="cptr", ty=float64, is_ptr=True), + ], + ), + "__nv_sincospif": ( + void, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="sptr", ty=float32, is_ptr=True), + arg(name="cptr", ty=float32, is_ptr=True), + ], + ), + "__nv_sinf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_sinh": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_sinhf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_sinpi": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_sinpif": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_sqrt": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_sqrtf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_tan": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_tanf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_tanh": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_tanhf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_tgamma": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_tgammaf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_trunc": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_truncf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_uhadd": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_uint2double_rn": (float64, [arg(name="i", ty=int32, is_ptr=False)]), + "__nv_uint2float_rd": (float32, [arg(name="in", ty=int32, is_ptr=False)]), + "__nv_uint2float_rn": (float32, [arg(name="in", ty=int32, is_ptr=False)]), + "__nv_uint2float_ru": (float32, [arg(name="in", ty=int32, is_ptr=False)]), + "__nv_uint2float_rz": (float32, [arg(name="in", ty=int32, is_ptr=False)]), + "__nv_ull2double_rd": (float64, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ull2double_rn": (float64, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ull2double_ru": (float64, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ull2double_rz": (float64, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ull2float_rd": (float32, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ull2float_rn": (float32, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ull2float_ru": (float32, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ull2float_rz": (float32, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ullmax": ( + int64, + [ + arg(name="x", ty=int64, is_ptr=False), + arg(name="y", ty=int64, is_ptr=False), + ], + ), + "__nv_ullmin": ( + int64, + [ + arg(name="x", ty=int64, is_ptr=False), + arg(name="y", ty=int64, is_ptr=False), + ], + ), + "__nv_umax": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_umin": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_umul24": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_umul64hi": ( + int64, + [ + arg(name="x", ty=int64, is_ptr=False), + arg(name="y", ty=int64, is_ptr=False), + ], + ), + "__nv_umulhi": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_urhadd": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_usad": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + arg(name="z", ty=int32, is_ptr=False), + ], + ), + "__nv_y0": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_y0f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_y1": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_y1f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_yn": ( + float64, + [ + arg(name="n", ty=int32, is_ptr=False), + arg(name="x", ty=float64, is_ptr=False), + ], + ), + "__nv_ynf": ( + float32, + [ + arg(name="n", ty=int32, is_ptr=False), + arg(name="x", ty=float32, is_ptr=False), + ], + ), +} + + +def create_signature(retty, args): + """ + Given the return type and arguments for a libdevice function, return the + signature of the stub function used to call it from CUDA Python. + """ + + # Any pointer arguments should be part of the return type. + return_types = [arg.ty for arg in args if arg.is_ptr] + # If the return type is void, there is no point adding it to the list of + # return types. + if retty != void: + return_types.insert(0, retty) + + if len(return_types) > 1: + retty = Tuple(return_types) + else: + retty = return_types[0] + + argtypes = [arg.ty for arg in args if not arg.is_ptr] + + return signature(retty, *argtypes) + + +# The following code generates the stubs for libdevice functions. +# +# Stubs can be regenerated (e.g. if the functions dict above is modified) with: +# +# python -c "from numba.cuda.libdevicefuncs import generate_stubs; \ +# generate_stubs()" > numba/cuda/libdevice.py + +docstring_template = """ +See https://docs.nvidia.com/cuda/libdevice-users-guide/{func}.html + +{param_types} +:rtype: {retty} +""" + +param_template = """\ +:param {a.name}: Argument. +:type {a.name}: {a.ty}""" + + +def generate_stubs(): + for name, (retty, args) in functions.items(): + # Some libdevice functions have arguments called `in`, which causes a + # syntax error in Python, so we rename these to `x`. + def argname(arg): + if arg.name == "in": + return "x" + else: + return arg.name + + argnames = [argname(a) for a in args if not a.is_ptr] + argstr = ", ".join(argnames) + signature = create_signature(retty, args) + + param_types = "\n".join( + [param_template.format(a=a) for a in args if not a.is_ptr] + ) + docstring = docstring_template.format( + param_types=param_types, retty=signature.return_type, func=name + ) + docstring = indent(docstring, " ") + print(f'def {name[5:]}({argstr}):\n """{docstring}"""\n\n') diff --git a/shared/package-files/73/73ce117587c8b85596ff7ebed5110b26ca307d0c178605316dd0bfc4a4321422/libarrow_acero.pxd b/shared/package-files/73/73ce117587c8b85596ff7ebed5110b26ca307d0c178605316dd0bfc4a4321422/libarrow_acero.pxd new file mode 100644 index 0000000000000000000000000000000000000000..dc9babee190e110583d9d2cc24b71567203290af --- /dev/null +++ b/shared/package-files/73/73ce117587c8b85596ff7ebed5110b26ca307d0c178605316dd0bfc4a4321422/libarrow_acero.pxd @@ -0,0 +1,118 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# distutils: language = c++ + +from pyarrow.includes.common cimport * +from pyarrow.includes.libarrow cimport * + + +cdef extern from "arrow/acero/options.h" namespace "arrow::acero" nogil: + cdef enum CJoinType "arrow::acero::JoinType": + CJoinType_LEFT_SEMI "arrow::acero::JoinType::LEFT_SEMI" + CJoinType_RIGHT_SEMI "arrow::acero::JoinType::RIGHT_SEMI" + CJoinType_LEFT_ANTI "arrow::acero::JoinType::LEFT_ANTI" + CJoinType_RIGHT_ANTI "arrow::acero::JoinType::RIGHT_ANTI" + CJoinType_INNER "arrow::acero::JoinType::INNER" + CJoinType_LEFT_OUTER "arrow::acero::JoinType::LEFT_OUTER" + CJoinType_RIGHT_OUTER "arrow::acero::JoinType::RIGHT_OUTER" + CJoinType_FULL_OUTER "arrow::acero::JoinType::FULL_OUTER" + + cdef cppclass CExecNodeOptions "arrow::acero::ExecNodeOptions": + pass + + cdef cppclass CSourceNodeOptions "arrow::acero::SourceNodeOptions"(CExecNodeOptions): + pass + + cdef cppclass CTableSourceNodeOptions "arrow::acero::TableSourceNodeOptions"(CExecNodeOptions): + CTableSourceNodeOptions(shared_ptr[CTable] table) + CTableSourceNodeOptions(shared_ptr[CTable] table, int64_t max_batch_size) + + cdef cppclass CSinkNodeOptions "arrow::acero::SinkNodeOptions"(CExecNodeOptions): + pass + + cdef cppclass CFilterNodeOptions "arrow::acero::FilterNodeOptions"(CExecNodeOptions): + CFilterNodeOptions(CExpression) + + cdef cppclass CProjectNodeOptions "arrow::acero::ProjectNodeOptions"(CExecNodeOptions): + CProjectNodeOptions(vector[CExpression] expressions) + CProjectNodeOptions(vector[CExpression] expressions, + vector[c_string] names) + + cdef cppclass CAggregateNodeOptions "arrow::acero::AggregateNodeOptions"(CExecNodeOptions): + CAggregateNodeOptions(vector[CAggregate] aggregates, vector[CFieldRef] names) + + cdef cppclass COrderByNodeOptions "arrow::acero::OrderByNodeOptions"(CExecNodeOptions): + COrderByNodeOptions(COrdering ordering) + + cdef cppclass CHashJoinNodeOptions "arrow::acero::HashJoinNodeOptions"(CExecNodeOptions): + CHashJoinNodeOptions(CJoinType, vector[CFieldRef] in_left_keys, + vector[CFieldRef] in_right_keys) + CHashJoinNodeOptions(CJoinType, vector[CFieldRef] in_left_keys, + vector[CFieldRef] in_right_keys, + CExpression filter, + c_string output_suffix_for_left, + c_string output_suffix_for_right) + CHashJoinNodeOptions(CJoinType join_type, + vector[CFieldRef] left_keys, + vector[CFieldRef] right_keys, + vector[CFieldRef] left_output, + vector[CFieldRef] right_output, + CExpression filter, + c_string output_suffix_for_left, + c_string output_suffix_for_right) + + cdef struct CAsofJoinKeys "arrow::acero::AsofJoinNodeOptions::Keys": + CFieldRef on_key + vector[CFieldRef] by_key + + cdef cppclass CAsofJoinNodeOptions "arrow::acero::AsofJoinNodeOptions"(CExecNodeOptions): + CAsofJoinNodeOptions(vector[CAsofJoinKeys] keys, int64_t tolerance) + + +cdef extern from "arrow/acero/exec_plan.h" namespace "arrow::acero" nogil: + cdef cppclass CDeclaration "arrow::acero::Declaration": + cppclass Input: + Input(CExecNode*) + Input(CDeclaration) + + c_string label + vector[Input] inputs + + CDeclaration() + CDeclaration(c_string factory_name, CExecNodeOptions options) + CDeclaration(c_string factory_name, vector[Input] inputs, shared_ptr[CExecNodeOptions] options) + + @staticmethod + CDeclaration Sequence(vector[CDeclaration] decls) + + cdef cppclass CExecNode "arrow::acero::ExecNode": + const vector[CExecNode*]& inputs() const + const shared_ptr[CSchema]& output_schema() const + + CResult[shared_ptr[CTable]] DeclarationToTable( + CDeclaration declaration, c_bool use_threads + ) + CResult[shared_ptr[CTable]] DeclarationToTable( + CDeclaration declaration, c_bool use_threads, + CMemoryPool* memory_pool, CFunctionRegistry* function_registry + ) + CResult[unique_ptr[CRecordBatchReader]] DeclarationToReader( + CDeclaration declaration, c_bool use_threads + ) + + CResult[c_string] DeclarationToString(const CDeclaration& declaration) diff --git a/shared/package-files/73/73ce858228fb9f8d96f8b3fe2fb41259e3ce409c9748591ffdb39bb13985332d/new_full_compositeexplicitautograd_dispatch.h b/shared/package-files/73/73ce858228fb9f8d96f8b3fe2fb41259e3ce409c9748591ffdb39bb13985332d/new_full_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..e8677fc1cbb3f97c464bf3c9681369a32ec435d1 --- /dev/null +++ b/shared/package-files/73/73ce858228fb9f8d96f8b3fe2fb41259e3ce409c9748591ffdb39bb13985332d/new_full_compositeexplicitautograd_dispatch.h @@ -0,0 +1,30 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor new_full(const at::Tensor & self, at::IntArrayRef size, const at::Scalar & fill_value, at::TensorOptions options={}); +TORCH_API at::Tensor new_full(const at::Tensor & self, at::IntArrayRef size, const at::Scalar & fill_value, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +TORCH_API at::Tensor new_full_symint(const at::Tensor & self, c10::SymIntArrayRef size, const at::Scalar & fill_value, at::TensorOptions options={}); +TORCH_API at::Tensor new_full_symint(const at::Tensor & self, c10::SymIntArrayRef size, const at::Scalar & fill_value, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +TORCH_API at::Tensor & new_full_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef size, const at::Scalar & fill_value); +TORCH_API at::Tensor & new_full_outf(const at::Tensor & self, at::IntArrayRef size, const at::Scalar & fill_value, at::Tensor & out); +TORCH_API at::Tensor & new_full_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef size, const at::Scalar & fill_value); +TORCH_API at::Tensor & new_full_symint_outf(const at::Tensor & self, c10::SymIntArrayRef size, const at::Scalar & fill_value, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/73/73d3240cdd1429775b9855224a9e0665507e372737be175c9f2a9dccc5cc3504/_local_scalar_dense_cpu_dispatch.h b/shared/package-files/73/73d3240cdd1429775b9855224a9e0665507e372737be175c9f2a9dccc5cc3504/_local_scalar_dense_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..42ad8d517f041f609a5ff671b69024e8cd29dc94 --- /dev/null +++ b/shared/package-files/73/73d3240cdd1429775b9855224a9e0665507e372737be175c9f2a9dccc5cc3504/_local_scalar_dense_cpu_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Scalar _local_scalar_dense(const at::Tensor & self); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/73/73d84452b50b30a5e26b98f721af3c603689ecbbf8446b2aab163a1c817da106/_cython_blas.pyx b/shared/package-files/73/73d84452b50b30a5e26b98f721af3c603689ecbbf8446b2aab163a1c817da106/_cython_blas.pyx new file mode 100644 index 0000000000000000000000000000000000000000..ac23d0c4000ff1cb1ae61019c89c765ba2d5bbe8 --- /dev/null +++ b/shared/package-files/73/73d84452b50b30a5e26b98f721af3c603689ecbbf8446b2aab163a1c817da106/_cython_blas.pyx @@ -0,0 +1,239 @@ +from cython cimport floating + +from scipy.linalg.cython_blas cimport sdot, ddot +from scipy.linalg.cython_blas cimport sasum, dasum +from scipy.linalg.cython_blas cimport saxpy, daxpy +from scipy.linalg.cython_blas cimport snrm2, dnrm2 +from scipy.linalg.cython_blas cimport scopy, dcopy +from scipy.linalg.cython_blas cimport sscal, dscal +from scipy.linalg.cython_blas cimport srotg, drotg +from scipy.linalg.cython_blas cimport srot, drot +from scipy.linalg.cython_blas cimport sgemv, dgemv +from scipy.linalg.cython_blas cimport sger, dger +from scipy.linalg.cython_blas cimport sgemm, dgemm + + +################ +# BLAS Level 1 # +################ + +cdef floating _dot(int n, const floating *x, int incx, + const floating *y, int incy) noexcept nogil: + """x.T.y""" + if floating is float: + return sdot(&n, x, &incx, y, &incy) + else: + return ddot(&n, x, &incx, y, &incy) + + +cpdef _dot_memview(const floating[::1] x, const floating[::1] y): + return _dot(x.shape[0], &x[0], 1, &y[0], 1) + + +cdef floating _asum(int n, const floating *x, int incx) noexcept nogil: + """sum(|x_i|)""" + if floating is float: + return sasum(&n, x, &incx) + else: + return dasum(&n, x, &incx) + + +cpdef _asum_memview(const floating[::1] x): + return _asum(x.shape[0], &x[0], 1) + + +cdef void _axpy(int n, floating alpha, const floating *x, int incx, + floating *y, int incy) noexcept nogil: + """y := alpha * x + y""" + if floating is float: + saxpy(&n, &alpha, x, &incx, y, &incy) + else: + daxpy(&n, &alpha, x, &incx, y, &incy) + + +cpdef _axpy_memview(floating alpha, const floating[::1] x, floating[::1] y): + _axpy(x.shape[0], alpha, &x[0], 1, &y[0], 1) + + +cdef floating _nrm2(int n, const floating *x, int incx) noexcept nogil: + """sqrt(sum((x_i)^2))""" + if floating is float: + return snrm2(&n, x, &incx) + else: + return dnrm2(&n, x, &incx) + + +cpdef _nrm2_memview(const floating[::1] x): + return _nrm2(x.shape[0], &x[0], 1) + + +cdef void _copy(int n, const floating *x, int incx, const floating *y, int incy) noexcept nogil: + """y := x""" + if floating is float: + scopy(&n, x, &incx, y, &incy) + else: + dcopy(&n, x, &incx, y, &incy) + + +cpdef _copy_memview(const floating[::1] x, const floating[::1] y): + _copy(x.shape[0], &x[0], 1, &y[0], 1) + + +cdef void _scal(int n, floating alpha, const floating *x, int incx) noexcept nogil: + """x := alpha * x""" + if floating is float: + sscal(&n, &alpha, x, &incx) + else: + dscal(&n, &alpha, x, &incx) + + +cpdef _scal_memview(floating alpha, const floating[::1] x): + _scal(x.shape[0], alpha, &x[0], 1) + + +cdef void _rotg(floating *a, floating *b, floating *c, floating *s) noexcept nogil: + """Generate plane rotation""" + if floating is float: + srotg(a, b, c, s) + else: + drotg(a, b, c, s) + + +cpdef _rotg_memview(floating a, floating b, floating c, floating s): + _rotg(&a, &b, &c, &s) + return a, b, c, s + + +cdef void _rot(int n, floating *x, int incx, floating *y, int incy, + floating c, floating s) noexcept nogil: + """Apply plane rotation""" + if floating is float: + srot(&n, x, &incx, y, &incy, &c, &s) + else: + drot(&n, x, &incx, y, &incy, &c, &s) + + +cpdef _rot_memview(floating[::1] x, floating[::1] y, floating c, floating s): + _rot(x.shape[0], &x[0], 1, &y[0], 1, c, s) + + +################ +# BLAS Level 2 # +################ + +cdef void _gemv(BLAS_Order order, BLAS_Trans ta, int m, int n, floating alpha, + const floating *A, int lda, const floating *x, int incx, + floating beta, floating *y, int incy) noexcept nogil: + """y := alpha * op(A).x + beta * y""" + cdef char ta_ = ta + if order == BLAS_Order.RowMajor: + ta_ = BLAS_Trans.NoTrans if ta == BLAS_Trans.Trans else BLAS_Trans.Trans + if floating is float: + sgemv(&ta_, &n, &m, &alpha, A, &lda, x, + &incx, &beta, y, &incy) + else: + dgemv(&ta_, &n, &m, &alpha, A, &lda, x, + &incx, &beta, y, &incy) + else: + if floating is float: + sgemv(&ta_, &m, &n, &alpha, A, &lda, x, + &incx, &beta, y, &incy) + else: + dgemv(&ta_, &m, &n, &alpha, A, &lda, x, + &incx, &beta, y, &incy) + + +cpdef _gemv_memview(BLAS_Trans ta, floating alpha, const floating[:, :] A, + const floating[::1] x, floating beta, floating[::1] y): + cdef: + int m = A.shape[0] + int n = A.shape[1] + BLAS_Order order = ( + BLAS_Order.ColMajor if A.strides[0] == A.itemsize else BLAS_Order.RowMajor + ) + int lda = m if order == BLAS_Order.ColMajor else n + + _gemv(order, ta, m, n, alpha, &A[0, 0], lda, &x[0], 1, beta, &y[0], 1) + + +cdef void _ger(BLAS_Order order, int m, int n, floating alpha, + const floating *x, int incx, const floating *y, + int incy, floating *A, int lda) noexcept nogil: + """A := alpha * x.y.T + A""" + if order == BLAS_Order.RowMajor: + if floating is float: + sger(&n, &m, &alpha, y, &incy, x, &incx, A, &lda) + else: + dger(&n, &m, &alpha, y, &incy, x, &incx, A, &lda) + else: + if floating is float: + sger(&m, &n, &alpha, x, &incx, y, &incy, A, &lda) + else: + dger(&m, &n, &alpha, x, &incx, y, &incy, A, &lda) + + +cpdef _ger_memview(floating alpha, const floating[::1] x, + const floating[::1] y, floating[:, :] A): + cdef: + int m = A.shape[0] + int n = A.shape[1] + BLAS_Order order = ( + BLAS_Order.ColMajor if A.strides[0] == A.itemsize else BLAS_Order.RowMajor + ) + int lda = m if order == BLAS_Order.ColMajor else n + + _ger(order, m, n, alpha, &x[0], 1, &y[0], 1, &A[0, 0], lda) + + +################ +# BLAS Level 3 # +################ + +cdef void _gemm(BLAS_Order order, BLAS_Trans ta, BLAS_Trans tb, int m, int n, + int k, floating alpha, const floating *A, int lda, const floating *B, + int ldb, floating beta, floating *C, int ldc) noexcept nogil: + """C := alpha * op(A).op(B) + beta * C""" + # TODO: Remove the pointer casts below once SciPy uses const-qualification. + # See: https://github.com/scipy/scipy/issues/14262 + cdef: + char ta_ = ta + char tb_ = tb + if order == BLAS_Order.RowMajor: + if floating is float: + sgemm(&tb_, &ta_, &n, &m, &k, &alpha, B, + &ldb, A, &lda, &beta, C, &ldc) + else: + dgemm(&tb_, &ta_, &n, &m, &k, &alpha, B, + &ldb, A, &lda, &beta, C, &ldc) + else: + if floating is float: + sgemm(&ta_, &tb_, &m, &n, &k, &alpha, A, + &lda, B, &ldb, &beta, C, &ldc) + else: + dgemm(&ta_, &tb_, &m, &n, &k, &alpha, A, + &lda, B, &ldb, &beta, C, &ldc) + + +cpdef _gemm_memview(BLAS_Trans ta, BLAS_Trans tb, floating alpha, + const floating[:, :] A, const floating[:, :] B, floating beta, + floating[:, :] C): + cdef: + int m = A.shape[0] if ta == BLAS_Trans.NoTrans else A.shape[1] + int n = B.shape[1] if tb == BLAS_Trans.NoTrans else B.shape[0] + int k = A.shape[1] if ta == BLAS_Trans.NoTrans else A.shape[0] + int lda, ldb, ldc + BLAS_Order order = ( + BLAS_Order.ColMajor if A.strides[0] == A.itemsize else BLAS_Order.RowMajor + ) + + if order == BLAS_Order.RowMajor: + lda = k if ta == BLAS_Trans.NoTrans else m + ldb = n if tb == BLAS_Trans.NoTrans else k + ldc = n + else: + lda = m if ta == BLAS_Trans.NoTrans else k + ldb = k if tb == BLAS_Trans.NoTrans else n + ldc = m + + _gemm(order, ta, tb, m, n, k, alpha, &A[0, 0], + lda, &B[0, 0], ldb, beta, &C[0, 0], ldc) diff --git a/shared/package-files/73/73d8e9b5482280de9ac510e145de1189ff7c4e6c5ea297359c5345848a5b1541/_tqdm_pandas.py b/shared/package-files/73/73d8e9b5482280de9ac510e145de1189ff7c4e6c5ea297359c5345848a5b1541/_tqdm_pandas.py new file mode 100644 index 0000000000000000000000000000000000000000..c4fe6efdc603579e7f8acfa27ac10dccdf3e94ce --- /dev/null +++ b/shared/package-files/73/73d8e9b5482280de9ac510e145de1189ff7c4e6c5ea297359c5345848a5b1541/_tqdm_pandas.py @@ -0,0 +1,24 @@ +import sys + +__author__ = "github.com/casperdcl" +__all__ = ['tqdm_pandas'] + + +def tqdm_pandas(tclass, **tqdm_kwargs): + """ + Registers the given `tqdm` instance with + `pandas.core.groupby.DataFrameGroupBy.progress_apply`. + """ + from tqdm import TqdmDeprecationWarning + + if isinstance(tclass, type) or (getattr(tclass, '__name__', '').startswith( + 'tqdm_')): # delayed adapter case + TqdmDeprecationWarning( + "Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm, ...)`.", + fp_write=getattr(tqdm_kwargs.get('file', None), 'write', sys.stderr.write)) + tclass.pandas(**tqdm_kwargs) + else: + TqdmDeprecationWarning( + "Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm(...))`.", + fp_write=getattr(tclass.fp, 'write', sys.stderr.write)) + type(tclass).pandas(deprecated_t=tclass) diff --git a/shared/package-files/73/73d961efa365162b0537d9ef35011c74910f70e6cf2feffa2d6576031f13d99f/cpp.py b/shared/package-files/73/73d961efa365162b0537d9ef35011c74910f70e6cf2feffa2d6576031f13d99f/cpp.py new file mode 100644 index 0000000000000000000000000000000000000000..f5466030daa6baba3899373d7af220bdfa102b72 --- /dev/null +++ b/shared/package-files/73/73d961efa365162b0537d9ef35011c74910f70e6cf2feffa2d6576031f13d99f/cpp.py @@ -0,0 +1,467 @@ +from typing import List, Optional, Sequence, Set, Union + +from torchgen import local +from torchgen.api.types import ( + ArgName, + ArrayCType, + ArrayRefCType, + BaseCType, + BaseTypeToCppMapping, + Binding, + boolT, + ConstRefCType, + CType, + dimnameListT, + intArrayRefT, + iTensorListRefT, + ListCType, + longT, + MutRefCType, + NamedCType, + OptionalCType, + optionalIntArrayRefT, + optionalSymIntArrayRefT, + scalarT, + SpecialArgName, + symIntArrayRefT, + SymIntT, + tensorListT, + tensorOptionsT, + tensorT, + TupleCType, + VectorCType, + voidT, +) +from torchgen.model import ( + Argument, + Arguments, + BaseTy, + BaseType, + FunctionSchema, + ListType, + NativeFunction, + OptionalType, + Return, + SelfArgument, + TensorOptionsArguments, + Type, +) +from torchgen.utils import assert_never + +# This file describes the translation of JIT schema to the public C++ +# API, which is what people use when they call functions like at::add. +# +# Prominent characteristics of the C++ API: +# +# - dtype, layout, device and pin_memory are collected into +# a single C++ type TensorOptions (the native functions API +# also has this, but tensor options is really most relevant +# for the C++ API; it makes calling kwarg factory functions +# pleasant) +# +# - defaulting lives here (in fact, the dispatcher is completely +# oblivious of defaults!) +# +# BTW: policy on name collisions: we try not to have types with +# collisions, but functions are fair game to collide + + +def name( + func: FunctionSchema, + *, + faithful_name_for_out_overloads: bool = False, + symint_overload: bool = False, +) -> str: + name = str(func.name.name) + if symint_overload: + name += "_symint" + if func.is_out_fn(): + if faithful_name_for_out_overloads: + name += "_outf" + else: + name += "_out" + + return name + + +# Translation of "value types" in JIT schema to C++ API type. Value +# types look the same no matter if they are argument types or return +# types. Returns None if the type in question is not a value type. +def valuetype_type( + t: Type, + *, + binds: ArgName, + remove_non_owning_ref_types: bool = False, + symint: bool = False, +) -> Optional[NamedCType]: + if isinstance(t, BaseType): + if t.name == BaseTy.Tensor or t.name == BaseTy.Scalar: + return None + elif str(t) == "SymInt": + if symint: + return NamedCType(binds, BaseCType(SymIntT)) + else: + return NamedCType(binds, BaseCType(longT)) + if remove_non_owning_ref_types: + if t.name == BaseTy.str: + raise AssertionError( + "string ref->value conversion: not implemented yet" + ) + # All other BaseType currently map directly to BaseCppTypes. + return NamedCType(binds, BaseCType(BaseTypeToCppMapping[t.name])) + elif isinstance(t, OptionalType): + elem = valuetype_type(t.elem, binds=binds, symint=symint) + if elem is None: + return None + return NamedCType(binds, OptionalCType(elem.type)) + elif isinstance(t, ListType): + if str(t.elem) == "bool": + assert t.size is not None + return NamedCType(binds, ArrayCType(BaseCType(boolT), t.size)) + else: + return None + else: + raise AssertionError(f"unrecognized type {repr(t)}") + + +# Translation of types occurring in JIT arguments to a C++ argument type. +# If remove_non_owning_ref_types is set, we'll guarantee that the outputed CType is not a non-owning reference type. +# For example, we'll return std::vector instead of IntArrayRef. +# See Note [translation from C++ reference to value types] +def argumenttype_type( + t: Type, + *, + mutable: bool, + binds: ArgName, + remove_non_owning_ref_types: bool = False, + symint: bool = False, +) -> NamedCType: + # If it's a value type, do the value type translation + r = valuetype_type( + t, + binds=binds, + symint=symint, + remove_non_owning_ref_types=remove_non_owning_ref_types, + ) + if r is not None: + return r + + if isinstance(t, BaseType): + if t.name == BaseTy.Tensor: + if mutable and not local.use_const_ref_for_mutable_tensors(): + return NamedCType(binds, MutRefCType(BaseCType(tensorT))) + else: + return NamedCType(binds, ConstRefCType(BaseCType(tensorT))) + elif t.name == BaseTy.Scalar: + return NamedCType(binds, ConstRefCType(BaseCType(scalarT))) + else: + raise AssertionError(f"base type should have been value type {t}") + elif isinstance(t, OptionalType): + if str(t.elem) == "Tensor": + if mutable and not local.use_const_ref_for_mutable_tensors(): + return NamedCType( + binds, MutRefCType(BaseCType(tensorT)) + ) # TODO: fix this discrepancy + else: + return NamedCType( + binds, ConstRefCType(OptionalCType(BaseCType(tensorT))) + ) + elif str(t.elem) == "Scalar": + return NamedCType(binds, ConstRefCType(OptionalCType(BaseCType(scalarT)))) + elif isinstance(t.elem, ListType) and str(t.elem.elem) == "int": + return NamedCType(binds, BaseCType(optionalIntArrayRefT)) + elif isinstance(t.elem, ListType) and str(t.elem.elem) == "SymInt": + if symint: + return NamedCType(binds, BaseCType(optionalSymIntArrayRefT)) + else: + return NamedCType(binds, BaseCType(optionalIntArrayRefT)) + elem = argumenttype_type(t.elem, mutable=mutable, binds=binds, symint=symint) + return NamedCType(binds, OptionalCType(elem.type)) + elif isinstance(t, ListType): + # TODO: remove these special cases, ArrayRef fallthrough works fine + if str(t.elem) == "int": + if remove_non_owning_ref_types: + return NamedCType(binds, VectorCType(BaseCType(longT))) + else: + return NamedCType(binds, BaseCType(intArrayRefT)) + if str(t.elem) == "SymInt": + if remove_non_owning_ref_types: + if symint: + return NamedCType(binds, VectorCType(BaseCType(SymIntT))) + else: + return NamedCType(binds, VectorCType(BaseCType(longT))) + else: + if symint: + return NamedCType(binds, BaseCType(symIntArrayRefT)) + else: + return NamedCType(binds, BaseCType(intArrayRefT)) + if str(t.elem) == "Tensor": + if local.use_ilistref_for_tensor_lists(): + return NamedCType(binds, ConstRefCType(BaseCType(iTensorListRefT))) + else: + return NamedCType(binds, BaseCType(tensorListT)) + elif str(t.elem) == "Scalar": + return NamedCType(binds, ArrayRefCType(BaseCType(scalarT))) + elif str(t.elem) == "Dimname": + return NamedCType(binds, BaseCType(dimnameListT)) + elif str(t.elem) == "Tensor?": + return NamedCType( + binds, ConstRefCType(ListCType(OptionalCType(BaseCType(tensorT)))) + ) + elem = argumenttype_type(t.elem, mutable=mutable, binds=binds, symint=symint) + return NamedCType(binds, ArrayRefCType(elem.type)) + else: + raise AssertionError(f"unrecognized type {repr(t)}") + + +# Translate a JIT argument into its C++ type +def argument_type(a: Argument, *, binds: ArgName, symint: bool = False) -> NamedCType: + return argumenttype_type(a.type, mutable=a.is_write, symint=symint, binds=binds) + + +# Translation of a (non-multi) return type from JIT to C++ +# N.B: returntype_type returns a CType, not a NamedCType. +# This is mostly because of the mismatch between return types and return names. +# e.g. a function with a return type of 'void' has 0 return names, +# and a function with a return type of 'std::tuple' has >1 return name. +def returntype_type(t: Type, *, mutable: bool, symint: bool = False) -> CType: + # placeholder is ignored + # NB: symint is ALWAYS respected for return types. So symint argument + # here is IGNORED + r = valuetype_type(t, binds="__placeholder__", symint=True) + if r is not None: + return r.type + + if isinstance(t, BaseType): + if t.name == BaseTy.Tensor: + if mutable: + if local.use_const_ref_for_mutable_tensors(): + return ConstRefCType(BaseCType(tensorT)) + else: + return MutRefCType(BaseCType(tensorT)) + else: + # Note [Tensor Copy Returns] + # Currently, we use "Argument.is_write" to determine + # whether or not Tensor return types should be copies or references. + # If that ever changes, take a look at other locations of this note! + return BaseCType(tensorT) + elif t.name == BaseTy.Scalar: + return BaseCType(scalarT) + elif isinstance(t, ListType): + assert ( + not mutable + ), "Native functions should never return a mutable tensor list. They should return void." + elem = returntype_type(t.elem, mutable=False) + assert t.size is None, f"fixed size list returns not supported: {t}" + return VectorCType(elem) + elif isinstance(t, OptionalType): + elem = returntype_type(t.elem, mutable=mutable) + if str(t.elem) == "Tensor": + return OptionalCType(elem) + + raise AssertionError(f"unrecognized return type {t}") + + +# Translation of a single return to its C++ type +def return_type(r: Return, *, symint: bool = False) -> CType: + return returntype_type(r.type, mutable=r.is_write, symint=symint) + + +# Translation of a full (possibly multi) return from JIT to its C++ type +def returns_type(rs: Sequence[Return], *, symint: bool = False) -> CType: + if len(rs) == 0: + return BaseCType(voidT) + elif len(rs) == 1: + return return_type(rs[0], symint=symint) + else: + return TupleCType([return_type(r, symint=symint) for r in rs]) + + +def return_names(f: NativeFunction, *, fallback_name: str = "result") -> Sequence[str]: + returns: List[str] = [] + for i, r in enumerate(f.func.returns): + # If we have an inplace function, the return argument is + # implicitly named self. + # TODO: Consider incorporating this into the data model + if f.func.name.name.inplace: + assert i == 0, "illegal inplace function with multiple returns" + name = "self" + # If we are out function, the name is the name of the + # corresponding output function (r.name will get recorded + # in field_name later.) + elif f.func.is_out_fn(): + name = f.func.arguments.out[i].name + # If the return argument is explicitly named... + elif r.name: + name_conflict = any( + r.name == a.name for a in f.func.schema_order_arguments() + ) + if name_conflict and not f.func.is_out_fn(): + name = f"{r.name}_return" + else: + name = r.name + # If there is no explicit name and no fallback name was passed in, we just name the output result, + # unless it's a multi-return, in which case it's result0, + # result1, etc (zero-indexed) + else: + name = fallback_name if len(f.func.returns) == 1 else f"{fallback_name}{i}" + returns.append(name) + return returns + + +JIT_TO_CPP_DEFAULT = { + "False": "false", + "True": "true", + "None": "c10::nullopt", # UGH this one is type directed + "Mean": "at::Reduction::Mean", + "[]": "{}", + "contiguous_format": "MemoryFormat::Contiguous", + "long": "at::kLong", +} + + +# Convert a JIT default into C++ expression representing the default +def default_expr(d: str, t: Type, *, symint: bool) -> str: + if d == "None" and str(t) == "Tensor?": + return "{}" + if isinstance(t, BaseType) and t.name is BaseTy.str: + # Schema allows single quotes but C++ needs double + if len(d) >= 2 and d[0] == "'" and d[-1] == "'": + s = "" + i = 1 + while i + 1 < len(d): + if d[i] != "\\": + if d[i] == '"': + s += '\\"' + else: + s += d[i] + i += 1 + else: + if d[i + 1] == "'": + s += "'" + else: + s += d[i : i + 2] + i += 2 + + return f'"{s}"' + + if isinstance(t, OptionalType): + if d == "None": + return "c10::nullopt" + + return default_expr(d, t.elem, symint=symint) + + if isinstance(t, ListType): + if d.startswith("[") and d.endswith("]"): + return "{" + d[1:-1] + "}" + elif symint and d.isdigit() and str(t.elem) == "SymInt": + return f"c10::SymInt({d})" + elif t.size is None: + # NOTE: Sized lists can have scalar defaults + raise ValueError(f"Expected a list default '[...]' but found: '{d}'") + + return JIT_TO_CPP_DEFAULT.get(d, d) + + +# Convert an argument into its C++ API form + + +def argument( + a: Union[Argument, TensorOptionsArguments, SelfArgument], + *, + cpp_no_default_args: Set[str], + method: bool, + faithful: bool, + symint: bool = False, + has_tensor_options: bool, +) -> List[Binding]: + def sub_argument( + a: Union[Argument, TensorOptionsArguments, SelfArgument] + ) -> List[Binding]: + return argument( + a, + cpp_no_default_args=cpp_no_default_args, + method=method, + faithful=faithful, + symint=symint, + has_tensor_options=has_tensor_options, + ) + + if isinstance(a, Argument): + binds: ArgName + if a.name == "memory_format" and has_tensor_options: + binds = SpecialArgName.possibly_redundant_memory_format + else: + binds = a.name + default: Optional[str] = None + if a.name not in cpp_no_default_args and a.default is not None: + default = default_expr(a.default, a.type, symint=symint) + return [ + Binding( + nctype=argument_type(a, binds=binds, symint=symint), + name=a.name, + default=default, + argument=a, + ) + ] + elif isinstance(a, TensorOptionsArguments): + if faithful: + return ( + sub_argument(a.dtype) + + sub_argument(a.layout) + + sub_argument(a.device) + + sub_argument(a.pin_memory) + ) + else: + default = None + # Enforced by NativeFunction.__post_init__ + assert "options" not in cpp_no_default_args + if all(x.default == "None" for x in a.all()): + default = "{}" + elif a.dtype.default == "long": + default = "at::kLong" # TODO: this is wrong + return [ + Binding( + nctype=NamedCType("options", BaseCType(tensorOptionsT)), + name="options", + default=default, + argument=a, + ) + ] + elif isinstance(a, SelfArgument): + if method: + # Caller is responsible for installing implicit this in context! + return [] + else: + return sub_argument(a.argument) + else: + assert_never(a) + + +def arguments( + arguments: Arguments, + *, + faithful: bool, + symint: bool = False, + method: bool, + cpp_no_default_args: Set[str], +) -> List[Binding]: + args: List[Union[Argument, TensorOptionsArguments, SelfArgument]] = [] + if faithful: + args.extend(arguments.non_out) + args.extend(arguments.out) + else: + args.extend(arguments.out) + args.extend(arguments.non_out) + return [ + r.no_default() if faithful else r + for a in args + for r in argument( + a, + faithful=faithful, + symint=symint, + method=method, + has_tensor_options=arguments.tensor_options is not None, + cpp_no_default_args=cpp_no_default_args, + ) + ] diff --git a/shared/package-files/73/73da0b1a7a1ca1fb1be32f423e90886463c517fb72b1a03a3fd8bf8370a96551/utils.pyi b/shared/package-files/73/73da0b1a7a1ca1fb1be32f423e90886463c517fb72b1a03a3fd8bf8370a96551/utils.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1eaa6668344019b42840b0ce441c2026a452295e --- /dev/null +++ b/shared/package-files/73/73da0b1a7a1ca1fb1be32f423e90886463c517fb72b1a03a3fd8bf8370a96551/utils.pyi @@ -0,0 +1,6 @@ +from datetime import datetime, timedelta, tzinfo +from typing import Optional + +def default_tzinfo(dt: datetime, tzinfo: tzinfo) -> datetime: ... +def today(tzinfo: Optional[tzinfo] = ...) -> datetime: ... +def within_delta(dt1: datetime, dt2: datetime, delta: timedelta) -> bool: ... diff --git a/shared/package-files/73/73db8396c370b66faab5fe97230c5d5a8c86c9ee6d1f73e14c8ac9460ec83cac/tanh_meta_dispatch.h b/shared/package-files/73/73db8396c370b66faab5fe97230c5d5a8c86c9ee6d1f73e14c8ac9460ec83cac/tanh_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..222cbb467d5c5f2772afed9916c0a9bfd55ec994 --- /dev/null +++ b/shared/package-files/73/73db8396c370b66faab5fe97230c5d5a8c86c9ee6d1f73e14c8ac9460ec83cac/tanh_meta_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor tanh(const at::Tensor & self); +TORCH_API at::Tensor & tanh_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & tanh_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & tanh_(at::Tensor & self); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/73/73dba37801fcad24be502e0536271f0e3738bdafdbc6b32a76ca20307927a355/distributed_test.py b/shared/package-files/73/73dba37801fcad24be502e0536271f0e3738bdafdbc6b32a76ca20307927a355/distributed_test.py new file mode 100644 index 0000000000000000000000000000000000000000..c0e4339e126cf856a4e04e5e2f2b8a591f43751a --- /dev/null +++ b/shared/package-files/73/73dba37801fcad24be502e0536271f0e3738bdafdbc6b32a76ca20307927a355/distributed_test.py @@ -0,0 +1,10062 @@ +# mypy: ignore-errors + +import copy +import itertools +import math +import os +import random +import sys +import tempfile +import time +from collections import namedtuple, OrderedDict +from contextlib import contextmanager, nullcontext +from dataclasses import dataclass +from datetime import timedelta +from functools import reduce +from typing import Union, NamedTuple, Callable, Any +import unittest +import numpy as np +import torch +import torch.cuda +import torch.distributed as dist +import torch.distributed.algorithms.model_averaging.averagers as averagers +import torch.distributed.algorithms.model_averaging.hierarchical_model_averager as hierarchicalSGD +import torch.distributed.algorithms.model_averaging.utils as model_averaging_utils +import torch.nn as nn +import torch.nn.functional as F +from torch._utils_internal import TEST_MASTER_ADDR as MASTER_ADDR +from torch._utils_internal import TEST_MASTER_PORT as MASTER_PORT +from torch.autograd import DeviceType +from torch.cuda.amp import GradScaler, autocast + +from torch.distributed.algorithms.ddp_comm_hooks import ( + post_localSGD_hook as post_localSGD, + powerSGD_hook as powerSGD, + default_hooks as default, + quantization as quantization_hooks, +) +from torch.distributed.optim import _apply_optimizer_in_backward + +from torch.distributed.distributed_c10d import ( + get_world_size, + _get_default_group, + _get_pg_config, +) +from torch.distributed.utils import ( + _verify_param_shape_across_processes, + _sync_module_states, +) + +from torch.nn.parallel import DistributedDataParallel +from torch.nn.parallel.distributed import _dump_DDP_relevant_env_vars, _MixedPrecision +from torch.testing._internal.common_distributed import ( + MultiProcessTestCase, + TEST_SKIPS, + init_multigpu_helper, + initialize_temp_directories, + cleanup_temp_dir, + simple_sparse_reduce_tests, + skip_if_rocm, + skip_if_small_worldsize, + skip_if_odd_worldsize, + skip_if_lt_x_gpu, + nccl_skip_if_lt_x_gpu, + skip_if_no_gpu, + require_n_gpus_for_nccl_backend, + requires_nccl_version, + captured_output, + with_nccl_blocking_wait, + with_dist_debug_levels, + verify_ddp_error_logged, + DistTestCases, +) +from torch.testing._internal.common_utils import ( + instantiate_parametrized_tests, + IS_MACOS, + IS_WINDOWS, + FILE_SCHEMA, + IS_FBCODE, + NO_MULTIPROCESSING_SPAWN, + IS_SANDCASTLE, + skip_but_pass_in_sandcastle, + skip_but_pass_in_sandcastle_if, +) + +import torch.distributed.optim.post_localSGD_optimizer as post_localSGD_optimizer + +from torch.utils.data.distributed import DistributedSampler +import operator + +try: + import torchvision + + HAS_TORCHVISION = True +except ImportError: + HAS_TORCHVISION = False + +if sys.platform == "win32": + import msvcrt +else: + import fcntl + + +class NetWithBuffers(nn.Module): + def __init__(self): + super().__init__() + self.a = nn.Linear(10, 10, bias=False) + self.b = nn.Linear(10, 1, bias=False) + self.register_buffer("buffer", torch.randn(1, 2)) + + def forward(self, x): + self.buffer.add_(1) + return self.b(self.a(x)) + + +class Foo: + def __init__(self, x): + # Can be tensor or int + self.x = x + + def __eq__(self, other): + def eq(value, other): + if isinstance(value, torch.Tensor): + return torch.equal(value, other) + return value == other + + for attr, value in self.__dict__.items(): + other_value = other.__dict__[attr] + if not eq(value, other_value): + return False + return True + + +f = Foo(10) +f.bar = 1 + +foo_cpu_tensor = Foo(torch.randn(3, 3)) + + +COLLECTIVES_OBJECT_TEST_LIST = [ + {"key1": 3, "key2": 4, "key3": {"nested": True}}, + f, + foo_cpu_tensor, + "foo", + [1, 2, True, "string", [4, 5, "nested"]], +] + +# Allowlist of distributed backends where profiling collectives is supported. +PROFILING_SUPPORTED_BACKENDS = [ + dist.Backend.NCCL, + dist.Backend.GLOO, + dist.Backend.MPI, + dist.Backend.UCC, +] + +# Allowlist of distributed backends where profiling is supported with use_cuda=True +CUDA_PROFILING_SUPPORTED_BACKENDS = [ + dist.Backend.GLOO, + dist.Backend.MPI, + dist.Backend.NCCL, + dist.Backend.UCC, +] + +# Allowlist of distributed backends where profiling is supported for p2p ops +SEND_RECV_PROFILING_SUPPORTED_BACKENDS = [ + dist.Backend.MPI, + dist.Backend.GLOO, + dist.Backend.NCCL, + dist.Backend.UCC, +] + +# Dummy NamedTuple data structures to test DDP support for NamedTuple types. +EXPECTED_FIELDS = ("a", "b") +TestNamedTupleInput_0 = namedtuple("NamedTuple", EXPECTED_FIELDS) + + +class TestNamedTupleInput_1(NamedTuple): + a: torch.tensor + b: torch.tensor + + +skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( + not HAS_TORCHVISION, "no torchvision" +) + +BACKEND = os.environ["BACKEND"] +INIT_METHOD = os.getenv("INIT_METHOD", "env://") + +DEFAULT_TIMEOUT = 300 +CUSTOMIZED_TIMEOUT = {"test_DistributedDataParallel": 500} + + +def get_profiling_event(event_name, profiler, dedup_gpu_user_annotation=False): + event_list = ( + profiler.events() + if isinstance(profiler, torch.profiler.profile) + else profiler.function_events + ) + return [ + event for event in event_list + if ( + (event.name.endswith(event_name) or event.name.startswith(event_name)) + and (not dedup_gpu_user_annotation or event.device_type != DeviceType.CUDA) + ) + ] + + +# Base error message substring on unfinished reductions. +ddp_prev_reduction_unfinished_str = ( + "Expected to have finished reduction in the prior iteration" +) +# Error message substring when find_unused_parameters=True has not been passed +ddp_recommend_find_unused_params_str = ( + "passing the keyword argument `find_unused_parameters=True`" +) +# Error message substring when find_unused_parameters=True is enabled +ddp_find_unused_params_enabled_str = "Since `find_unused_parameters=True` is enabled" +# Error message substring for possibility of not all model outputs being used +# in loss computation +ddp_outputs_not_used_in_loss_str = ( + "`forward` function outputs participate in calculating loss" +) +# Error message substring suggesting to use TORCH_DISTRIBUTED_DEBUG +ddp_suggest_debug_mode_str = ( + "set the environment variable TORCH_DISTRIBUTED_DEBUG to either INFO or DETAIL" +) + + +class DDPUnevenTestInput(NamedTuple): + name: str + model: nn.Module + inp: Union[torch.tensor, tuple] + sync_interval: int + throw_on_early_termination: bool = False + hook: Callable = None + state: Any = None + + +class _FC2(nn.Module): + def __init__(self): + super().__init__() + self.fc = nn.Linear(10, 50, bias=True) + self.fc.bias.requires_grad = False + + def forward(self, x): + x = self.fc(x) + return x + + +class Net(nn.Module): + def __init__(self): + super().__init__() + self.fc1 = nn.Linear(2, 10, bias=False) + self.fc2 = _FC2() + self.fc3 = nn.Linear(50, 4, bias=False) + self.relu = nn.ReLU() + self.no_grad_param = nn.Parameter( + torch.tensor([2, 2]).long(), requires_grad=False + ) + + def forward(self, x): + x = self.relu(self.fc1(x)) + x = self.relu(self.fc2(x)) + x = self.fc3(x) + return F.softmax(x, dim=1) + + +class LargeNet(nn.Module): + def __init__(self): + super().__init__() + self.fc1 = nn.Linear(1000, 2000, bias=False) + self.fc2 = nn.Linear(2000, 500, bias=False) + + def forward(self, x): + x = self.fc1(x) + x = self.fc2(x) + return x + + +class Task(nn.Module): + def __init__(self): + super().__init__() + self.p = nn.Parameter(torch.ones(2, 2)) + + def forward(self, x): + return self.p + x + + +class BatchNormNet(nn.Module): + def __init__(self, affine=True): + super().__init__() + self.fc1 = nn.Linear(2, 40, bias=False) + self.bn = nn.BatchNorm1d(4, affine=affine) + self.fc2 = nn.Linear(40, 4, bias=False) + + def forward(self, x): + x = torch.reshape(self.fc1(x), (-1, 4, 10)) + x = self.bn(x) + x = torch.reshape(x, (-1, 40)) + x = self.fc2(x) + return F.softmax(x, dim=1) + + +class UnusedParamTwoLinLayerNet(nn.Module): + def __init__(self): + super().__init__() + self.a = nn.Linear(10, 10, bias=False) + self.b = nn.Linear(10, 10, bias=False) + self.c = nn.Linear(5, 5, bias=False) + + def forward(self, x): + a = self.a(x) + b = self.b(x) + return (a, b) + + +class DictOutputModule(nn.Module): + def __init__(self): + super().__init__() + self.module = UnusedParamTwoLinLayerNet() + + def forward(self, x): + predictions = self.module(x) + loss = (predictions[0] + predictions[1]).sum() + return { + "predictions": predictions, + "loss": loss, + } + + +class TwoLinLayerNet(nn.Module): + def __init__(self): + super().__init__() + self.a = nn.Linear(10, 10, bias=False) + self.b = nn.Linear(10, 1, bias=False) + + def forward(self, x): + a = self.a(x) + b = self.b(x) + return (a, b) + + +class EmbeddingNetDifferentParams(nn.Module): + """ + A module containing an embedding with different dimension or different # of + parameters depending on the rank. + """ + + def __init__(self, rank, diff_num_params=False): + super().__init__() + embedding_dim = 500 if diff_num_params or rank == 0 else 50 + self.embedding = nn.Embedding(num_embeddings=10, embedding_dim=embedding_dim) + self.lin = nn.Linear(embedding_dim, 1) + if diff_num_params: + self.lin2 = nn.Linear(1, 1, bias=False) + + def forward(self, x): + x = self.embedding(x) + return self.lin(x) + + +class ControlFlowToyModel(nn.Module): + def __init__(self): + super().__init__() + self.lin1 = nn.Linear(10, 10, bias=False) + self.lin2 = nn.Linear(10, 10, bias=False) + + def forward(self, x): + # Second layer is used dependent on input x. + use_second_layer = torch.equal(x, torch.ones(20, 10, device=x.device)) + if use_second_layer: + return self.lin2(F.relu(self.lin1(x))) + else: + return F.relu(self.lin1(x)) + + +DDP_NET = Net() +BN_NET = BatchNormNet() +BN_NET_NO_AFFINE = BatchNormNet(affine=False) +ONLY_SBN_NET = nn.SyncBatchNorm(2, momentum=0.99) + + +def get_timeout(test_id): + test_name = test_id.split(".")[-1] + if test_name in CUSTOMIZED_TIMEOUT: + return CUSTOMIZED_TIMEOUT[test_name] + else: + return DEFAULT_TIMEOUT + + +default_pg_timeout = 60 + +CUSTOM_PG_TIMEOUT = { + # This test runs slowly and needs additional time to complete, otherwise can + # be taken down by TORCH_NCCL_ASYNC_ERROR_HANDLING + "test_ddp_uneven_inputs": 300, + # This test has a short timeout since it tests being taken down by + # TORCH_NCCL_ASYNC_ERROR_HANDLING which we want to happen quickly. + "test_ddp_model_diff_across_ranks": 5, + # This test has a short timeout since it tests being taken down by + # TORCH_NCCL_ASYNC_ERROR_HANDLING which we want to happen quickly. + "test_ddp_has_finalized": 5, +} + +def require_backend_is_available(backends): + def check(backend): + if backend == dist.Backend.GLOO: + return dist.is_gloo_available() + if backend == dist.Backend.NCCL: + return dist.is_nccl_available() + if backend == dist.Backend.MPI: + return dist.is_mpi_available() + if backend == dist.Backend.UCC: + return dist.is_ucc_available() + if backend in DistTestCases.backend_feature["plugin"]: + return True + return False + + if BACKEND not in backends: + return skip_but_pass_in_sandcastle( + f"Test requires backend {BACKEND} to be one of {backends}" + ) + + if not check(dist.Backend(BACKEND)): + return skip_but_pass_in_sandcastle( + f"Test requires backend {BACKEND} to be available" + ) + return lambda func: func + + +def require_world_size(world_size): + if int(os.environ["WORLD_SIZE"]) < world_size: + return skip_but_pass_in_sandcastle( + "Test requires world size of %d" % world_size + ) + return lambda func: func + + +@contextmanager +def _lock(): + TEMP_DIR = os.environ["TEMP_DIR"] + lockfile = os.path.join(TEMP_DIR, "lockfile") + with open(lockfile, "w") as lf: + try: + if sys.platform == "win32": + msvcrt.locking(lf.fileno(), msvcrt.LK_RLCK, 1) + yield + else: + fcntl.flock(lf.fileno(), fcntl.LOCK_EX) + yield + finally: + if sys.platform == "win32": + msvcrt.locking(lf.fileno(), msvcrt.LK_UNLCK, 1) + else: + fcntl.flock(lf.fileno(), fcntl.LOCK_UN) + lf.close() + + +@contextmanager +def _rank_temp_file(): + if dist.get_rank() == 0: + fd, name = tempfile.mkstemp() + os.close(fd) + else: + name = None + object_list = [name] + dist.broadcast_object_list(object_list) + name = object_list[0] + try: + yield name + finally: + if dist.get_rank() == 0: + os.remove(name) + + +def _build_tensor(size, value=None, dtype=torch.float, device_id=None): + if value is None: + value = size + if device_id is None: + return torch.empty(size, size, size, dtype=dtype).fill_(value) + else: + return torch.empty(size, size, size, dtype=dtype).fill_(value).cuda(device_id) + + +def _build_multidim_tensor(dim, dim_size, value=None, dtype=torch.float): + if value is None: + value = dim + return torch.empty(size=[dim_size for _ in range(dim)], dtype=dtype).fill_(value) + + +def _create_autograd_profiler(): + return torch.autograd.profiler.profile(record_shapes=True) + + +def _create_torch_profiler(): + return torch.profiler.profile( + activities=[ + torch.profiler.ProfilerActivity.CPU, + ], + record_shapes=True, + ) + + +class Barrier: + barrier_id = 0 + + @classmethod + def init(cls): + cls.barrier_id = 0 + barrier_dir = os.path.join(os.environ["TEMP_DIR"], "barrier") + for f_name in os.listdir(barrier_dir): + os.unlink(os.path.join(barrier_dir, f_name)) + + @classmethod + def sync(cls, wait_for=None, timeout=10): + if wait_for is None: + wait_for = dist.get_world_size() + cls.barrier_id += 1 + barrier_dir = os.path.join(os.environ["TEMP_DIR"], "barrier") + pid = str(os.getpid()) + barrier_file = os.path.join(barrier_dir, pid) + with _lock(): + with open(barrier_file, "w") as f: + f.write(str(cls.barrier_id)) + + start_time = time.time() + while True: + arrived = 0 + with _lock(): + for f_name in os.listdir(barrier_dir): + with open(os.path.join(barrier_dir, f_name)) as f: + data = f.read() + if int(data) >= cls.barrier_id: + arrived += 1 + if arrived == wait_for: + break + + if time.time() - start_time > timeout: + raise RuntimeError("barrier timeout") + time.sleep(0.1) + + +class TestDistBackend(MultiProcessTestCase): + @classmethod + def setUpClass(cls): + os.environ["MASTER_ADDR"] = str(MASTER_ADDR) + # Not setting MASTER_PORT and get a random free port + super().setUpClass() + + def setUp(self): + super().setUp() + # initialize temp directories + initialize_temp_directories() + # initialize Barrier + Barrier.init() + # Skip return code checking for following tests as they are expected to + # crash a process due to TORCH_NCCL_ASYNC_ERROR_HANDLING. + self.skip_return_code_checks = [self.test_ddp_has_finalized.__wrapped__] + + def tearDown(self): + cleanup_temp_dir() + super().tearDown() + + @property + def init_method(self): + return f"{FILE_SCHEMA}{self.file_name}" + + @classmethod + def _run(cls, rank, test_name, file_name, pipe): + if BACKEND == "nccl" and not torch.cuda.is_available(): + sys.exit(TEST_SKIPS["no_cuda"].exit_code) + self = cls(test_name) + self.rank = rank + self.file_name = file_name + + if torch.cuda.is_available() and torch.cuda.device_count() < int( + self.world_size + ): + sys.exit(TEST_SKIPS[f"multi-gpu-{self.world_size}"].exit_code) + try: + pg_timeout_seconds = CUSTOM_PG_TIMEOUT.get(test_name, default_pg_timeout) + timeout = timedelta(seconds=pg_timeout_seconds) + dist.init_process_group( + init_method=self.init_method, + backend=BACKEND, + world_size=int(self.world_size), + rank=self.rank, + timeout=timeout, + ) + except RuntimeError as e: + if "recompile" in e.args[0]: + sys.exit(TEST_SKIPS["backend_unavailable"].exit_code) + + raise + + # Execute barrier prior to running test to ensure that every process + # has finished initialization and that the following test + # immediately exiting due to a skip doesn't cause flakiness. + self._barrier() + + self.run_test(test_name, pipe) + self._barrier() + dist.destroy_process_group() + sys.exit(0) + + # Needed since MultiProcessTestCase assumes a world_size of 4, but we + # run these tests under other various world_sizes. + @property + def world_size(self): + return os.environ["WORLD_SIZE"] + + +class DistributedTest: + class _DistTestBase: + def _barrier(self, *args, **kwargs): + Barrier.sync(*args, **kwargs) + + def _init_group_test(self, **kwargs): + group = [1, 2] + group_id = dist.new_group(group, **kwargs) + rank = dist.get_rank() + if rank not in group: + return ([], None, rank) + + return (group, group_id, rank) + + def _init_full_group_test(self, **kwargs): + group = list(range(0, dist.get_world_size())) + group_id = dist.new_group(**kwargs) + rank = dist.get_rank() + return (group, group_id, rank) + + def _init_global_test(self): + group = list(range(0, dist.get_world_size())) + group_id = dist.group.WORLD + rank = dist.get_rank() + return (group, group_id, rank) + + def _verify_buffers_equal(self, m1, m2): + # verify buffers across models + m1_buf_dict = dict(m1.module.named_buffers()) + for name, buf in m2.module.named_buffers(): + self.assertEqual(buf, m1_buf_dict[name]) + + # Verify buffers across ranks. + m1_buffers = list(m1.buffers()) + m2_buffers = list(m2.buffers()) + for (buf1, buf2) in zip(m1_buffers, m2_buffers): + gathered_bufs = [ + torch.empty_like(buf1) for _ in range(dist.get_world_size()) + ] + dist.all_gather(gathered_bufs, buf1) + gathered_bufs_m2 = [ + torch.empty_like(buf2) for _ in range(dist.get_world_size()) + ] + for b in gathered_bufs: + self.assertEqual(b, buf1) + dist.all_gather(gathered_bufs_m2, buf2) + for b in gathered_bufs_m2: + self.assertEqual(b, buf2) + + def test_dump_DDP_relevant_env_vars(self): + with captured_output() as (out, _): + _dump_DDP_relevant_env_vars() + lines = out.getvalue().splitlines() + + def format_line(var): + return f"env:{var}={os.environ[var] if var in os.environ else 'N/A'}" + + # Check relevant env vars + vars = [ + "MASTER_ADDR", + "MASTER_PORT", + "WORLD_SIZE", + "NCCL_TOPO_DUMP_FILE", # N/A + "TORCH_NCCL_ASYNC_ERROR_HANDLING", + ] + for var in vars: + line = format_line(var) + self.assertIn(line, lines) + # Check irrelevant env vars + vars = [ + "xxx", + "yyy", + "zzz", + ] + for var in vars: + line = format_line(var) + self.assertNotIn(line, lines) + + # GET RANK + def test_get_rank(self): + test_dir = os.path.join(os.environ["TEMP_DIR"], "test_dir") + pid = str(os.getpid()) + num_processes = dist.get_world_size() + with open(os.path.join(test_dir, pid), "w") as f: + f.write(str(dist.get_rank())) + + self._barrier() + + all_ranks = set() + for f_name in os.listdir(test_dir): + with open(os.path.join(test_dir, f_name)) as f: + all_ranks.add(int(f.read())) + self.assertEqual(len(all_ranks), num_processes) + + self._barrier() + + if dist.get_rank() == 0: + for f_name in os.listdir(test_dir): + os.unlink(os.path.join(test_dir, f_name)) + + self._barrier() + + def test_get_backend(self): + if dist.get_world_size() > 2: + group = [1, 2] + else: + group = [0, 1] + group_id = dist.new_group(group) + backend_str = BACKEND.lower() + self.assertEqual(dist.get_backend(), backend_str) + if dist.get_rank() in group: + self.assertEqual(dist.get_backend(group_id), backend_str) + else: + with self.assertRaisesRegex( + ValueError, "Invalid process group specified" + ): + dist.get_backend(group_id) + + def test_Backend_enum_class(self): + # test parsing + backend = BACKEND.lower() + self.assertEqual(dist.Backend(BACKEND.upper()), backend) + self.assertEqual(dist.Backend(BACKEND), backend) + with self.assertRaises(ValueError): + dist.Backend(None) + with self.assertRaises(ValueError): + dist.Backend(3) + with self.assertRaises(ValueError): + dist.Backend(["gloo"]) + + # Test destroy + def test_destroy_group(self): + if dist.get_world_size() > 2: + group = [1, 2] + else: + group = [0, 1] + group_id = dist.new_group(group) + self._barrier() + dist.destroy_process_group(group_id) + + # Test get rank and size of group + def test_get_rank_size_group(self): + if dist.get_world_size() > 2: + group = [1, 2] + else: + group = [0, 1] + group_id = dist.new_group(group) + if dist.get_rank() in group: + self.assertEqual(dist.get_world_size(group_id), 2) + self.assertTrue(dist.get_rank(group_id) in list(range(2))) + else: + self.assertEqual(dist.get_world_size(group_id), -1) + self.assertEqual(dist.get_rank(group_id), -1) + + # Test destroy full groups + def test_destroy_full_group(self): + _, group_id, _ = self._init_full_group_test() + self._barrier() + dist.destroy_process_group(group_id) + + # Test get rank and size of full group + def test_get_rank_size_full_group(self): + _, group_id, _ = self._init_full_group_test() + self.assertEqual(dist.get_world_size(group_id), dist.get_world_size()) + self.assertEqual(dist.get_rank(group_id), dist.get_rank()) + + def _test_barrier_timeout(self, group_id, timeout): + local_rank = dist.get_rank(group_id) + + # Only execute barrier on rank == 0, causing it to timeout + if local_rank == 0: + expected_time = time.time() + timeout.total_seconds() + # In debug mode, we execute a monitored_barrier before the + # collective, so assert on that. + if dist.get_debug_level() == dist.DebugLevel.DETAIL: + exception_ctx = self.assertRaisesRegex( + Exception, "failed to pass monitoredBarrier" + ) + else: + exception_ctx = self.assertRaisesRegex( + Exception, " (Timed out|closed|timeout) " + ) + with exception_ctx: + dist.barrier(group_id) + self.assertGreaterAlmostEqual(time.time(), expected_time, delta=0.1) + else: + pass + + @skip_but_pass_in_sandcastle_if( + BACKEND != "gloo", "Only gloo backend supports timeouts" + ) + @skip_but_pass_in_sandcastle_if( + not INIT_METHOD.startswith("file://"), + "Requires file:// initialization method. " + + "Both tcp:// and env:// rely on the TCP store for which " + "reinitialization has proven racy.", + ) + def test_barrier_timeout_global(self): + dist.destroy_process_group() + + # Explicitly pass world size to the barrier because we've + # just destroyed any state in torch.distributed. + self._barrier(wait_for=int(os.environ["WORLD_SIZE"])) + + # Reinitialize global process group + timeout = timedelta(seconds=1) + dist.init_process_group( + init_method=INIT_METHOD, + backend=BACKEND, + world_size=int(os.environ["WORLD_SIZE"]), + rank=self.rank, + timeout=timeout, + ) + self._test_barrier_timeout(dist.group.WORLD, timeout) + + @skip_if_small_worldsize + @skip_but_pass_in_sandcastle_if( + BACKEND != "gloo", "Only gloo backend supports timeouts" + ) + def test_barrier_timeout_group(self): + timeout = timedelta(seconds=5) + _, group_id, _ = self._init_group_test(timeout=timeout) + if group_id is not None: + self._test_barrier_timeout(group_id, timeout) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "gloo", "Only gloo backend supports timeouts" + ) + def test_barrier_timeout_full_group(self): + timeout = timedelta(seconds=1) + _, group_id, _ = self._init_full_group_test(timeout=timeout) + if group_id is not None: + self._test_barrier_timeout(group_id, timeout) + + # This test helper can only be used when using the Gloo or NCCL backend + # **and** both the Gloo and NCCL backends are available. + # See the @skip annotations below. + def _test_group_override_backend(self, initializer): + if BACKEND == "gloo": + new_backend = "nccl" + elif BACKEND == "nccl": + new_backend = "gloo" + elif BACKEND in DistTestCases.backend_feature["plugin"]: + new_backend = "gloo" + + group, group_id, rank = initializer(backend=new_backend) + if group_id is None: + return + + if new_backend == "gloo": + self.assertTrue(group_id._get_backend_name(), "gloo") + if new_backend == "nccl": + self.assertTrue(group_id._get_backend_name(), "nccl") + + self.assertEqual(rank, group[dist.get_rank(group_id)]) + self.assertEqual(len(group), dist.get_world_size(group_id)) + + # Pin device (so we avoid NCCL race conditions/deadlocks). + group_rank = dist.get_rank(group_id) + torch.cuda.set_device(group_rank) + + # Run broadcast of CUDA tensor (so it works for both Gloo and NCCL). + tensor = _build_tensor(2, value=group_rank).cuda() + dist.broadcast(tensor, src=group[0], group=group_id) + self.assertEqual(_build_tensor(2, value=0), tensor.to("cpu")) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @require_world_size(3) + @skip_if_lt_x_gpu(2) + def test_backend_group(self): + self._test_group_override_backend(self._init_group_test) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + @unittest.skipIf(BACKEND == "ucc", "broken, see https://github.com/pytorch/pytorch/pull/113620") + def test_backend_full_group(self): + self._test_group_override_backend(self._init_full_group_test) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["subgroup"], + f"The {BACKEND} backend does not support creating subgroups on CUDA devices", + ) + @require_world_size(4) + @skip_if_lt_x_gpu(2) + def test_new_subgroups(self): + subgroup_size = 2 + cur_subgroup, subgroups = dist.new_subgroups(subgroup_size) + + world_size = dist.get_world_size() + self.assertEqual(cur_subgroup.size(), subgroup_size) + self.assertEqual(len(subgroups), world_size / subgroup_size) + self.assertFalse(dist._rank_not_in_group(cur_subgroup)) + + for subgroup in subgroups: + dist.destroy_process_group(subgroup) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["subgroup"], + f"The {BACKEND} backend does not support creating subgroups on CUDA devices", + ) + @skip_if_no_gpu + def test_new_subgroups_group_size_exceeds_world_size(self): + with self.assertRaisesRegex(ValueError, "must not exceed"): + dist.new_subgroups(100) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["subgroup"], + f"The {BACKEND} backend does not support creating subgroups on CUDA devices", + ) + @require_world_size(4) + @skip_if_lt_x_gpu(4) + def test_new_subgroups_world_size_not_divisible_by_group_size(self): + with self.assertRaisesRegex( + ValueError, "The world size must be divisible by 'group_size'" + ): + dist.new_subgroups(3) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["subgroup"], + f"The {BACKEND} backend does not support creating subgroups on CUDA devices", + ) + @require_world_size(4) + @skip_if_lt_x_gpu(4) + def test_new_subgroups_by_enumeration(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + device_id = rank_to_GPU[rank][0] + cur_subgroup, subgroups = dist.new_subgroups_by_enumeration( + ranks_per_subgroup_list=[[0, 2], [1, 3]] + ) + if device_id >= 4: + self.assertIsNone(cur_subgroup) + else: + self.assertEqual(cur_subgroup.size(), 2) + self.assertEqual(len(subgroups), 2) + if device_id == 0 or device_id == 2: + self.assertEqual(cur_subgroup, subgroups[0]) + else: + self.assertEqual(cur_subgroup, subgroups[1]) + + for subgroup in subgroups: + dist.destroy_process_group(subgroup) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["subgroup"], + f"The {BACKEND} backend does not support creating subgroups on CUDA devices", + ) + @require_world_size(4) + @skip_if_lt_x_gpu(4) + def test_new_subgroups_by_enumeration_input_rank_exceeds_world_size(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + device_id = rank_to_GPU[rank][0] + world_size = get_world_size(group_id) + + with self.assertRaisesRegex( + RuntimeError, + "The new group's rank should be within the world_size set by init_process_group", + ): + dist.new_subgroups_by_enumeration( + ranks_per_subgroup_list=[[0, 1], [world_size, 2]] + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["subgroup"], + f"The {BACKEND} backend does not support creating subgroups on CUDA devices", + ) + @skip_if_no_gpu + def test_new_subgroups_by_enumeration_negative_input_rank(self): + group, group_id, rank = self._init_global_test() + + with self.assertRaisesRegex( + ValueError, + "The new group's rank should be within the world_size set by init_process_group", + ): + dist.new_subgroups_by_enumeration( + ranks_per_subgroup_list=[[-1, -2], [-3, -4]] + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["subgroup"], + f"The {BACKEND} backend does not support creating subgroups on CUDA devices", + ) + @require_world_size(4) + @skip_if_lt_x_gpu(4) + def test_new_subgroups_overlap_not_allowed(self): + with self.assertRaisesRegex( + ValueError, "Rank 1 has appeared in both subgroup" + ): + dist.new_subgroups_by_enumeration( + ranks_per_subgroup_list=[[0], [1, 2], [1, 3]] + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["subgroup"], + f"The {BACKEND} backend does not support creating subgroups on CUDA devices", + ) + @skip_if_lt_x_gpu(2) + def test_average_parameters(self): + rank = dist.get_rank() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + device_id = rank_to_GPU[rank][0] + + model = nn.Sequential( + nn.Conv2d(3, 3, kernel_size=3, padding=1), + nn.ReLU(), + nn.Linear(1, 5, bias=False), + ).cuda(device_id) + # Test global model averaging + for p in model.parameters(): + p.data = torch.ones_like(p.data) + model_averaging_utils.average_parameters( + params=model.parameters(), process_group=None + ) + # Every element will be the same as the input. + for p in model.parameters(): + self.assertEqual(p.data, torch.ones_like(p.data)) + + # Test partial model averaging + for p in model.parameters(): + p.data = torch.ones_like(p.data) * rank + group_nccl = dist.new_group(ranks=[0, 1], backend="nccl") + model_averaging_utils.average_parameters( + params=model.parameters(), process_group=group_nccl + ) + if not dist._rank_not_in_group(group_nccl): + # Every element on device 0 or 1 should be the average of 0 and 1, i.e., 0.5. + for p in model.parameters(): + self.assertEqual(p.data, torch.ones_like(p.data) * 0.5) + else: + # Every element on device not in the subgroup should remain the same. + for p in model.parameters(): + self.assertEqual(p.data, torch.ones_like(p.data) * rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["subgroup"], + f"The {BACKEND} backend does not support creating subgroups on CUDA devices", + ) + @skip_if_lt_x_gpu(2) + def test_periodic_model_averager(self): + rank = dist.get_rank() + world_size = dist.get_world_size() + rank_to_GPU = init_multigpu_helper(world_size, BACKEND) + device_id = rank_to_GPU[rank][0] + + model = nn.Linear(1, 5, bias=False).cuda(device_id) + param = next(model.parameters()) + tensor = torch.ones_like(param.data) * rank + expected_avg_tensor = ( + torch.ones_like(param.data) * sum(range(world_size)) / world_size + ) + period = 4 + for warmup_steps in [12, 13, 14, 15]: + averager = averagers.PeriodicModelAverager( + period=period, warmup_steps=warmup_steps + ) + for step in range(0, 20): + # Reset the parameters at every step. + param.data = copy.deepcopy(tensor) + for params in model.parameters(): + # mock grad + params.grad = torch.ones_like(param.data) + averager.average_parameters(model.parameters()) + if step >= warmup_steps and (step - warmup_steps) % period == 0: + self.assertEqual(param.data, expected_avg_tensor) + else: + # No model averaging, so the parameters are not updated. + self.assertEqual(param.data, tensor) + + @skip_if_lt_x_gpu(2) + def test_periodic_model_averager_param_group(self): + rank = dist.get_rank() + world_size = dist.get_world_size() + rank_to_GPU = init_multigpu_helper(world_size, BACKEND) + device_id = rank_to_GPU[rank][0] + + model = nn.Linear(1, 5, bias=False).cuda(device_id) + param = next(model.parameters()) + opt = torch.optim.SGD(model.parameters(), lr=0.1) + + period = 4 + for warmup_steps in [12, 13, 14, 15]: + averager = averagers.PeriodicModelAverager( + period=period, warmup_steps=warmup_steps + ) + for step in range(0, 20): + # Reset the parameters at every step. + for param_group in opt.param_groups: + for params in param_group["params"]: + # mock grad + params.grad = torch.ones_like(param.data) * rank + params.data = torch.ones_like(param.data) * rank + averager.average_parameters(opt.param_groups) + if step >= warmup_steps and (step - warmup_steps) % period == 0: + for param_group in opt.param_groups: + for params in param_group["params"]: + if params.grad is None: + continue + self.assertEqual( + param.data, + torch.ones_like(param.data) + * sum(range(world_size)) + / world_size, + ) + else: + # No model averaging, so the parameters are not updated. + for param_group in opt.param_groups: + for params in param_group["params"]: + if params.grad is None: + continue + self.assertEqual( + param.data, torch.ones_like(param.data) * rank + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["subgroup"], + f"The {BACKEND} backend does not support creating subgroups on CUDA devices", + ) + @skip_if_lt_x_gpu(2) + def test_1_level_hierarchical_model_averager_equivalent_to_periodic_model_averager( + self, + ): + rank = dist.get_rank() + world_size = dist.get_world_size() + rank_to_GPU = init_multigpu_helper(world_size, BACKEND) + device_id = rank_to_GPU[rank][0] + + model = nn.Linear(1, 5, bias=False).cuda(device_id) + param = next(model.parameters()) + tensor = torch.ones_like(param.data) * rank + expected_avg_tensor = ( + torch.ones_like(param.data) * sum(range(world_size)) / world_size + ) + period = 4 + for warmup_steps in [12, 13, 14, 15]: + averager = hierarchicalSGD.HierarchicalModelAverager( + # Run the global averaging at a period of 4, + # which is equivalent to the above periodic model averaging test case. + period_group_size_dict=OrderedDict([(period, world_size)]), + warmup_steps=warmup_steps, + ) + + averager = averagers.PeriodicModelAverager( + period=period, warmup_steps=warmup_steps + ) + for step in range(0, 20): + # Reset the parameters at every step. + param.data = copy.deepcopy(tensor) + for params in model.parameters(): + # mock grad + params.grad = torch.ones_like(param.data) + averager.average_parameters(model.parameters()) + if step >= warmup_steps and (step - warmup_steps) % period == 0: + self.assertEqual(param.data, expected_avg_tensor) + else: + # No model averaging, so the parameters are not updated. + self.assertEqual(param.data, tensor) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["subgroup"], + f"The {BACKEND} backend does not support creating subgroups on CUDA devices", + ) + @require_world_size(4) + @skip_if_lt_x_gpu(4) + def test_3_level_hierarchical_model_averager(self): + rank = dist.get_rank() + world_size = dist.get_world_size() + rank_to_GPU = init_multigpu_helper(world_size, BACKEND) + device_id = rank_to_GPU[rank][0] + + model = nn.Linear(1, 5, bias=False).cuda(device_id) + param = next(model.parameters()) + tensor = torch.ones_like(param.data) * rank + # Set up such a hierarchical model averaging as follows: + # after the first 10 warmup steps, + # run model averaging every 2 steps within each subgroup of size 2, + # run model averaging every 4 steps within each subgroup of size 3, + # and run the global model averaging every 8 steps. + # If there is a conflict in model averaging at a step, only run the highest-level model averaging. + warmup_steps = 10 + subgroup_size1 = 2 + subgroup_avg_period1 = 2 + subgroup_size2 = 4 + subgroup_avg_period2 = 4 + global_avg_period = 8 + period_group_size_dict = OrderedDict( + [ + (subgroup_avg_period1, subgroup_size1), + (subgroup_avg_period2, subgroup_size2), + (global_avg_period, world_size), + ] + ) + averager = hierarchicalSGD.HierarchicalModelAverager( + period_group_size_dict=period_group_size_dict, warmup_steps=warmup_steps + ) + self.assertEqual(dist.get_pg_count(), len(period_group_size_dict)) + + subgroup1 = averager.period_process_group_dict[subgroup_avg_period1] + subgroup2 = averager.period_process_group_dict[subgroup_avg_period2] + real_group_ranks_res1 = _get_pg_config(subgroup1)['ranks'] + real_group_ranks_res2 = _get_pg_config(subgroup2)['ranks'] + + expect_group_ranks_res1 = ( + rank // subgroup_size1 * subgroup_size1 + + np.array(list(range(subgroup_size1))) + ).tolist() + expect_group_ranks_res2 = ( + rank // subgroup_size2 * subgroup_size2 + + np.array(list(range(subgroup_size2))) + ).tolist() + self.assertEqual(real_group_ranks_res1, expect_group_ranks_res1) + self.assertEqual(real_group_ranks_res2, expect_group_ranks_res2) + + expected_avg_tensor_within_subgroup1 = ( + torch.ones_like(param.data) + * sum(real_group_ranks_res1) + / subgroup_size1 + ) + expected_avg_tensor_within_subgroup2 = ( + torch.ones_like(param.data) + * sum(real_group_ranks_res2) + / subgroup_size2 + ) + expected_global_avg_tensor = ( + torch.ones_like(param.data) * sum(range(world_size)) / world_size + ) + for step in range(0, 25): + # Reset the parameters at every step. + param.data = copy.deepcopy(tensor) + for params in model.parameters(): + # mock grad + params.grad = torch.ones_like(param.data) + averager.average_parameters(model.parameters()) + if step == 16 or step == 24: + # Run global model averaging when `step` can be divided by 8. + self.assertEqual(param.data, expected_global_avg_tensor) + elif step == 12 or step == 20: + # Run model averaging within subgroup when `step` can be divided by 4 but not by 8. + self.assertEqual(param.data, expected_avg_tensor_within_subgroup2) + elif step == 10 or step == 14 or step == 18 or step == 22: + # Run model averaging within subgroup when `step` can be divided by 2 but not by 4 or 8. + self.assertEqual(param.data, expected_avg_tensor_within_subgroup1) + else: + # No model averaging, so the parameters are not updated. + self.assertEqual(param.data, tensor) + + # Coalescing manager (sync mode) + @skip_if_no_gpu + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl" or IS_FBCODE or IS_SANDCASTLE, + "Coalescing manager currently tests with NCCL only; internal test flaky" + ) + def test_coalescing_manager(self): + self._barrier() + rank = dist.get_rank() + world_size = dist.get_world_size() + rank_to_GPU = init_multigpu_helper(world_size, BACKEND) + device_id = rank_to_GPU[rank][0] + torch.cuda.set_device(device_id) + num_colls = 2 + size_per_coll = 8 + small_tensors = [ + torch.ones(size_per_coll, device=device_id) for _ in range(num_colls) + ] + + with dist._coalescing_manager(): + for i in range(num_colls): + dist.all_reduce(small_tensors[i]) + + big_tensor = torch.ones(num_colls * size_per_coll, device=device_id) + dist.all_reduce(big_tensor) + + for i in range(num_colls): + self.assertEqual( + small_tensors[i], + big_tensor[i * size_per_coll : (i + 1) * size_per_coll] + ) + + self._barrier() + + # Coalescing manager (async mode) + @skip_if_no_gpu + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl" or IS_FBCODE or IS_SANDCASTLE, + "Coalescing manager currently tests with NCCL only; internal test flaky" + ) + def test_coalescing_manager_async(self): + self._barrier() + rank = dist.get_rank() + world_size = dist.get_world_size() + rank_to_GPU = init_multigpu_helper(world_size, BACKEND) + device_id = rank_to_GPU[rank][0] + torch.cuda.set_device(device_id) + num_colls = 2 + size_per_coll = 8 + small_tensors = [ + torch.ones(size_per_coll, device=device_id) for _ in range(num_colls) + ] + + with dist._coalescing_manager(async_ops=True) as cm: + for i in range(num_colls): + dist.all_reduce(small_tensors[i]) + cm.wait() + + big_tensor = torch.ones(num_colls * size_per_coll, device=device_id) + dist.all_reduce(big_tensor) + + for i in range(num_colls): + self.assertEqual( + small_tensors[i], + big_tensor[i * size_per_coll : (i + 1) * size_per_coll] + ) + + self._barrier() + + # NCCL Batch SEND RECV + @skip_if_no_gpu + @skip_but_pass_in_sandcastle_if(BACKEND != "nccl", "NCCL Batch Send Recv Only") + @requires_nccl_version((2, 7, 0), "Need NCCL 2.7+ for send/recv") + def test_batch_isend_irecv_nccl(self): + self._barrier() + rank = dist.get_rank() + world_size = dist.get_world_size() + rank_to_GPU = init_multigpu_helper(world_size, BACKEND) + device_id = rank_to_GPU[rank][0] + torch.cuda.set_device(device_id) + p2p_op_list = [] + recv_tensors = [None for _ in range(world_size)] + expected_tensors = [None for _ in range(world_size)] + + for val in ["1", "0"]: + os.environ["TORCH_NCCL_BLOCKING_WAIT"] = val + for src in range(0, world_size): + send_tensor = _build_tensor(rank + 1, device_id=device_id).fill_( + src + ) + recv_tensors[src] = _build_tensor( + src + 1, value=-1, device_id=device_id + ).fill_(-1) + expected_tensors[src] = _build_tensor( + src + 1, value=-1, device_id=device_id + ).fill_(rank) + recv_op = dist.P2POp(dist.irecv, recv_tensors[src], src) + p2p_op_list.append(recv_op) + send_op = dist.P2POp(dist.isend, send_tensor, src) + p2p_op_list.append(send_op) + + reqs = dist.batch_isend_irecv(p2p_op_list) + for req in reqs: + req.wait() + + for src in range(0, world_size): + self.assertEqual(recv_tensors[src], expected_tensors[src]) + + self._barrier() + + @skip_if_no_gpu + @skip_but_pass_in_sandcastle_if(BACKEND != "nccl", "NCCL Batch Send Recv Only") + @requires_nccl_version((2, 7, 0), "Need NCCL 2.7+ for send/recv") + def test_batch_isend_irecv_ring_exchange_nccl(self): + self._barrier() + rank = dist.get_rank() + world_size = dist.get_world_size() + rank_to_GPU = init_multigpu_helper(world_size, BACKEND) + device_id = rank_to_GPU[rank][0] + torch.cuda.set_device(device_id) + p2p_op_list = [] + + send_tensor = _build_tensor(world_size, device_id=device_id) + recv_tensor = _build_tensor(world_size, value=-1, device_id=device_id) + send_op = dist.P2POp(dist.isend, send_tensor, (rank + 1) % world_size) + recv_op = dist.P2POp( + dist.irecv, recv_tensor, (rank - 1 + world_size) % world_size + ) + reqs = dist.batch_isend_irecv([send_op, recv_op]) + for req in reqs: + req.wait() + + self._barrier() + + @skip_if_no_gpu + @skip_but_pass_in_sandcastle_if(BACKEND != "nccl", "NCCL Batch Send Recv Only") + @requires_nccl_version((2, 7, 0), "Need NCCL 2.7+ for send/recv") + def test_batch_isend_irecv_self_nccl(self): + self._barrier() + # Ensure the process group has been fully initialized (needed by + # the first sub-group batch_isend_irecv call) + dist.barrier() + rank = dist.get_rank() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + device_id = rank_to_GPU[rank][0] + p2p_op_list = [] + + if rank == 0: + send_tensor = _build_tensor(rank + 1, device_id=device_id) + recv_tensor = _build_tensor(rank + 1, value=-1, device_id=device_id) + recv_op = dist.P2POp(dist.irecv, recv_tensor, 0) + p2p_op_list.append(recv_op) + send_op = dist.P2POp(dist.isend, send_tensor, 0) + p2p_op_list.append(send_op) + + reqs = dist.batch_isend_irecv(p2p_op_list) + for req in reqs: + req.wait() + + self._barrier() + + @skip_if_no_gpu + @skip_if_small_worldsize + @skip_but_pass_in_sandcastle_if(BACKEND != "nccl", "NCCL Batch Send Recv Only") + @requires_nccl_version((2, 7, 0), "Need NCCL 2.7+ for send/recv") + def test_batch_isend_irecv_no_rank_zero_nccl(self): + self._barrier() + # Ensure the process group has been fully initialized (needed by + # the first sub-group batch_isend_irecv call) + dist.barrier() + rank = dist.get_rank() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + device_id = rank_to_GPU[rank][0] + torch.cuda.set_device(device_id) + p2p_op_list = [] + + if rank == 1: + peer = 2 + elif rank == 2: + peer = 1 + + if rank in [1, 2]: + send_tensor = _build_tensor(rank + 1, device_id=device_id) + recv_tensor = _build_tensor(peer + 1, value=-1, device_id=device_id) + recv_op = dist.P2POp(dist.irecv, recv_tensor, peer) + p2p_op_list.append(recv_op) + send_op = dist.P2POp(dist.isend, send_tensor, peer) + p2p_op_list.append(send_op) + + reqs = dist.batch_isend_irecv(p2p_op_list) + for req in reqs: + req.wait() + + self._barrier() + + # GLOO Batch SEND RECV CPU + @skip_but_pass_in_sandcastle_if(BACKEND != "gloo", "GLOO Batch Send Recv CPU") + def test_batch_isend_irecv_gloo(self): + self._barrier() + rank = dist.get_rank() + p2p_op_list = [] + + for src in range(0, dist.get_world_size()): + if src == rank: + continue + send_tensor = _build_tensor(rank + 1) + recv_tensor = _build_tensor(src + 1, value=-1) + recv_op = dist.P2POp(dist.irecv, recv_tensor, src) + p2p_op_list.append(recv_op) + send_op = dist.P2POp(dist.isend, send_tensor, src) + p2p_op_list.append(send_op) + + reqs = dist.batch_isend_irecv(p2p_op_list) + for req in reqs: + req.wait() + + self._barrier() + + # GLOO Batch SEND RECV CPU with provided tags + @skip_but_pass_in_sandcastle_if(BACKEND != "gloo", "GLOO Batch Send Recv CPU") + def test_batch_isend_irecv_gloo_tags(self): + self._barrier() + rank = dist.get_rank() + p2p_op_list = [] + + for src in range(0, dist.get_world_size()): + if src == rank: + continue + send_tensor = _build_tensor(rank + 1) + recv_tensor = _build_tensor(src + 1, value=-1) + recv_op = dist.P2POp(dist.irecv, recv_tensor, src, tag=src) + p2p_op_list.append(recv_op) + send_op = dist.P2POp(dist.isend, send_tensor, src, tag=rank) + p2p_op_list.append(send_op) + + reqs = dist.batch_isend_irecv(p2p_op_list) + for req in reqs: + req.wait() + + self._barrier() + + # NCCL Batch SEND RECV Op Error + @skip_but_pass_in_sandcastle_if(BACKEND != "nccl", "NCCL Batch Send Recv Only") + @requires_nccl_version((2, 7, 0), "Need NCCL 2.7+ for send/recv") + def test_batch_isend_irecv_op_err(self): + self._barrier() + rank = dist.get_rank() + if rank == 0: + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + device_id = rank_to_GPU[rank][0] + with self.assertRaisesRegex(ValueError, "^Invalid ``op``"): + send_tensor = _build_tensor(rank + 1, device_id=device_id) + send_op = dist.P2POp(dist.broadcast, send_tensor, 1) + dist.batch_isend_irecv([send_op]) + + # NCCL Batch SEND RECV p2p_op_list Error + @skip_but_pass_in_sandcastle_if(BACKEND != "nccl", "NCCL Batch Send Recv Only") + @requires_nccl_version((2, 7, 0), "Need NCCL 2.7+ for send/recv") + def test_batch_isend_irecv_op_list_err(self): + self._barrier() + rank = dist.get_rank() + if rank == 0: + with self.assertRaisesRegex(ValueError, "^Invalid ``p2p_op_list``"): + dist.batch_isend_irecv([1, 2]) + + # NCCL Batch SEND RECV Mixed Backend Error + @skip_but_pass_in_sandcastle_if(BACKEND != "nccl", "NCCL Batch Send Recv Only") + @requires_nccl_version((2, 7, 0), "Need NCCL 2.7+ for send/recv") + def test_batch_isend_irecv_mixed_backend_err(self): + self._barrier() + rank = dist.get_rank() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + device_id = rank_to_GPU[rank][0] + group_gloo = dist.new_group(ranks=[0, 1], backend="gloo") + group_nccl = dist.new_group(ranks=[0, 1], backend="nccl") + if rank == 0: + with self.assertRaisesRegex( + ValueError, "All ops need to use the same group" + ): + send_tensor = _build_tensor(rank + 1) + send_op_gloo = dist.P2POp(dist.isend, send_tensor, 1, group_gloo) + send_op_nccl = dist.P2POp(dist.isend, send_tensor, 1, group_nccl) + dist.batch_isend_irecv([send_op_gloo, send_op_nccl]) + + # NCCL SEND RECV + @skip_if_no_gpu + @skip_but_pass_in_sandcastle_if(BACKEND != "nccl", "NCCL Send Recv Only") + @requires_nccl_version((2, 7, 0), "Need NCCL 2.7+ for send/recv") + def _test_send_recv_nccl(self, profiler_ctx=None): + # TODO: now that nccl send/recv is supported, there does not seem to + # be a need to have nccl send/recv be tested separately. + rank = dist.get_rank() + world_size = dist.get_world_size() + rank_to_GPU = init_multigpu_helper(world_size, BACKEND) + device_id = rank_to_GPU[rank][0] + torch.cuda.set_device(device_id) + + tensor = _build_tensor(rank + 1, device_id=device_id) + profiler_cls = profiler_ctx if profiler_ctx is not None else nullcontext() + with profiler_cls as prof: + for src in range(0, world_size): + if src == rank: + # Send mode + for dst in range(0, world_size): + if dst == rank: + continue + dist.send(tensor, dst) + else: + # Recv mode + expected_tensor = _build_tensor(src + 1) + output_tensor = _build_tensor( + src + 1, value=-1, device_id=device_id + ) + dist.recv(output_tensor, src) + self.assertEqual(output_tensor, expected_tensor) + + self._barrier() + + if profiler_ctx is not None: + backend = dist.get_backend() + if backend in SEND_RECV_PROFILING_SUPPORTED_BACKENDS: + for event_name in [f"{backend}:send", f"{backend}:recv"]: + events = get_profiling_event(event_name, prof, dedup_gpu_user_annotation=True) + self.assertTrue(events) + # Event order is not deterministic, so simply assert their shape + # is found in the following list. + expected_shapes = [ + [[rank + 1] * 3] for rank in range(dist.get_world_size()) + ] + for event in events: + self.assertTrue(event.input_shapes in expected_shapes) + + @skip_if_no_gpu + @skip_but_pass_in_sandcastle_if(BACKEND != "nccl", "NCCL Send Recv Only") + @requires_nccl_version((2, 7, 0), "Need NCCL 2.7+ for send/recv") + def test_send_recv_nccl(self): + self._test_send_recv_nccl() + + @skip_if_no_gpu + @skip_but_pass_in_sandcastle_if(BACKEND != "nccl", "NCCL Send Recv Only") + @requires_nccl_version((2, 7, 0), "Need NCCL 2.7+ for send/recv") + def test_send_recv_nccl_autograd_profiler(self): + profiler_ctx = torch.autograd.profiler.profile(record_shapes=True) + self._test_send_recv_nccl(profiler_ctx) + + @skip_if_no_gpu + @skip_but_pass_in_sandcastle_if(BACKEND != "nccl", "NCCL Send Recv Only") + @requires_nccl_version((2, 7, 0), "Need NCCL 2.7+ for send/recv") + @skip_but_pass_in_sandcastle_if(IS_FBCODE, "Kineto in fbcode causes hang") + @skip_but_pass_in_sandcastle_if( + IS_MACOS or IS_WINDOWS, + "torch.profiler not enabled for mac/windows: https://github.com/pytorch/pytorch/pull/56124", + ) + def test_send_recv_nccl_torch_profiler(self): + profiler_ctx = torch.profiler.profile( + activities=[ + torch.profiler.ProfilerActivity.CPU, + torch.profiler.ProfilerActivity.CUDA, + ], + record_shapes=True, + ) + self._test_send_recv_nccl(profiler_ctx) + + # SEND RECV + def _test_send_recv(self, profiler_ctx): + rank = dist.get_rank() + send_size = rank + 1 + tensor = _build_tensor(send_size) + ctx = profiler_ctx if profiler_ctx is not None else nullcontext() + with ctx as prof: + for src in range(0, dist.get_world_size()): + if src == rank: + # Send mode + for dst in range(0, dist.get_world_size()): + if dst == rank: + continue + dist.send(tensor, dst) + else: + # Recv mode + recv_size = src + 1 + expected_tensor = _build_tensor(recv_size) + output_tensor = _build_tensor(recv_size, value=-1) + dist.recv(output_tensor, src) + self.assertEqual(output_tensor, expected_tensor) + + if profiler_ctx is not None: + backend = dist.get_backend() + if backend in SEND_RECV_PROFILING_SUPPORTED_BACKENDS: + for event_name in [f"{backend}:send", f"{backend}:recv"]: + events = get_profiling_event(event_name, prof) + # Each rank sends/recvs from all other ranks. + event_count = sum(e.count for e in events) + expected_event_count = dist.get_world_size() - 1 + self.assertEqual(event_count, expected_event_count) + # Event order is not deterministic, so simply assert their shape + # is found in the following list. + expected_shapes = [ + [[rank + 1] * 3] for rank in range(dist.get_world_size()) + ] + for event in events: + self.assertTrue(event.is_async) + self.assertTrue(event.input_shapes in expected_shapes) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl send/recv tested by test_send_recv_nccl" + ) + def test_send_recv(self): + self._test_send_recv(profiler_ctx=None) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "NCCL send/recv tested by test_send_recv_nccl" + ) + def test_send_recv_autograd_profiler(self): + autograd_profiler_ctx = _create_autograd_profiler() + self._test_send_recv(profiler_ctx=autograd_profiler_ctx) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "NCCL send/recv tested by test_send_recv_nccl" + ) + @skip_but_pass_in_sandcastle_if(IS_FBCODE, "Kineto in fbcode causes hang") + @skip_but_pass_in_sandcastle_if( + IS_MACOS or IS_WINDOWS, + "torch.profiler not enabled for mac/windows: https://github.com/pytorch/pytorch/pull/56124", + ) + def test_send_recv_torch_profiler(self): + torch_profiler_ctx = _create_torch_profiler() + return self._test_send_recv(profiler_ctx=torch_profiler_ctx) + + # SEND RECV ANY SOURCE + def _test_send_recv_any_source(self, profiler_ctx): + rank = dist.get_rank() + send_recv_size = 10 + tensor = _build_tensor(send_recv_size, value=rank) + recv_ranks = list() + irecv_ranks = list() + + ctx = profiler_ctx if profiler_ctx is not None else nullcontext() + with ctx as prof: + for dst in range(0, dist.get_world_size()): + if dst == rank: + # Recv mode + for dst in range(0, dist.get_world_size()): + if dst == rank: + continue + + for recv in ["recv", "irecv"]: + output_tensor = _build_tensor(send_recv_size, value=-1) + + if recv == "recv": + sender = dist.recv(output_tensor) + recv_ranks.append(sender) + elif recv == "irecv": + work = dist.irecv(output_tensor) + work.wait() + sender = work._source_rank() + irecv_ranks.append(sender) + + # Assert the scalar value "sender" that should be + # equal to the rank of the sender is equal to all + # values in the received tensor. + self.assertTrue(output_tensor.eq(sender).all()) + else: + # Send mode + dist.send(tensor, dst) # recv + dist.send(tensor, dst) # irecv + + if profiler_ctx is not None: + backend = dist.get_backend() + if backend in SEND_RECV_PROFILING_SUPPORTED_BACKENDS: + for event_name in [f"{backend}:send", f"{backend}:recvAnySource"]: + events = get_profiling_event(event_name, prof) + # Each rank sends/recvs from other rank twice. + self.assertEqual( + sum(event.count for event in events), + 2 * (dist.get_world_size() - 1), + ) + for event in events: + self.assertTrue(event.is_async) + self.assertEqual(event.input_shapes, [[send_recv_size] * 3]) + + # Each rank would have 2 * (world_size - 1) sends, verify that + # globally we receive the same amount on the other end. + recv_ranks_tensor = torch.cat( + (torch.tensor(recv_ranks), torch.tensor(irecv_ranks)), 0 + ) + global_recv_ranks = [ + torch.empty_like(recv_ranks_tensor) + for _ in range(dist.get_world_size()) + ] + dist.all_gather(global_recv_ranks, recv_ranks_tensor) + global_recv_ranks_list = [] + for tensor in global_recv_ranks: + global_recv_ranks_list += tensor.tolist() + + from itertools import groupby + + global_recv_ranks_list.sort() + frequency = [ + len(list(group)) for key, group in groupby(global_recv_ranks_list) + ] + self.assertEqual(dist.get_world_size(), len(frequency)) + self.assertEqual( + [2 * (dist.get_world_size() - 1)] * dist.get_world_size(), frequency + ) + self._barrier() + + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["sendrecv anysource"], + f"{BACKEND} does not support send/recv from any source", + ) + def test_send_recv_any_source(self): + self._test_send_recv_any_source(profiler_ctx=None) + + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["sendrecv anysource"], + f"{BACKEND} does not support send/recv from any source", + ) + def test_send_recv_any_source_autograd_profiler(self): + autograd_profiler_ctx = _create_autograd_profiler() + self._test_send_recv_any_source(profiler_ctx=autograd_profiler_ctx) + + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["sendrecv anysource"], + f"{BACKEND} does not support send/recv from any source", + ) + @skip_but_pass_in_sandcastle_if(IS_FBCODE, "Kineto in fbcode code causes hang") + @skip_but_pass_in_sandcastle_if( + IS_MACOS or IS_WINDOWS, + "torch.profiler not enabled for mac/windows: https://github.com/pytorch/pytorch/pull/56124", + ) + def test_send_recv_any_source_torch_profiler(self): + torch_profiler_ctx = _create_torch_profiler() + return self._test_send_recv_any_source(profiler_ctx=torch_profiler_ctx) + + # SEND RECV WITH TAG + def _test_send_recv_with_tag(self, profiler_ctx): + rank = dist.get_rank() + world_size = dist.get_world_size() + send_recv_size = 10 + tensor = _build_tensor(send_recv_size, value=rank) + ctx = profiler_ctx if profiler_ctx is not None else nullcontext() + with ctx as prof: + for dst in range(0, world_size): + if dst == rank: + # Recv mode + for src in range(0, world_size): + if src == rank: + continue + output_tensor = _build_tensor(send_recv_size, value=-1) + dist.recv(output_tensor, src, tag=src) + self.assertTrue(output_tensor.eq(src).all()) + else: + # Send mode + dist.send(tensor, dst, tag=rank) + + if profiler_ctx is not None: + backend = dist.get_backend() + if backend in SEND_RECV_PROFILING_SUPPORTED_BACKENDS: + for event_name in [f"{backend}:send", f"{backend}:recv"]: + events = get_profiling_event(event_name, prof) + # Each rank sends/recvs from all other ranks + event_count = sum(e.count for e in events) + expected_event_count = dist.get_world_size() - 1 + self.assertEqual(event_count, expected_event_count) + for event in events: + self.assertTrue(event.is_async) + self.assertEqual(event.name, event_name) + self.assertEqual(event.input_shapes, [[send_recv_size] * 3]) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "NCCL send/recv tested by test_send_recv_nccl" + ) + def test_send_recv_with_tag(self): + self._test_send_recv_with_tag(profiler_ctx=None) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "NCCL send/recv tested by test_send_recv_nccl" + ) + def test_send_recv_with_tag_autograd_profiler(self): + autograd_profiler_ctx = _create_autograd_profiler() + return self._test_send_recv_with_tag(profiler_ctx=autograd_profiler_ctx) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "NCCL send/recv tested by test_send_recv_nccl" + ) + @skip_but_pass_in_sandcastle_if(IS_FBCODE, "Kineto in fbcode code causes hang") + @skip_but_pass_in_sandcastle_if( + IS_MACOS or IS_WINDOWS, + "torch.profiler not enabled for mac/windows: https://github.com/pytorch/pytorch/pull/56124", + ) + def test_send_recv_with_tag_torch_profiler(self): + torch_profiler_ctx = _create_torch_profiler() + return self._test_send_recv_with_tag(profiler_ctx=torch_profiler_ctx) + + # ISEND + def _test_isend(self, profiler_ctx): + rank = dist.get_rank() + world_size = dist.get_world_size() + ctx = profiler_ctx if profiler_ctx is not None else nullcontext() + with ctx as prof: + if rank == 0: + requests = [ + dist.isend(_build_tensor(dest, 10), dest) + for dest in range(1, world_size) + ] + for request in requests: + request.wait() + self.assertTrue(request.is_completed()) + else: + tensor = _build_tensor(rank, -1) + dist.recv(tensor, 0) + self.assertEqual(tensor, _build_tensor(rank, 10)) + + self._barrier() + + if profiler_ctx is not None: + backend = dist.get_backend() + if backend in SEND_RECV_PROFILING_SUPPORTED_BACKENDS: + expected_event_name = ( + f"{backend}:send" if rank == 0 else f"{backend}:recv" + ) + events = get_profiling_event(expected_event_name, prof) + event_count = sum(e.count for e in events) + expected_count = dist.get_world_size() - 1 if rank == 0 else 1 + self.assertEqual(expected_count, event_count) + # Event ordering is not guaranteed, so simply ensure the shapes are + # found in the following map. + expected_shapes = { + r: [[r] * 3] for r in range(1, dist.get_world_size()) + } + for event in events: + self.assertTrue(event.is_async) + self.assertEqual(event.name, expected_event_name) + if rank == 0: + self.assertTrue( + event.input_shapes in expected_shapes.values() + ) + else: + self.assertEqual(event.input_shapes, expected_shapes[rank]) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support isend" + ) + def test_isend(self): + self._test_isend(profiler_ctx=None) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support isend" + ) + def test_isend_autograd_profiler(self): + autograd_profiler_ctx = _create_autograd_profiler() + self._test_isend(profiler_ctx=autograd_profiler_ctx) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support isend" + ) + @skip_but_pass_in_sandcastle_if(IS_FBCODE, "Kineto in fbcode code causes hang") + @skip_but_pass_in_sandcastle_if( + IS_MACOS or IS_WINDOWS, + "torch.profiler not enabled for mac/windows: https://github.com/pytorch/pytorch/pull/56124", + ) + def test_isend_torch_profiler(self): + torch_profiler_ctx = _create_torch_profiler() + self._test_isend(profiler_ctx=torch_profiler_ctx) + + # IRECV + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support irecv" + ) + def test_irecv(self): + rank = dist.get_rank() + world_size = dist.get_world_size() + + if rank == 0: + expected_tensors = [ + _build_tensor(src, -1) for src in range(1, world_size) + ] + requests = [ + dist.irecv(expected_tensors[src - 1], src) + for src in range(1, world_size) + ] + + for src in range(1, world_size): + requests[src - 1].wait() + self.assertTrue(requests[src - 1].is_completed()) + self.assertEqual(expected_tensors[src - 1], _build_tensor(src, 10)) + else: + tensor = _build_tensor(rank, 10) + dist.send(tensor, 0) + + self._barrier() + + # BROADCAST + def _test_broadcast_helper( + self, + group, + group_id, + rank, + cuda=False, + rank_to_GPU=None, + with_options=False, + ): + for dtype, value, requires_cuda in [ + (torch.float, -1e-10, False), + (torch.double, -1e-100, False), + (torch.half, -0.1, True), + (torch.int8, -2, False), + (torch.uint8, 129, False), + (torch.int, -1e5, False), + (torch.long, -1e15, False), + ]: + if requires_cuda and not cuda: + continue + for src in group: + expected_tensor = _build_tensor(src + 1, value, dtype) + if cuda: + expected_tensor = expected_tensor.cuda(rank_to_GPU[rank][0]) + if rank == src: + if with_options: + opts = dist.BroadcastOptions() + opts.rootTensor = 0 + opts.rootRank = src + self.call_dist_op( + ":broadcast", + True, + group_id.broadcast, + [expected_tensor], + opts, + ) + else: + self.call_dist_op( + ":broadcast", + False, + dist.broadcast, + expected_tensor, + src, + group_id, + ) + else: + tensor = _build_tensor(src + 1, -1, dtype) + if cuda: + tensor = tensor.cuda(rank_to_GPU[rank][0]) + if with_options: + opts = dist.BroadcastOptions() + opts.rootTensor = 0 + opts.rootRank = src + self.call_dist_op( + ":broadcast", True, group_id.broadcast, [tensor], opts + ) + else: + self.call_dist_op( + ":broadcast", + False, + dist.broadcast, + tensor, + src, + group_id, + ) + self.assertEqual(tensor.size(), expected_tensor.size()) + self.assertEqual( + tensor.ne(expected_tensor).max(), torch.tensor(False) + ) + + self._barrier() + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_broadcast(self): + group, group_id, rank = self._init_global_test() + self._test_broadcast_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "gloo" and BACKEND != "nccl", + "Only Gloo and Nccl backend supports CUDA allReduce", + ) + @skip_if_no_gpu + def test_broadcast_cuda(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + device_id = rank_to_GPU[rank][0] + torch.cuda.set_device(device_id) + self._test_broadcast_helper(group, group_id, rank, True, rank_to_GPU) + + @skip_if_small_worldsize + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_broadcast_group(self): + group, group_id, rank = self._init_group_test() + self._test_broadcast_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_broadcast_full_group(self): + group, group_id, rank = self._init_full_group_test() + self._test_broadcast_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", + "Only NCCL backend supports high priority stream", + ) + @skip_if_no_gpu + def test_nccl_high_priority_stream(self): + group, _, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + device_id = rank_to_GPU[rank][0] + torch.cuda.set_device(device_id) + + new_port = str(MASTER_PORT + 1) + os.environ["MASTER_PORT"] = new_port + gen_iterator = dist.rendezvous("env://", rank, dist.get_world_size()) + store, rank, size = next(gen_iterator) + store = dist.PrefixStore(new_port, store) + + opts = dist.ProcessGroupNCCL.Options() + opts.is_high_priority_stream = False + group_id = dist.ProcessGroupNCCL(store, rank, size, opts) + + self._test_broadcast_helper(group, group_id, rank, True, rank_to_GPU, True) + + # REDUCE + def _test_reduce_helper( + self, + group, + group_id, + rank, + op, + master_value, + worker_value, + expected_value, + cuda=False, + rank_to_GPU=None, + ): + for src in group: + tensor = _build_tensor(src + 1).fill_( + master_value if rank == src else worker_value + ) + if cuda: + tensor = tensor.cuda(rank_to_GPU[rank][0]) + self.call_dist_op( + ":reduce", + False, + dist.reduce, + tensor, + src, + op, + group_id, + tensor_shapes=[tensor.shape], + ) + if rank == src: + self.assertEqual(tensor, _build_tensor(src + 1, expected_value)) + + self._barrier() + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["reduce"], + f"{BACKEND} does not support reduce", + ) + def test_reduce_sum(self): + group, group_id, rank = self._init_global_test() + self._test_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.SUM, + 2, + 10, + 2 + (10 * (len(group) - 1)), + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA reduce" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["reduce"], + f"{BACKEND} does not support reduce", + ) + @skip_if_no_gpu + def test_reduce_sum_cuda(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + device_id = rank_to_GPU[rank][0] + torch.cuda.set_device(device_id) + self._test_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.SUM, + 2, + 10, + 2 + 10 * (len(group) - 1), + True, + rank_to_GPU, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["reduce"], + f"{BACKEND} does not support reduce", + ) + def test_reduce_product(self): + group, group_id, rank = self._init_global_test() + self._test_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.PRODUCT, + 2, + 10, + reduce(operator.mul, [10] * (len(group) - 1), 2), + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["reduce"], + f"{BACKEND} does not support reduce", + ) + def test_reduce_min(self): + group, group_id, rank = self._init_global_test() + self._test_reduce_helper( + group, group_id, rank, dist.ReduceOp.MIN, 1010, 1, 1 + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["reduce"], + f"{BACKEND} does not support reduce", + ) + def test_reduce_max(self): + group, group_id, rank = self._init_global_test() + self._test_reduce_helper( + group, group_id, rank, dist.ReduceOp.MAX, -1, 10, 10 + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["reduce"], + f"{BACKEND} does not support reduce", + ) + @skip_if_small_worldsize + def test_reduce_group_sum(self): + group, group_id, rank = self._init_group_test() + self._test_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.SUM, + 2, + 10, + 2 + (10 * (len(group) - 1)), + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["reduce"], + f"{BACKEND} does not support reduce", + ) + @skip_if_small_worldsize + def test_reduce_group_product(self): + group, group_id, rank = self._init_group_test() + self._test_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.PRODUCT, + 2, + 10, + reduce(operator.mul, [10] * (len(group) - 1), 2), + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["reduce"], + f"{BACKEND} does not support reduce", + ) + @skip_if_small_worldsize + def test_reduce_group_min(self): + group, group_id, rank = self._init_group_test() + self._test_reduce_helper( + group, group_id, rank, dist.ReduceOp.MIN, 1010, 1, 1 + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["reduce"], + f"{BACKEND} does not support reduce", + ) + @skip_if_small_worldsize + def test_reduce_group_max(self): + group, group_id, rank = self._init_group_test() + self._test_reduce_helper( + group, group_id, rank, dist.ReduceOp.MAX, -1, 10, 10 + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["reduce"], + f"{BACKEND} does not support reduce", + ) + def test_reduce_full_group_sum(self): + group, group_id, rank = self._init_full_group_test() + self._test_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.SUM, + 2, + 10, + 2 + (10 * (len(group) - 1)), + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["reduce"], + f"{BACKEND} does not support reduce", + ) + def test_reduce_full_group_product(self): + group, group_id, rank = self._init_full_group_test() + self._test_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.PRODUCT, + 2, + 10, + reduce(operator.mul, [10] * (len(group) - 1), 2), + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["reduce"], + f"{BACKEND} does not support reduce", + ) + def test_reduce_full_group_min(self): + group, group_id, rank = self._init_full_group_test() + self._test_reduce_helper( + group, group_id, rank, dist.ReduceOp.MIN, 1010, 1, 1 + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["reduce"], + f"{BACKEND} does not support reduce", + ) + def test_reduce_full_group_max(self): + group, group_id, rank = self._init_full_group_test() + self._test_reduce_helper( + group, group_id, rank, dist.ReduceOp.MAX, -1, 10, 10 + ) + + # REDUCE TWICE + def _test_reduce_twice_helper( + self, + group, + group_id, + rank, + op, + master_value, + worker_value, + expected_value, + cuda=False, + rank_to_GPU=None, + ): + for src in group: + tensors = [ + _build_tensor(src + 1).fill_( + master_value if rank == src else worker_value + ) + for i in range(2) + ] + if cuda: + for i in range(2): + tensors[i] = tensors[i].cuda(rank_to_GPU[rank][0]) + self.call_dist_op( + ":reduce", + False, + dist.reduce, + tensors[0], + src, + op, + group_id, + secondary_op_call=lambda: dist.reduce( + tensors[1], src, op, group_id + ), + tensor_shapes=[tensors[0].shape], + ) + if rank == src: + for tensor in tensors: + self.assertEqual(tensor, _build_tensor(src + 1, expected_value)) + + self._barrier() + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["reduce"], + f"{BACKEND} does not support reduce", + ) + def test_reduce_sum_twice(self): + group, group_id, rank = self._init_global_test() + self._test_reduce_twice_helper( + group, + group_id, + rank, + dist.ReduceOp.SUM, + 2, + 10, + 2 + (10 * (len(group) - 1)), + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA reduce" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["reduce"], + f"{BACKEND} does not support reduce", + ) + @skip_if_no_gpu + def test_reduce_sum_cuda_twice(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + device_id = rank_to_GPU[rank][0] + torch.cuda.set_device(device_id) + self._test_reduce_twice_helper( + group, + group_id, + rank, + dist.ReduceOp.SUM, + 2, + 10, + 2 + 10 * (len(group) - 1), + True, + rank_to_GPU, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports reduce_scatter_v" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["reduce"], + f"{BACKEND} does not support reduce", + ) + @skip_if_no_gpu + def test_reduce_scatter_v_cuda(self): + self._barrier() + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + device_id = rank_to_GPU[rank][0] + + input_split_sizes = [] + for src in group: + input_split_sizes.append(src + 1) + start_len = sum(input_split_sizes[:rank]) + end_len = start_len + input_split_sizes[rank] + sum_len = sum(input_split_sizes) + master_value = 2 + worker_value = 10 + + for async_val in [True, False]: + tensor = _build_tensor(sum_len, worker_value, device_id=device_id) + tensor[start_len:end_len].fill_(master_value) + out_tensor = ( + torch.empty( + input_split_sizes[rank], sum_len, sum_len, dtype=torch.float + ) + .fill_(-1) + .cuda(device_id) + ) + + req = dist.reduce_scatter( + out_tensor, + list(torch.split(tensor, input_split_sizes)), + dist.ReduceOp.SUM, + group_id, + async_val, + ) + if async_val: + req.wait() + + expected_value = 2 + (10 * (len(group) - 1)) + expected_tensor = torch.empty( + input_split_sizes[rank], sum_len, sum_len, dtype=torch.float + ) + expected_tensor = expected_tensor.fill_(expected_value).cuda(device_id) + + self.assertEqual(out_tensor, expected_tensor) + self._barrier() + + # Test reduce_scatter_tensor accepting single tensor as input + def _reduce_scatter_tensor_helper( + self, tensor_out, tensor_in, group_id, rank, cuda=True, rank_to_GPU=None + ): + if cuda: + tensor_in = tensor_in.cuda(rank_to_GPU[rank][0]) + tensor_out = tensor_out.cuda(rank_to_GPU[rank][0]) + tensor_shapes = [tensor_out.shape] + self.call_dist_op( + ":reduce_scatter_tensor", + False, + dist.reduce_scatter_tensor, + tensor_out, + tensor_in, + dist.ReduceOp.SUM, + group_id, + False, + expect_event=False, + tensor_shapes=tensor_shapes, + ) + return tensor_out + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA reduce_scatter_tensor" + ) + @skip_if_no_gpu + def test_reduce_scatter_tensor_cuda(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + size = 2 + tensor_out = torch.zeros(size, dtype=torch.int64) + + # Concatenated input + tensor_in = torch.arange(len(group) * size) + tensor_out = self._reduce_scatter_tensor_helper( + tensor_out, tensor_in, group_id, rank, True, rank_to_GPU + ) + # Check result + expected_tensor = torch.arange(rank * size, (rank + 1) * size) * len(group) + self.assertEqual(tensor_out, expected_tensor) + self._barrier() + + # Stacked input + tensor_in = torch.reshape(tensor_in, (len(group), size)) + tensor_out = self._reduce_scatter_tensor_helper( + tensor_out, tensor_in, group_id, rank, True, rank_to_GPU + ) + # Check result + # Should be the same as the result in concatenated case + self.assertEqual(tensor_out, expected_tensor) + self._barrier() + + def call_dist_op( + self, + profiling_title_postfix, + is_async, + op, + *args, + expect_event=True, + secondary_op_call=None, + profile_cuda=False, + tensor_shapes=None, + **kwargs, + ): + op_calls = [lambda: op(*args, **kwargs)] + if secondary_op_call is not None: + op_calls.append(secondary_op_call) + + autograd_profiler_ctx = torch.autograd.profiler.profile( + use_cuda=profile_cuda, record_shapes=True + ) + + # TODO: move this test to use torch.profiler once kineto issues are + # fixed internally. + with autograd_profiler_ctx as prof: + works = [op_call() for op_call in op_calls] + if is_async: + for work in works: + work.wait() + + if expect_event and dist.get_backend() in PROFILING_SUPPORTED_BACKENDS: + # We are only interested in the backend's implementation not the dispatcher wrapper. + events = get_profiling_event( + dist.get_backend() + profiling_title_postfix, autograd_profiler_ctx + ) + # DETAIL debug mode can use a pg wrapper that issues more collectives + # under the hood + if dist.get_debug_level() != dist.DebugLevel.DETAIL: + self.assertEqual(len(events), len(op_calls)) + for e in events: + self.assertTrue(e.is_async) + self.assertEqual(e.count, 1) + self.assertGreaterEqual(e.cpu_time, 0) + # Verify tensor shapes if given + # DETAIL debug mode can use a pg wrapper that issues more collectives + # under the hood + if ( + tensor_shapes is not None + and dist.get_debug_level() != dist.DebugLevel.DETAIL + ): + self.assertEqual( + e.input_shapes, + tensor_shapes, + f"event shape: {e.input_shapes} vs tensor {tensor_shapes}", + ) + + # ALL REDUCE + def _test_all_reduce_helper( + self, + group, + group_id, + rank, + op, + master_value, + worker_value, + expected_value, + cuda=False, + rank_to_GPU=None, + dtype=torch.float, + async_op=False, + ): + for src in group: + curr_value = master_value if rank == src else worker_value + + tensor = _build_tensor(src + 1, dtype=dtype).fill_(curr_value) + if cuda: + tensor = tensor.cuda(rank_to_GPU[rank][0]) + if tensor.dtype == torch.complex64: + tensor_shapes = [torch.view_as_real(tensor).shape] + else: + tensor_shapes = [tensor.shape] + self.call_dist_op( + ":all_reduce", + async_op, + dist.all_reduce, + tensor, + op, + group_id, + async_op=async_op, + tensor_shapes=tensor_shapes, + ) + # Currently, only Gloo backend has profiling tested with CUDA enabled. + # Only run cuda profiling test for one rank to speed up since + # running with different src_rank does not affect the correctness. + if ( + src == 0 + and cuda + and dist.get_backend() in CUDA_PROFILING_SUPPORTED_BACKENDS + ): + self.call_dist_op( + ":all_reduce", + async_op, + dist.all_reduce, + tensor, + op, + group_id, + async_op=async_op, + profile_cuda=True, + tensor_shapes=tensor_shapes, + ) + + self._barrier() + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_reduce_sum(self): + group, group_id, rank = self._init_global_test() + self._test_all_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.SUM, + 2, + 10, + 2 + (10 * (len(group) - 1)), + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_reduce_sum_async(self): + group, group_id, rank = self._init_global_test() + self._test_all_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.SUM, + 2, + 10, + 2 + (10 * (len(group) - 1)), + async_op=True, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "gloo" and BACKEND != "nccl", + "Only Gloo and NCCL backends will have CUDA allReduce tested", + ) + @skip_if_no_gpu + def test_all_reduce_sum_cuda(self): + torch.cuda.set_device(self.rank) + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.SUM, + 2, + 10, + 2 + (10 * (len(group) - 1)), + True, + rank_to_GPU, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "gloo" and BACKEND != "nccl", + "Only Gloo and NCCL backends will have CUDA allReduce tested", + ) + @skip_if_no_gpu + def test_all_reduce_sum_cuda_async(self): + torch.cuda.set_device(self.rank) + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.SUM, + 2, + 10, + 2 + (10 * (len(group) - 1)), + True, + rank_to_GPU, + async_op=True, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_reduce_sum_complex(self): + group, group_id, rank = self._init_global_test() + self._test_all_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.SUM, + complex(2, 3), + complex(10, 11), + complex(2, 3) + (complex(10, 11) * (len(group) - 1)), + dtype=torch.cfloat, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_reduce_complex_unsupported_ops(self): + unsupported_ops = [ + dist.ReduceOp.MAX, + dist.ReduceOp.MIN, + dist.ReduceOp.PRODUCT, + dist.ReduceOp.BAND, + dist.ReduceOp.BOR, + dist.ReduceOp.BXOR, + ] + group, group_id, rank = self._init_global_test() + for unsupported_op in unsupported_ops: + with self.assertRaisesRegex( + ValueError, "all_reduce does not support" + ): + dist.all_reduce( + _build_tensor(1, dtype=torch.cfloat), unsupported_op, group_id + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "gloo" and BACKEND != "nccl", + "Only Gloo and NCCL backends will have CUDA allReduce tested", + ) + @skip_if_no_gpu + def test_all_reduce_sum_cuda_complex(self): + torch.cuda.set_device(self.rank) + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.SUM, + complex(2, 3), + complex(10, 11), + complex(2, 3) + (complex(10, 11) * (len(group) - 1)), + True, + rank_to_GPU, + dtype=torch.cfloat, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_reduce_product(self): + group, group_id, rank = self._init_global_test() + self._test_all_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.PRODUCT, + 2, + 10, + reduce(operator.mul, [10] * (len(group) - 1), 2), + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_reduce_min(self): + group, group_id, rank = self._init_global_test() + self._test_all_reduce_helper( + group, group_id, rank, dist.ReduceOp.MIN, 1010, 1, 1 + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_reduce_max(self): + group, group_id, rank = self._init_global_test() + self._test_all_reduce_helper( + group, group_id, rank, dist.ReduceOp.MAX, -1, 10, 10 + ) + + @skip_if_small_worldsize + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_reduce_group_sum(self): + group, group_id, rank = self._init_group_test() + self._test_all_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.SUM, + 2, + 10, + 2 + (10 * (len(group) - 1)), + ) + + @skip_if_small_worldsize + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_reduce_group_product(self): + group, group_id, rank = self._init_group_test() + self._test_all_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.PRODUCT, + 2, + 10, + reduce(operator.mul, [10] * (len(group) - 1), 2), + ) + + @skip_if_small_worldsize + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_reduce_group_min(self): + group, group_id, rank = self._init_group_test() + self._test_all_reduce_helper( + group, group_id, rank, dist.ReduceOp.MIN, 1010, 1, 1 + ) + + @skip_if_small_worldsize + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_reduce_group_max(self): + group, group_id, rank = self._init_group_test() + self._test_all_reduce_helper( + group, group_id, rank, dist.ReduceOp.MAX, -1, 10, 10 + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_reduce_full_group_sum(self): + group, group_id, rank = self._init_full_group_test() + self._test_all_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.SUM, + 2, + 10, + 2 + (10 * (len(group) - 1)), + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_reduce_full_group_product(self): + group, group_id, rank = self._init_full_group_test() + self._test_all_reduce_helper( + group, + group_id, + rank, + dist.ReduceOp.PRODUCT, + 2, + 10, + reduce(operator.mul, [10] * (len(group) - 1), 2), + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_reduce_full_group_min(self): + group, group_id, rank = self._init_full_group_test() + self._test_all_reduce_helper( + group, group_id, rank, dist.ReduceOp.MIN, 1010, 1, 1 + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_reduce_full_group_max(self): + group, group_id, rank = self._init_full_group_test() + self._test_all_reduce_helper( + group, group_id, rank, dist.ReduceOp.MAX, -1, 10, 10 + ) + + # SPARSE ALL REDUCE + def _test_sparse_all_reduce_sum(self, fn): + group, group_id, rank = self._init_global_test() + + tests = simple_sparse_reduce_tests( + rank, dist.get_world_size(), num_inputs=1 + ) + for (inputs, outputs) in tests: + tensors = [fn(input) for input in inputs] + dist.all_reduce(tensors[0], dist.ReduceOp.SUM, group_id) + self.assertEqual(tensors[0], outputs[0]) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "gloo", "Only Gloo backend support sparse all reduce" + ) + def test_sparse_all_reduce_sum(self): + self._test_sparse_all_reduce_sum(lambda t: t) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "gloo", "Only Gloo backend support sparse all reduce" + ) + @skip_if_no_gpu + def test_sparse_all_reduce_sum_cuda(self): + self._test_sparse_all_reduce_sum(lambda t: t.clone().cuda()) + + # ALL REDUCE - COALESCED + @staticmethod + def _all_reduce_coalesced_sum_test_cases(group_size): + return ( + [2, 3, complex(2, 3)], + [10, 11, complex(10, 11)], + [ + 2 + 10 * (group_size - 1), + 3 + 11 * (group_size - 1), + complex(2, 3) + complex(10, 11) * (group_size - 1), + ], + [torch.float, torch.float, torch.cfloat], + ) + + @staticmethod + def _all_reduce_coalesced_product_test_cases(group_size): + return ( + [1, 2], + [3, 4], + [1 * 3 ** (group_size - 1), 2 * 4 ** (group_size - 1)], + [torch.float, torch.float], + ) + + @staticmethod + def _all_reduce_coalesced_min_test_cases(group_size): + return ( + [1, 4], + [2, 3], + [1, 3], + [torch.float, torch.float], + ) + + @staticmethod + def _all_reduce_coalesced_max_test_cases(group_size): + return ( + [1, 4], + [2, 3], + [2, 4], + [torch.float, torch.float], + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_reduce_coalesced_max_complex_unsupported(self): + group, group_id, rank = self._init_global_test() + with self.assertRaisesRegex(ValueError, "all_reduce does not support"): + dist.all_reduce_coalesced( + [_build_tensor(1, dtype=torch.cfloat)], dist.ReduceOp.MAX, group_id + ) + + def _test_all_reduce_coalesced_helper( + self, + group, + group_id, + rank, + op, + cuda=False, + rank_to_GPU=None, + ): + test_case_func = { + dist.ReduceOp.SUM: self._all_reduce_coalesced_sum_test_cases, + dist.ReduceOp.PRODUCT: self._all_reduce_coalesced_product_test_cases, + dist.ReduceOp.MIN: self._all_reduce_coalesced_min_test_cases, + dist.ReduceOp.MAX: self._all_reduce_coalesced_max_test_cases, + }[op] + + master_values, worker_values, expected_values, dtypes = test_case_func( + len(group) + ) + + for src in group: + curr_values = master_values if rank == src else worker_values + tensors = [ + _build_tensor(src + 1, val, dtype=dtype) + for dtype, val in zip(dtypes, curr_values) + ] + if cuda: + tensors = [t.cuda(rank_to_GPU[rank][0]) for t in tensors] + tensor_shapes = [] + for tensor in tensors: + if tensor.dtype == torch.complex64: + tensor_shapes.append(torch.view_as_real(tensor).shape) + else: + tensor_shapes.append(tensor.shape) + self.call_dist_op( + ":all_reduce", + False, + dist.all_reduce_coalesced, + tensors, + op, + group_id, + tensor_shapes=tensor_shapes, + ) + expected_tensors = [ + _build_tensor(src + 1, expected_value, dtype=dtype) + for dtype, expected_value in zip(dtypes, expected_values) + ] + self.assertEqual(tensors, expected_tensors) + + self._barrier() + + @require_backend_is_available({"gloo"}) + def test_all_reduce_coalesced_sum(self): + group, group_id, rank = self._init_global_test() + self._test_all_reduce_coalesced_helper( + group, + group_id, + rank, + dist.ReduceOp.SUM, + cuda=False, + rank_to_GPU=None, + ) + + @require_backend_is_available({"gloo"}) + def test_all_reduce_coalesced_product(self): + group, group_id, rank = self._init_global_test() + self._test_all_reduce_coalesced_helper( + group, + group_id, + rank, + dist.ReduceOp.PRODUCT, + cuda=False, + rank_to_GPU=None, + ) + + @require_backend_is_available({"gloo"}) + def test_all_reduce_coalesced_min(self): + group, group_id, rank = self._init_global_test() + self._test_all_reduce_coalesced_helper( + group, + group_id, + rank, + dist.ReduceOp.MIN, + cuda=False, + rank_to_GPU=None, + ) + + @require_backend_is_available({"gloo"}) + def test_all_reduce_coalesced_max(self): + group, group_id, rank = self._init_global_test() + self._test_all_reduce_coalesced_helper( + group, group_id, rank, dist.ReduceOp.MAX, cuda=False, rank_to_GPU=None + ) + + @skip_if_small_worldsize + @require_backend_is_available({"gloo"}) + def test_all_reduce_coalesced_group_sum(self): + group, group_id, rank = self._init_group_test() + self._test_all_reduce_coalesced_helper( + group, group_id, rank, dist.ReduceOp.SUM, cuda=False, rank_to_GPU=None + ) + + @skip_if_small_worldsize + @require_backend_is_available({"gloo"}) + def test_all_reduce_coalesced_group_product(self): + group, group_id, rank = self._init_group_test() + self._test_all_reduce_coalesced_helper( + group, + group_id, + rank, + dist.ReduceOp.PRODUCT, + cuda=False, + rank_to_GPU=None, + ) + + @skip_if_small_worldsize + @require_backend_is_available({"gloo"}) + def test_all_reduce_coalesced_group_min(self): + group, group_id, rank = self._init_group_test() + self._test_all_reduce_coalesced_helper( + group, group_id, rank, dist.ReduceOp.MIN, cuda=False, rank_to_GPU=None + ) + + @skip_if_small_worldsize + @require_backend_is_available({"gloo"}) + def test_all_reduce_coalesced_group_max(self): + group, group_id, rank = self._init_group_test() + self._test_all_reduce_coalesced_helper( + group, group_id, rank, dist.ReduceOp.MAX, cuda=False, rank_to_GPU=None + ) + + @require_backend_is_available({"gloo"}) + def test_all_reduce_coalesced_full_group_sum(self): + group, group_id, rank = self._init_full_group_test() + self._test_all_reduce_coalesced_helper( + group, group_id, rank, dist.ReduceOp.SUM, cuda=False, rank_to_GPU=None + ) + + @require_backend_is_available({"gloo"}) + def test_all_reduce_coalesced_full_group_product(self): + group, group_id, rank = self._init_full_group_test() + self._test_all_reduce_coalesced_helper( + group, + group_id, + rank, + dist.ReduceOp.PRODUCT, + cuda=False, + rank_to_GPU=None, + ) + + @require_backend_is_available({"gloo"}) + def test_all_reduce_coalesced_full_group_min(self): + group, group_id, rank = self._init_full_group_test() + self._test_all_reduce_coalesced_helper( + group, + group_id, + rank, + dist.ReduceOp.MIN, + cuda=False, + rank_to_GPU=None, + ) + + @require_backend_is_available({"gloo"}) + def test_all_reduce_coalesced_full_group_max(self): + group, group_id, rank = self._init_full_group_test() + self._test_all_reduce_coalesced_helper( + group, group_id, rank, dist.ReduceOp.MAX, cuda=False, rank_to_GPU=None + ) + + # SCATTER + def _test_scatter_helper( + self, group, group_id, rank, cuda=False, rank_to_GPU=None, dtype=torch.float + ): + for dest in group: + tensor = _build_tensor(dest + 1, -1, dtype=dtype) + expected_tensor = _build_tensor(dest + 1, rank, dtype=dtype) + tensors = ( + [_build_tensor(dest + 1, i, dtype=dtype) for i in group] + if rank == dest + else [] + ) + if cuda: + tensor = tensor.cuda(rank_to_GPU[rank][0]) + tensors = [t.cuda(rank_to_GPU[rank][0]) for t in tensors] + if dtype == torch.complex64: + tensor_shapes = [torch.view_as_real(t).shape for t in tensors] + else: + tensor_shapes = [t.shape for t in tensors] + self.call_dist_op( + ":scatter", + False, + dist.scatter, + tensor, + src=dest, + scatter_list=tensors, + group=group_id, + expect_event=False, + tensor_shapes=tensor_shapes, + ) + self.assertEqual(tensor, expected_tensor) + + self._barrier() + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND == "ucc", "CPU tensor ops not supported by UCP TL" + ) + def test_scatter_checks(self): + group, group_id, rank = self._init_global_test() + one = torch.ones([1]) + + # Specify scatter_list argument only on source rank. + output = one.clone() * -1 + if rank == 0: + scatter_list = [one.clone() * i for i in group] + dist.scatter(output, src=0, scatter_list=scatter_list) + else: + dist.scatter(output, src=0) + self.assertEqual(output, one * rank) + + # Don't specify src argument. + output = one.clone() * -1 + if rank == 0: + scatter_list = [one.clone() * i for i in group] + dist.scatter(output, scatter_list=scatter_list) + else: + dist.scatter(output) + self.assertEqual(output, one * rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND == "ucc", "CPU tensor ops not supported by UCP TL" + ) + def test_scatter(self): + group, group_id, rank = self._init_global_test() + self._test_scatter_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA gather" + ) + @skip_if_no_gpu + def test_scatter_cuda(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_scatter_helper(group, group_id, rank, True, rank_to_GPU) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND == "ucc", "CPU tensor ops not supported by UCP TL" + ) + def test_scatter_complex(self): + group, group_id, rank = self._init_global_test() + self._test_scatter_helper(group, group_id, rank, dtype=torch.cfloat) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA gather" + ) + @skip_if_no_gpu + def test_scatter_cuda_complex(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_scatter_helper( + group, group_id, rank, True, rank_to_GPU, dtype=torch.cfloat + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND == "ucc", "CPU tensor ops not supported by UCP TL" + ) + @skip_if_small_worldsize + def test_scatter_group(self): + group, group_id, rank = self._init_group_test() + self._test_scatter_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND == "ucc", "CPU tensor ops not supported by UCP TL" + ) + def test_scatter_full_group(self): + group, group_id, rank = self._init_full_group_test() + self._test_scatter_helper(group, group_id, rank) + + # GATHER + def _test_gather_helper( + self, group, group_id, rank, cuda=False, rank_to_GPU=None + ): + for dest in group: + tensor = _build_tensor(dest + 1, rank) + tensors = ( + [_build_tensor(dest + 1, -1) for i in group] if rank == dest else [] + ) + if cuda: + tensor = tensor.cuda(rank_to_GPU[rank][0]) + tensors = [t.cuda(rank_to_GPU[rank][0]) for t in tensors] + self.call_dist_op( + ":gather", + False, + dist.gather, + tensor, + dst=dest, + gather_list=tensors, + group=group_id, + expect_event=False, + tensor_shapes=[tensors[0].shape] if len(tensors) > 0 else None, + ) + if rank == dest: + expected_tensors = [_build_tensor(dest + 1, i) for i in group] + for t1, t2 in zip(tensors, expected_tensors): + self.assertEqual(t1, t2) + + self._barrier() + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND == "ucc", "CPU tensor ops not supported by UCP TL" + ) + def test_gather_checks(self): + group, group_id, rank = self._init_global_test() + one = torch.ones([1]) + + # Specify gather_list argument only on destination rank. + if rank == 0: + gather_list = [one.clone() for _ in group] + dist.gather(one * rank, dst=0, gather_list=gather_list) + for i in group: + self.assertEqual(gather_list[i], one * i) + else: + dist.gather(one * rank, dst=0) + + # Don't specify dst argument. + if rank == 0: + gather_list = [one.clone() for _ in group] + dist.gather(one * rank, gather_list=gather_list) + for i in group: + self.assertEqual(gather_list[i], one * i) + else: + dist.gather(one * rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND == "ucc", "CPU tensor ops not supported by UCP TL" + ) + def test_gather(self): + group, group_id, rank = self._init_global_test() + self._test_gather_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA gather" + ) + @skip_if_no_gpu + def test_gather_cuda(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_gather_helper(group, group_id, rank, True, rank_to_GPU) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND == "ucc", "CPU tensor ops not supported by UCP TL" + ) + @skip_if_small_worldsize + def test_gather_group(self): + group, group_id, rank = self._init_group_test() + self._test_gather_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND == "ucc", "CPU tensor ops not supported by UCP TL" + ) + def test_gather_full_group(self): + group, group_id, rank = self._init_full_group_test() + self._test_gather_helper(group, group_id, rank) + + # ALL GATHER + def _test_all_gather_helper( + self, group, group_id, rank, cuda=False, rank_to_GPU=None, dtype=torch.float + ): + for dest in group: + tensor = _build_tensor(dest + 1, rank, dtype=dtype) + tensors = [_build_tensor(dest + 1, -1, dtype=dtype) for i in group] + allgather = dist.all_gather + if cuda: + tensor = tensor.cuda(rank_to_GPU[rank][0]) + tensors = [t.cuda(rank_to_GPU[rank][0]) for t in tensors] + if tensors[0].dtype == torch.complex64: + tensor_shapes = [torch.view_as_real(tensors[0]).shape] + else: + tensor_shapes = [tensors[0].shape] + self.call_dist_op( + ":all_gather", + False, + allgather, + tensors, + tensor, + group_id, + False, + tensor_shapes=tensor_shapes, + ) + + expected_tensors = [ + _build_tensor(dest + 1, i, dtype=dtype) for i in group + ] + for t1, t2 in zip(tensors, expected_tensors): + self.assertEqual(t1, t2) + + self._barrier() + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_gather(self): + group, group_id, rank = self._init_global_test() + self._test_all_gather_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA all gather" + ) + @skip_if_no_gpu + def test_all_gather_cuda(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_gather_helper(group, group_id, rank, True, rank_to_GPU) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_gather_complex(self): + group, group_id, rank = self._init_global_test() + self._test_all_gather_helper(group, group_id, rank, dtype=torch.cfloat) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA all gather" + ) + @skip_if_no_gpu + def test_all_gather_cuda_complex(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_gather_helper( + group, group_id, rank, True, rank_to_GPU, dtype=torch.cfloat + ) + + @skip_if_small_worldsize + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_gather_group(self): + group, group_id, rank = self._init_group_test() + self._test_all_gather_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "Nccl does not support CPU tensors" + ) + def test_all_gather_full_group(self): + group, group_id, rank = self._init_full_group_test() + self._test_all_gather_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports all_gather_v" + ) + @skip_if_no_gpu + def test_all_gather_v_cuda(self): + self._barrier() + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + device_id = rank_to_GPU[rank][0] + + output_split_sizes = [] + for dst in group: + output_split_sizes.append(dst + 1) + sum_len = sum(output_split_sizes) + value = 2 + + for async_val in [True, False]: + tensor = ( + torch.empty( + output_split_sizes[rank], sum_len, sum_len, dtype=torch.float + ) + .fill_(value) + .cuda(device_id) + ) + out_tensor = _build_tensor(sum_len, -1, device_id=device_id) + + req = dist.all_gather( + list(torch.split(out_tensor, output_split_sizes)), + tensor, + group_id, + async_val, + ) + if async_val: + req.wait() + + expected_value = value + expected_tensor = _build_tensor( + sum_len, expected_value, device_id=device_id + ) + + self.assertEqual(out_tensor, expected_tensor) + self._barrier() + + # Test all_gather accepting single tensor as output + def _all_gather_into_tensor_helper( + self, tensor_out, tensor_in, group_id, rank, cuda=True, rank_to_GPU=None + ): + if cuda: + tensor_in = tensor_in.cuda(rank_to_GPU[rank][0]) + tensor_out = tensor_out.cuda(rank_to_GPU[rank][0]) + if tensor_out.dtype == torch.complex64: + tensor_shapes = [torch.view_as_real(tensor_in).shape] + else: + tensor_shapes = [tensor_in.shape] + self.call_dist_op( + ":all_gather_into_tensor", + False, + dist.all_gather_into_tensor, + tensor_out, + tensor_in, + group_id, + False, + expect_event=False, + tensor_shapes=tensor_shapes, + ) + return tensor_out + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA all_gather_into_tensor" + ) + @skip_if_no_gpu + def test_all_gather_into_cat_tensor_cuda(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + size = 2 + tensor_in = torch.ones([size, size]) * rank + # Concatenated output + tensor_out = torch.ones([len(group) * size, size]) * (-1) + tensor_out = self._all_gather_into_tensor_helper( + tensor_out, tensor_in, group_id, rank, True, rank_to_GPU + ) + + # Check result + # Concatenate all blocks into a bigger tensor + expected_tensor = torch.cat([torch.ones([size, size]) * i for i in group]) + self.assertEqual(tensor_out, expected_tensor) + self._barrier() + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA all_gather_into_tensor" + ) + @skip_if_no_gpu + def test_all_gather_into_stack_tensor_cuda(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + size = 2 + tensor_in = torch.ones([size, size]) * rank + # Stacked output + tensor_out = torch.ones([len(group), size, size]) * (-1) + tensor_out = self._all_gather_into_tensor_helper( + tensor_out, tensor_in, group_id, rank, True, rank_to_GPU + ) + + # Check result + # Stack all blocks into a bigger tensor + expected_tensor = torch.stack([torch.ones([size, size]) * i for i in group]) + self.assertEqual(tensor_out, expected_tensor) + self._barrier() + + def _run_all_gather_coalesced_and_verify( + self, output_tensor_lists, input_tensors, expected_tensors, group_id + ): + """ + Helper that runs all_gather_coalesced and returns true if output + matches expectations. + """ + tensor_shapes = [] + for input_tensor in input_tensors: + if input_tensor.dtype == torch.complex64: + tensor_shapes.append(torch.view_as_real(input_tensor).shape) + else: + tensor_shapes.append(input_tensor.shape) + self.call_dist_op( + ":all_gather", + False, + dist.all_gather_coalesced, + output_tensor_lists, + input_tensors, + group_id, + tensor_shapes=tensor_shapes, + ) + + for l1, l2 in zip(output_tensor_lists, expected_tensors): + for t1, t2 in zip(l1, l2): + if not torch.equal(t1, t2): + return False + return True + + def _test_all_gather_coalesced_helper( + self, group, group_id, rank, dtype=torch.float + ): + # TODO: Instead we should probably go through _rank_not_in_group + # mechanism to disable sending tensors + if group_id is not None: + for test_case_id in range(2, 5): + # Make sure we create tensors of incompatible sizes, e.g. + # [1], [2x2], [3x3x3] ... to be sent in one batch + input_tensors = [ + _build_multidim_tensor( + tensor_id, tensor_id, rank + tensor_id, dtype=dtype + ) + for tensor_id in range(1, test_case_id) + ] + output_tensor_lists = [ + [ + _build_multidim_tensor( + tensor_id, tensor_id, -1, dtype=dtype + ) + for tensor_id in range(1, test_case_id) + ] + for _ in group + ] + expected_tensors = [ + [ + _build_multidim_tensor( + tensor_id, tensor_id, rank_iter + tensor_id, dtype=dtype + ) + for tensor_id in range(1, test_case_id) + ] + for rank_iter in group + ] + assert self._run_all_gather_coalesced_and_verify( + output_tensor_lists, input_tensors, expected_tensors, group_id + ), "output tensors do not match expected outputs" + + self._barrier() + + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["allgather_coalesced"], + f"{BACKEND} does not support all_gather_coalesced", + ) + def test_all_gather_coalesced_simple(self): + group, group_id, rank = self._init_global_test() + self._test_all_gather_coalesced_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["allgather_coalesced"], + f"{BACKEND} does not support all_gather_coalesced", + ) + def test_all_gather_coalesced_complex(self): + group, group_id, rank = self._init_global_test() + self._test_all_gather_coalesced_helper( + group, group_id, rank, dtype=torch.cfloat + ) + + @skip_if_small_worldsize + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["allgather_coalesced"], + f"{BACKEND} does not support all_gather_coalesced", + ) + def test_all_gather_coalesced_group(self): + group, group_id, rank = self._init_group_test() + self._test_all_gather_coalesced_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["allgather_coalesced"], + f"{BACKEND} does not support all_gather_coalesced", + ) + def test_all_gather_coalesced_full_group(self): + group, group_id, rank = self._init_full_group_test() + self._test_all_gather_coalesced_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["allgather_coalesced"], + f"{BACKEND} does not support all_gather_coalesced", + ) + def test_all_gather_coalesced_with_empty(self): + group, group_id, rank = self._init_global_test() + input_tensors = [ + rank * torch.ones([2, 2]), + torch.ones([0]), + (rank + 1) * torch.ones([3, 3]), + torch.ones([0]), + torch.ones([0]), + ] + output_tensors_lists = [ + [ + -1 * torch.ones([2, 2]), + -1 * torch.ones([0]), + -1 * torch.ones([3, 3]), + -1 * torch.ones([0]), + -1 * torch.ones([0]), + ] + for _ in group + ] + expected_tensors = [ + [ + r * torch.ones([2, 2]), + torch.ones([0]), + (r + 1) * torch.ones([3, 3]), + torch.ones([0]), + torch.ones([0]), + ] + for r in group + ] + assert self._run_all_gather_coalesced_and_verify( + output_tensors_lists, input_tensors, expected_tensors, group_id + ) + self._barrier() + + # AllToAll + def _test_all_to_all_single_equal_split_helper( + self, group, group_id, rank, cuda=False, rank_to_GPU=None, dtype=torch.float + ): + if group_id is not None: + size = len(group) + in_tensor = torch.ones([size, size], dtype=dtype) * rank + expected_tensor = torch.cat( + [torch.ones([1, size], dtype=dtype) * i for i in group] + ) + out_tensor = torch.ones([size, size], dtype=dtype) * -1 + if cuda: + in_tensor = in_tensor.cuda(rank_to_GPU[rank][0]) + expected_tensor = expected_tensor.cuda(rank_to_GPU[rank][0]) + out_tensor = out_tensor.cuda(rank_to_GPU[rank][0]) + if dtype == torch.complex64: + tensor_shapes = [torch.view_as_real(in_tensor).shape] + else: + tensor_shapes = [in_tensor.shape] + self.call_dist_op( + ":all_to_all", + False, + dist.all_to_all_single, + out_tensor, + in_tensor, + group=group_id, + tensor_shapes=tensor_shapes, + ) + self.assertEqual(out_tensor, expected_tensor) + self._barrier() + + def _test_all_to_all_single_unequal_split_helper( + self, group, group_id, rank, cuda=False, rank_to_GPU=None, dtype=torch.float + ): + if group_id is not None: + size = len(group) + in_splits = [i + 1 for i in group] + out_splits = [rank + 1 for _ in group] + in_tensor = torch.ones([sum(in_splits), size], dtype=dtype) * rank + out_tensor = torch.ones([(rank + 1) * size, size], dtype=dtype) + expected_tensor = torch.cat( + [torch.ones([rank + 1, size], dtype=dtype) * i for i in group] + ) + if cuda: + in_tensor = in_tensor.cuda(rank_to_GPU[rank][0]) + expected_tensor = expected_tensor.cuda(rank_to_GPU[rank][0]) + out_tensor = out_tensor.cuda(rank_to_GPU[rank][0]) + dist.all_to_all_single( + out_tensor, in_tensor, out_splits, in_splits, group=group_id + ) + self.assertEqual(out_tensor, expected_tensor) + self._barrier() + + def _test_all_to_all_helper( + self, + group, + group_id, + rank, + cuda=False, + rank_to_GPU=None, + dtype=torch.float, + ): + if group_id is not None: + size = len(group) + in_splits = [i + 1 for i in group] + in_tensors = [ + torch.ones([in_splits[i], size], dtype=dtype) * rank + for i, _ in enumerate(group) + ] + out_tensors = [ + torch.ones([(rank + 1), size], dtype=dtype) for _ in group + ] + expected_tensors = [ + torch.ones([rank + 1, size], dtype=dtype) * i for i in group + ] + if cuda: + in_tensors = [t.cuda(rank_to_GPU[rank][0]) for t in in_tensors] + expected_tensors = [ + t.cuda(rank_to_GPU[rank][0]) for t in expected_tensors + ] + out_tensors = [t.cuda(rank_to_GPU[rank][0]) for t in out_tensors] + dist.all_to_all(out_tensors, in_tensors, group=group_id) + for t1, t2 in zip(out_tensors, expected_tensors): + self.assertEqual(t1, t2) + self._barrier() + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi", "Only MPI supports CPU all_to_all_single" + ) + def test_all_to_all_single_equal_split(self): + group, group_id, rank = self._init_global_test() + self._test_all_to_all_single_equal_split_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA all_to_all_single" + ) + @skip_if_no_gpu + def test_all_to_all_single_equal_split_cuda(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_to_all_single_equal_split_helper( + group, + group_id, + rank, + True, + rank_to_GPU, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi", "Only MPI supports CPU all_to_all_single" + ) + def test_all_to_all_single_equal_split_complex(self): + group, group_id, rank = self._init_global_test() + self._test_all_to_all_single_equal_split_helper( + group, group_id, rank, dtype=torch.cfloat + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA all_to_all_single" + ) + @skip_if_no_gpu + def test_all_to_all_single_equal_split_cuda_complex(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_to_all_single_equal_split_helper( + group, group_id, rank, True, rank_to_GPU, dtype=torch.cfloat + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi", "Only MPI supports CPU all_to_all_single" + ) + def test_all_to_all_single_unequal_split(self): + group, group_id, rank = self._init_global_test() + self._test_all_to_all_single_unequal_split_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA all_to_all_single" + ) + @skip_if_no_gpu + def test_all_to_all_single_unequal_split_cuda(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_to_all_single_unequal_split_helper( + group, + group_id, + rank, + True, + rank_to_GPU, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi", "Only MPI supports CPU all_to_all_single" + ) + def test_all_to_all_single_unequal_split_complex(self): + group, group_id, rank = self._init_global_test() + self._test_all_to_all_single_unequal_split_helper( + group, group_id, rank, dtype=torch.cfloat + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA all_to_all_single" + ) + @skip_if_no_gpu + def test_all_to_all_single_unequal_split_cuda_complex(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_to_all_single_unequal_split_helper( + group, + group_id, + rank, + True, + rank_to_GPU, + dtype=torch.cfloat, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi", "Only MPI supports all_to_all" + ) + def test_all_to_all(self): + group, group_id, rank = self._init_global_test() + self._test_all_to_all_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only NCCL supports CUDA all_to_all" + ) + @skip_if_rocm + def test_all_to_all_cuda(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_to_all_helper(group, group_id, rank, True, rank_to_GPU) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi", "Only MPI supports all_to_all" + ) + def test_all_to_all_complex(self): + group, group_id, rank = self._init_global_test() + self._test_all_to_all_helper(group, group_id, rank, dtype=torch.cfloat) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only NCCL supports CUDA all_to_all" + ) + @skip_if_rocm + def test_all_to_all_cuda_complex(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_to_all_helper( + group, group_id, rank, True, rank_to_GPU, dtype=torch.cfloat + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi", "Only MPI supports CPU all_to_all_single" + ) + @skip_if_small_worldsize + def test_all_to_all_single_equal_split_group(self): + group, group_id, rank = self._init_group_test() + self._test_all_to_all_single_equal_split_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA all_to_all_single" + ) + @skip_if_no_gpu + @skip_if_small_worldsize + def test_all_to_all_single_equal_split_group_cuda(self): + group, group_id, rank = self._init_group_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_to_all_single_equal_split_helper( + group, + group_id, + rank, + True, + rank_to_GPU, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi", "Only MPI supports CPU all_to_all_single" + ) + @skip_if_small_worldsize + def test_all_to_all_single_unequal_split_group(self): + group, group_id, rank = self._init_group_test() + self._test_all_to_all_single_unequal_split_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA all_to_all_single" + ) + @skip_if_no_gpu + @skip_if_small_worldsize + def test_all_to_all_single_unequal_split_group_cuda(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_to_all_single_unequal_split_helper( + group, + group_id, + rank, + True, + rank_to_GPU, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi", "Only MPI supports all_to_all" + ) + @skip_if_small_worldsize + def test_all_to_all_group(self): + group, group_id, rank = self._init_group_test() + self._test_all_to_all_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA all_to_all_single" + ) + @skip_if_small_worldsize + @skip_if_rocm + def test_all_to_all_group_cuda(self): + group, group_id, rank = self._init_group_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_to_all_helper(group, group_id, rank, True, rank_to_GPU) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi", "Only MPI supports CPU all_to_all_single" + ) + def test_all_to_all_single_equal_split_full_group(self): + group, group_id, rank = self._init_full_group_test() + self._test_all_to_all_single_equal_split_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA all_to_all_single" + ) + @skip_if_no_gpu + def test_all_to_all_single_equal_split_full_group_cuda(self): + group, group_id, rank = self._init_full_group_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_to_all_single_equal_split_helper( + group, + group_id, + rank, + True, + rank_to_GPU, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi", "Only MPI supports CPU all_to_all_single" + ) + def test_all_to_all_single_unequal_split_full_group(self): + group, group_id, rank = self._init_full_group_test() + self._test_all_to_all_single_unequal_split_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only Nccl supports CUDA all_to_all_single" + ) + @skip_if_no_gpu + def test_all_to_all_single_unequal_split_full_group_cuda(self): + group, group_id, rank = self._init_full_group_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_to_all_single_unequal_split_helper( + group, + group_id, + rank, + True, + rank_to_GPU, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi", "Only MPI supports all_to_all" + ) + def test_all_to_all_full_group(self): + group, group_id, rank = self._init_full_group_test() + self._test_all_to_all_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", "Only NCCL supports CUDA all_to_all" + ) + @skip_if_rocm + def test_all_to_all_full_group_cuda(self): + group, group_id, rank = self._init_full_group_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_all_to_all_helper(group, group_id, rank, True, rank_to_GPU) + + # BARRIER + def _test_barrier_helper( + self, group, group_id, rank, cuda=False, rank_to_GPU=None + ): + WAIT_TIME = 0.3 # seconds + + for dest in group: + expected_time = torch.DoubleTensor(1).fill_(0.0) + if cuda: + expected_time = expected_time.cuda(rank_to_GPU[rank][0]) + if dest == rank: + expected_time.fill_(time.time() + WAIT_TIME) + dist.broadcast(expected_time, dest, group_id) + time.sleep(WAIT_TIME + 0.1) # sleep a little bit longer + dist.barrier(group_id) + else: + dist.broadcast(expected_time, dest, group_id) + dist.barrier(group_id) + self.assertGreaterAlmostEqual( + float(time.time()), + float(expected_time[0]), + "destination rank: %d, my rank: %d" % (dest, rank) + + " (if you see this failure, please report in #14554)", + ) + + # Use higher timeout for the instance where the test runs + # against a subgroup and uses a CUDA tensor for expected time. + # The CUDA initialization for the participating processes can + # take long enough for the barrier timeout to trigger on the + # process that doesn't participate in the group. + self._barrier(timeout=20) + + @skip_if_no_gpu + @skip_but_pass_in_sandcastle_if( + BACKEND == "mpi", "MPI doesn't supports GPU barrier" + ) + @skip_but_pass_in_sandcastle_if( + BACKEND == "ucc" and IS_SANDCASTLE, "Skipped internally" + ) + def test_barrier_cuda(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_barrier_helper(group, group_id, rank, True, rank_to_GPU) + + @skip_if_small_worldsize + @skip_if_no_gpu + @skip_but_pass_in_sandcastle_if( + BACKEND == "mpi", "MPI doesn't supports GPU barrier" + ) + def test_barrier_group_cuda(self): + group, group_id, rank = self._init_group_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_barrier_helper(group, group_id, rank, True, rank_to_GPU) + + @skip_if_small_worldsize + @skip_if_no_gpu + @skip_but_pass_in_sandcastle_if( + BACKEND == "mpi", "MPI doesn't supports GPU barrier" + ) + def test_barrier_full_group_cuda(self): + group, group_id, rank = self._init_full_group_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + self._test_barrier_helper(group, group_id, rank, True, rank_to_GPU) + + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["cpu barrier"], + f"{BACKEND} does not support CPU barrier", + ) + def test_barrier(self): + group, group_id, rank = self._init_global_test() + self._test_barrier_helper(group, group_id, rank) + + @skip_if_small_worldsize + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["cpu barrier"], + f"{BACKEND} does not support CPU barrier", + ) + def test_barrier_group(self): + group, group_id, rank = self._init_group_test() + self._test_barrier_helper(group, group_id, rank) + + @skip_but_pass_in_sandcastle_if( + BACKEND in DistTestCases.skip_collective["cpu barrier"], + f"{BACKEND} does not support CPU barrier", + ) + def test_barrier_full_group(self): + group, group_id, rank = self._init_full_group_test() + self._test_barrier_helper(group, group_id, rank) + + def _model_step(self, model): + for param in model.parameters(): + if param.grad is not None: + with torch.no_grad(): + param += param.grad + param.grad = None + + def _model_step_with_zero_grad(self, model): + for param in model.parameters(): + if param.grad is not None: + with torch.no_grad(): + param += param.grad + param.grad.requires_grad_(False) + param.grad.zero_() + + def _prepare_dummy_data(self, local_bs): + # global_bs for DDP should be divisible by WORLD_SIZE + world_size = int(os.environ["WORLD_SIZE"]) + global_bs = world_size * local_bs + input_cpu = torch.randn(global_bs, 2) + target = torch.randn(global_bs, 4) + loss = nn.MSELoss() + return global_bs, input_cpu, target, loss + + # END TO END TEST FOR DISTRIBUTEDDATAPARALLEL + def _test_DDP_helper( + self, model, input_var, target, loss, scale_factor=1.0, memory_format=None + ): + model.train() + output = model(input_var) + l = loss(output, target) * scale_factor + l.backward() + if memory_format is not None: + self.assertTrue(output.is_contiguous(memory_format=memory_format)) + + def _assert_equal_param(self, param_gpu, param_DDP): + self.assertEqual(len(param_gpu), len(param_DDP)) + for p_gpu, p_DDP in zip(param_gpu, param_DDP): + self.assertEqual(p_gpu, p_DDP) + + def _test_DDP_niter( + self, + model_base, + model_DDP, + input, + target, + loss, + local_bs, + rank, + batch_size, + test_save, + offset=None, + world_size=0, + zero_grad=False, + memory_format=None, + n_iter=5, + ): + for idx in range(n_iter): + # single cpu/gpu training + self._test_DDP_helper( + model_base, input, target, loss, memory_format=memory_format + ) + + if offset is None: + offset = rank * local_bs + + # DDP training, DDP scatters subsets of input_cpu to nodes/GPUs + self._test_DDP_helper( + model_DDP, + input[offset : offset + local_bs], + target[offset : offset + local_bs], + loss, + world_size * local_bs / batch_size if world_size != 0 else 1, + memory_format=memory_format, + ) + + # Update weights and run a second iteration to shake out errors + if zero_grad: + self._model_step_with_zero_grad(model_base) + self._model_step_with_zero_grad(model_DDP) + else: + self._model_step(model_base) + self._model_step(model_DDP) + self._assert_equal_param( + list(model_base.parameters()), list(model_DDP.module.parameters()) + ) + + # Shuffle the input so that DDP input is different + input = input[torch.randperm(batch_size)] + + # save the model in the middle and reload + if test_save and idx == 2 and INIT_METHOD.startswith("file://"): + with tempfile.NamedTemporaryFile() as tmp: + if sys.platform == "win32": + torch.save(model_DDP, tmp) + tmp.seek(0) + model_DDP = torch.load(tmp) + else: + torch.save(model_DDP, tmp.name) + model_DDP = torch.load(tmp.name) + + with tempfile.TemporaryFile() as tmp_file: + torch.save(model_DDP, tmp_file) + tmp_file.seek(0) + saved_model = torch.load(tmp_file) + for k in model_DDP.state_dict(): + self.assertEqual(model_DDP.state_dict()[k], saved_model.state_dict()[k]) + + def _test_DistributedDataParallel( + self, + gpu_subset, + rank, + output_device=None, + gradient_as_bucket_view=False, + static_graph=False, + set_static_graph_twice=False, + ): + # Run a simple end to end DDP model, use result of single node model + # as baseline + + # cpu training setup + model = DDP_NET + + # single gpu training setup + model_gpu = copy.deepcopy(model) + model_gpu.cuda(gpu_subset[0]) + + # DDP training setup + model_DDP = copy.deepcopy(model) + model_DDP.cuda(gpu_subset[0]) + model_DDP = nn.parallel.DistributedDataParallel( + model_DDP, + device_ids=gpu_subset, + gradient_as_bucket_view=gradient_as_bucket_view, + static_graph=static_graph, + ) + + if set_static_graph_twice: + model_DDP._set_static_graph() + + # test serializable/unserializable + with tempfile.NamedTemporaryFile() as tmp: + if sys.platform == "win32": + torch.save(model_DDP, tmp) + tmp.seek(0) + model_DDP = torch.load(tmp) + else: + torch.save(model_DDP, tmp.name) + model_DDP = torch.load(tmp.name) + + # dummy data initialization + local_bs = len(gpu_subset) + global_bs, input_cpu, target, loss = self._prepare_dummy_data(local_bs) + + # check two model parameters over 5 iterations + self._test_DDP_niter( + model_gpu, + model_DDP, + input_cpu.cuda(gpu_subset[0]), + target.cuda(gpu_subset[0]), + loss, + local_bs, + rank, + global_bs, + True, + ) + self._barrier() + + def _test_DistributedDataParallelCPU(self, gradient_as_bucket_view=False): + # Run a simple end to end DDP-CPU model, use result of single node + # model as baseline + group, group_id, rank = self._init_global_test() + + # cpu training setup + model_base = DDP_NET + + # DDP-CPU training setup + model_DDP = copy.deepcopy(model_base) + model_DDP = nn.parallel.DistributedDataParallel( + model_DDP, gradient_as_bucket_view=gradient_as_bucket_view + ) + + # dummy data initialization + local_bs = 2 + global_bs, input_cpu, target, loss = self._prepare_dummy_data(local_bs) + + # check two model parameters over 5 iterations + self._test_DDP_niter( + model_base, + model_DDP, + input_cpu, + target, + loss, + local_bs, + rank, + global_bs, + False, + zero_grad=True, + ) + self._barrier() + + return model_DDP + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "nccl does not support DDP on CPU models" + ) + def test_DistributedDataParallelCPU(self): + self._test_DistributedDataParallelCPU() + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "nccl does not support DDP on CPU models" + ) + def test_DistributedDataParallelCPU_grad_is_view(self): + self._test_DistributedDataParallelCPU(gradient_as_bucket_view=True) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_DistributedDataParallel_requires_grad(self): + # a module without gradients shouldn't be accepted + self.assertRaises( + RuntimeError, lambda: nn.parallel.DistributedDataParallel(nn.Module()) + ) + self._barrier() + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_lt_x_gpu(int(os.environ["WORLD_SIZE"])) + def test_ddp_zero_output_features(self): + class ToyModel(nn.Module): + def __init__(self): + super().__init__() + self.net1 = nn.Linear(10, 10) + self.relu = nn.ReLU() + self.net2 = nn.Linear(10, 0) + + model = ToyModel().to(self.rank) + ddp_model = nn.parallel.DistributedDataParallel( + model, device_ids=[self.rank] + ) + + @skip_but_pass_in_sandcastle_if(BACKEND == "nccl", "Gloo-only test") + def test_ddp_create_graph(self): + class Model(nn.Module): + def __init__(self): + super().__init__() + self.p = nn.Parameter(torch.tensor(1.0)) + + def forward(self): + return self.p.pow(2) + + model = Model() + ddp_model = torch.nn.parallel.DistributedDataParallel(model) + for _ in range(6): + # Verify DDP doesn't throw when ran with create_graph=True. + # Although we do warn about potential issues, please see + # https://github.com/pytorch/pytorch/issues/63929 for details. + ddp_model().backward(create_graph=True) + # grad tensors should require grad. + self.assertTrue( + all(param.requires_grad for param in ddp_model.parameters()) + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_lt_x_gpu(int(os.environ["WORLD_SIZE"])) + def test_DistributedDataParallel_non_default_stream(self): + stream = torch.cuda.Stream(self.rank) + rank = self.rank + with torch.cuda.stream(stream): + net = torch.nn.parallel.DistributedDataParallel( + torch.nn.Linear(1, 1, bias=False).cuda(rank), device_ids=[rank] + ) + for i in range(1000): + # Clear gradients manually + grad = net.module.weight.grad + if grad is not None: + grad.requires_grad_(False) + grad.zero_() + # Forward + BW + batch = torch.tensor([rank]).float().cuda(rank) + loss = net(batch).sum() + loss.backward() + # For each worker, the gradient on the weight should be worker_rank. + grad = net.module.weight.grad + avg = grad.clone() + # All-reducing the gradient averages should give us the gradient + # average. If not, then one of the workers has not correctly + # written back the averaged gradient before this all-reduce call. + dist.all_reduce(avg) + world_size = int(os.environ["WORLD_SIZE"]) + avg.div_(world_size) + expected_grad = sum(i for i in range(world_size)) / world_size + self.assertEqual( + avg[0, 0], + expected_grad, + msg=f"Expected gradient of {expected_grad} but got {avg} on rank {self.rank}", + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["cuda"], + f"The {BACKEND} backend does not support DDP communication hook on CUDA devices", + ) + @skip_if_lt_x_gpu(int(os.environ["WORLD_SIZE"])) + def test_ddp_comm_hook_logging(self): + hooks = [ + default.allreduce_hook, + default.fp16_compress_hook, + powerSGD.powerSGD_hook, + powerSGD.batched_powerSGD_hook, + quantization_hooks.quantization_pertensor_hook, + quantization_hooks.quantization_perchannel_hook, + ] + + cpp_builtin_hooks = [ + dist.BuiltinCommHookType.ALLREDUCE, + dist.BuiltinCommHookType.FP16_COMPRESS, + ] + + for hook in hooks: + ddp_model = torch.nn.parallel.DistributedDataParallel( + torch.nn.Linear(1, 1, bias=False).cuda(self.rank), + device_ids=[self.rank], + ) + ddp_logging_data = ddp_model._get_ddp_logging_data() + # Hook not registered yet, so should be empty + self.assertEqual(ddp_logging_data.get("comm_hook"), None) + ddp_model.register_comm_hook(None, hook) + ddp_logging_data = ddp_model._get_ddp_logging_data() + self.assertEqual(ddp_logging_data.get("comm_hook"), hook.__qualname__) + + for hook in cpp_builtin_hooks: + ddp_model = torch.nn.parallel.DistributedDataParallel( + torch.nn.Linear(1, 1, bias=False).cuda(self.rank), + device_ids=[self.rank], + ) + ddp_logging_data = ddp_model._get_ddp_logging_data() + # Hook not registered yet, so should be empty + self.assertEqual(ddp_logging_data.get("comm_hook"), None) + ddp_model._register_builtin_comm_hook(hook) + ddp_logging_data = ddp_model._get_ddp_logging_data() + self.assertEqual(ddp_logging_data.get("comm_hook"), str(hook)) + + # No hook registered + ddp_model = torch.nn.parallel.DistributedDataParallel( + torch.nn.Linear(1, 1, bias=False).cuda(self.rank), + device_ids=[self.rank], + ) + ddp_logging_data = ddp_model._get_ddp_logging_data() + # Hook not registered yet, so should be empty + self.assertEqual(ddp_logging_data.get("comm_hook"), None) + # After second forward pass, hook should still be empty string + for i in range(2): + inp = torch.ones(1, 1, device=self.rank) + loss = ddp_model(inp).sum() + loss.backward() + + ddp_logging_data = ddp_model._get_ddp_logging_data() + # Note: DETAIL debug mode logs DDP logging data to stdout and + # thus accesses std::map, which fills in a default value for the + # type if it didn't exist. + self.assertEqual(ddp_logging_data.get("comm_hook", ""), "") + + def _test_ddp_hook_with_optimizer_parity( + self, + grad_as_bucket_view, + static_graph, + optim_cls, + optimize_subset, + *functional_optim_args, + **functional_optim_kwargs, + ): + rank = self.rank + torch.cuda.set_device(rank) + torch.manual_seed(rank) + torch.cuda.manual_seed(rank) + models_to_test = [ + (LargeNet(), torch.randn(1, 1000).cuda()), + ] + if HAS_TORCHVISION: + models_to_test.append( + (torchvision.models.resnet50(), torch.randn(1, 3, 3, 1000).cuda()) + ) + for (model, inp) in models_to_test: + # Enable determinism in cudnn operators + with torch.backends.cudnn.flags( + enabled=True, deterministic=True, benchmark=False + ): + # Create DDP model that runs optimizer in fused fashion. + ddp_model_with_optimizer_hook = ( + torch.nn.parallel.DistributedDataParallel( + copy.deepcopy(model).cuda(), + device_ids=[self.rank], + gradient_as_bucket_view=grad_as_bucket_view, + static_graph=static_graph, + ) + ) + + # Create DDP model with no hook that does optimizer after + # backward. + ddp_model_with_no_hook = torch.nn.parallel.DistributedDataParallel( + copy.deepcopy(model).cuda(), + device_ids=[self.rank], + gradient_as_bucket_view=grad_as_bucket_view, + static_graph=static_graph, + ) + hook_params = ddp_model_with_optimizer_hook.parameters() + no_hook_params = ddp_model_with_no_hook.parameters() + if optimize_subset: + hook_params = list(hook_params) + no_hook_params = list(no_hook_params) + self.assertGreater(len(hook_params), 0) + hook_params = [hook_params[0]] + no_hook_params = [no_hook_params[0]] + + # Register a fused optimizer that will run optimizer in step + # with allreduce. + + if optimize_subset: + # API where optim_params is specified. + ddp_model_with_optimizer_hook._register_fused_optim( + optim_cls, + *functional_optim_args, + optim_params=hook_params, + **functional_optim_kwargs, + ) + else: + # API where optim_params is omitted + ddp_model_with_optimizer_hook._register_fused_optim( + optim_cls, + *functional_optim_args, + **functional_optim_kwargs, + ) + + optimizer_no_hook = optim_cls( + no_hook_params, + *functional_optim_args, + **functional_optim_kwargs, + ) + + # Verify parameters are equal initially. + for hook_param, allreduce_param in zip( + ddp_model_with_optimizer_hook.parameters(), + ddp_model_with_no_hook.parameters(), + ): + self.assertEqual(hook_param, allreduce_param) + + # Save old parameters to later verify optimizer modified them. + opt_hook_init_params = copy.deepcopy( + list(ddp_model_with_optimizer_hook.parameters()) + ) + + # Run optimizer with hook model. + for i in range(6): + ddp_model_with_optimizer_hook.zero_grad() + out = ddp_model_with_optimizer_hook(inp) + loss = out.sum() + loss.backward() + + dist.barrier() + + # Run regular model. + for i in range(6): + ddp_model_with_no_hook.zero_grad() + out = ddp_model_with_no_hook(inp) + loss = out.sum() + loss.backward() + optimizer_no_hook.step() + + dist.barrier() + + # Now verify parameters are equal. + for hook_param, allreduce_param in zip( + ddp_model_with_optimizer_hook.parameters(), + ddp_model_with_no_hook.parameters(), + ): + self.assertEqual(hook_param, allreduce_param) + + # Verify optimizer modified appropriate parameter set, + # otherwise they'd be trivially equal above. + if optimize_subset: + self.assertNotEqual( + opt_hook_init_params[0], + next(iter(ddp_model_with_optimizer_hook.parameters())), + ) + # Untouched params should be equal + self.assertEqual( + opt_hook_init_params[1:], + list(ddp_model_with_optimizer_hook.parameters())[1:], + ) + else: + self.assertNotEqual( + opt_hook_init_params, + list(ddp_model_with_optimizer_hook.parameters()), + ) + dist.barrier() + + """ + # Commenting out the following 3 tests as they cause Sandcastle jobs to fail + # Failure signature: + # AttributeError: type object 'TestDistBackendWithSpawn' has no attribute 'test_ddp_hook_with_optimizer_parity_adamw + + from torch.testing._internal.common_utils import parametrize + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl" or BACKEND == "ucc", + "Issues with async error handling, see https://github.com/pytorch/pytorch/issues/73259", + ) + @skip_if_lt_x_gpu(2) + @parametrize("grad_as_bucket_view", [True, False]) + @parametrize("static_graph", [True, False]) + @parametrize("optimize_subset", [True, False]) + def test_ddp_hook_with_optimizer_parity_adamw( + self, + grad_as_bucket_view, + static_graph, + optimize_subset, + ): + adamw_lr = 1e-2 + adamw_betas = (0.9, 0.99) + adamw_eps = 1e-6 + self._test_ddp_hook_with_optimizer_parity( + grad_as_bucket_view, + static_graph, + torch.optim.AdamW, + optimize_subset, + adamw_lr, + betas=adamw_betas, + eps=adamw_eps, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl" or BACKEND == "ucc", + "Issues with async error handling, see https://github.com/pytorch/pytorch/issues/73259", + ) + @skip_if_lt_x_gpu(2) + @parametrize("optimize_subset", [True, False]) + def test_ddp_hook_with_optimizer_parity_adam(self, optimize_subset): + adam_lr = 1e-2 + adam_betas = (0.9, 0.99) + adam_eps = 1e-6 + self._test_ddp_hook_with_optimizer_parity( + True, # grad as bucket view + False, # static graph + torch.optim.Adam, + optimize_subset, + adam_lr, + betas=adam_betas, + eps=adam_eps, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl" or BACKEND == "ucc", + "Issues with async error handling, see https://github.com/pytorch/pytorch/issues/73259", + ) + @skip_if_lt_x_gpu(2) + @parametrize("optimize_subset", [True, False]) + def test_ddp_hook_with_optimizer_parity_sgd(self, optimize_subset): + sgd_lr = 1e-2 + sgd_momentum = 0.9 + sgd_weight_decay = 0.01 + # Not testing grad_as_bucket_view and static_graph as they are + # tested in AdamW test above. + self._test_ddp_hook_with_optimizer_parity( + True, # grad as bucket view + False, # static_graph + torch.optim.SGD, + optimize_subset, + sgd_lr, + momentum=sgd_momentum, + weight_decay=sgd_weight_decay, + ) + """ + + @skip_if_lt_x_gpu(2) + def test_get_data_parallel_params(self): + torch.cuda.set_device(self.rank) + model = TwoLinLayerNet().cuda() + # Parameters to ignore are in the format {module_name}.{param_name} + params_to_ignore = ["a.weight"] + torch.nn.parallel.DistributedDataParallel._set_params_and_buffers_to_ignore_for_model( + model, params_to_ignore + ) + ddp_model = torch.nn.parallel.DistributedDataParallel( + model, device_ids=[self.rank] + ) + dp_params = torch.nn.parallel.DistributedDataParallel._get_data_parallel_params( + model, named_params=True + ) + for name, _ in dp_params: + self.assertNotEqual(f"module.{params_to_ignore[0]}", name) + + # test named_params=False, just check if returns the expected + # no of parameters. + num_ddp_params = len(list(model.parameters())) - 1 + count = 0 + dp_params = torch.nn.parallel.DistributedDataParallel._get_data_parallel_params(model, named_params=False) + for _ in dp_params: + count += 1 + self.assertEqual(count, num_ddp_params) + + def _test_ddp_apply_optim_in_backward( + self, + optim_cls, + optim_kwargs, + init_before, + gradient_as_bucket_view=True, + ): + # Need to seed to ensure inputs are unique across rank. Otherwise, + # allreduce won't have any effect. + torch.manual_seed(self.rank) + torch.cuda.manual_seed(self.rank) + torch.cuda.set_device(self.rank) + + # Test a simple linear as well as a ResNet model. + models_to_test = [ + nn.Sequential(nn.Linear(3, 3), nn.Linear(3, 3), nn.Linear(3, 3)).cuda() + ] + if HAS_TORCHVISION: + models_to_test.append(torchvision.models.resnet50().cuda()) + + for j, model in enumerate(models_to_test): + model_optim_in_bwd = copy.deepcopy(model) + model = nn.parallel.DistributedDataParallel( + model, + device_ids=[self.rank], + gradient_as_bucket_view=gradient_as_bucket_view, + ) + optim = optim_cls(model.parameters(), **optim_kwargs) + if init_before: + _apply_optimizer_in_backward( + optimizer_class=optim_cls, + params=model_optim_in_bwd.parameters(), + optimizer_kwargs=optim_kwargs, + ) + model_optim_in_bwd = nn.parallel.DistributedDataParallel( + model_optim_in_bwd, + device_ids=[self.rank], + gradient_as_bucket_view=gradient_as_bucket_view, + ) + if not init_before: + _apply_optimizer_in_backward( + optimizer_class=optim_cls, + params=model_optim_in_bwd.parameters(), + optimizer_kwargs=optim_kwargs, + ) + + for p1, p2 in zip(model.parameters(), model_optim_in_bwd.parameters()): + self.assertEqual(p1, p2, "Parameters not initially equal!") + # Enable determinism in cudnn operators + with torch.backends.cudnn.flags( + enabled=True, deterministic=True, benchmark=False + ): + for i in range(8): + inp = ( + torch.randn(1, 3, 1000, 1000, device="cuda") + if j == 1 + else torch.randn(10, 3, device="cuda") + ) + model(inp).sum().backward() + optim.step() + model_optim_in_bwd( + inp + ).sum().backward() # runs optimizer as well + for p1, p2 in zip( + model.parameters(), model_optim_in_bwd.parameters() + ): + self.assertEqual( + p1, p2, f"Params not equal at iteration {i}" + ) + self.assertTrue( + p2.grad is None, + f"Optim in backward grad is not None at {i}", + ) + + # set_to_none for regular optimizer to match in backward + # case. + optim.zero_grad(set_to_none=True) + + @skip_if_lt_x_gpu(2) + def test_ddp_apply_optim_in_backward(self): + for optim_cls, init_before in itertools.product( + [torch.optim.SGD, torch.optim.Adam], [True, False] + ): + with self.subTest(optim_cls=optim_cls): + self._test_ddp_apply_optim_in_backward( + optim_cls=optim_cls, + optim_kwargs={"lr": 0.03}, + init_before=init_before, + ) + + @skip_if_lt_x_gpu(2) + def test_ddp_apply_optim_in_backward_grad_as_bucket_view_false(self): + for init_before in [True, False]: + self._test_ddp_apply_optim_in_backward( + optim_cls=torch.optim.SGD, + optim_kwargs={"lr": 0.03}, + init_before=init_before, + gradient_as_bucket_view=False, + ) + + @skip_if_lt_x_gpu(2) + def test_ddp_apply_optim_in_backward_ignored_params(self): + torch.cuda.set_device(self.rank) + for init_before in [True, False]: + with self.subTest(init_before=init_before): + torch.manual_seed(self.rank) + torch.cuda.manual_seed(self.rank) + model = TwoLinLayerNet() + # Parameters to ignore are in the format {module_name}.{param_name} + params_to_ignore = ["a.weight"] + torch.nn.parallel.DistributedDataParallel._set_params_and_buffers_to_ignore_for_model( + model, params_to_ignore + ) + if init_before: + _apply_optimizer_in_backward( + optimizer_class=torch.optim.SGD, + params=model.parameters(), + optimizer_kwargs={"lr": 0.03}, + ) + net = torch.nn.parallel.DistributedDataParallel( + model.cuda(self.rank), + device_ids=[self.rank], + ) + if not init_before: + _apply_optimizer_in_backward( + optimizer_class=torch.optim.SGD, + params=model.parameters(), + optimizer_kwargs={"lr": 0.03}, + ) + inp = torch.randn(1, 10) + a, b = net(inp) + (a.transpose(0, 1) @ b).sum().backward() + # a.weight did not go through allreduce, so optimizer acted on local + # gradient, which should be different across ranks. Remaining params + # should be equal. + models = [None for _ in range(dist.get_world_size())] + dist.all_gather_object(models, model) + rank0_model, remainder = models[0], models[1:] + for m in remainder: + self.assertNotEqual(rank0_model.a.weight, m.a.weight) + self.assertEqual( + list(rank0_model.b.parameters()), list(m.b.parameters()) + ) + self.assertEqual(rank0_model.a.bias, m.a.bias) + + def _get_fp16_config(self) -> _MixedPrecision: + return _MixedPrecision( + param_dtype=torch.float16, + reduce_dtype=torch.float16, + buffer_dtype=torch.float16, + ) + + @skip_if_lt_x_gpu(2) + def test_ddp_native_mixed_precision_ignored_params(self): + rank = self.rank + torch.manual_seed(rank) + torch.cuda.manual_seed(rank) + torch.cuda.set_device(rank) + model = TwoLinLayerNet() + model.register_buffer("buffer", torch.ones(5)) + # Parameters to ignore are in the format {module_name}.{param_name} + to_ignore = ["a.weight", "buffer"] + torch.nn.parallel.DistributedDataParallel._set_params_and_buffers_to_ignore_for_model( + model, to_ignore, + ) + mp_config = self._get_fp16_config() + net = torch.nn.parallel.DistributedDataParallel( + model.to(rank), + device_ids=[rank], + mixed_precision=mp_config, + gradient_as_bucket_view=True, + ) + to_ignore = [f"module.{name}" for name in to_ignore] + expected_ignored = len(to_ignore) + n_ignored = 0 + # ignored params should not have _mp_param or _fp_param fields. + for (n, p) in itertools.chain(net.named_parameters(), net.named_buffers()): + if n in to_ignore: + n_ignored += 1 + self.assertFalse(hasattr(p, '_mp_param')) + self.assertFalse(hasattr(p, '_fp_param')) + else: + self.assertEqual(mp_config.param_dtype, p._mp_param.dtype) + self.assertEqual(torch.float32, p._fp_param.dtype) + + self.assertEqual(expected_ignored, n_ignored) + + def _test_ddp_native_mixed_precision( + self, gradient_as_bucket_view, set_grad_to_none + ): + rank = self.rank + torch.manual_seed(rank) + torch.cuda.manual_seed(rank) + torch.cuda.set_device(rank) + inp = torch.randn(10, 1) + mp_config = self._get_fp16_config() + + class MyModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.m = torch.nn.Linear(1, 5) + self.register_buffer('buffer', torch.randn(1, 2)) + self.p = torch.nn.Parameter( + torch.randn(10, 5), requires_grad=False + ) + + def forward(self_, x): # noqa: B902 + params = self_.m.parameters() + for p in params: + self.assertEqual(mp_config.param_dtype, p.dtype) + + self.assertEqual(self_.buffer.dtype, mp_config.buffer_dtype) + + self.assertEqual(mp_config.param_dtype, x.dtype) + return self_.m(x) + self_.p + + m = MyModel() + + net = torch.nn.parallel.DistributedDataParallel( + m.to(rank), + device_ids=[rank], + mixed_precision=mp_config, + gradient_as_bucket_view=gradient_as_bucket_view, + ) + # Buffers are casted in constructor. + self.assertEqual(net.module.buffer.dtype, mp_config.buffer_dtype) + # Each param should have an mp_param in the lower precision, and + # an fp_param in the higher precision. + for p in net.parameters(): + self.assertEqual(mp_config.param_dtype, p._mp_param.dtype) + self.assertEqual(torch.float32, p._fp_param.dtype) + + for i in range(6): + loss = net(inp).sum() + loss.backward() + # Verify gradient synchronization and params and grads are fp32. + for n, param in net.named_parameters(): + self.assertEqual(param.dtype, torch.float32) + if param.grad is None: + assert n == 'module.p' # Only param that doesn't require grad + else: + self.assertEqual(param.grad.dtype, torch.float32) + tensor_list = [ + torch.zeros_like(param.grad) + for _ in range(dist.get_world_size(net.process_group)) + ] + dist.all_gather(tensor_list, param.grad) + g, rest = tensor_list[0], tensor_list[1:] + self.assertEqual(g.dtype, torch.float32) + for g_ in rest: + self.assertEqual(g_.dtype, torch.float32) + self.assertEqual(g, g_) + net.zero_grad(set_to_none=set_grad_to_none) + + @skip_if_lt_x_gpu(2) + def test_ddp_native_mixed_precision_no_grad_as_bucket_view_no_set_grad_none(self): + self._test_ddp_native_mixed_precision( + gradient_as_bucket_view=False, + set_grad_to_none=False, + ) + + @skip_if_lt_x_gpu(2) + def test_ddp_native_mixed_precision_grad_as_bucket_view_no_set_grad_none(self): + self._test_ddp_native_mixed_precision( + gradient_as_bucket_view=True, + set_grad_to_none=False, + ) + + @skip_if_lt_x_gpu(2) + def test_ddp_native_mixed_precision_grad_as_bucket_view_set_grad_to_none(self): + self._test_ddp_native_mixed_precision( + gradient_as_bucket_view=True, set_grad_to_none=True + ) + + @skip_if_lt_x_gpu(2) + def test_ddp_native_mixed_precision_no_grad_as_bucket_view_set_grad_to_none(self): + self._test_ddp_native_mixed_precision( + gradient_as_bucket_view=True, set_grad_to_none=True + ) + + def _test_ddp_hook_parity(self, state, hook, num_validated_iters=100): + rank = self.rank + m = torch.nn.Linear(1, 5) + try: + process_group = state.process_group + except AttributeError: + process_group = state + + net_with_hook = torch.nn.parallel.DistributedDataParallel( + copy.deepcopy(m).to(rank), + device_ids=[rank], + process_group=process_group, + ) + net_with_hook.register_comm_hook(state=state, hook=hook) + net_without_hook = torch.nn.parallel.DistributedDataParallel( + copy.deepcopy(m).to(rank), + device_ids=[rank], + process_group=process_group, + ) + for i in range(100): + # Clear gradients manually. + for g in [ + net_without_hook.module.weight.grad, + net_with_hook.module.weight.grad, + ]: + if g is not None: + g.requires_grad_(False) + g.zero_() + # Forward + BW + batch = torch.tensor([rank]).float().cuda(rank) + loss = net_without_hook(batch).sum() + loss.backward() + # For each worker, the gradient on the weight should be worker_rank. + grad = net_without_hook.module.weight.grad + avg = grad.clone() + expected_grad = ( + sum(i for i in range(dist.get_world_size())) / dist.get_world_size() + ) + loss_hook = net_with_hook(batch).sum() + loss_hook.backward() + grad_hook = net_with_hook.module.weight.grad + avg_hook = grad_hook.clone() + + if i < num_validated_iters: + # Verify hook grad with expected. + self.assertEqual( + avg_hook[0, 0].item(), + expected_grad, + msg=f"Expected hook grad of {expected_grad} but got {avg_hook[0, 0]}", + ) + # Verify hook grad with vanilla allreduce + self.assertEqual( + avg_hook[0, 0], + avg[0, 0], + msg=f"Expected hook grad to be close to allreduce {avg[0, 0]}, but got {avg_hook[0, 0]}", + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["cuda"], + f"The {BACKEND} backend does not support DDP communication hook on CUDA devices", + ) + @skip_if_lt_x_gpu(int(os.environ["WORLD_SIZE"])) + def test_ddp_hook_parity_allreduce(self): + self._test_ddp_hook_parity(state=None, hook=default.allreduce_hook) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["cuda"], + f"The {BACKEND} backend does not support DDP communication hook on CUDA devices", + ) + @skip_if_lt_x_gpu(int(os.environ["WORLD_SIZE"])) + def test_ddp_hook_parity_allreduce_process_group(self): + # process_group is passed in to both DDP and comm. hook + world_size = dist.get_world_size() + rank_to_GPU = init_multigpu_helper(world_size, BACKEND) + gpus = [rank_to_GPU[int(r)][0] for r in range(world_size)] + process_group = torch.distributed.new_group(gpus) + self._test_ddp_hook_parity(state=process_group, hook=default.allreduce_hook) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["cuda"], + f"The {BACKEND} backend does not support DDP communication hook on CUDA devices", + ) + @skip_if_lt_x_gpu(int(os.environ["WORLD_SIZE"])) + def test_ddp_hook_parity_powerSGD(self): + for warm_start in [True, False]: + powersgd_state = powerSGD.PowerSGDState( + process_group=None, + matrix_approximation_rank=1, + start_powerSGD_iter=2, + warm_start=warm_start, + ) + self._test_ddp_hook_parity( + state=powersgd_state, hook=powerSGD.powerSGD_hook + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["cuda"], + f"The {BACKEND} backend does not support DDP communication hook on CUDA devices", + ) + @skip_but_pass_in_sandcastle_if( + NO_MULTIPROCESSING_SPAWN, + "Disabled for environments that \ + don't support multiprocessing with spawn start method", + ) + @skip_if_lt_x_gpu(int(os.environ["WORLD_SIZE"])) + def test_ddp_hook_parity_post_localSGD(self): + # Although we start run local SGD at iteration 10, since we still use the global process group to run it, + # the post-LocalSGD actually still allreduces gradients globally for the remaining iterations. + state = post_localSGD.PostLocalSGDState( + process_group=None, subgroup=dist.group.WORLD, start_localSGD_iter=10 + ) + self._test_ddp_hook_parity( + state=state, hook=post_localSGD.post_localSGD_hook + ) + # Only validate the warmup iterations before local SGD is applied, + # because when `post_local_gradient_allreduce` is disabled, the gradients will not be synchronized at all. + # Note that in practice a model averager has to be applied to run model averaging, + # so local gradient averaging is not necessary. + start_localSGD_iter = 10 + state = post_localSGD.PostLocalSGDState( + process_group=None, + subgroup=dist.group.WORLD, + start_localSGD_iter=start_localSGD_iter, + post_local_gradient_allreduce=False, + ) + self._test_ddp_hook_parity( + state=state, + hook=post_localSGD.post_localSGD_hook, + num_validated_iters=start_localSGD_iter, + ) + + # When `subgroup` is None, it is equivalent to the subgroup on the each node. + # For this single-node test environment, the intra-node process group is equivalent to + # the global process group. + if self.world_size == dist.get_world_size(): + state = post_localSGD.PostLocalSGDState( + process_group=None, subgroup=None, start_localSGD_iter=10 + ) + self._test_ddp_hook_parity( + state=state, hook=post_localSGD.post_localSGD_hook + ) + + # Since we start local SGD later than the total number of 100 iterations, + # no local SGD actually is executed, and we don't even need to provide a subgroup for this case. + state = post_localSGD.PostLocalSGDState( + process_group=None, subgroup=None, start_localSGD_iter=1000 + ) + self._test_ddp_hook_parity( + state=state, hook=post_localSGD.post_localSGD_hook + ) + + def _prepare_single_device_module( + self, + rank, + process_group, + devices, + device_ids, + global_batch_size, + gradient_as_bucket_view=False, + ): + model = Net() + device = devices[0] if devices else torch.device("cuda:%d" % rank) + ddp_model = DistributedDataParallel( + copy.deepcopy(model).to(device), + device_ids=device_ids, + process_group=process_group, + bucket_cap_mb=0.001, + gradient_as_bucket_view=gradient_as_bucket_view, + ) + + model.to(device) + + input = torch.randn(global_batch_size, 2).to(device) + target = torch.randn(global_batch_size, 4).to(device) + + return model, ddp_model, input, target + + def _prepare_cpu_module( + self, + process_group, + global_batch_size, + gradient_as_bucket_view=False, + ): + model = Net() + ddp_model = DistributedDataParallel( + copy.deepcopy(model), + process_group=process_group, + bucket_cap_mb=0.001, + gradient_as_bucket_view=gradient_as_bucket_view, + ) + input = torch.randn(global_batch_size, 2) + target = torch.randn(global_batch_size, 4) + return model, ddp_model, input, target + + def _test_accumulate_gradients_no_sync( + self, num_iters=2, ddp_comm_hook=None, gradient_as_bucket_view=False + ): + """ + This is the recommended way to implement accumulate grads. + If ``ddp_comm_hook`` input was specified, it will also register that hook + to the ``ddp_model``. The hook fed into this function should not change + the resulting gradients. + """ + group, group_id, rank = self._init_global_test() + world_size = get_world_size() + + # FIXME: Add testing for gloo/CUDA + if BACKEND == "mpi" or BACKEND == "gloo": + global_batch_size = world_size + local_batch_size = 1 + model, ddp_model, input, target = self._prepare_cpu_module( + group_id, global_batch_size, gradient_as_bucket_view + ) + + if BACKEND == "nccl": + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + int_devices = rank_to_GPU[rank][:1] + devices = [torch.device("cuda:" + str(i)) for i in int_devices] + global_batch_size = world_size + local_batch_size = len(devices) + model, ddp_model, input, target = self._prepare_single_device_module( + rank, + group_id, + devices, + devices, + global_batch_size, + gradient_as_bucket_view, + ) + + if ddp_comm_hook is not None: + ddp_model.register_comm_hook(group_id, ddp_comm_hook) + + def step_model(model, input, target): + model.train() + output = model(input) + loss = F.mse_loss(output, target.to(output.device)) + loss.backward() + + # ensure accumulate grads works with no_grad => no grads are accumulated. + with torch.no_grad(): + with ddp_model.no_sync(): + ddp_model.train() + ddp_model(input) + + # check two model parameters over num_iters iterations + for iteration in range(num_iters): + step_model(model, input, target) + + ddp_input = input[ + rank * local_batch_size : (rank + 1) * local_batch_size + ] + ddp_target = target[ + rank * local_batch_size : (rank + 1) * local_batch_size + ] + + if iteration % 2 == 0: + # accumulate grads locally + with ddp_model.no_sync(): + step_model(ddp_model, ddp_input, ddp_target) + else: + # sync grads + step_model(ddp_model, ddp_input, ddp_target) + + for i, j in zip(model.parameters(), ddp_model.parameters()): + if not i.requires_grad: + continue + if iteration % 2 == 0: + self.assertNotEqual(i.grad, j.grad) + else: + self.assertEqual(i.grad, j.grad) + + # Shuffle the input so that DDP input is different + torch.manual_seed(1337 + iteration) + input = input[torch.randperm(global_batch_size)] + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi" and BACKEND != "nccl" and BACKEND != "gloo", + "get_future is only supported on mpi, nccl and gloo", + ) + @nccl_skip_if_lt_x_gpu(BACKEND, 2) + def test_accumulate_gradients_no_sync(self): + """ + Runs _test_accumulate_gradients_no_sync using default inputs + """ + self._test_accumulate_gradients_no_sync() + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi" and BACKEND != "nccl" and BACKEND != "gloo", + "get_future is only supported on mpi, nccl and gloo", + ) + @nccl_skip_if_lt_x_gpu(BACKEND, 2) + def test_accumulate_gradients_no_sync_grad_is_view(self): + """ + Runs _test_accumulate_gradients_no_sync using default inputs + """ + self._test_accumulate_gradients_no_sync(gradient_as_bucket_view=True) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi" and BACKEND != "nccl" and BACKEND != "gloo", + "get_future is only supported on mpi, nccl and gloo", + ) + @nccl_skip_if_lt_x_gpu(BACKEND, 2) + def test_accumulate_gradients_no_sync_allreduce_hook(self): + """ + Runs multiple iterations on _test_accumulate_gradients_no_sync + using allreduce hook and validates whether future result was properly + passed as gradients in reducer. + """ + + world_size = get_world_size() + + def allreduce_hook( + group_id: object, bucket: dist.GradBucket + ) -> torch.futures.Future[torch.Tensor]: + tensors = [bucket.buffer() / world_size] + return ( + group_id.allreduce(tensors) + .get_future() + .then(lambda fut: fut.value()[0]) + ) + + self._test_accumulate_gradients_no_sync( + num_iters=4, ddp_comm_hook=allreduce_hook + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi" and BACKEND != "nccl" and BACKEND != "gloo", + "get_future is only supported on mpi, nccl and gloo", + ) + @nccl_skip_if_lt_x_gpu(BACKEND, 2) + def test_accumulate_gradients_no_sync_allreduce_with_then_hook(self): + """ + Runs multiple iterations on _test_accumulate_gradients_no_sync using allreduce + hook that also uses then callbacks. In first then callback result is multiplied + by 2, and the second callback divides the result by 2 * world_size. It validates + whether final result was properly passed as gradients in reducer. + """ + + world_size = get_world_size() + + def allreduce_with_then_hook( + group_id: object, bucket: dist.GradBucket + ) -> torch.futures.Future[torch.Tensor]: + fut = group_id.allreduce([bucket.buffer()]).get_future() + + def mult(fut): + # Multiply the result by 2. + return 2 * fut.wait()[0] + + def div(fut): + # Divide the result by 2 * world_size. + return fut.wait() / (2 * world_size) + + return fut.then(mult).then(div) + + self._test_accumulate_gradients_no_sync( + num_iters=4, ddp_comm_hook=allreduce_with_then_hook + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND != "mpi" and BACKEND != "nccl" and BACKEND != "gloo", + "get_future is only supported on mpi, nccl and gloo", + ) + @nccl_skip_if_lt_x_gpu(BACKEND, 2) + def test_get_future(self): + def mult(fut): + return [t * 3 for t in fut.wait()] + + def add(fut): + return [t + 1 for t in fut.wait()] + + group, group_id, rank = self._init_global_test() + input = _build_tensor(3, 2) + if BACKEND == "nccl": + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + device_id = rank_to_GPU[rank][0] + input = input.to(device_id) + fut = group_id.allreduce([input]).get_future() + res = fut.then(mult).then(add).wait() + expected = _build_tensor(3, 2 * len(group) * 3 + 1) + + self.assertEqual(res[0], expected) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_no_gpu + def test_DistributedDataParallel(self): + group, group_id, rank = self._init_global_test() + rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND) + gpus = list(rank_to_GPU[rank]) + + for use_bucket_view, static_graph in itertools.product( + (False, True), (False, True) + ): + self._test_DistributedDataParallel( + gpu_subset=gpus, + rank=rank, + gradient_as_bucket_view=use_bucket_view, + static_graph=static_graph, + ) + + # test set static graph twice + self._test_DistributedDataParallel( + gpu_subset=gpus, + rank=rank, + gradient_as_bucket_view=use_bucket_view, + static_graph=static_graph, + set_static_graph_twice=True, + ) + + # test output_device + self._test_DistributedDataParallel( + gpu_subset=gpus, + rank=rank, + output_device=torch.device("cuda"), + gradient_as_bucket_view=use_bucket_view, + static_graph=static_graph, + ) + + # test device_ids + gpus_list = [torch.device("cuda:" + str(i)) for i in gpus] + self._test_DistributedDataParallel( + gpu_subset=gpus_list, + rank=rank, + output_device=torch.device("cuda"), + gradient_as_bucket_view=use_bucket_view, + static_graph=static_graph, + ) + + def _test_DistributedDataParallel_with_amp(self, grad_is_view=False): + torch.manual_seed(31415) + # Creates model and optimizer in default precision + model = copy.deepcopy(DDP_NET).cuda() + optimizer = torch.optim.SGD(model.parameters(), lr=0.03) + + # Creates a GradScaler once at the beginning of training. + scaler = GradScaler() + + ddp_model = nn.parallel.DistributedDataParallel( + model, device_ids=[self.rank], gradient_as_bucket_view=grad_is_view + ) + + input = torch.randn(dist.get_world_size() * 2, 2).cuda() + target = torch.randn(dist.get_world_size() * 2, 4).cuda() + loss_fn = nn.MSELoss() + + # verify grads are none before training + for p in ddp_model.parameters(): + self.assertTrue(p is not None) + self.assertTrue(p.grad is None) + + for idx in range(20): + optimizer.zero_grad() + # Runs the forward pass with autocasting. + with autocast(): + output = ddp_model(input) + loss = loss_fn(output, target) + + # Scales loss. Calls backward() on scaled loss to create scaled gradients. + # Backward passes under autocast are not recommended. + # Backward ops run in the same dtype autocast chose for corresponding forward ops. + scaler.scale(loss).backward() + + # verify grads are not none and are valid during training + for p in ddp_model.parameters(): + if p.requires_grad: + self.assertTrue(p.grad is not None) + self.assertFalse(p.grad.isnan().any()) + self.assertFalse(p.grad.isinf().any()) + + # scaler.step() first unscales the gradients of the optimizer's assigned params. + # If these gradients do not contain infs or NaNs, optimizer.step() is then called, + # otherwise, optimizer.step() is skipped. + scaler.step(optimizer) + + # Updates the scale for next iteration. + scaler.update() + + # Shuffle the input so that DDP input is different + torch.manual_seed(1337 + idx) + input = input[torch.randperm(dist.get_world_size() * 2)] + + return ddp_model + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_no_gpu + def test_DistributedDataParallel_with_amp_and_grad_is_view(self): + torch.cuda.set_device(self.rank) + ddp_model_grad_not_view = self._test_DistributedDataParallel_with_amp( + grad_is_view=False + ) + ddp_model_grad_is_view = self._test_DistributedDataParallel_with_amp( + grad_is_view=True + ) + for i, j in zip( + ddp_model_grad_not_view.parameters(), + ddp_model_grad_is_view.parameters(), + ): + self.assertEqual(i, j) + + def _test_DistributedDataParallel_SyncBatchNorm( + self, + gpu_subset, + rank, + local_bs, + global_bs, + offset, + output_device=None, + affine=True, + ): + # Run a simple end to end DDP model, use result of single node model + # as baseline + + # cpu training setup + model = BN_NET if affine else BN_NET_NO_AFFINE + + # single gpu training setup + model_gpu = copy.deepcopy(model) + model_gpu.cuda(gpu_subset[0]) + + # DDP training setup + model_DDP = nn.SyncBatchNorm.convert_sync_batchnorm(copy.deepcopy(model)) + model_DDP.cuda(gpu_subset[0]) + model_DDP = nn.parallel.DistributedDataParallel( + model_DDP, device_ids=gpu_subset + ) + + # test serializable/unserializable + with tempfile.NamedTemporaryFile() as tmp: + if sys.platform == "win32": + torch.save(model_DDP, tmp) + tmp.seek(0) + model_DDP = torch.load(tmp) + else: + torch.save(model_DDP, tmp.name) + model_DDP = torch.load(tmp.name) + + # data initialization + input_cpu = torch.randn(global_bs, 2) + target = torch.randn(global_bs, 4) + loss = nn.MSELoss() + + # check two model parameters over 5 iterations + self._test_DDP_niter( + model_gpu, + model_DDP, + input_cpu.cuda(gpu_subset[0]), + target.cuda(gpu_subset[0]), + loss, + local_bs, + rank, + global_bs, + True, + offset, + dist.get_world_size(), + 5 if affine else 2, + ) + self._barrier() + + def _test_post_localSGD_optimizer_parity(self, create_averager, grad_is_view): + learning_rate = 0.03 + + net = torch.nn.parallel.DistributedDataParallel( + copy.deepcopy(DDP_NET).cuda(), + device_ids=[self.rank], + gradient_as_bucket_view=grad_is_view, + ) + averager = create_averager() + opt = torch.optim.SGD(net.parameters(), lr=learning_rate) + + net_using_post_localSGD_opt = torch.nn.parallel.DistributedDataParallel( + copy.deepcopy(DDP_NET).cuda(), + device_ids=[self.rank], + gradient_as_bucket_view=grad_is_view, + ) + # Process group cannot be pickled in some environments, + # so cannot deep copy an averager. See: + # https://github.com/pytorch/pytorch/pull/74737#pullrequestreview-922487496 + averager2 = create_averager() + post_localSGD_opt = self._create_post_localSGD_optimizer( + net_using_post_localSGD_opt, learning_rate, averager2 + ) + + input = torch.randn(dist.get_world_size() * 2, 2).cuda() + target = torch.randn(dist.get_world_size() * 2, 4).cuda() + loss_fn = nn.MSELoss() + + for _ in range(20): + self._perform_a_train_step(opt, net, loss_fn, input, target) + averager.average_parameters(net.parameters()) + + self._perform_a_train_step( + post_localSGD_opt, + net_using_post_localSGD_opt, + loss_fn, + input, + target, + ) + for p1, p2 in zip( + net.parameters(), net_using_post_localSGD_opt.parameters() + ): + self.assertEqual(p1.data, p2.data) + + # Also check if the built-in step counters are the same to prevent a bug like #74737. + self.assertEqual(averager.step, averager2.step) + + def _create_periodic_model_averager(self): + return averagers.PeriodicModelAverager(period=4, warmup_steps=10) + + def _create_post_localSGD_optimizer(self, net, learning_rate, averager): + return post_localSGD_optimizer.PostLocalSGDOptimizer( + optim=torch.optim.SGD(net.parameters(), lr=learning_rate), + averager=averager, + ) + + def _perform_a_train_step(self, optimizer, net, loss_fn, input, target): + optimizer.zero_grad() + output = net(input) + loss = loss_fn(output, target) + loss.backward() + optimizer.step() + + def _test_post_localSGD_optimizer_step_reload( + self, create_averager, chkpt_file + ): + learning_rate = 0.03 + + net_using_post_localSGD_opt = torch.nn.parallel.DistributedDataParallel( + copy.deepcopy(DDP_NET).cuda(), device_ids=[self.rank] + ) + + averager = create_averager() + post_localSGD_opt = self._create_post_localSGD_optimizer( + net_using_post_localSGD_opt, learning_rate, averager + ) + + averager2 = create_averager() + dummy_post_localSGD_opt = self._create_post_localSGD_optimizer( + net_using_post_localSGD_opt, learning_rate, averager2 + ) + + input = torch.randn(dist.get_world_size() * 2, 2).cuda() + target = torch.randn(dist.get_world_size() * 2, 4).cuda() + loss_fn = nn.MSELoss() + + for _ in range(20): + self._perform_a_train_step( + post_localSGD_opt, + net_using_post_localSGD_opt, + loss_fn, + input, + target, + ) + + if self.rank == 0: + torch.save( + {"optimizer_state_dict": post_localSGD_opt.state_dict()}, chkpt_file + ) + + dist.barrier() + map_location = {"cuda:%d" % 0: "cuda:%d" % self.rank} + checkpoint = torch.load(chkpt_file, map_location=map_location) + dummy_post_localSGD_opt.load_state_dict(checkpoint["optimizer_state_dict"]) + + # Check that we didn't hit the trivial case + self.assertNotEqual(averager2.step, 0) + # Check if dummy averager was initialized to a correct value + self.assertEqual(averager.step, averager2.step) + + # Remove 'step' entry from a checkpoint. + # And make sure it is not in the state dictionary + del checkpoint["optimizer_state_dict"]["step"] + self.assertNotIn("step", checkpoint["optimizer_state_dict"]) + + # Check if checkpoint without a 'step' entry invokes a warning + with self.assertWarnsRegex( + expected_warning=UserWarning, + expected_regex="Loaded state dict does not contain a step counter for an averager. " + "Setting step counter to 0.", + ): + dummy_post_localSGD_opt.load_state_dict( + checkpoint["optimizer_state_dict"] + ) + + self.assertEqual(averager2.step, 0) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_post_localSGD_optimizer_parity(self): + torch.cuda.set_device(self.rank) + self._test_post_localSGD_optimizer_parity( + self._create_periodic_model_averager, + grad_is_view=False, + ) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_post_localSGD_optimizer_parity_grad_is_view(self): + torch.cuda.set_device(self.rank) + self._test_post_localSGD_optimizer_parity( + self._create_periodic_model_averager, + grad_is_view=True, + ) + + def _create_hierarchical_model_averager(self): + period_group_size_dict = OrderedDict([(2, 2), (4, dist.get_world_size())]) + return hierarchicalSGD.HierarchicalModelAverager( + period_group_size_dict=period_group_size_dict, warmup_steps=4 + ) + + @skip_if_lt_x_gpu(4) + @skip_if_odd_worldsize + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_post_localSGD_optimizer_parity_with_hierarchical_sgd(self): + torch.cuda.set_device(self.rank) + self._test_post_localSGD_optimizer_parity( + self._create_hierarchical_model_averager, + grad_is_view=False, + ) + + @skip_if_lt_x_gpu(4) + @skip_if_odd_worldsize + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_post_localSGD_optimizer_parity_with_hierarchical_sgd_grad_is_view( + self, + ): + torch.cuda.set_device(self.rank) + self._test_post_localSGD_optimizer_parity( + self._create_hierarchical_model_averager, + grad_is_view=True, + ) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_post_localSGD_optimizer_step_reload(self): + torch.cuda.set_device(self.rank) + with _rank_temp_file() as tmp_file: + self._test_post_localSGD_optimizer_step_reload( + self._create_periodic_model_averager, tmp_file + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_no_gpu + def test_DistributedDataParallel_SyncBatchNorm_Channels_Last(self): + self._test_DistributedDataParallel_SyncBatchNorm_with_memory_format( + torch.channels_last + ) + self._test_DistributedDataParallel_SyncBatchNorm_with_memory_format( + torch.channels_last_3d + ) + + def _test_DistributedDataParallel_SyncBatchNorm_with_memory_format( + self, memory_format + ): + group, group_id, rank = self._init_global_test() + num_processes = dist.get_world_size() + local_bs = 2 + bs_offset = int(rank * 2) + global_bs = int(num_processes * 2) + + model = ONLY_SBN_NET + model_gpu = copy.deepcopy(model).cuda(rank) + model_DDP = nn.parallel.DistributedDataParallel( + model_gpu, device_ids=[rank] + ) + + shapes = [global_bs, 2, 4, 4] + ( + [] if memory_format is torch.channels_last else [4] + ) + + input_gpu = ( + torch.randn(*shapes, dtype=torch.float) + .cuda(rank) + .to(memory_format=memory_format) + ) + target_gpu = ( + torch.randn(*shapes, dtype=torch.float) + .cuda(rank) + .to(memory_format=memory_format) + ) + loss = nn.MSELoss() + + # check two model parameters over 5 iterations + self._test_DDP_niter( + model_gpu, + model_DDP, + input_gpu, + target_gpu, + loss, + local_bs, + rank, + global_bs, + True, + bs_offset, + dist.get_world_size(), + memory_format=memory_format, + ) + self._barrier() + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_no_gpu + def test_DistributedDataParallel_SyncBatchNorm(self): + group, group_id, rank = self._init_global_test() + world_size = dist.get_world_size() + # DDP does not support replicating BN layers within a process, hence + # testing with one module replica per process + gpus = [rank] + + local_bs = 2 + bs_offset = int(rank * 2) + global_bs = int(world_size * 2) + + self._test_DistributedDataParallel_SyncBatchNorm( + gpu_subset=gpus, + rank=rank, + local_bs=local_bs, + global_bs=global_bs, + offset=bs_offset, + ) + + # test output_device + self._test_DistributedDataParallel_SyncBatchNorm( + gpu_subset=gpus, + rank=rank, + local_bs=local_bs, + global_bs=global_bs, + offset=bs_offset, + output_device=torch.device("cuda"), + ) + + # test device_ids + gpus = [torch.device("cuda:" + str(i)) for i in gpus] + self._test_DistributedDataParallel_SyncBatchNorm( + gpu_subset=gpus, + rank=rank, + local_bs=local_bs, + global_bs=global_bs, + offset=bs_offset, + output_device=torch.device("cuda"), + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_no_gpu + def test_DistributedDataParallel_SyncBatchNorm_No_Affine(self): + group, group_id, rank = self._init_global_test() + world_size = dist.get_world_size() + # DDP does not support replicating BN layers within a process, hence + # testing with one module replica per process + gpus = [rank] + + local_bs = 2 + bs_offset = int(rank * 2) + global_bs = int(world_size * 2) + + self._test_DistributedDataParallel_SyncBatchNorm( + gpu_subset=gpus, + rank=rank, + local_bs=local_bs, + global_bs=global_bs, + offset=bs_offset, + affine=False, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_no_gpu + def test_DistributedDataParallel_SyncBatchNorm_2D_Input(self): + group, group_id, rank = self._init_global_test() + # DDP does not support replicating BN layers within a process, hence + # testing with one module replica per process + gpus = [rank] + + model = nn.BatchNorm1d(2) + + # single gpu training setup + model_gpu = copy.deepcopy(model) + model_gpu.cuda(gpus[0]) + + # DDP training setup + model_DDP = nn.SyncBatchNorm.convert_sync_batchnorm(copy.deepcopy(model)) + model_DDP.cuda(gpus[0]) + model_DDP = nn.parallel.DistributedDataParallel(model_DDP, device_ids=gpus) + + local_bs = len(gpus) * 2 + global_bs = dist.get_world_size() * local_bs + input_cpu = torch.randn(global_bs, 2) + target = torch.randn(global_bs, 2) + loss = nn.MSELoss() + + # disabling cudnn. + # SyncBatchNorm goes through native_batch_norm kernel, this avoids the + # numerical issue created by the divergent code path. + with torch.backends.cudnn.flags(False): + # check two model parameters over 5 iterations + self._test_DDP_niter( + model_gpu, + model_DDP, + input_cpu.cuda(gpus[0]), + target.cuda(gpus[0]), + loss, + local_bs, + rank, + global_bs, + True, + ) + self._barrier() + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_no_gpu + @require_world_size(2) + def test_DistributedDataParallel_SyncBatchNorm_Single_Input_Per_Process(self): + group, group_id, rank = self._init_global_test() + # DDP does not support replicating BN layers within a process, hence + # testing with one module replica per process + gpus = [rank] + + model = nn.BatchNorm1d(2) + + # single gpu training setup + model_gpu = copy.deepcopy(model) + model_gpu.cuda(gpus[0]) + + # DDP training setup + model_DDP = nn.SyncBatchNorm.convert_sync_batchnorm(copy.deepcopy(model)) + model_DDP.cuda(gpus[0]) + model_DDP = nn.parallel.DistributedDataParallel(model_DDP, device_ids=gpus) + + local_bs = 1 + global_bs = dist.get_world_size() + input_cpu = torch.randn(global_bs, 2) + target = torch.randn(global_bs, 2) + loss = nn.MSELoss() + + # disabling cudnn. + # SyncBatchNorm goes through native_batch_norm kernel, this avoids the + # numerical issue created by the divergent code path. + with torch.backends.cudnn.flags(False): + # check two model parameters over 5 iterations + self._test_DDP_niter( + model_gpu, + model_DDP, + input_cpu.cuda(gpus[0]), + target.cuda(gpus[0]), + loss, + local_bs, + rank, + global_bs, + True, + ) + self._barrier() + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_no_gpu + def test_DistributedDataParallel_SyncBatchNorm_Diff_Input_Sizes_Running_Value( + self, + ): + group, group_id, rank = self._init_global_test() + model = nn.parallel.DistributedDataParallel( + ONLY_SBN_NET.cuda(rank), device_ids=[rank] + ) + + input_var = [] + for i in range(dist.get_world_size()): + input_var_rank = torch.cat( + [ + torch.ones(2, 1, 10 ** (i + 1)) * (0.1 ** (i - 1)), + torch.ones(2, 1, 10 ** (i + 1)) * (0.3 ** (i - 1)), + ], + dim=1, + ) + input_var.append(input_var_rank) + + all_input_var = torch.cat( + [ + x.permute(1, 0, 2).contiguous().view(ONLY_SBN_NET.num_features, -1) + for x in input_var + ], + dim=1, + ).cuda(rank) + + for i in range(100): + y = model(input_var[rank].cuda(rank)) + y.mean().backward() + + running_mean, running_var = ( + model.module.running_mean, + model.module.running_var, + ) + torch.testing.assert_close(running_mean, all_input_var.mean(1)) + torch.testing.assert_close(running_var, all_input_var.var(1)) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_no_gpu + def test_DistributedDataParallel_SyncBatchNorm_Diff_Input_Sizes_gradient(self): + group, group_id, rank = self._init_global_test() + # only do single GPU per process + gpus = [rank] + + # cpu training setup + model = BN_NET + + num_processes = dist.get_world_size() + local_bs = rank + 2 + bs_offset = int((rank + 3) * rank / 2) + global_bs = int((num_processes + 3) * num_processes / 2) + + self._test_DistributedDataParallel_SyncBatchNorm( + gpu_subset=gpus, + rank=rank, + local_bs=local_bs, + global_bs=global_bs, + offset=bs_offset, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_no_gpu + def test_DistributedDataParallel_SyncBatchNorm_half(self): + group, group_id, rank = self._init_global_test() + + model = copy.deepcopy(BN_NET) + model = model.half() + model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) + model = nn.parallel.DistributedDataParallel(model.cuda(rank), device_ids=[rank]) + inp = torch.randn(2, 2, dtype=torch.float16, device=torch.device(rank)) + # Check that forward/backward do not error with dtype mismatch + out = model(inp) + self.assertEqual(out.dtype, torch.float16) + out.sum().backward() + for param in model.parameters(): + self.assertEqual(param.grad.dtype, torch.float16) + + def _test_ddp_logging_data(self, is_gpu): + rank = dist.get_rank() + model_DDP = copy.deepcopy(DDP_NET) + if is_gpu: + model_DDP = nn.parallel.DistributedDataParallel( + model_DDP.cuda(rank), device_ids=[rank] + ) + else: + model_DDP = nn.parallel.DistributedDataParallel(model_DDP) + + # dummy data initialization + local_bs = 2 + batch_size, input, target, loss = self._prepare_dummy_data(local_bs) + if is_gpu: + input = input.cuda(rank) + target = target.cuda(rank) + + model_DDP._set_ddp_runtime_logging_sample_rate(2) + + for idx in range(20): + offset = rank * local_bs + + # DDP training, DDP scatters subsets of input to nodes/GPUs + self._test_DDP_helper( + model_DDP, + input[offset : offset + local_bs], + target[offset : offset + local_bs], + loss, + 1, + ) + + self._model_step_with_zero_grad(model_DDP) + + # Verify DDP logging data is sampled as expected + # If it has ran more than 10 iterations and this is + # the sampled iteration for measuring run time stats, + # the run time stats for this idx-th iteration will not + # be zeros. + ddp_logging_data = model_DDP._get_ddp_logging_data() + if idx > 0 and (idx < 10 or idx % 2 == 0): + self.assertGreaterEqual( + ddp_logging_data.get("forward_compute_time"), 1 + ) + self.assertGreaterEqual( + ddp_logging_data.get("backward_compute_time"), 1 + ) + self.assertGreaterEqual( + ddp_logging_data.get("backward_comm_time"), 1 + ) + self.assertGreaterEqual( + ddp_logging_data.get("backward_compute_time"), + ddp_logging_data.get("backward_compute_comm_overlap_time"), + ) + self.assertGreaterEqual( + ddp_logging_data.get("backward_comm_time"), + ddp_logging_data.get("backward_compute_comm_overlap_time"), + ) + self.assertEqual(ddp_logging_data.get("iteration"), idx) + elif idx > 0: + # if the idx-th iteration is not sampled to set runtime stats, + # ddp_logging_data.iteration will not be updated to current + # iteration. + self.assertNotEqual(ddp_logging_data.get("iteration"), idx) + + # Shuffle the input so that DDP input is different + input = input[torch.randperm(batch_size)] + + return model_DDP + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "nccl does not support DDP on CPU models" + ) + def test_ddp_logging_data_cpu(self): + def parse_env(var): + return os.environ[var] if var in os.environ else "N/A" + + dist.set_debug_level(dist.DebugLevel.INFO) + group, group_id, rank = self._init_global_test() + model_DDP = self._test_ddp_logging_data(is_gpu=False) + + ddp_logging_data = model_DDP._get_ddp_logging_data() + self.assertEqual(ddp_logging_data.get("world_size"), dist.get_world_size()) + self.assertEqual(ddp_logging_data.get("rank"), dist.get_rank()) + self.assertEqual(ddp_logging_data.get("module_name"), "Net") + self.assertEqual(ddp_logging_data.get("device_ids"), "") + # output_device is -1 in default if it is not set, e.g. + # output_device of CPU training is -1. + self.assertEqual(ddp_logging_data.get("output_device"), -1) + self.assertEqual(ddp_logging_data.get("broadcast_buffers"), 1) + self.assertEqual(ddp_logging_data.get("bucket_cap_bytes"), 25 * 1024 * 1024) + self.assertEqual(ddp_logging_data.get("find_unused_parameters"), 0) + self.assertEqual(ddp_logging_data.get("gradient_as_bucket_view"), 0) + self.assertEqual( + ddp_logging_data.get("backend_name"), dist.get_backend(group_id) + ) + self.assertEqual(ddp_logging_data.get("iteration"), 18) + params = list(model_DDP.parameters()) + num_params = 0 + param_size = 0 + params = list(filter(lambda parameter: parameter.requires_grad, params)) + for p in params: + num_params += 1 + param_size += p.numel() * p.element_size() + self.assertEqual(ddp_logging_data.get("dtypes"), "float") + self.assertEqual( + ddp_logging_data.get("total_parameter_size_bytes"), param_size + ) + self.assertEqual(ddp_logging_data.get("num_parameter_tensors"), num_params) + self.assertEqual(ddp_logging_data.get("bucket_sizes"), str(param_size)) + self.assertEqual( + ddp_logging_data.get("master_port"), parse_env("MASTER_PORT") + ) + self.assertEqual( + ddp_logging_data.get("master_addr"), parse_env("MASTER_ADDR") + ) + self.assertEqual( + ddp_logging_data.get("torch_distributed_debug"), + parse_env("TORCH_DISTRIBUTED_DEBUG"), + ) + self.assertEqual( + ddp_logging_data.get("cuda_visible_devices"), + parse_env("CUDA_VISIBLE_DEVICES"), + ) + if ddp_logging_data.get("backend_name") == "gloo": + self.assertEqual( + ddp_logging_data.get("gloo_socket_ifname"), + parse_env("GLOO_SOCKET_IFNAME"), + ) + self.assertEqual( + ddp_logging_data.get("gloo_device_transport"), + parse_env("GLOO_DEVICE_TRANSPORT"), + ) + default_gloo_threads = 2 + self.assertEqual( + ddp_logging_data.get("gloo_num_threads"), + default_gloo_threads, + ) + + self.assertEqual(ddp_logging_data.get("nccl_socket_ifname"), None) + self.assertEqual(ddp_logging_data.get("nccl_blocking_wait"), None) + self.assertEqual(ddp_logging_data.get("nccl_async_error_handling"), None) + self.assertEqual(ddp_logging_data.get("nccl_debug"), None) + self.assertEqual(ddp_logging_data.get("nccl_nthreads"), None) + self.assertEqual(ddp_logging_data.get("nccl_ib_timeout"), None) + # test runtime logging fields + # Note: DETAIL debug mode logs DDP logging data to stdout and + # thus accesses std::map, which fills in a default value for the + # type if it didn't exist. + self.assertEqual(ddp_logging_data.get("unused_parameter_size", 0), 0) + self.assertEqual(ddp_logging_data.get("has_rebuilt_buckets"), 1) + self.assertEqual( + ddp_logging_data.get("rebuilt_bucket_sizes"), str(param_size) + ) + grad_ready_order = ddp_logging_data.get( + "prev_iteration_grad_ready_order_indices" + ) + expected_order = list(reversed([str(x) for x in range(3)])) + self.assertEqual(grad_ready_order, ", ".join(expected_order)) + bucket_indices = ddp_logging_data.get("rebuilt_per_bucket_param_indices") + self.assertEqual(bucket_indices, " ".join(expected_order)) + # It is hard to test accurate latency, but it can test whether the latency is + # a valid value and in the expected range. + self.assertGreaterEqual(ddp_logging_data.get("avg_forward_compute_time"), 1) + self.assertGreaterEqual( + ddp_logging_data.get("avg_backward_compute_time"), 1 + ) + self.assertGreaterEqual(ddp_logging_data.get("avg_backward_comm_time"), 1) + self.assertGreaterEqual( + ddp_logging_data.get("avg_backward_compute_time"), + ddp_logging_data.get("avg_backward_compute_comm_overlap_time"), + ) + self.assertGreaterEqual( + ddp_logging_data.get("avg_backward_comm_time"), + ddp_logging_data.get("avg_backward_compute_comm_overlap_time"), + ) + # Test host-side times are roughly in the order that we expect + fwd_host_side_time = ddp_logging_data.get("forward_compute_time_start") + bwd_comp_start_host_side_time = ddp_logging_data.get( + "backward_compute_time_start" + ) + bwd_comp_end_host_side_time = ddp_logging_data.get( + "backward_compute_time_end" + ) + bwd_comm_start_host_side_time = ddp_logging_data.get( + "backward_comm_time_start" + ) + bwd_comm_end_host_side_time = ddp_logging_data.get("backward_comm_time_end") + self.assertGreaterEqual( + bwd_comm_end_host_side_time, bwd_comm_start_host_side_time + ) + self.assertGreaterEqual( + bwd_comm_start_host_side_time, bwd_comp_start_host_side_time + ) + self.assertGreaterEqual( + bwd_comp_end_host_side_time, bwd_comp_start_host_side_time + ) + self.assertGreaterEqual(bwd_comp_start_host_side_time, fwd_host_side_time) + + # test larger net with mixed data types, verify multiple bucket sizes + model = LargeNet() + model.float() + model.fc1.double() + model_DDP = nn.parallel.DistributedDataParallel(model, bucket_cap_mb=1.5) + ddp_logging_data = model_DDP._get_ddp_logging_data() + params = list(model_DDP.parameters()) + self.assertEqual( + ddp_logging_data.get("bucket_cap_bytes"), int(1.5 * 1024 * 1024) + ) + bucket_sizes = [ + params[1].numel() * params[1].element_size(), + params[0].numel() * params[0].element_size(), + ] + self.assertEqual( + ddp_logging_data.get("bucket_sizes"), + ", ".join(str(x) for x in bucket_sizes), + ) + self.assertEqual(ddp_logging_data.get("dtypes"), "double, float") + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_no_gpu + def test_ddp_logging_data_gpu(self): + group, group_id, rank = self._init_global_test() + model_DDP = self._test_ddp_logging_data(is_gpu=True) + ddp_logging_data = model_DDP._get_ddp_logging_data() + self.assertEqual(ddp_logging_data.get("device_ids"), str(rank)) + self.assertEqual(ddp_logging_data.get("output_device"), rank) + grad_ready_order = ddp_logging_data.get( + "prev_iteration_grad_ready_order_indices" + ) + expected_order = list(reversed([str(x) for x in range(3)])) + self.assertEqual(grad_ready_order, ", ".join(expected_order)) + bucket_indices = ddp_logging_data.get("rebuilt_per_bucket_param_indices") + self.assertEqual(bucket_indices, " ".join(expected_order)) + # test runtime logging fields + # It is hard to test accurate latency, but it can test whether the latency is + # a valid value and in the expected range. + self.assertGreaterEqual(ddp_logging_data.get("avg_forward_compute_time"), 1) + self.assertGreaterEqual( + ddp_logging_data.get("avg_backward_compute_comm_overlap_time"), 1 + ) + self.assertGreaterEqual( + ddp_logging_data.get("avg_backward_compute_time"), + ddp_logging_data.get("avg_backward_compute_comm_overlap_time"), + ) + self.assertGreaterEqual( + ddp_logging_data.get("avg_backward_comm_time"), + ddp_logging_data.get("avg_backward_compute_comm_overlap_time"), + ) + # Test host-side times are roughly in the order that we expect + fwd_host_side_time = ddp_logging_data.get("forward_compute_time_start") + bwd_comp_start_host_side_time = ddp_logging_data.get( + "backward_compute_time_start" + ) + bwd_comp_end_host_side_time = ddp_logging_data.get( + "backward_compute_time_end" + ) + bwd_comm_start_host_side_time = ddp_logging_data.get( + "backward_comm_time_start" + ) + bwd_comm_end_host_side_time = ddp_logging_data.get("backward_comm_time_end") + self.assertGreaterEqual( + bwd_comm_end_host_side_time, bwd_comm_start_host_side_time + ) + self.assertGreaterEqual( + bwd_comm_start_host_side_time, bwd_comp_start_host_side_time + ) + self.assertGreaterEqual( + bwd_comp_end_host_side_time, bwd_comp_start_host_side_time + ) + self.assertGreaterEqual(bwd_comp_start_host_side_time, fwd_host_side_time) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "nccl", "nccl does not support DDP on CPU models" + ) + def test_static_graph_api_cpu(self): + model_DDP = nn.parallel.DistributedDataParallel(DDP_NET) + expected_err = "should be called before training loop starts" + with self.assertRaisesRegex(RuntimeError, expected_err): + local_bs = 2 + batch_size, input, target, loss = self._prepare_dummy_data(local_bs) + offset = dist.get_rank() * local_bs + + # DDP training, DDP scatters subsets of input to nodes/GPUs + self._test_DDP_helper( + model_DDP, + input[offset : offset + local_bs], + target[offset : offset + local_bs], + loss, + 1, + ) + model_DDP._set_static_graph() + + # Verify error was logged in ddp_logging_data. + verify_ddp_error_logged(model_DDP, expected_err) + + @skipIfNoTorchVision + def test_SyncBatchNorm_process_group(self): + # When adopting `convert_sync_batchnorm` to convert a `nn.modules`, + # it need to recursively pass the `process_group` in the module when the `SyncBatchNorm` + # is nested in a sub-module or sub-sub-module (e.g. resnet50 in torchvision.models). + + process_ids = 0 + process_group = torch.distributed.new_group([process_ids]) + res50_model = torchvision.models.resnet50() + res50_model_sync = nn.SyncBatchNorm.convert_sync_batchnorm( + copy.deepcopy(res50_model), process_group + ) + process_group_sync = res50_model_sync.layer1[0].bn1.process_group + self.assertEqual(process_group_sync, process_group) + + def _run_reduction_test( + self, tensor, expected_tensor, op, reduction_fn=dist.all_reduce, dst=None + ): + if reduction_fn != dist.all_reduce and dst is None: + raise ValueError(f"Reduction fn {reduction_fn} must specify dst!") + if dst is not None: + reduction_fn(tensor, dst, op) + # Only destination rank tensor is expected to have final result. + if dist.get_rank() == dst: + self.assertEqual(tensor, expected_tensor) + else: + reduction_fn(tensor, op) + self.assertEqual(tensor, expected_tensor) + + @require_backend_is_available({"nccl"}) + @skip_if_lt_x_gpu(2) + def test_nccl_backend_bool_allreduce(self): + torch.cuda.set_device(self.rank) + # Run all_reduce with PRODUCT + element = self.rank % 2 == 0 + for op in [dist.ReduceOp.PRODUCT, dist.ReduceOp.MIN]: + input_tensor = torch.tensor([element, element]).to(self.rank) + self._run_reduction_test( + input_tensor, torch.tensor([False, False]).to(self.rank), op + ) + # Ensure that all ranks contributing True (cast to 1) results in the + # correct reduction. + input_tensor = torch.tensor([True, True]).to(self.rank) + expected_tensor = input_tensor.clone() + self._run_reduction_test(input_tensor, expected_tensor, op) + + # Run all_reduce with SUM + for op in [dist.ReduceOp.SUM, dist.ReduceOp.MAX]: + input_tensor = torch.tensor([element, element]).to(self.rank) + self._run_reduction_test( + input_tensor, torch.tensor([True, True]).to(self.rank), op + ) + # TODO: NCCL backend does not work correctly for bitwise reduction ops + # (see https://github.com/pytorch/pytorch/issues/41362). Add tests for + # these once it is supported. + + @require_backend_is_available({"nccl"}) + @skip_if_lt_x_gpu(2) + def test_nccl_backend_bool_allgather(self): + torch.cuda.set_device(self.rank) + inp = {0: [True, True], 1: [False, True]} + input_tensor = torch.tensor(inp[self.rank % 2]).to(self.rank) + # Preserve a copy of the tensor to compare against after allgather. + input_tensor_copy = input_tensor.clone() + tensor_list = [ + torch.tensor([False, False]).to(self.rank) + for _ in range(dist.get_world_size()) + ] + dist.all_gather(tensor_list, input_tensor) + + self.assertEqual(len(tensor_list), dist.get_world_size()) + for i, t in enumerate(tensor_list): + expected = torch.tensor(inp[i % 2]).to(self.rank) + self.assertEqual(t, expected) + # Ensure that the input tensor is not modified, since this collective + # does not modify its input. + self.assertEqual(input_tensor_copy, input_tensor) + + @require_backend_is_available({"nccl"}) + @skip_if_lt_x_gpu(int(os.environ["WORLD_SIZE"])) + def test_nccl_backend_bool_reduce(self): + torch.cuda.set_device(self.rank) + inp = {0: [True, True], 1: [False, False]} + # Run reduce() with product op + for op in [dist.ReduceOp.PRODUCT, dist.ReduceOp.MIN]: + input_tensor = torch.tensor(inp[self.rank % 2]).to(self.rank) + expected = torch.tensor([False, False]).to(self.rank) + self._run_reduction_test(input_tensor, expected, op, dist.reduce, dst=0) + # Ensure that all ranks contributing True (cast to 1) results in the + # correct reduction. + input_tensor = torch.tensor([True, True]).to(self.rank) + expected_tensor = input_tensor.clone() + self._run_reduction_test( + input_tensor, expected_tensor, op, dist.reduce, dst=0 + ) + + for op in [dist.ReduceOp.SUM, dist.ReduceOp.MAX]: + input_tensor = torch.tensor(inp[self.rank % 2]).to(self.rank) + expected = ( + torch.tensor([True, True]).to(self.rank) + if self.rank == 0 + else input_tensor.clone() + ) + self._run_reduction_test(input_tensor, expected, op, dist.reduce, dst=0) + + @require_backend_is_available({"nccl"}) + @skip_if_lt_x_gpu(2) + def test_nccl_backend_bool_broadcast(self): + tensor_size = 10 + bcast_tensor = torch.tensor( + [ + (random.random() < 0.5 if self.rank == 0 else False) + for _ in range(tensor_size) + ] + ).to(self.rank) + dist.broadcast(bcast_tensor, src=0) + # Now allgather and ensure the tensors are equal. + tensor_list = [ + torch.tensor([False for _ in range(tensor_size)]).to(self.rank) + for _ in range(dist.get_world_size()) + ] + dist.all_gather(tensor_list, bcast_tensor) + expected = tensor_list[0] + for tensor in tensor_list[1:]: + self.assertEqual(tensor, expected) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_lt_x_gpu(int(os.environ["WORLD_SIZE"])) + def test_DistributedSampler_padding(self): + # Tests padding of distributed sampler. + world_size = dist.get_world_size() + + # Simulates the 'casual' dataset size + dataset_size = 100 + world_size + 1 + dataset = [torch.ones(1).to(self.rank) * i for i in range(dataset_size)] + + # Simulates the 'tiny' dataset size + dataset_tiny_size = max(world_size // 2 - 1, 1) + dataset_tiny = [ + torch.ones(1).to(self.rank) * i for i in range(dataset_tiny_size) + ] + + # Specifying drop_last=True will cause the tail of the data to be dropped. + dist_sampler = DistributedSampler(dataset=dataset, drop_last=True) + local_num_samples, local_dataset_size = ( + dist_sampler.num_samples, + dist_sampler.total_size, + ) + # The effective dataset size should be the greatest integer that is <= + # dataset_size that is divisible by the world_size. This is to ensure each + # rank processes the same number of samples. + effective_dataset_size = ( + math.ceil((dataset_size - world_size) / world_size) + if dataset_size % world_size != 0 + else dataset_size / world_size + ) + self.assertEqual(local_num_samples, effective_dataset_size) + self.assertEqual(local_dataset_size, local_num_samples * world_size) + indices_list = list(iter(dist_sampler)) + self.assertEqual(len(indices_list), local_num_samples) + + def validate_global_samples(local_num_samples): + # Ensure that each rank processes the same number of samples. + world_samples = [ + torch.LongTensor([0]).to(self.rank) for _ in range(world_size) + ] + dist.all_gather( + world_samples, torch.tensor([local_num_samples]).to(self.rank) + ) + world_samples = [sample.item() for sample in world_samples] + self.assertEqual(len(set(world_samples)), 1) + + validate_global_samples(local_num_samples) + + # drop_last=False is the default and will add additional indices to be sampled, + # increasing the effective dataset size. + dist_sampler_added_samples = DistributedSampler(dataset=dataset) + local_num_samples, local_dataset_size = ( + dist_sampler_added_samples.num_samples, + dist_sampler_added_samples.total_size, + ) + # The effective dataset size is the smallest integer that is >= dataset_size + # and divisible by the world size. + self.assertEqual(local_num_samples, math.ceil(dataset_size / world_size)) + self.assertEqual(local_dataset_size, local_num_samples * world_size) + indices_list = list(iter(dist_sampler_added_samples)) + self.assertEqual(len(indices_list), local_num_samples) + + # Ensure that each rank processes the same number of samples. + validate_global_samples(local_num_samples) + + # Ensure additional samples are padded even when + # the extremely small dataset is given. + dist_sampler_added_samples_tiny = DistributedSampler(dataset=dataset_tiny) + local_num_samples, local_dataset_size = ( + dist_sampler_added_samples_tiny.num_samples, + dist_sampler_added_samples_tiny.total_size, + ) + self.assertEqual( + local_num_samples, math.ceil(dataset_tiny_size / world_size) + ) + self.assertEqual(local_dataset_size, local_num_samples * world_size) + indices_list = list(iter(dist_sampler_added_samples_tiny)) + self.assertEqual(len(indices_list), local_num_samples) + validate_global_samples(local_num_samples) + + def _test_allgather_object(self, subgroup=None): + # Only set device for NCCL backend since it must use GPUs. + + gather_objects = COLLECTIVES_OBJECT_TEST_LIST.copy() + + backend = os.environ["BACKEND"] + if backend == "nccl": + # Case where rank != GPU device. + next_rank = (self.rank + 1) % int(self.world_size) + torch.cuda.set_device(next_rank) + + # If GPU test, add object with GPU tensor + if backend == "nccl": + gather_objects.append(Foo(torch.randn(3, 3, device=0))) + + output_gathered = [None for _ in range(dist.get_world_size())] + dist.all_gather_object( + output_gathered, + gather_objects[self.rank % len(gather_objects)], + group=subgroup, + ) + + for i, val in enumerate(output_gathered): + expected = gather_objects[i % len(gather_objects)] + self.assertEqual(val, expected) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @require_n_gpus_for_nccl_backend( + int(os.environ["WORLD_SIZE"]), os.environ["BACKEND"] + ) + @with_dist_debug_levels(levels=["OFF", "INFO", "DETAIL"]) + def test_all_gather_object_default_pg(self): + return self._test_allgather_object() + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @require_n_gpus_for_nccl_backend( + int(os.environ["WORLD_SIZE"]), os.environ["BACKEND"] + ) + @with_dist_debug_levels(levels=["DETAIL", "OFF", "INFO"]) + def test_all_gather_object_subgroup(self): + default = _get_default_group() + backend = dist.get_backend(default) + subgroup = dist.new_group(backend=backend) + return self._test_allgather_object(subgroup=subgroup) + + def _test_gather_object(self, pg=None): + # Ensure stateful objects can be gathered + gather_objects = COLLECTIVES_OBJECT_TEST_LIST.copy() + my_rank = dist.get_rank(pg) + + backend = os.environ["BACKEND"] + if backend == "nccl": + # Case where rank != GPU device. + next_rank = (self.rank + 1) % int(self.world_size) + torch.cuda.set_device(next_rank) + + # If GPU test, add object with GPU tensor + if backend == "nccl": + gather_objects.append(Foo(torch.randn(3, 3, device=my_rank))) + + output_gathered = [None for _ in range(dist.get_world_size(pg))] + gather_on_rank = 0 + dist.gather_object( + gather_objects[self.rank % len(gather_objects)], + object_gather_list=output_gathered + if my_rank == gather_on_rank + else None, + dst=gather_on_rank, + group=pg, + ) + if my_rank != gather_on_rank: + self.assertEqual( + output_gathered, [None for _ in range(dist.get_world_size())] + ) + else: + for i, val in enumerate(output_gathered): + expected = gather_objects[i % len(gather_objects)] + self.assertEqual(val, expected) + + # Validate errors when objects can't be pickled. + class Bar: + pass + + b = Bar() + gather_objects = [b for _ in range(dist.get_world_size())] + with self.assertRaisesRegex(AttributeError, "Can't pickle local object"): + dist.all_gather_object( + [None for _ in range(dist.get_world_size())], + gather_objects[self.rank], + group=pg, + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND == "ucc", "CPU tensor ops not supported by UCP TL" + ) + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @with_dist_debug_levels(levels=["DETAIL", "OFF", "INFO"]) + def test_gather_object(self): + return self._test_gather_object() + + @skip_but_pass_in_sandcastle_if( + BACKEND == "ucc", "CPU tensor ops not supported by UCP TL" + ) + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @with_dist_debug_levels(levels=["DETAIL", "OFF", "INFO"]) + def test_gather_object_subgroup(self): + default = _get_default_group() + backend = dist.get_backend(default) + subgroup = dist.new_group(backend=backend) + return self._test_gather_object(subgroup) + + def validate_net_equivalence(self, net): + # Helper to validate synchronization of nets across ranks. + net_module_states = list(net.module.state_dict().values()) + # Check that all tensors in module's state_dict() are equal. + for t in net_module_states: + tensor_list = [ + torch.zeros_like(t) for _ in range(dist.get_world_size()) + ] + dist.all_gather(tensor_list, t) + for tensor in tensor_list: + self.assertEqual(tensor, t) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_sync_module_states(self): + # Test that after calling _sync_module_states, models across ranks + # are the same and are equal to the model on the input rank. + dim = 2 + rank = self.rank + rank_to_broadcast = 1 + # Seed to ensure that ranks are initialized with different initial models. + torch.manual_seed(rank) + model = nn.Linear(dim, dim, bias=False) + net = torch.nn.parallel.DistributedDataParallel( + model.cuda(rank), device_ids=[self.rank], bucket_cap_mb=1 + ) + new_model = nn.Linear(dim, dim, bias=False).cuda(rank) + net.module = copy.deepcopy(new_model) + # Assert params are different + net_module_states = list(net.module.state_dict().values()) + for t in net_module_states: + tensor_list = [ + torch.zeros_like(t) for _ in range(dist.get_world_size()) + ] + dist.all_gather(tensor_list, t) + for i, tensor in enumerate(tensor_list): + if i == rank: + self.assertEqual(t, tensor) + else: + # tensor from another rank should be different. + self.assertNotEqual(t, tensor) + + _sync_module_states( + module=net.module, + process_group=net.process_group, + broadcast_bucket_size=net.broadcast_bucket_size, + src=rank_to_broadcast, + params_and_buffers_to_ignore=net.parameters_to_ignore, + ) + # Now all model params should be the same. + self.validate_net_equivalence(net) + # Since the network params were broadcast from rank_to_broadcast, validate that + # they are the same as new_model on rank_to_broadcast. + if rank == rank_to_broadcast: + expected_states = new_model.state_dict().values() + for t, expected in zip(net_module_states, expected_states): + self.assertEqual(t, expected) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_grad_div_uneven_inputs(self): + # Test gradient division during training with join() API. If + # divide_by_initial_world_size=False, we scale by the effective world + # size when allreducing grads. + dim = 5 + batch = 1 + grad_scale = 50 + rank = self.rank + model = nn.Linear(dim, dim, bias=False) + inp = torch.ones(batch, dim, device=self.rank) * grad_scale + net = torch.nn.parallel.DistributedDataParallel( + model.cuda(rank), device_ids=[self.rank], bucket_cap_mb=1 + ) + n_iters = 3 + if self.rank > 0: + n_iters += 2 + + with net.join(divide_by_initial_world_size=False): + for _ in range(n_iters): + loss = net(inp).sum() + loss.backward() + # The grad is always expected_grad, since we divide by the number + # of currently active processes and inactive processes contribute + # zero gradient. If we kept dividing by static initial world + # size as processes leave, the grad would be smaller. + expected_grad = torch.ones(dim, dim, device=self.rank) * grad_scale + param = next(iter(net.parameters())) + self.assertEqual(expected_grad, param.grad) + # Avoid accumulating grads so that it's the same every iteration + net.zero_grad() + torch.cuda.synchronize(device=self.rank) + + # If divide_by_initial_world_size=True (default), we always scale grads + # by the initial world_size. + with net.join(divide_by_initial_world_size=True): + for i in range(n_iters): + loss = net(inp).sum() + loss.backward() + effective_ws = dist.get_world_size() + if i >= 3: + effective_ws -= 1 + expected_grad = ( + torch.ones(dim, dim, device=self.rank) + * grad_scale + * effective_ws + ) / dist.get_world_size() + param = next(iter(net.parameters())) + self.assertEqual(expected_grad, param.grad) + # Avoid accumulating grad so that it's the same every iteration. + net.zero_grad() + torch.cuda.synchronize(device=self.rank) + + def _test_ddp_profiling(self, profiler_ctx): + batch = 3 + dim = 10 + num_iters = 6 + torch.cuda.set_device(self.rank) + model = nn.Linear(dim, dim, bias=False) + inp = torch.rand(batch, dim, device=self.rank) + net = torch.nn.parallel.DistributedDataParallel( + model.cuda(self.rank), + device_ids=[self.rank], + ) + profiler_ctx_copy = copy.deepcopy(profiler_ctx) + + with profiler_ctx as prof: + for i in range(num_iters): + loss = net(inp).sum() + loss.backward() + + all_reduce_event_name = f"{dist.get_backend()}:all_reduce" + events = get_profiling_event(all_reduce_event_name, prof, dedup_gpu_user_annotation=True) + event_count = sum(e.count for e in events) + self.assertEqual(event_count, num_iters) + for event in events: + self.assertTrue(event.is_async) + self.assertEqual(event.name, all_reduce_event_name) + + broadcast_event_name = f"{dist.get_backend()}:broadcast" + broadcast_events = get_profiling_event(broadcast_event_name, prof, dedup_gpu_user_annotation=True) + event_count = sum(e.count for e in broadcast_events) + # Broadcast is called during rebuild_buckets + self.assertGreaterEqual(event_count, 1) + for event in broadcast_events: + self.assertEqual(event.name, broadcast_event_name) + + # Run DDP with profiling for a few iterations, then enable profiling + # for a single pass, and ensure it is recorded. This tests that the + # thread local state is correctly updated. + net = torch.nn.parallel.DistributedDataParallel( + model.cuda(self.rank), + device_ids=[self.rank], + find_unused_parameters=True, + ) + for i in range(3): + loss = net(inp).sum() + loss.backward() + # Now enable the profiler. + with profiler_ctx_copy as prof: + loss = net(inp).sum() + loss.backward() + + events = get_profiling_event(all_reduce_event_name, prof, dedup_gpu_user_annotation=True) + self.assertGreaterEqual(len(events), 1) + self.assertGreaterEqual(events[0].count, 1) + self.assertEqual(events[0].name, all_reduce_event_name) + for event in events: + self.assertTrue(event.is_async) + # Ensure searching unused parameters was profiled + events = get_profiling_event("search_unused_parameters", prof) + self.assertEqual(len(events), 1) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle("Currently failing in NVIDIA internal CI") + def test_ddp_profiling_autograd_profiler(self): + autograd_profiler_ctx = torch.autograd.profiler.profile() + return self._test_ddp_profiling(profiler_ctx=autograd_profiler_ctx) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if(IS_FBCODE, "Kineto in fbcode code causes hang") + @skip_but_pass_in_sandcastle_if( + IS_MACOS or IS_WINDOWS, + "torch.profiler not enabled for mac/windows: https://github.com/pytorch/pytorch/pull/56124", + ) + def test_ddp_profiling_torch_profiler(self): + cpu_act = torch.profiler.ProfilerActivity.CPU + cuda_act = torch.profiler.ProfilerActivity.CUDA + torch_profiler_ctx = torch.profiler.profile(activities=[cpu_act, cuda_act]) + self._test_ddp_profiling(profiler_ctx=torch_profiler_ctx) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_join_model_equivalence(self): + # Verifies equivalence with model training locally and with DDP under + # the join context manager. + batch = 3 + dim = 10 + learning_rate = 0.03 + model = nn.Linear(dim, dim, bias=False) + inp = torch.rand(batch, dim, device=self.rank) + local_model = copy.deepcopy(model) + local_model = local_model.cuda(self.rank) + rank_to_iter_mapping = { + rank: 2 * (rank + 1) for rank in range(dist.get_world_size()) + } + # run local model + local_iters = sum(rank_to_iter_mapping.values()) + local_optim = torch.optim.SGD(local_model.parameters(), lr=learning_rate) + for _ in range(local_iters): + local_optim.zero_grad() + out = local_model(inp) + loss = out.sum() + loss.backward() + local_optim.step() + + # run DDP model with join API + num_iters = rank_to_iter_mapping[self.rank] + net = torch.nn.parallel.DistributedDataParallel( + model.cuda(self.rank), device_ids=[self.rank] + ) + ddp_optim = torch.optim.SGD( + model.parameters(), lr=learning_rate * dist.get_world_size() + ) + with net.join(): + for i in range(num_iters): + ddp_optim.zero_grad() + out = net(inp) + loss = out.sum() + loss.backward() + torch.cuda.synchronize(device=self.rank) + ddp_optim.step() + + # Validate model state dicts are equal + for (_, local_tensor), (_, dist_tensor) in zip( + local_model.state_dict().items(), net.module.state_dict().items() + ): + self.assertEqual(local_tensor, dist_tensor) + + def _run_uneven_inputs_test( + self, + test_case, + iteration_mapping, + find_unused_params, + ): + model = test_case.model + inp = test_case.inp + rank = self.rank + sync_interval = test_case.sync_interval + torch.cuda.set_device(rank) + # Ensure all outstanding GPU work is completed so this test runs independently. + dist.barrier() + # Bucket_cap_mb is intentionally low to test allreduce scheduling when + # there are many buckets. + net = torch.nn.parallel.DistributedDataParallel( + model.cuda(rank), + device_ids=[rank], + bucket_cap_mb=1, + find_unused_parameters=find_unused_params, + ) + # Register hook if specified + if test_case.hook is not None: + net.register_comm_hook(test_case.state, test_case.hook) + print(f"registered hook {test_case.hook}") + + # Determine num iters for this rank via the passed in mapping. + num_iters = iteration_mapping[rank] + # If we throw when earliest rank terminates, we should ensure + # that we iterate for that minimum number of times. + num_iters_tensor = torch.tensor( + [num_iters], device=torch.cuda.current_device() + ) + dist.all_reduce(num_iters_tensor, op=dist.ReduceOp.MIN) + min_num_iters = num_iters_tensor.item() + total_iters = 0 + if test_case.throw_on_early_termination: + if min_num_iters == num_iters: + # Early termination rank(s) + exception_ctx = self.assertRaisesRegex( + RuntimeError, f"Rank {self.rank} exhausted all inputs" + ) + else: + # Non early termination rank + exception_ctx = self.assertRaisesRegex( + RuntimeError, + "Detected at least one rank that exhausted inputs.", + ) + else: + exception_ctx = nullcontext() + with exception_ctx: + with net.join( + throw_on_early_termination=test_case.throw_on_early_termination + ): + for i in range(num_iters): + # Use model.no_sync() to disable grad synchronization every + # sync_interval. + if i % sync_interval != 0: + context = net.no_sync() + else: + context = nullcontext() + with context: + if isinstance(inp, tuple): + loss = net(*inp).sum() + else: + loss = net(inp).sum() + loss.backward() + self._model_step(net) + # Ensure completion of GPU kernels (including allreduce). If the + # join API is not properly implemented, then this should hang + # since the allreduce will hang. + torch.cuda.synchronize(device=rank) + total_iters += 1 + if test_case.throw_on_early_termination: + # Ensure we iterated min_num_iters times. + self.assertEqual(total_iters, min_num_iters) + else: + # Ensure we iterated at least min_num_iters times. + self.assertGreaterEqual(total_iters, min_num_iters) + + # Ensure completion of all GPU kernels. + torch.cuda.synchronize(device=rank) + # When throwing on early rank termination, we do not + # broadcast model state from an authoritative rank. All models + # should already be in sync. + if not test_case.throw_on_early_termination: + self.assertTrue(net._authoritative_rank) + # All ranks should have agreed on the same authoritative_rank! + final_rank_tensor = torch.tensor( + [net._authoritative_rank], device=self.rank + ) + tensor_list = [ + torch.zeros_like(final_rank_tensor) + for _ in range(dist.get_world_size()) + ] + dist.all_gather(tensor_list, final_rank_tensor) + max_rank = dist.get_world_size() - 1 + self.assertSetEqual( + {max_rank}, {tensor.item() for tensor in tensor_list} + ) + # Ensure that all models are the same across ranks after all have joined. + self.validate_net_equivalence(net) + # Ensure that running with DDP uneven inputs was logged. + ddp_logging_data = net._get_ddp_logging_data() + self.assertTrue(ddp_logging_data.get("join_uneven_inputs")) + dist.barrier() + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_uneven_inputs_stop_iteration_sync_bn(self): + # Tests that uneven inputs join handler correctly throws StopIteration + # for models with SyncBN or general collective comm when + # throw_on_early_termination=True. + class ModelWithComm(torch.nn.Module): + def __init__(self): + super().__init__() + self.lin = nn.Linear(2, 40, bias=False) + + def forward(self, x): + x = self.lin(x) + dist.all_reduce(x) + return x + + torch.cuda.set_device(self.rank) + model_bn = BN_NET + model_bn = nn.SyncBatchNorm.convert_sync_batchnorm( + copy.deepcopy(model_bn) + ).cuda(self.rank) + comm_model = ModelWithComm().cuda(self.rank) + model_input = torch.randn(10, 2).cuda(torch.cuda.current_device()) + + for model in [model_bn, comm_model]: + model = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[self.rank], + ) + min_num_iters = 5 + if self.rank != 0: + # Early termination rank(s) + num_iters = min_num_iters + exception_ctx = self.assertRaisesRegex( + RuntimeError, f"Rank {self.rank} exhausted all inputs" + ) + else: + # Non early termination rank + num_iters = min_num_iters * 2 + exception_ctx = self.assertRaisesRegex( + RuntimeError, + "Detected at least one rank that exhausted inputs.", + ) + n = 0 + with exception_ctx: + with model.join(throw_on_early_termination=True): + for i in range(num_iters): + loss = model(model_input).sum() + loss.backward() + self._model_step(model) + n += 1 + + self.assertEqual(n, min_num_iters) + # Verify model equivalence + self.validate_net_equivalence(model) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_uneven_inputs(self): + dim = 1000 + batch = 1 + # Create a variety of models to run uneven input tests on. + large_model = nn.Sequential( + nn.Conv2d(1, 20, 5), + nn.ReLU(), + nn.Conv2d(20, 32, 5), + nn.ReLU(), + nn.Conv2d(32, 256, 5), + nn.ReLU(), + ) + small_model = nn.Linear(dim, dim, bias=False) + bn_net = BatchNormNet() + + class UnusedParamModule(nn.Module): + def __init__(self, unused_params_rank): + super().__init__() + self.t0 = Task() + self.t1 = Task() + self.unused_params_rank = unused_params_rank + + def task_parameters(self): + return (self.t0.p, self.t1.p) + + def forward(self, x, rank): + return ( + self.t1(self.t0(x)) + if rank != self.unused_params_rank + else self.t1(x) + ) + + unjoined_rank_with_unused_params_model = UnusedParamModule(1) + joined_rank_with_unused_params_model = UnusedParamModule(0) + + rank = self.rank + models_to_test = [ + # Network with batchnorm + DDPUnevenTestInput( + name="batch_norm_net", + model=bn_net, + inp=torch.ones(batch, 2, device=rank), + sync_interval=1, + ), + DDPUnevenTestInput( + name="large_conv_model", + model=large_model, + inp=torch.ones(batch, batch, dim, dim, device=rank), + sync_interval=1, + ), + DDPUnevenTestInput( + name="small_model", + model=small_model, + inp=torch.ones(batch, dim, device=rank), + sync_interval=1, + ), + # Unused parameter test where rank that does not join early has unused params + DDPUnevenTestInput( + name="unjoined_rank_with_unused_params_model", + model=unjoined_rank_with_unused_params_model, + inp=(torch.ones(batch, 2, device=rank), rank), + sync_interval=1, + ), + # Unused parameter test where rank that does join early has unused params + DDPUnevenTestInput( + name="joined_rank_with_unused_params_model", + model=joined_rank_with_unused_params_model, + inp=(torch.ones(batch, 2, device=rank), rank), + sync_interval=1, + ), + ] + + # Test models that have hook installed. + models_with_hook = [ + DDPUnevenTestInput( + name="small_model_allreduce_hook", + model=small_model, + hook=default.allreduce_hook, + state=None, + inp=torch.ones(batch, dim, device=rank), + sync_interval=1, + ), + DDPUnevenTestInput( + name="small_model_power_sgd_hook", + model=small_model, + hook=powerSGD.powerSGD_hook, + state=powerSGD.PowerSGDState( + process_group=None, + matrix_approximation_rank=1, + # Config so that powerSGD runs immediately instead of + # allreduce. + start_powerSGD_iter=1, + warm_start=False, + use_error_feedback=False, + ), + inp=torch.ones(batch, dim, device=rank), + sync_interval=1, + ), + ] + models_to_test.extend(models_with_hook) + + # Add resnet model if we have torchvision installed. + if HAS_TORCHVISION: + resnet_model = torchvision.models.resnet50() + models_to_test.append( + DDPUnevenTestInput( + name="resnet_model", + model=resnet_model, + inp=torch.ones(1, 3, 1000, 1000), + sync_interval=1, + ) + ) + + # Test with no_sync every 2, 3, 4, ... iterations. + models_with_sync = [] + for i, test_input in enumerate(models_to_test): + models_with_sync.append( + DDPUnevenTestInput( + name=test_input.name, + model=test_input.model, + inp=test_input.inp, + sync_interval=i + 2, + ) + ) + + throw_on_early_term_tests = [] + for test_input in models_to_test: + throw_on_early_term_tests.append( + DDPUnevenTestInput( + name=test_input.name, + model=test_input.model, + inp=test_input.inp, + sync_interval=test_input.sync_interval, + throw_on_early_termination=True, + ) + ) + + models_to_test.extend(models_with_sync) + models_to_test.extend(throw_on_early_term_tests) + + # 0 iteration tests for when one process does not train model at all, so + # we must shadow the broadcast calls made when rebuilding buckets. + baseline_num_iters = [0, 5] + iteration_offsets = [2, 3, 10] + num_uneven_ranks = [1] + if dist.get_world_size() > 2: + num_uneven_ranks.append(2) + iteration_mappings = [] + # Generate rank : num_iters mappings for various uneven input scenarios. + # This includes cases where rank 0 joins early and all other ranks join + # later, and scenarios where multiple ranks join early, but at different + # iterations, and later ranks join later. + for num_early_join_ranks in num_uneven_ranks: + for baseline_iter in baseline_num_iters: + for offset in iteration_offsets: + mapping = dict.fromkeys(range(0, num_early_join_ranks), baseline_iter) + # if num_early_join_ranks > 1, ranks > 0 that will join early + # iterate offset//2 more times than rank 0, to test nodes + # depleting inputs at different times. + if num_early_join_ranks > 1: + for rank in mapping.keys(): + if rank > 0: + mapping[rank] += offset // 2 + mapping.update( + dict.fromkeys(range(num_early_join_ranks, dist.get_world_size()), baseline_iter + offset) + ) + iteration_mappings.append(mapping) + + for (test_case, iteration_mapping) in itertools.product( + models_to_test, iteration_mappings + ): + if self.rank == 0: + print( + f"""Running test: {test_case.name} sync interval + {test_case.sync_interval} with iteration mapping + {iteration_mapping}""" + ) + self._run_uneven_inputs_test( + test_case, + iteration_mapping, + find_unused_params=("unused_params_model" in test_case.name), + ) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_uneven_input_join_disable(self): + # tests that if net.join() with enable=False is specified, DDP works as + # expected with even inputs. + torch.manual_seed(self.rank) + net = torch.nn.parallel.DistributedDataParallel( + torch.nn.Linear(1, 1).cuda(self.rank), device_ids=[self.rank] + ) + inp = torch.ones(1) * self.rank + n_iters = 5 + world_size = dist.get_world_size() + with net.join(enable=False): + for _ in range(n_iters): + # Clear grads + grad = net.module.weight.grad + if grad is not None: + grad.requires_grad_(False) + grad.zero_() + out = net(inp) + loss = out.sum() + loss.backward() + # Validate gradients to ensure that we divide by the correct + # world_size when join mode is disabled. + expected_grad = sum(i for i in range(world_size)) / world_size + self.assertEqual(net.module.weight.grad.item(), expected_grad) + + join_config = net._join_config + self.assertFalse(join_config.enable) + self.validate_net_equivalence(net) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_uneven_input_exception(self): + # Tests that exceptions during training are correctly propagated by the + # context manager. + error_str = "Intentional error" + + class ExceptionModule(nn.Module): + def __init__(self): + super().__init__() + self.param = nn.Parameter(torch.ones(1, requires_grad=True)) + + def forward(self, _): + raise ValueError(error_str) + + exception_module = ExceptionModule() + net = torch.nn.parallel.DistributedDataParallel( + exception_module.cuda(self.rank), device_ids=[self.rank] + ) + inp = torch.ones(1) + with self.assertRaisesRegex(ValueError, error_str): + with net.join(): + out = net(inp) + loss = out.sum() + loss.backward() + + def _test_broadcast_object_list(self, group=None): + gather_objects = COLLECTIVES_OBJECT_TEST_LIST.copy() + + # Only set device for NCCL backend since it must use GPUs. + # Case where rank != GPU device. + next_rank = (self.rank + 1) % int(self.world_size) + backend = os.environ["BACKEND"] + if backend == "nccl": + torch.cuda.set_device(next_rank) + + src_rank = 0 + # If GPU test, add object with GPU tensor + if backend == "nccl": + gather_objects.append(Foo(torch.randn(3, 3, device=0))) + + if IS_FBCODE: + # Create Tensor with > 2^31 Bytes storage requirements + # Only on FBCODE as testing OOMs in OSS + gather_objects.append(Foo(torch.randn(3, 178956971))) + objects = ( + gather_objects + if self.rank == src_rank + else [None for _ in gather_objects] + ) + + # Single object test with device specified. Backend="gloo", device=cpu + if backend != "nccl": + single_obj_list = [objects[0]] + if self.rank != src_rank: + self.assertNotEqual(single_obj_list[0], gather_objects[0]) + dist.broadcast_object_list( + single_obj_list, src=0, group=group, device=torch.device("cpu") + ) + self.assertEqual(single_obj_list[0], gather_objects[0]) + + # Single object test with device specified. Backend="gloo", device=current_device+1 + # The test is gated by the fact GPU count is the same as world size to avoid the case + # when backend is gloo but there is no multiple GPU devices. + if backend != "nccl" and torch.cuda.device_count() == int(self.world_size): + single_obj_list = [objects[0]] + if self.rank != src_rank: + self.assertNotEqual(single_obj_list[0], gather_objects[0]) + dist.broadcast_object_list( + single_obj_list, src=0, group=group, device=torch.device(next_rank) + ) + self.assertEqual(single_obj_list[0], gather_objects[0]) + + # Single object test with device specified. Backend="nccl", device=current_device+1 + if backend == "nccl" and torch.cuda.device_count() == int(self.world_size): + single_obj_list = [objects[0]] + if self.rank != src_rank: + self.assertNotEqual(single_obj_list[0], gather_objects[0]) + dist.broadcast_object_list( + single_obj_list, src=0, group=group, device=torch.device(next_rank) + ) + self.assertEqual(single_obj_list[0], gather_objects[0]) + + # Single object test: backward compatibility with device unspecified + single_obj_list = [objects[0]] + if self.rank != src_rank: + self.assertNotEqual(single_obj_list[0], gather_objects[0]) + dist.broadcast_object_list(single_obj_list, src=0, group=group) + self.assertEqual(single_obj_list[0], gather_objects[0]) + + # Multiple input objects test + if self.rank != src_rank: + self.assertNotEqual(objects, gather_objects) + dist.broadcast_object_list(objects, src=0, group=group) + self.assertEqual(objects, gather_objects) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @require_n_gpus_for_nccl_backend( + int(os.environ["WORLD_SIZE"]), os.environ["BACKEND"] + ) + @with_dist_debug_levels(levels=["DETAIL"]) + @unittest.skip("Test is failing, see https://github.com/pytorch/pytorch/pull/113620") + def test_broadcast_object_list(self): + return self._test_broadcast_object_list() + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @require_n_gpus_for_nccl_backend( + int(os.environ["WORLD_SIZE"]), os.environ["BACKEND"] + ) + @with_dist_debug_levels(levels=["DETAIL"]) + def _test_broadcast_object_list_subgroup(self): + default = _get_default_group() + backend = dist.get_backend(default) + subgroup = dist.new_group(backend=backend) + return self._test_broadcast_object_list(subgroup) + + def _test_ddp_ignore_params_arg(self, static_graph=False): + class TestModel(nn.Module): + def __init__(self, rank): + self.rank = rank + super().__init__() + self.fc1 = nn.Linear(1, 1, bias=False) + # Proxy that will be materialized to another architecture later. + # (after wrapping model with DDP) + if self.rank == 0: + self.fc2 = nn.Linear(1, 10, bias=False) + else: + self.fc2 = nn.Linear(10, 10, bias=False) + + def forward(self, x): + x = self.fc1(x) + x = self.fc2(x) + return x + + device_id = self.rank + # Ensure the test works for both find_unused_parameter and broadcast_buffer settings. + for (find_unused, broadcast_buffers) in itertools.product( + [False, True], [False, True] + ): + model = TestModel(self.rank).float().to(device_id) + # Note that the model can have different shape buffers if we pass + # them in to be ignored as well. + model.fc2.register_buffer( + "ignore_buffer", torch.zeros(5 + self.rank, device=self.rank) + ) + proxy_params = list(model.fc2.parameters()) + proxy_buffers = list(model.fc2.buffers()) + model_fc2_name = next( + module_name + for module_name, module in model.named_modules() + if module is model.fc2 + ) + proxy_param_names = [ + f"{model_fc2_name}.{param_name}" + for param_name, _ in model.fc2.named_parameters() + ] + proxy_buffer_names = [ + f"{model_fc2_name}.{buf_name}" + for buf_name, _ in model.fc2.named_buffers() + ] + # Specify that we should ignore proxy_params since it will be + # materialized later. + torch.nn.parallel.DistributedDataParallel._set_params_and_buffers_to_ignore_for_model( + model, proxy_param_names + proxy_buffer_names + ) + ddp = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[device_id], + find_unused_parameters=find_unused, + broadcast_buffers=broadcast_buffers, + static_graph=static_graph, + ) + # Materialize new params. These are not registered in DDP and thus + # don't have autograd hooks installed on them. + ddp.module.fc2 = nn.Linear(1, 1, bias=False).to(device_id) + + # local model with the new materialized parameters. + local_model = copy.deepcopy(ddp.module).cuda(self.rank) + + inp = torch.ones(1, dtype=torch.float).to(device_id) * (self.rank + 1) + for i in range(6): + ddp(inp).sum().backward() + + local_model(inp).sum().backward() + # materialized param grad is not touched by DDP, so its grad should + # be the same as if running locally. + for materialized_param, local_param in zip( + ddp.module.fc2.parameters(), local_model.fc2.parameters() + ): + self.assertEqual(materialized_param.grad, local_param.grad) + + # fc1 parameter grad should still be different, due to allreduce. + for synced_param, local_param in zip( + ddp.module.fc1.parameters(), local_model.fc1.parameters() + ): + self.assertFalse(synced_param.grad == local_param.grad) + + # Proxy module grad should not be touched + for proxy_param in proxy_params: + self.assertTrue(proxy_param.grad is None) + + # Synchronize since we run multiple iterations of this test, to + # isolate failure hangs. + torch.cuda.synchronize(device=self.rank) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + def test_ddp_ignore_params_arg(self): + self._test_ddp_ignore_params_arg(static_graph=False) + self._test_ddp_ignore_params_arg(static_graph=True) + + @with_dist_debug_levels(levels=["OFF", "INFO", "DETAIL"]) + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + def test_ddp_unused_params_rebuild_buckets_exception(self): + class ToyModel(nn.Module): + def __init__(self): + super().__init__() + self.net1 = nn.Linear(10, 10, bias=False) + self.net2 = nn.Linear(10, 10, bias=False) + + def forward(self, x): + return self.net1(x) + + ddp = torch.nn.parallel.DistributedDataParallel( + ToyModel().cuda(self.rank), device_ids=[self.rank] + ) + for i in range(2): + inp = torch.rand(1, 10) + if i > 0: + # On 2nd iteration, this will fail during rebuild_buckets, + # but we should report an error regarding unused parameters + # since that is the underlying root cause. + try: + ddp(inp).sum().backward() + except RuntimeError as e: + msg = str(e) + verify_ddp_error_logged(ddp, msg) + expected_strs = [ + ddp_prev_reduction_unfinished_str, + ddp_recommend_find_unused_params_str, + ddp_outputs_not_used_in_loss_str, + ] + # In debug mode, should show parameters that weren't reduced. + # Without debug mode, should show suggestion to use debug mode. + if dist.get_debug_level() == dist.DebugLevel.OFF: + expected_strs.append(ddp_suggest_debug_mode_str) + else: + unreduced_params = ", ".join(["net2.weight"]) + expected_strs.append( + f"did not receive grad for rank {self.rank}: {unreduced_params}" + ) + for s in expected_strs: + self.assertTrue(s in msg, f"Expected {s} to be in {msg}") + self.assertFalse(ddp_find_unused_params_enabled_str in msg) + else: + self.assertFalse( + True, "DDP unused parameters error not raised." + ) + else: + ddp(inp).sum().backward() + + dist.barrier() + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + def test_ddp_shared_grad_acc_unused_params(self): + # When find_unused_parameters=True, ensure we mark unused parameters + # even if they share gradient accumulators. + class ToyModel(nn.Module): + def __init__(self): + super().__init__() + # net1, bias, and net1.bias are all unused params. + self.net1 = nn.Linear(10, 5, bias=False) + self.bias = nn.Parameter(torch.zeros(5)) + # net1.bias and self.bias are names for the same underlying + # parameter, so they share the same grad acc. This caused + # the bug reported in https://github.com/pytorch/pytorch/issues/41324. + self.net1.bias = self.bias + self.net2 = nn.Linear(10, 5) + + def forward(self, x): + return self.net2(x).sum() + + torch.cuda.set_device(self.rank) + model = ToyModel().to(torch.cuda.current_device()) + for static in [True, False]: + ddp_model = torch.nn.parallel.DistributedDataParallel( + copy.deepcopy(model), + device_ids=[self.rank], + find_unused_parameters=True, + static_graph=static, + ) + inp = torch.randn(20, 10, device=self.rank) + for i in range(6): + loss = ddp_model(inp) + # To test https://github.com/pytorch/pytorch/issues/61982 + loss /= 10 + loss.backward() + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + def test_ddp_device(self): + m = nn.Linear(10, 10).to(self.rank) + expected_len = 2 + + class TensorWrapper: + __slots__ = ["t", "moved_to_gpu"] + + def __init__(self, t): + self.t = t + self.moved_to_gpu = False + + # Handlers for specific types of validation we want to do based on + # the input type. + + def tuple_and_list_validator(x): + self.assertTrue(len(x), expected_len) + self.assertEqual(1, len({t.device for t in x})) + self.assertEqual(x[0].device.index, self.rank) + return x[0] + x[1] + + def namedtuple_validator(x): + self.assertEqual(x._fields, EXPECTED_FIELDS) + self.assertEqual(x.a.device.index, x.b.device.index) + self.assertEqual(x.a.device.index, self.rank) + return x.a + x.b + + def custom_type_validator(x): + self.assertTrue(x.moved_to_gpu or (str(x.t.device) == "cpu")) + x.t = x.t.to(self.rank) + x.moved_to_gpu = True + return x.t + + def dict_validator(x): + self.assertTrue(EXPECTED_FIELDS[0] in x.keys()) + self.assertTrue(EXPECTED_FIELDS[1] in x.keys()) + self.assertEqual(1, len({t.device for t in x.values()})) + self.assertEqual(x[EXPECTED_FIELDS[0]].device.index, self.rank) + return x[EXPECTED_FIELDS[0]] + x[EXPECTED_FIELDS[1]] + + validators = { + TensorWrapper: custom_type_validator, + tuple: tuple_and_list_validator, + list: tuple_and_list_validator, + TestNamedTupleInput_0: namedtuple_validator, + TestNamedTupleInput_1: namedtuple_validator, + dict: dict_validator, + } + + class ToyModel(torch.nn.Module): + def __init__(_self): # noqa: B902 + super().__init__() + _self.lin = nn.Linear(10, 10, bias=False) + + def forward(_self, x, expected_type): # noqa: B902 + # Similar to scatter, the recursive to in the single-device + # case does not move tensors if they are in a custom type. + self.assertTrue(isinstance(x, expected_type)) + fwd_tensor = validators[expected_type](x) + return _self.lin(fwd_tensor) + + model = torch.nn.parallel.DistributedDataParallel( + ToyModel().to(self.rank), device_ids=[self.rank] + ) + + def train_iter(inp, input_type): + for _ in range(4): + out = model(inp, input_type) + out.sum().backward() + + # CPU tuple input, should be moved to the proper device before call + # to forward. + inp = tuple(torch.randn(10, 10) for _ in range(expected_len)) + train_iter(inp, tuple) + + # List CPU input, should be moved to proper device before call to + # forward. + inp = [torch.randn(10, 10) for _ in range(expected_len)] + train_iter(inp, list) + # Custom type containing tensor. The type is maintained, but the + # device is not propagated (which is what happens with scatter too) + inp = TensorWrapper(torch.randn(10, 10)) + train_iter(inp, TensorWrapper) + # NamedTuple input. The type should be maintained and tensor inputs + # should be moved to the correct device as in scatter. + batch = 5 + dim = 10 + a = torch.rand(batch, dim) + b = torch.rand(batch, dim) + + inp = TestNamedTupleInput_0(a, b) + train_iter(inp, type(inp)) + + inp = TestNamedTupleInput_1(a, b) + train_iter(inp, type(inp)) + + # dictionary input. + inp = { + EXPECTED_FIELDS[0]: a, + EXPECTED_FIELDS[1]: b, + } + train_iter(inp, type(inp)) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + def test_ddp_namedtuple(self): + batch = 5 + dim = 10 + + a = torch.rand(batch, dim, device=self.rank) + b = torch.rand(batch, dim, device=self.rank) + + class NamedTupleModule(torch.nn.Module): + def __init__(_self): # noqa: B902 + super().__init__() + _self.lin = nn.Linear(10, 1) + + def forward(_self, input, expected_type): # noqa: B902 + # Without NamedTuple support, this would be of type tuple. + self.assertTrue( + isinstance(input, expected_type), + f"Expected type {expected_type} but got {type(input)}", + ) + self.assertEqual(input._fields, EXPECTED_FIELDS) + self.assertEqual(a, input.a) + self.assertEqual(b, input.b) + return _self.lin(torch.mul(input.a, input.b)) + + model = torch.nn.parallel.DistributedDataParallel( + NamedTupleModule().cuda(self.rank), device_ids=[self.rank] + ) + inp = TestNamedTupleInput_0(a, b) + # The following would fail if DDP does not propagate NamedTuples correctly. + model(inp, type(inp)) + + inp = TestNamedTupleInput_1(a, b) + model(inp, type(inp)) + + @with_dist_debug_levels(levels=["OFF", "INFO", "DETAIL"]) + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + def test_ddp_control_flow_same_across_ranks(self): + # Control flow that is the same across ranks. + batch = 20 + dim = 10 + + world_size = dist.get_world_size() + torch.cuda.set_device(self.rank) + model = torch.nn.parallel.DistributedDataParallel( + ControlFlowToyModel().cuda(self.rank), + device_ids=[self.rank], + find_unused_parameters=True, + ) + random_input = torch.randn(batch, dim, device=self.rank) + ones_input = torch.ones(batch, dim, device=self.rank) + for i in range(6): + if i % 2 == 0: + out = model(random_input) + else: + out = model(ones_input) + loss = out.sum() + loss.backward() + # On even iterations, 2nd param goes unused, on odd iterations, + # it is used. + local_used_map = model.reducer._get_local_used_map() + if i % 2 == 0: + expected = torch.tensor( + [world_size, 0], device=self.rank, dtype=torch.int32 + ) + else: + expected = torch.tensor( + [world_size, world_size], device=self.rank, dtype=torch.int32 + ) + + # Validate parameter usage. + variable_usage_tensor = local_used_map + self.assertEqual(variable_usage_tensor, expected) + + # Validate appropriate error message when DDP is used with + # find_unused_parameters=False. + model = torch.nn.parallel.DistributedDataParallel( + ControlFlowToyModel().cuda(self.rank), + device_ids=[self.rank], + find_unused_parameters=False, + ) + for i in range(2): + if i == 0: + loss = model(random_input).sum() + loss.backward() + else: + try: + loss = model(random_input).sum() + loss.backward() + except RuntimeError as e: + msg = str(e) + verify_ddp_error_logged(model, msg) + # 2nd linear layer is unused + unused_param_index = 1 + expected_strs = [ + ddp_prev_reduction_unfinished_str, + ddp_recommend_find_unused_params_str, + ddp_outputs_not_used_in_loss_str, + f"Parameter indices which did not receive grad for rank {self.rank}: {unused_param_index}", + ] + # In debug mode, should show parameters that weren't reduced. + # Without debug mode, should show suggestion to use debug mode. + if dist.get_debug_level() == dist.DebugLevel.OFF: + expected_strs.append(ddp_suggest_debug_mode_str) + else: + unreduced_params = ", ".join(["lin2.weight"]) + expected_strs.append( + f"did not receive grad for rank {self.rank}: {unreduced_params}" + ) + for s in expected_strs: + self.assertTrue(s in msg, f"Expected {s} to be in {msg}") + self.assertFalse(ddp_find_unused_params_enabled_str in msg) + else: + self.assertFalse(True, "DDP error not raised") + + dist.barrier() + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + def test_invalid_static_graph(self): + world_size = dist.get_world_size() + torch.cuda.set_device(self.rank) + model = torch.nn.parallel.DistributedDataParallel( + ControlFlowToyModel().cuda(self.rank), + device_ids=[self.rank], + static_graph=True, + ) + random_input = torch.randn(20, 10, device=self.rank) + ones_input = torch.ones(20, 10, device=self.rank) + # unused parameter in the first iteration got used + # in second iteration. + expected_err = "Your training graph has changed in this iteration" + with self.assertRaisesRegex(RuntimeError, expected_err): + for i in range(2): + if i % 2 == 0: + out = model(random_input) + else: + out = model(ones_input) + loss = out.sum() + loss.backward() + + verify_ddp_error_logged(model, expected_err) + + # used parameter in the first iteration got unused + # in second iteration. + with self.assertRaisesRegex( + RuntimeError, + "Expected to have finished reduction in the prior iteration " + "before starting a new one. This error indicates that your " + "training graph has changed in this iteration, " + "e.g., one parameter is used in first iteration, " + "but then got unused in the second iteration. " + "this is not compatible with static_graph set to True.\n" + "Parameter indices which did not receive grad for", + ): + for i in range(2): + if i % 2 != 0: + out = model(random_input) + else: + out = model(ones_input) + loss = out.sum() + loss.backward() + + verify_ddp_error_logged(model, "Expected to have finished reduction") + + @with_dist_debug_levels(levels=["OFF", "INFO", "DETAIL"]) + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + def test_ddp_control_flow_different_across_ranks(self): + # Control flow that is different across ranks. + batch = 20 + dim = 10 + + class ToyModel(nn.Module): + def __init__(self, rank): + super().__init__() + self.lin1 = nn.Linear(10, 10, bias=False) + self.lin2 = nn.Linear(10, 10, bias=False) + self.rank = rank + + def forward(self, x): + # Control-flow that is rank and input dependent for the + # model. + use_second_layer = ( + torch.equal(x, torch.ones(batch, dim, device=x.device)) + and self.rank == 1 + ) + + if use_second_layer: + return self.lin2(F.relu(self.lin1(x))) + else: + return F.relu(self.lin1(x)) + + world_size = dist.get_world_size() + torch.cuda.set_device(self.rank) + model = torch.nn.parallel.DistributedDataParallel( + ToyModel(self.rank).cuda(self.rank), + device_ids=[self.rank], + find_unused_parameters=True, + ) + random_input = torch.randn(batch, dim, device=self.rank) + ones_input = torch.ones(batch, dim, device=self.rank) + for i in range(6): + if i % 2 == 0: + out = model(random_input) + else: + out = model(ones_input) + loss = out.sum() + loss.backward() + # On even iterations, 2nd param goes unused, on odd iterations, + # it is used only on rank 1. + local_used_map = model.reducer._get_local_used_map() + + if i % 2 == 0: + expected = torch.tensor( + [world_size, 0], device=self.rank, dtype=torch.int32 + ) + else: + expected = torch.tensor( + [world_size, 1], device=self.rank, dtype=torch.int32 + ) + + variable_usage_tensor = local_used_map + # Validate parameter usage. On odd iterations, 2nd param is only + # used on rank 1. + self.assertEqual(variable_usage_tensor, expected) + + # Validate appropriate error message when DDP is used with + # find_unused_parameters=False. + model = torch.nn.parallel.DistributedDataParallel( + ToyModel(self.rank).cuda(self.rank), + device_ids=[self.rank], + find_unused_parameters=False, + ) + for i in range(2): + if i == 0: + loss = model(random_input).sum() + loss.backward() + else: + try: + loss = model(random_input).sum() + loss.backward() + except RuntimeError as e: + msg = str(e) + verify_ddp_error_logged(model, msg) + unused_param_index = 1 + expected_strs = [ + ddp_prev_reduction_unfinished_str, + ddp_recommend_find_unused_params_str, + ddp_outputs_not_used_in_loss_str, + f"Parameter indices which did not receive grad for rank {self.rank}: {unused_param_index}", + ] + # In debug mode, should show parameters that weren't reduced. + # Without debug mode, should show suggestion to use debug mode. + if dist.get_debug_level() == dist.DebugLevel.OFF: + expected_strs.append(ddp_suggest_debug_mode_str) + else: + unreduced_params = ", ".join(["lin2.weight"]) + expected_strs.append( + f"did not receive grad for rank {self.rank}: {unreduced_params}" + ) + for s in expected_strs: + self.assertTrue(s in msg, f"Expected {s} to be in {msg}") + self.assertFalse(ddp_find_unused_params_enabled_str in msg) + else: + self.assertFalse(True, "DDP error not raised") + + dist.barrier() + + @require_backend_is_available({"gloo"}) + def test_scatter_object_list(self): + src_rank = 0 + scatter_list = ( + COLLECTIVES_OBJECT_TEST_LIST + if self.rank == src_rank + else [None for _ in COLLECTIVES_OBJECT_TEST_LIST] + ) + world_size = dist.get_world_size() + scatter_list = scatter_list[:world_size] + i = 0 + while len(scatter_list) < world_size: + scatter_list.append(scatter_list[i]) + i += 1 + + output_obj_list = [None] + dist.scatter_object_list(output_obj_list, scatter_list, src=src_rank) + self.assertEqual( + output_obj_list[0], + COLLECTIVES_OBJECT_TEST_LIST[ + self.rank % len(COLLECTIVES_OBJECT_TEST_LIST) + ], + ) + # Ensure errors are raised upon incorrect arguments. + with self.assertRaisesRegex( + ValueError, + "Expected argument scatter_object_output_list to be a list of size at least 1.", + ): + dist.scatter_object_list([], scatter_list, src=src_rank) + + def _generate_sparse_tensors_for_bucket_assignment_test(self): + tensors = [ + torch.empty([50], dtype=torch.float), + torch.empty([25], dtype=torch.double), + torch.empty([50], dtype=torch.float), + torch.empty([25], dtype=torch.double), + torch.empty([50], dtype=torch.float), + torch.empty([25], dtype=torch.double), + ] + + tensors_sparse = [t.to_sparse() for t in tensors] + return tensors_sparse + + def _test_compute_bucket_assignment_by_size(self, use_logger): + group_gloo = dist.new_group( + timeout=timedelta(seconds=60), backend=dist.Backend.GLOO + ) + # Set TORCH_NCCL_BLOCKING_WAIT and use a new NCCL group to improve test + # determinism. + os.environ["TORCH_NCCL_BLOCKING_WAIT"] = "1" + group_to_use = dist.new_group( + backend=dist.get_backend(), timeout=timedelta(seconds=5) + ) + torch.cuda.set_device(self.rank) + + # Create a valid model. The constructor initializes the logger that we use later. + # We never actually use the rest of the model - we only need its logger. + net = EmbeddingNetDifferentParams(0) + net = torch.nn.parallel.DistributedDataParallel( + net.to(self.rank), + device_ids=[self.rank], + process_group=group_to_use, + ) + + # if we don't pass a logger then we can only check that an exception was thrown. + expected_err = "No support for sparse tensors." + with self.assertRaisesRegex(RuntimeError, expected_err): + tensors_sparse = ( + self._generate_sparse_tensors_for_bucket_assignment_test() + ) + if use_logger: + result = dist._compute_bucket_assignment_by_size( + tensors_sparse, [400], logger=net.logger + ) + else: + result = dist._compute_bucket_assignment_by_size( + tensors_sparse, [400] + ) + if use_logger: + verify_ddp_error_logged(net, expected_err) + + # Perform gloo-based barrier to ensure one rank doesn't exit test + # early which causes failure with Barrier.sync. + dist.barrier(group_gloo) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + def test_compute_bucket_assignment_by_size_sparse_error_without_logger(self): + self._test_compute_bucket_assignment_by_size(use_logger=False) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + def test_compute_bucket_assignment_by_size_sparse_error_with_logger(self): + self._test_compute_bucket_assignment_by_size(use_logger=True) + + def _determine_expected_error_verify_model_across_rank( + self, group_to_use, diff_num_params=False + ): + # When running with NCCL backend, we don't expect an error on rank 0, + # rather, it will be taken down by TORCH_NCCL_ASYNC_ERROR_HANDLING. When + # running with Gloo or with debug mode wrapper, we expect the error + # to be caught inline. + # All ranks report same error when there is a # of parameter + # mismatch since we use allgather in the impl. + if diff_num_params: + expected_err = "DDP expects same model across all ranks" + ctx = self.assertRaisesRegex(RuntimeError, expected_err) + return ctx, expected_err + + is_detail_dbg_mode = dist.get_debug_level() == dist.DebugLevel.DETAIL + if self.rank == 0: + if ( + dist.get_backend(group_to_use) == dist.Backend.NCCL + and not is_detail_dbg_mode + ): + expected_err = "caught collective operation timeout" + ctx = self.assertRaisesRegex(RuntimeError, expected_err) + else: + expected_err = None + ctx = self.assertRaises(RuntimeError) + else: + expected_err = "appears not to match" + ctx = self.assertRaisesRegex(RuntimeError, expected_err) + return ctx, expected_err + + def _test_verify_model_across_rank(self, use_logger): + group_gloo = dist.new_group( + timeout=timedelta(seconds=60), backend=dist.Backend.GLOO + ) + # Set TORCH_NCCL_BLOCKING_WAIT and use a new NCCL group to improve test + # determinism. + os.environ["TORCH_NCCL_BLOCKING_WAIT"] = "1" + group_to_use = dist.new_group( + backend=dist.get_backend(), timeout=timedelta(seconds=5) + ) + torch.cuda.set_device(self.rank) + ctx, expected_err = self._determine_expected_error_verify_model_across_rank( + group_to_use + ) + + # Create a valid model. The constructor initializes the logger that we use later. + net = EmbeddingNetDifferentParams(0) + net = torch.nn.parallel.DistributedDataParallel( + net.to(self.rank), + device_ids=[self.rank], + process_group=group_to_use, + ) + + # Modify the model so that the number of parameters are different for each rank. + # This will cause a RuntimeError to be thrown below in _verify_param_shape_across_processes, + # so we can check if the correct error is thrown and is logged. + # We can't do this in the constructor above otherwise the logger will + # not be properly initialized. + net.module.lin = nn.Linear(100 if self.rank == 0 else 10, 1) + + # if we pass a logger we can verify that it was logged + with ctx: + if use_logger: + _verify_param_shape_across_processes( + net.process_group, list(net.parameters()), net.logger + ) + else: + _verify_param_shape_across_processes( + net.process_group, list(net.parameters()) + ) + # Should only be run by rank 0, and blocking_wait catches and + # reports exception. + dist.barrier(group_to_use) + + # We don't check when self.rank != 0 because the logger doesn't log + # the error "Caught collective operation" as that is not thrown in the reducer. + if use_logger and self.rank != 0: + verify_ddp_error_logged(net, expected_err) + + # Perform gloo-based barrier to ensure one rank doesn't exit test + # early which causes failure with Barrier.sync. + dist.barrier(group_gloo) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_but_pass_in_sandcastle_if( + BACKEND == "ucc" and IS_SANDCASTLE, "Skipped internally" + ) + @skip_if_lt_x_gpu(2) + def test_verify_model_across_rank_with_logger(self): + self._test_verify_model_across_rank(use_logger=True) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_but_pass_in_sandcastle_if( + BACKEND == "ucc" and IS_SANDCASTLE, "Skipped internally" + ) + @skip_if_lt_x_gpu(2) + def test_verify_model_across_rank_without_logger(self): + self._test_verify_model_across_rank(use_logger=False) + + def _run_test_ddp_model_with_diff_params(self, ctx, net, ddp_group, group_gloo): + with ctx: + net = torch.nn.parallel.DistributedDataParallel( + net.to(self.rank), device_ids=[self.rank], process_group=ddp_group + ) + # Should only be run by rank 0, and blocking_wait catches and + # reports exception. + dist.barrier(ddp_group) + + # can't use verify_ddp_error_logged here because net was never properly constructed + + # Perform gloo-based barrier to ensure one rank doesn't exit test + # early which causes failure with Barrier.sync. + dist.barrier(group_gloo) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_but_pass_in_sandcastle_if( + BACKEND == "ucc" and IS_SANDCASTLE, "Skipped internally" + ) + @skip_if_lt_x_gpu(2) + def test_ddp_model_diff_shape_across_ranks(self): + group_gloo = dist.new_group( + timeout=timedelta(seconds=60), backend=dist.Backend.GLOO + ) + # Set TORCH_NCCL_BLOCKING_WAIT and use a new NCCL group to improve test + # determinism. + os.environ["TORCH_NCCL_BLOCKING_WAIT"] = "1" + group_to_use = dist.new_group( + backend=dist.get_backend(), timeout=timedelta(seconds=10) + ) + torch.cuda.set_device(self.rank) + ctx, expected_err = self._determine_expected_error_verify_model_across_rank( + group_to_use + ) + # Creates network with different sized embedding table on different + # ranks. This should throw an error during DDP init. + net = EmbeddingNetDifferentParams(self.rank) + self._run_test_ddp_model_with_diff_params( + ctx, net, group_to_use, group_gloo + ) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_but_pass_in_sandcastle_if( + BACKEND == "ucc" and IS_SANDCASTLE, "Skipped internally" + ) + @skip_if_lt_x_gpu(2) + def test_ddp_model_diff_num_params_across_ranks(self): + group_gloo = dist.new_group( + timeout=timedelta(seconds=60), backend=dist.Backend.GLOO + ) + # Set TORCH_NCCL_BLOCKING_WAIT and use a new NCCL group to improve test + # determinism. + os.environ["TORCH_NCCL_BLOCKING_WAIT"] = "1" + group_to_use = dist.new_group( + backend=dist.get_backend(), timeout=timedelta(seconds=10) + ) + torch.cuda.set_device(self.rank) + ctx, expected_err = self._determine_expected_error_verify_model_across_rank( + group_to_use, diff_num_params=True + ) + + # Creates network with diff # of param across ranks, reducer should + # recognize this and throw appropriate error. + net = EmbeddingNetDifferentParams( + self.rank, diff_num_params=(self.rank == 1) + ) + + self._run_test_ddp_model_with_diff_params( + ctx, + net, + group_to_use, + group_gloo, + ) + + def _test_output_unused_in_loss(self, module_cls, gradient_as_bucket_view): + model = module_cls() + local_net = copy.deepcopy(model) + net = torch.nn.parallel.DistributedDataParallel( + copy.deepcopy(model).cuda(self.rank), + device_ids=[self.rank], + find_unused_parameters=True, + ) + + # Tests that certain parameters not getting gradient since the + # output is unused in loss computation is supported. Specifically, + # checks that the grads remain unchanged and are the same as local + # training. + inp = torch.randn(10, 10) + + # Ensure that if a param is not used in loss computation, its + # gradient is untouched, i.e. if it is None before it is None after, + # not zero. + if module_cls == DictOutputModule: + a, b = local_net(inp)["predictions"] + a_dist, b_dist = net(inp)["predictions"] + else: + a, b = local_net(inp) + a_dist, b_dist = net(inp) + + loss_dist = b_dist.sum() + loss_dist.backward() + + # Ensure that gradient corresponding to parameter "a" was not + # touched, i.e. it is None and matches the local grad. + if module_cls == DictOutputModule: + self.assertTrue(net.module.module.a.weight.grad is None) + self.assertEqual( + net.module.module.a.weight.grad, local_net.module.a.weight.grad + ) + else: + self.assertTrue(net.module.a.weight.grad is None) + self.assertEqual(net.module.a.weight.grad, local_net.a.weight.grad) + + saved_a_local_grad = None + saved_a_dist_grad = None + net.zero_grad() + local_net.zero_grad() + for i in range(6): + if module_cls == DictOutputModule: + a, b = local_net(inp)["predictions"] + a_dist, b_dist = net(inp)["predictions"] + else: + a, b = local_net(inp) + a_dist, b_dist = net(inp) + if i < 2: + # Use both params in loss computation. Later, "a" will go + # unused and we check to ensure DDP supports this and + # gradients remain the same as local training. + t = a @ b + t_dist = a_dist @ b_dist + loss = t.sum() + loss_dist = t_dist.sum() + else: + # Model output "a" unused in loss. + loss = b.sum() + loss_dist = b_dist.sum() + loss.backward() + loss_dist.backward() + if i == 1: + # Save grads to compare with them in next iterations. + if module_cls == DictOutputModule: + saved_a_local_grad = local_net.module.a.weight.grad + saved_a_dist_grad = net.module.module.a.weight.grad + else: + saved_a_local_grad = local_net.a.weight.grad + saved_a_dist_grad = net.module.a.weight.grad + self.assertEqual(saved_a_local_grad, saved_a_dist_grad) + elif i >= 2: + # parameter "a" of both models should be the same and not change + if module_cls == DictOutputModule: + self.assertEqual( + net.module.module.a.weight.grad, saved_a_dist_grad + ) + self.assertEqual( + local_net.module.a.weight.grad, saved_a_local_grad + ) + else: + self.assertEqual(net.module.a.weight.grad, saved_a_dist_grad) + self.assertEqual(local_net.a.weight.grad, saved_a_local_grad) + + # Verify grads are the same + for (local_param, dist_param) in zip( + local_net.parameters(), net.parameters() + ): + local_grad = local_param.grad + dist_grad = dist_param.grad + self.assertEqual(local_grad, dist_grad) + + dist.barrier() + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_lt_x_gpu(2) + def test_output_unused_in_loss_tuple_module(self): + module_cls = UnusedParamTwoLinLayerNet + for grad_as_bucket_view in [True, False]: + self._test_output_unused_in_loss(module_cls, grad_as_bucket_view) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_lt_x_gpu(2) + def test_output_unused_in_loss_dict_module(self): + module_cls = DictOutputModule + for grad_as_bucket_view in [True, False]: + self._test_output_unused_in_loss(module_cls, grad_as_bucket_view) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_lt_x_gpu(2) + def test_undefined_grad_parity_unused_parameters(self): + # TODO: enable this for general training use cases: + # https://github.com/pytorch/pytorch/issues/58511. + x = torch.ones(1, 2).to(self.rank) + net = Net().to(self.rank) + local_net = copy.deepcopy(net) + net = torch.nn.parallel.DistributedDataParallel( + net, + device_ids=[self.rank], + find_unused_parameters=True, + ) + out = net(x).sum() + local_out = local_net(x).sum() + # Simulates undefined gradients. + torch._C._functions.UndefinedGrad()(out).backward() + torch._C._functions.UndefinedGrad()(local_out).backward() + for (dist_param_name, dist_param), (local_param_name, local_param) in zip( + net.named_parameters(), local_net.named_parameters() + ): + dist_grad = dist_param.grad + local_grad = local_param.grad + self.assertEqual( + dist_grad, + local_grad, + f"""DDP param {dist_param_name} with grad {dist_grad} + does not match local param {local_param_name} with grad + {local_grad}""", + ) + + def _test_different_graph_across_ranks( + self, find_unused_parameters=False, static_graph=False + ): + class ToyModel(nn.Module): + def __init__(self, rank): + super().__init__() + self.lin1 = nn.Linear(10, 10, bias=False) + self.lin2 = nn.Linear(10, 10, bias=False) + self.rank = rank + + def forward(self, x): + if self.rank == 0: + return self.lin2(F.relu(self.lin1(x))) + else: + return F.relu(self.lin1(x)) + + torch.manual_seed(31415) + world_size = dist.get_world_size() + torch.cuda.set_device(self.rank) + model = ToyModel(self.rank).cuda(self.rank) + ddp_model = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[self.rank], + find_unused_parameters=find_unused_parameters, + gradient_as_bucket_view=True, + static_graph=static_graph, + ) + random_input = torch.randn(20, 10, device=self.rank) + for i in range(10): + out = ddp_model(random_input) + loss = out.sum() + loss.backward() + return ddp_model + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + def test_different_graph_across_ranks(self): + base_model = self._test_different_graph_across_ranks( + find_unused_parameters=True + ) + self.assertFalse( + base_model._get_ddp_logging_data().get("has_rebuilt_buckets", 0) + ) + static_model = self._test_different_graph_across_ranks(static_graph=True) + self.assertTrue( + static_model._get_ddp_logging_data().get("has_rebuilt_buckets", 0) + ) + for i, j in zip(base_model.parameters(), static_model.parameters()): + self.assertEqual(i, j) + + @require_backend_is_available({"gloo"}) + @skip_but_pass_in_sandcastle_if( + IS_MACOS or IS_WINDOWS, + "MacOS uses uv transport which does not have as robust error handling as tcp transport", + ) + def test_monitored_barrier_gloo(self): + tensors = [torch.ones(10) * self.rank] + # Kick off some allreduce work on all ranks + for _ in range(10): + dist.all_reduce(torch.cat(tensors)) + # Run monitored barrier and ensure it passes + timeout = timedelta(seconds=2) + dist.monitored_barrier(timeout=timeout) + # Check monitored_barrier success with wait_all_ranks=True + for _ in range(10): + dist.all_reduce(torch.cat(tensors)) + dist.monitored_barrier(timeout=timeout, wait_all_ranks=True) + # All ranks besides 1 call into barrier, rank 0 should report failure + # while others report gloo error. + failed_rank = 1 + src_rank = 0 + if self.rank == src_rank: + with self.assertRaisesRegex( + RuntimeError, f"Rank {failed_rank} failed to pass monitoredBarrier" + ): + dist.monitored_barrier(timeout=timeout) + elif self.rank != failed_rank: + # Other ranks should not pass barrier since rank 0 failed. + err_regex = ( + f"Rank {self.rank} successfully reached monitoredBarrier," + f" but received errors while waiting for send/recv from rank" + f" {src_rank}" + ) + with self.assertRaisesRegex(RuntimeError, err_regex): + dist.monitored_barrier(timeout=timeout) + + # We need a barrier since otherwise failed_rank exits too early + # and cause a timeout. + self._barrier(timeout=30) + + @require_backend_is_available({"gloo"}) + def test_monitored_barrier_gloo_subgroup(self): + # Tests that monitored_barrier works as expected on non-default + # process groups. + failed_rank = 1 + timeout = 0.1 + subgroup = dist.new_group(ranks=[0, 1]) + + if self.rank == failed_rank: + return + + if self.rank == 0: + with self.assertRaisesRegex( + RuntimeError, f"Rank {failed_rank} failed to pass monitoredBarrier" + ): + dist.monitored_barrier(subgroup, timeout) + else: + # Other ranks call into monitored_barrier, but this should be a + # noop because they are not part of the subgroup. Verify that + # there are no errors here. + dist.monitored_barrier(subgroup, timeout) + + def _test_monitored_barrier_allreduce_hang(self, wait_all_ranks): + # tests expected behavior when nonzero rank hangs. + nccl_pg = dist.new_group( + ranks=list(range(int(self.world_size))), + # provide sufficient timeout so communicators + # can be initialized in ctor. + timeout=timedelta(seconds=15), + backend=dist.Backend.NCCL, + ) + gloo_pg = dist.new_group( + ranks=list(range(int(self.world_size))), + backend=dist.Backend.GLOO, + ) + tensors = [torch.ones(10, device=self.rank) * self.rank] + # Let all ranks call allreduce first to set up communicators etc. + # Directly simulating error here will run into store issue described + # in https://github.com/pytorch/pytorch/issues/54524. + nccl_pg.allreduce(tensors).wait(timedelta(seconds=5)) + # All ranks besides 0 call into allreduce. This is to simulate a + # desync across the world, where some ranks call into + # monitored_barrier() and others are stuck in collective comm. In + # practice, we don't need TORCH_NCCL_BLOCKING_WAIT, but we use it in this + # test to ensure it exits cleanly. + if self.rank != 0: + # Can get different errors here depending on whether gloo-based + # wrapper PG is enabled or not, since with wrapper pg, it will + # fail in a collective synchronization check and not actually + # call into the nccl pg. + if dist.get_debug_level() == dist.DebugLevel.DETAIL: + err_regex = "Timed out waiting" + else: + err_regex = "caught collective operation timeout" + with self.assertRaisesRegex(RuntimeError, err_regex): + nccl_pg.allreduce(tensors).wait(timedelta(seconds=0.1)) + else: + # Rank 0 should report first (in order) timed out rank or all ranks + # depending on wait_all_ranks flag passed into monitored_barrier. + if wait_all_ranks: + rank_str = ", ".join( + [str(i) for i in range(1, int(self.world_size))] + ) + err_regex = f"Ranks {rank_str} failed to pass monitoredBarrier" + else: + expected_first_fail_rank = 1 + err_regex = f"Rank {expected_first_fail_rank} failed to pass monitoredBarrier" + monitored_barrier_timeout_seconds = timedelta(seconds=0.1) + with self.assertRaisesRegex(RuntimeError, err_regex): + gloo_pg.monitored_barrier( + monitored_barrier_timeout_seconds, wait_all_ranks=wait_all_ranks + ) + + self._barrier(timeout=30) + + @with_nccl_blocking_wait + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(int(os.environ["WORLD_SIZE"])) + def test_monitored_barrier_allreduce_hang(self): + # tests expected behavior when nonzero rank hangs and we want to + # report first timed out rank. + self._test_monitored_barrier_allreduce_hang(wait_all_ranks=False) + + @with_nccl_blocking_wait + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(int(os.environ["WORLD_SIZE"])) + def test_monitored_barrier_allreduce_hang_wait_all_ranks(self): + # tests expected behavior when nonzero rank hangs and we want to + # report all timed out ranks. + self._test_monitored_barrier_allreduce_hang(wait_all_ranks=True) + + @require_backend_is_available({"gloo"}) + def test_monitored_barrier_gloo_rank_0_timeout(self): + # tests error when rank 0 exhausts its given timeout. + process_group = dist.new_group(ranks=list(range(int(self.world_size)))) + timeout = timedelta(seconds=0) + if self.rank == 0: + with self.assertRaisesRegex( + RuntimeError, f"Rank {self.rank} timed out in monitoredBarrier" + ): + process_group.monitored_barrier(timeout) + + @require_backend_is_available({"gloo"}) + @skip_if_small_worldsize + @skip_but_pass_in_sandcastle_if( + IS_MACOS or IS_WINDOWS, + "MacOS uses uv transport which does not have as robust error handling as tcp transport", + ) + def test_monitored_barrier_failure_order(self): + # Ensure that the first (in sorted order) rank is reported when + # multiple ranks fail to pass the monitored_barrier. + # TODO(#54879): Provide ability to wait and report all failed ranks + expected_first_failed_rank = 2 + timeout = timedelta(seconds=2) + src_rank = 0 + if self.rank == src_rank: + with self.assertRaisesRegex( + RuntimeError, f"Rank {expected_first_failed_rank}" + ): + dist.monitored_barrier(timeout=timeout) + elif self.rank == 1: + err_regex = ( + f"Rank {self.rank} successfully reached monitoredBarrier," + f" but received errors while waiting for send/recv from rank" + f" {src_rank}" + ) + with self.assertRaisesRegex(RuntimeError, err_regex): + dist.monitored_barrier(timeout=timeout) + + @require_backend_is_available({"gloo"}) + @skip_if_small_worldsize + def test_monitored_barrier_wait_all_ranks(self): + # Tests simple case where > 1 rank does not call into monitored + # barrier and verifies all ranks are reported by rank 0. + if self.rank == 0: + timeout = timedelta(seconds=0.1) + rank_str = ", ".join([str(i) for i in range(1, int(self.world_size))]) + err_regex = f"Ranks {rank_str} failed to pass monitoredBarrier" + with self.assertRaisesRegex(RuntimeError, err_regex): + dist.monitored_barrier(timeout=timeout, wait_all_ranks=True) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @with_dist_debug_levels(levels=["INFO"]) + @skip_if_lt_x_gpu(2) + def test_ddp_build_debug_param_to_name_mapping(self): + model = TwoLinLayerNet() + net = torch.nn.parallel.DistributedDataParallel( + model.cuda(self.rank), + device_ids=[self.rank], + ) + expected_mapping = {0: "a.weight", 1: "b.weight"} + net_params, _ = net._build_params_for_reducer() + param_to_name_mapping = net._build_debug_param_to_name_mapping(net_params) + self.assertDictEqual(expected_mapping, param_to_name_mapping) + + # Test when DDP is used with ignored parameters. + model = TwoLinLayerNet() + # Parameters to ignore are in the format {module_name}.{param_name} + params_to_ignore = ["a.weight"] + torch.nn.parallel.DistributedDataParallel._set_params_and_buffers_to_ignore_for_model( + model, params_to_ignore + ) + net = torch.nn.parallel.DistributedDataParallel( + model.cuda(self.rank), + device_ids=[self.rank], + ) + expected_mapping = {0: "b.weight"} + net_params, _ = net._build_params_for_reducer() + param_to_name_mapping = net._build_debug_param_to_name_mapping(net_params) + self.assertDictEqual(expected_mapping, param_to_name_mapping) + + # Test errors are raised when DDP and module parameters mismatch. + # This generally indicates a bug with DDP and is not expected to + # happen in user applications. + model = TwoLinLayerNet() + net = torch.nn.parallel.DistributedDataParallel( + model.cuda(self.rank), + device_ids=[self.rank], + ) + net_params, _ = net._build_params_for_reducer() + if self.rank == 0: + print(type(net_params[0])) + + net_params.extend( + [ + torch.nn.Parameter(torch.ones(1)), + torch.nn.Parameter(torch.ones(1)), + ] + ) + + with self.assertRaisesRegex(ValueError, "Expected param to name mapping"): + net._build_debug_param_to_name_mapping(net_params) + + net_params = net_params[:-3] + with self.assertRaisesRegex(ValueError, "Param with name"): + net._build_debug_param_to_name_mapping(net_params) + + net_params.extend( + [ + torch.nn.Parameter(torch.ones(1)), + torch.nn.Parameter(torch.ones(1)), + ] + ) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @with_dist_debug_levels(levels=["INFO"]) + @skip_if_lt_x_gpu(2) + def test_ddp_build_debug_param_to_name_mapping_requires_grad(self): + class Net(nn.Module): + def __init__(self): + super().__init__() + self.lin = nn.Linear(10, 10) + # Is not tracked by DDP and should not show up in param to + # name mapping. + self.lin.bias.requires_grad_(False) + + def forward(self, x): + return self.lin(x) + + model = Net() + net = torch.nn.parallel.DistributedDataParallel( + model.cuda(self.rank), device_ids=[self.rank] + ) + expected_mapping = { + 0: "lin.weight", + } + net_params, _ = net._build_params_for_reducer() + param_to_name_mapping = net._build_debug_param_to_name_mapping(net_params) + self.assertEqual(param_to_name_mapping, expected_mapping) + + def _test_ddp_multiple_nested_unused_params_error(self, ignore_sparse): + debug_mode_off = dist.get_debug_level() == dist.DebugLevel.OFF + + class SubModule(nn.Module): + def __init__(self): + super().__init__() + self.embedding_net = EmbeddingNetDifferentParams(0) + self.lin = TwoLinLayerNet() + self.bn = BatchNormNet() + self.lin_layer = nn.Linear(4, 10, bias=False) + + def forward(self, x): + x = self.bn(x) + x = self.lin_layer(x) + x = self.lin.a(x) # self.lin.b param unused + # EmbeddingNetDifferentParams entirely unused: self.embedding_net.embedding and + # self.embedding_net.lin unused. + return x + + class MyModel(nn.Module): + def __init__(self): + super().__init__() + self.sub_module = SubModule() + + def forward(self, x): + return self.sub_module(x) + + model = MyModel() + sparse_embedding_fqns = [] + if ignore_sparse: + for module_name, module in model.named_modules(): + if module == model.sub_module.embedding_net.embedding: + for parameter_name, param in module.named_parameters( + recurse=False + ): + fqn = f"{module_name}.{parameter_name}" + sparse_embedding_fqns.append(fqn) + + torch.nn.parallel.DistributedDataParallel._set_params_and_buffers_to_ignore_for_model( + model, sparse_embedding_fqns + ) + unused_modules = [ + model.sub_module.embedding_net.lin, + model.sub_module.lin.b, + ] + else: + unused_modules = list(model.sub_module.embedding_net.modules()) + [ + model.sub_module.lin.b, + ] + + expected_unused_param_fqns = [] + used_param_fqns = [] # Validate that these don't mistakenly show up. + fqn_to_param_index = {} + index = 0 + for module_name, module in model.named_modules(): + for parameter_name, param in module.named_parameters(recurse=False): + fqn = f"{module_name}.{parameter_name}" + fqn_to_param_index[fqn] = index + if fqn not in sparse_embedding_fqns: + index += 1 + if module in unused_modules: + expected_unused_param_fqns.append(fqn) + else: + if ( + not ignore_sparse + or module != model.sub_module.embedding_net.embedding + ): + used_param_fqns.append(fqn) + + net = torch.nn.parallel.DistributedDataParallel( + model.cuda(self.rank), + device_ids=[self.rank], + ) + batch, dim = 10, 2 + inp = torch.ones(batch, dim) + for i in range(2): + if i == 0: + out = net(inp) + loss = out.sum() + loss.backward() + else: + try: + out = net(inp) + loss = out.sum() + loss.backward() + except RuntimeError as e: + e = str(e) + + unused_param_substr = e[e.find("did not receive grad") :] + # Validate that each unused param fully qualified name + # shows up in error logs. We do this instead of + # constructing a joined string since order of parameters + # can be different in Reducer. In addition, validate + # param indices show up as well. + for unused_param_fqn in expected_unused_param_fqns: + self.assertTrue( + unused_param_fqn in unused_param_substr + or debug_mode_off + ) + self.assertTrue( + str(fqn_to_param_index[unused_param_fqn]) + in unused_param_substr, + f"Did not find index {fqn_to_param_index[unused_param_fqn]} for {unused_param_fqn}", + ) + + # Validate that used param fqns don't show up in error + # logs. + for used_param_fqn in used_param_fqns: + self.assertFalse(used_param_fqn in unused_param_substr) + # Validate that ignored param fqns don't show up as unused + # (since DDP does not track them) + for sparse_param_fqn in sparse_embedding_fqns: + self.assertFalse(sparse_param_fqn in unused_param_substr) + else: + self.assertTrue(False, "Expected error was not raised!") + + @with_dist_debug_levels(levels=["OFF", "INFO", "DETAIL"]) + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + def test_ddp_multiple_nested_unused_params_error(self): + self._test_ddp_multiple_nested_unused_params_error(ignore_sparse=False) + + @with_dist_debug_levels(levels=["OFF", "INFO", "DETAIL"]) + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + def test_ddp_multiple_nested_unused_params_err_ignore_params(self): + # Tests unused parameter reporting when DDP is configured to ignore + # certain parameters. + self._test_ddp_multiple_nested_unused_params_error(ignore_sparse=True) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_lt_x_gpu(2) + def test_ddp_inference(self): + # tests that DDP module can be run on a single node with no_grad + # or eval setting and there is no hang. + rank = self.rank + torch.cuda.set_device(rank) + model = Net().cuda() + local_model = copy.deepcopy(model) + model = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[rank], + ) + syncbn_model = nn.SyncBatchNorm( + 2, momentum=0.99, track_running_stats=False + ).cuda() + local_syncbn_model = copy.deepcopy(syncbn_model) + syncbn_model = torch.nn.parallel.DistributedDataParallel( + syncbn_model, device_ids=[rank] + ) + inp = torch.randn(10, 2, device=rank) + inp_syncbn = torch.randn(10, 2, 4, 4, device=rank) + tests = [ + (model, local_model, inp), + (syncbn_model, local_syncbn_model, inp_syncbn), + ] + for test in tests: + test_model, test_local_model, test_inp = test + if self.rank == 0: + test_model.eval() + test_local_model.eval() + for _ in range(6): + self.assertEqual( + test_model(test_inp), test_local_model(test_inp) + ) + + # Barrier since only rank 0 runs inference. Test should be + # much faster than 30s, but this is to avoid flakiness. + self._barrier(timeout=30) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @skip_if_lt_x_gpu(2) + @unittest.skip("Test is failing, see https://github.com/pytorch/pytorch/pull/113620") + def test_ddp_sync_bn_training_vs_eval(self): + rank = self.rank + torch.cuda.set_device(rank) + # Need to set track_running_stats=False, when track_running_stats=True, + # bn_training is False and sync could not occur in eval model. + model = nn.SyncBatchNorm(2, momentum=0.99, track_running_stats=False).cuda( + rank + ) + model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[rank]) + # Test sync occurs in training mode. + with torch.autograd.profiler.profile() as prof: + for i in range(6): + inp = torch.randn(10, 2, 4, 4).cuda(rank) + out = model(inp) + loss = out.sum() + loss.backward() + + # SyncBN allgathers stats across all ranks, so verify call to + # all_gather in profiler. + if BACKEND == "nccl": + all_gather_calls = get_profiling_event("_all_gather_base", prof) + else: + all_gather_calls = get_profiling_event("all_gather", prof) + self.assertNotEqual([], all_gather_calls) + + # Only do inference on one rank. If SyncBN did collective stats sync, + # this would hang/error. + model_inference = model.module + if self.rank == 0: + model_inference.eval() + with torch.autograd.profiler.profile() as prof: + for i in range(6): + inp = torch.randn(10, 2, 4, 4).cuda(rank) + out = model_inference(inp) + loss = out.sum() + loss.backward() + + # Ensure sync does not occur in eval() mode. + if BACKEND == "nccl": + all_gather_calls = get_profiling_event("_all_gather_base", prof) + else: + all_gather_calls = get_profiling_event("all_gather", prof) + self.assertEqual([], all_gather_calls) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_python_error_logged(self): + # Most python exceptions in DDP are raised during init before + # reducer is constructed, so we don't have a logger in those cases. + # However, the below is one example where a python error is thrown + # after reducer is constructed. + model = TwoLinLayerNet().cuda(self.rank) + model = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[self.rank], + ) + expected_err = "must be callable" + with self.assertRaisesRegex(TypeError, expected_err): + model.register_comm_hook({}, {}) + + verify_ddp_error_logged(model, expected_err) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_static_graph_nested_types(self): + # Tests for static graph training when outputs are not just tensors + # but can be (nested) tuple, list, dict, etc. + rank = self.rank + torch.cuda.set_device(rank) + + class NestedOutputModule(torch.nn.Module): + def __init__(self): + super().__init__() + self.lin = nn.Linear(100, 1, bias=False) + + def forward(self, inp, output_type): + if output_type == "tuple": + return ( + self.lin(inp), + ( + self.lin(inp), + self.lin(inp), + ), + ) + elif output_type == "list": + return [ + self.lin(inp), + [ + self.lin(inp), + self.lin(inp), + ], + ] + elif output_type == "dict": + return { + "a": self.lin(inp), + "b": { + "c": self.lin(inp), + }, + } + + def get_loss(model_output): + loss = 0.0 + if isinstance(model_output, torch.Tensor): + return model_output.sum() + elif isinstance(model_output, dict): + for value in model_output.values(): + loss += get_loss(value) + elif isinstance(model_output, (tuple, list)): + for x in model_output: + loss += get_loss(x) + else: + raise ValueError(f"Unknown model output type {type(model_output)}") + return loss + + model = NestedOutputModule().cuda(rank) + model_static_graph = copy.deepcopy(model) + model = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[rank], + ) + model_static_graph = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[rank], + static_graph=True, + ) + inp = torch.randn(10, 100) + type_mapping = { + "list": list, + "tuple": tuple, + "dict": dict, + } + for output_type in type_mapping.keys(): + for i in range(6): + out = model(inp, output_type=output_type) + loss = get_loss(out) + loss.backward() + self._model_step(model) + out_static = model_static_graph(inp, output_type=output_type) + self.assertTrue(isinstance(out_static, type_mapping[output_type])) + loss_static = get_loss(out_static) + loss_static.backward() + self._model_step(model_static_graph) + for (p, p_static) in zip( + model.parameters(), model_static_graph.parameters() + ): + self.assertEqual(p, p_static) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_returns_tensor_with_no_grad(self): + # Tests case where module returns tensor that does not require grad. + torch.cuda.set_device(self.rank) + + class MyModel(nn.Module): + def __init__(self): + super().__init__() + self.fc1 = nn.Linear(10, 10, bias=False) + self.fc2 = nn.Linear(10, 10, bias=False) + + def forward(self, x): + x = self.fc2(F.relu(self.fc1(x))) + y = x.clone() + x = x.detach() + assert not x.requires_grad + return (x, y) + + model = MyModel().to(self.rank) + inp = torch.randn(1, 10, device=self.rank) + for (find_unused, static_graph) in itertools.product( + [True, False], [True, False] + ): + ddp = DistributedDataParallel( + model, + device_ids=[self.rank], + output_device=self.rank, + find_unused_parameters=find_unused, + static_graph=static_graph, + ) + for i in range(6): + out = ddp(inp) + self.assertFalse(out[0].requires_grad) + o = (out[0] + out[1]).sum() + o.backward() + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_detect_ddp_is_actually_static(self): + class ToyModel(nn.Module): + def __init__(self): + super().__init__() + self.net1 = nn.Linear(10, 10, bias=False) + self.net2 = nn.Linear(10, 10) + + def forward(self, x, find_unused, dynamic): + if find_unused: + if dynamic: + return self.net2(self.net1(x)) + else: + return self.net2(x) + else: + return self.net2(self.net1(x)) + + # Set of unused parameters don't change across iterations + torch.cuda.set_device(self.rank) + model = ToyModel().cuda() + for find_unused in [True, False]: + ddp = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[self.rank], + find_unused_parameters=find_unused, + ) + inp = torch.randn(1, 10, device="cuda") + for _ in range(6): + out = ddp(inp, find_unused=find_unused, dynamic=False) + loss = out.sum() + loss.backward() + self.assertTrue(ddp.reducer._ddp_graph_static()) + + # Set of unused parameters dynamically change + ddp = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[self.rank], + find_unused_parameters=True, + ) + inp = torch.randn(1, 10, device="cuda") + for i in range(6): + out = ddp(inp, find_unused=True, dynamic=i % 2 == 0) + loss = out.sum() + loss.backward() + self.assertFalse(ddp.reducer._ddp_graph_static()) + + def _test_ddp_new_tensor_in_fwd(self, static_graph): + # Test from https://github.com/pytorch/pytorch/issues/60733 + class MyModel(nn.Module): + def __init__(self): + super().__init__() + self.fc1 = nn.Linear(10, 10, bias=False) + self.fc2 = nn.Linear(10, 10, bias=False) + self.device = self.fc1.weight.device + + def __init_opt(self): + opt = torch.randn(1, 10, device=self.device) + return opt + + def forward(self, x, opt_1, opt_2, opt_nested): + x = F.relu(self.fc1(x)) + x = self.fc2(x) + if opt_1 is None: + opt_1 = self.__init_opt() + if opt_2 is None: + opt_2 = self.__init_opt() + if opt_nested is None or not torch.is_tensor(opt_nested): + opt_nested = self.__init_opt() + # Test multiple tensors as well as newly created tensors + # within a struct. + return x, opt_1, opt_2, {"tensor": opt_nested} + + model = MyModel().to(self.rank) + for find_unused in [True, False]: + ddp = DistributedDataParallel( + model, + device_ids=[self.rank], + output_device=self.rank, + broadcast_buffers=False, + find_unused_parameters=find_unused, + static_graph=static_graph, + ) + + opt = [None for _ in range(3)] + for i in range(2): + ddp.zero_grad() + x = torch.randn(1, 10, device=self.rank) + out, opt[0], opt[1], opt[2] = ddp( + x, opt_1=opt[0], opt_2=opt[1], opt_nested=opt[2] + ) + for i in range(len(opt)): + if torch.is_tensor(opt[i]): + self.assertEqual(opt[i].grad_fn, None) + else: + self.assertEqual(opt[i]["tensor"].grad_fn, None) + out.mean().backward() + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_new_tensor_in_fwd(self): + return self._test_ddp_new_tensor_in_fwd(static_graph=False) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_new_tensor_in_fwd_static_graph(self): + return self._test_ddp_new_tensor_in_fwd(static_graph=True) + + def _test_ddp_buffer_hook_allreduce(self, return_futures): + rank = self.rank + torch.cuda.set_device(rank) + torch.manual_seed(rank) + torch.cuda.manual_seed(rank) + + def buffer_comm_hook(ddp, named_buffers): + buffers = [buffer for (_, buffer) in named_buffers.items()] + futs = [ + dist.all_reduce( + buffer, group=ddp.process_group, async_op=True + ).get_future() + for buffer in buffers + ] + if return_futures: + return futs + else: + torch.futures.collect_all(futs).wait() + + hook_pre_fwd = ( + torch.nn.parallel.distributed._BufferCommHookLocation.PRE_FORWARD + ) + hook_post_fwd = ( + torch.nn.parallel.distributed._BufferCommHookLocation.POST_FORWARD + ) + for hook_run_location in [ + hook_pre_fwd, + hook_post_fwd, + ]: + model = NetWithBuffers().cuda(rank) + model_ddp = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[self.rank], + ) + model_ddp._register_buffer_comm_hook( + model_ddp, buffer_comm_hook, hook_run_location + ) + model_ddp_no_hook = torch.nn.parallel.DistributedDataParallel( + copy.deepcopy(model), + device_ids=[self.rank], + broadcast_buffers=False, + ) + inp = torch.randn(2, 10, device=rank) + for i in range(2): + loss_hook = model_ddp(inp).sum() + # Since buffer reduction is done pre-forward, simulate it for + # no hook case here. + # Simulate allreduce appropriately depending on hook location. + if hook_run_location == hook_pre_fwd: + model_no_hook_buffers = list(model_ddp_no_hook.module.buffers()) + for tensor in model_no_hook_buffers: + dist.all_reduce(tensor) + + loss_no_hook = model_ddp_no_hook(inp).sum() + if hook_run_location == hook_post_fwd: + model_no_hook_buffers = list(model_ddp_no_hook.module.buffers()) + for tensor in model_no_hook_buffers: + dist.all_reduce(tensor) + torch.cuda.synchronize() + + # if return_futures, they are only awaited on by DDP + # at the end of the backwards pass for maximum overlap. + if not return_futures: + self._verify_buffers_equal(model_ddp, model_ddp_no_hook) + loss_hook.backward() + loss_no_hook.backward() + # Note that when custom hooks return futures, this + # comparison is not expected to work when hook run location + # is pre-forward pass. This is because the hook does async + # communication and forward pass modifies the buffer without + # appropriate synchronization. Therefore, if returning + # futures from custom buffer hooks, it is advised to set + # hook run location to post forward. + if return_futures and hook_run_location == hook_post_fwd: + self._verify_buffers_equal(model_ddp, model_ddp_no_hook) + dist.barrier() + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_buffer_hook_allreduce_return_future(self): + self._test_ddp_buffer_hook_allreduce(return_futures=True) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_buffer_hook_allreduce(self): + self._test_ddp_buffer_hook_allreduce(return_futures=False) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_broadcast_buffer_via_hook(self): + # test that _distributed_broadcast_coalesced via registered hook is + # equivalent to DDP's default broadcast coalesced. + rank = self.rank + torch.cuda.set_device(rank) + torch.manual_seed(rank) + torch.cuda.manual_seed(rank) + + def buffer_comm_hook(ddp, named_buffers): + # named_buffers is a Dict[str, Tensor] representing a mapping + # from buffer name to buffer. + buffers = [buffer for (_, buffer) in named_buffers.items()] + ddp._default_broadcast_coalesced(buffers) + + model = NetWithBuffers().cuda(rank) + model_ddp = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[self.rank], + ) + model_ddp._register_buffer_comm_hook(model_ddp, buffer_comm_hook) + model_ddp_no_hook = torch.nn.parallel.DistributedDataParallel( + copy.deepcopy(model), + device_ids=[self.rank], + ) + inp = torch.randn(2, 10, device=rank) + for i in range(2): + loss_hook = model_ddp(inp).sum() + loss_no_hook = model_ddp_no_hook(inp).sum() + self._verify_buffers_equal(model_ddp, model_ddp_no_hook) + loss_hook.backward() + loss_no_hook.backward() + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_remove_autograd_hooks(self): + + class SimulateError(torch.autograd.Function): + @staticmethod + def forward(ctx, input): + return input + + @staticmethod + def backward(ctx, grad_output): + raise RuntimeError() + + class MyModel(nn.Module): + def __init__(self, device): + super().__init__() + self.error = True + self.fc1 = nn.Linear(10, 10).cuda(device) + + def forward(self, inp): + if self.error: + return self.fc1(SimulateError.apply(inp)) + else: + return self.fc1(inp) + + + # Run with error to trigger backward pass that marks fc1 as being marked + # ready. If we don't remove autograd hooks before running below it would + # fail on the old autograd hook. + model = MyModel(self.rank) + input = torch.rand(10, 10, requires_grad=True).cuda(self.rank) + model_ddp1 = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[self.rank], + ) + + with self.assertRaises(RuntimeError): + model_ddp1(input).sum().backward() + + # Remove autograd hooks on old instance. + model_ddp1._remove_autograd_hooks() + + # Try another DDP instance without error now. + model.error = False + model_ddp2 = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[self.rank], + ) + model_ddp2(input).sum().backward() + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + @unittest.skip("Test is failing, tracking issue at https://github.com/pytorch/pytorch/issues/102751") + def test_ddp_has_finalized(self): + + @dataclass + class MyClass: + obj: torch.Tensor + + class MyModel(nn.Module): + def __init__(self, rank): + super().__init__() + self.rank = rank + self.fc1 = nn.Linear(1024, 1024).cuda(rank) + self.fc2 = nn.Linear(1024, 2 * 1024).cuda(rank) + + def forward(self, inp): + if self.rank == 0: + return self.fc1(inp), MyClass(self.fc2(inp)) + else: + return self.fc1(inp), self.fc2(inp) + + model = MyModel(self.rank) + input = torch.rand(10, 1024, requires_grad=True).cuda(self.rank) + ddp = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[self.rank], + find_unused_parameters=True, + bucket_cap_mb=(1024 * 4 / 1024 / 1024), # One bucket per parameter. + ) + + if self.rank == 0: + out1, _ = ddp(input) + out1.sum().backward() + else: + out1, out2 = ddp(input) + (out1.sum() + out2.sum()).backward() + + if self.rank == 0: + with self.assertRaisesRegex(RuntimeError, "Expected to have finished reduction in the prior iteration"): + ddp._check_reducer_finalized() + + with self.assertRaisesRegex(RuntimeError, "Expected to have finished reduction in the prior iteration"): + ddp(input) + else: + ddp._check_reducer_finalized() + ddp(input) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl", + "TORCH_NCCL_USE_COMM_NONBLOCKING only applies to NCCL" + ) + def test_nccl_init_abort(self): + """ + Tests that we can abort a NCCL communicator during initialization and + recover appropriately. + """ + # Reinitialize global process group with TORCH_NCCL_USE_COMM_NONBLOCKING=1 + os.environ["TORCH_NCCL_USE_COMM_NONBLOCKING"] = "1" + dist.destroy_process_group() + timeout = timedelta(seconds=1) + dist.init_process_group( + init_method=INIT_METHOD, + backend=BACKEND, + world_size=int(os.environ["WORLD_SIZE"]), + rank=self.rank, + timeout=timeout, + ) + + # Abort pg in background thread. + running = True + + def abort(device): + pg = _get_default_group() + while running: + pg._get_backend(torch.device(device))._shutdown() + time.sleep(1) + + if self.rank != 1: + import threading + t = threading.Thread(target=abort, args=(self.rank,)) + t.start() + with self.assertRaises(RuntimeError): + # First collective triggers initialization via ncclCommInitRank. + torch.distributed.barrier() + running = False + t.join() + + def _run_ddp_update_process_group(self, new_pg): + def get_num_torch_recompiles(): + guard_failures = torch._dynamo.utils.guard_failures + num_recompiles = [len(guard_failures[code]) for code in guard_failures] + return 0 if len(num_recompiles) == 0 else max(num_recompiles) + + class SimulateError(torch.autograd.Function): + @staticmethod + def forward(ctx, input): + return input + + @staticmethod + def backward(ctx, grad_output): + raise RuntimeError() + + class MyModel(torch.nn.Module): + def __init__(self, device): + super().__init__() + # 4MB for multiple buckets. + self.fc1 = torch.nn.Linear(1024, 1024).cuda(device) + self.fc2 = torch.nn.Linear(1024, 1024).cuda(device) + self.fc3 = torch.nn.Linear(1024, 1024).cuda(device) + + def forward(self, inp, error): + if error: + return self.fc3(self.fc2(self.fc1(SimulateError.apply(inp)))) + else: + return self.fc3(self.fc2(self.fc1(inp))) + + + input = torch.rand(10, 1024, requires_grad=True).cuda(self.rank) + ddp = torch.nn.parallel.DistributedDataParallel( + MyModel(self.rank), + device_ids=[self.rank], + find_unused_parameters=True, + bucket_cap_mb=1, + ) + model = torch.compile(ddp) + + def run_iteration(): + # Run regular iteration. + out = model(input, error=False) + out.sum().backward() + torch.cuda.synchronize() + + # Run with error. + with self.assertRaises(RuntimeError): + out = model(input, error=True) + out.sum().backward() + torch.cuda.synchronize() + + run_iteration() + assert 0 == get_num_torch_recompiles() + + if new_pg: + # Now reduce world_size and run iteration. + group_size_2 = dist.new_group(ranks=[0, 1]) + ddp._update_process_group(group_size_2) + if self.rank in [0, 1]: + run_iteration() + + # Increase the world size and run iteration. + group_size_3 = dist.new_group(ranks=[1, 2, 3]) + ddp._update_process_group(group_size_3) + if self.rank in [1, 2, 3]: + run_iteration() + + # Back to default size. + ddp._update_process_group(_get_default_group()) + run_iteration() + else: + # Create default pg of smaller size. + dist.destroy_process_group() + + if self.rank in [1, 2, 3]: + dist.init_process_group( + init_method=self.init_method, + backend=BACKEND, + world_size=3, + rank=self.rank - 1, + timeout=timedelta(seconds=default_pg_timeout), + ) + ddp._update_process_group(_get_default_group()) + run_iteration() + dist.destroy_process_group() + + # Need a barrier here to ensure ranks 1, 2 and 3 are done. + self._barrier(wait_for=4) + + # Need to init pg again for "_barrier" to succeed. + dist.init_process_group( + init_method=self.init_method, + backend=BACKEND, + world_size=4, + rank=self.rank, + timeout=timedelta(seconds=default_pg_timeout), + ) + + # Validate no more recompiles. + assert 0 == get_num_torch_recompiles() + + @skip_if_lt_x_gpu(4) + @require_world_size(4) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_update_process_group_new_group(self): + self._run_ddp_update_process_group(new_pg=True) + + @skip_if_lt_x_gpu(4) + @require_world_size(4) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_update_process_group_default_group(self): + self._run_ddp_update_process_group(new_pg=False) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_broadcast_buffer(self): + rank = self.rank + torch.cuda.set_device(rank) + torch.manual_seed(rank) + torch.cuda.manual_seed(rank) + + class NetWithBuffers(nn.Module): + def __init__(self): + super().__init__() + self.a = nn.Linear(10, 10, bias=False) + self.b = nn.Linear(10, 1, bias=False) + self.register_buffer("buffer", torch.randn(1, 2)) + + def forward(self, x): + return self.b(self.a(x)) + + model = NetWithBuffers().cuda(rank) + model_ddp = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[self.rank], + ) + inp = torch.randn(2, 10, device=rank) + for i in range(2): + if rank == 0: + model_ddp.module.buffer = model_ddp.module.buffer + 1 + loss = model_ddp(inp).sum() + loss.backward() + # Ensure all buffers are synchronized. + bufs = [ + torch.empty_like(model_ddp.module.buffer) + for _ in range(dist.get_world_size()) + ] + dist.all_gather(bufs, model_ddp.module.buffer) + rank_0_buf = bufs[0] + for buf in bufs[1:]: + self.assertEqual(rank_0_buf, buf) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl" and BACKEND != "gloo", + "Only Nccl & Gloo backend support DistributedDataParallel", + ) + def test_static_graph_multi_forward(self): + class Net(nn.Module): + def __init__(self): + super().__init__() + self.lin = nn.Linear(10, 10) + self.relu = nn.ReLU() + + def forward(self, x): + return self.relu(self.lin(x)) + + torch.cuda.set_device(self.rank) + torch.manual_seed(42 << 1337 % (self.rank + 1)) + model = Net().cuda(self.rank) + local_model = copy.deepcopy(model) + model = torch.nn.parallel.DistributedDataParallel( + model, device_ids=[self.rank], static_graph=True + ) + inp = torch.ones(2, 10, device="cuda") + for _ in range(3): + model.zero_grad() + local_model.zero_grad() + a = model(inp) + b = model(inp) + loss = a.sum() + b.sum() + loss.backward() + # Grads should be equal to a local model that ran through inp twice and averaged grads + if self.rank == 0: + inp_clone = inp.clone() + for _ in range(2): + a = local_model(inp_clone) + b = local_model(inp_clone) + loss = a.sum() + b.sum() + loss.backward() + + ws = dist.get_world_size() + for p in local_model.parameters(): + p.grad.data = p.grad / dist.get_world_size() + + for p_ddp, p_local in zip( + model.parameters(), + local_model.parameters() + ): + self.assertTrue( + torch.allclose( + p_ddp.grad, p_local.grad + ), + f"{p_ddp.grad} vs {p_local.grad}" + ) + + dist.barrier() + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND != "nccl" and BACKEND != "gloo", + "Only Nccl & Gloo backend support DistributedDataParallel", + ) + def test_sync_bn_logged(self): + model = BN_NET + rank = self.rank + # single gpu training setup + model_gpu = model.cuda(rank) + no_sync_bn = torch.nn.parallel.DistributedDataParallel( + copy.deepcopy(model_gpu), + device_ids=[self.rank], + ) + ddp_logging_data = no_sync_bn._get_ddp_logging_data() + sync_bn_logged = ddp_logging_data.get("has_sync_bn", True) + self.assertFalse(sync_bn_logged) + model_DDP = nn.SyncBatchNorm.convert_sync_batchnorm(model_gpu) + model_DDP = torch.nn.parallel.DistributedDataParallel( + model_DDP, + device_ids=[self.rank], + ) + ddp_logging_data = model_DDP._get_ddp_logging_data() + sync_bn_logged = ddp_logging_data.get("has_sync_bn", False) + self.assertTrue(sync_bn_logged) + + @skip_if_lt_x_gpu(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_stateless_api_with_ddp(self): + class MockModule(torch.nn.Module): + def __init__(self): + super().__init__() + self.l1 = torch.nn.Linear(1, 1) + buffer = torch.ones(1) + self.register_buffer("buffer", buffer) + + def forward(self, x): + return self.l1(x) + self.buffer + + device = self.rank + module = MockModule().to(device) + module = torch.nn.parallel.DistributedDataParallel( + module, device_ids=[device] + ) + x = torch.rand((1, 1)).to(device) + weight = torch.tensor([[1.0]], device=device, requires_grad=True) + bias = torch.tensor([0.0], device=device, requires_grad=True) + buffer = torch.tensor([0.0], device=device) + parameters = { + "module.l1.weight": weight, + "module.l1.bias": bias, + "module.buffer": buffer, + } + prev_weight = module.module.l1.weight.clone() + prev_buffer = module.module.buffer.clone() + + res = torch.func.functional_call(module, parameters, x) + self.assertEqual(x, res) + # check that the weight remain unmodified + cur_weight = module.module.l1.weight + cur_buffer = module.module.buffer + self.assertEqual(cur_weight, prev_weight) + self.assertEqual(cur_buffer, prev_buffer) + # run a backward pass and check the gradients + res.backward() + self.assertIsNotNone(weight.grad) + self.assertIsNotNone(bias.grad) + # Gradient was not calculated for the module stated and buffers + self.assertIsNone(buffer.grad) + self.assertIsNone(module.module.l1.weight.grad) + self.assertIsNone(module.module.l1.bias.grad) + self.assertIsNone(module.module.buffer.grad) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + def test_ddp_forward_backward_hook(self): + class DummyTestModel(nn.Module): + def __init__(self): + super().__init__() + torch.manual_seed(0) + self.fc = nn.Linear(2, 2) + + def forward(self, x): + return self.fc(x) + + def relu_hook(module, input): + return nn.functional.relu(input[0]) + + def gelu_hook(module, _input, output): + return nn.functional.gelu(output) + + def celu_hook(module, _input, output): + return (nn.functional.celu(output[0]),) + + local_model = DummyTestModel() + ddp_model = DummyTestModel() + local_model.fc.register_forward_pre_hook(relu_hook) + local_model.fc.register_forward_hook(gelu_hook) + ddp_model.fc.register_forward_pre_hook(relu_hook) + ddp_model.fc.register_forward_hook(gelu_hook) + local_model.fc.register_backward_hook(celu_hook) + ddp_model.fc.register_backward_hook(celu_hook) + ddp_model = DistributedDataParallel( + ddp_model.to(self.rank), device_ids=[self.rank] + ) + input_data = torch.rand(5, 2) + output_local = local_model(input_data) + output_ddp = ddp_model(input_data.to(self.rank)) + self.assertEqual(output_local, output_ddp) + output_local.sum().backward() + output_ddp.sum().backward() + ddp_grads = [p.grad for p in ddp_model.parameters()] + self.assertEqual(ddp_grads[0], local_model.fc.weight.grad) + self.assertEqual(ddp_grads[1], local_model.fc.bias.grad) + + def _test_hook_pickling(self, hook, hook_state): + torch.manual_seed(0) + learning_rate = 0.01 + chkpt_file = tempfile.gettempdir() + "/checkpoint.pt" + rank = self.rank + + input = torch.randn(7, 1, device=rank) + target = torch.randn(7, 5, device=rank) + net = torch.nn.Linear(1, 5).to(rank) + ddp_model = DistributedDataParallel(copy.deepcopy(net), device_ids=[rank]) + dummy_ddp_model = DistributedDataParallel( + copy.deepcopy(net), device_ids=[rank] + ) + optimizer = torch.optim.SGD(ddp_model.parameters(), lr=learning_rate) + ddp_model.register_comm_hook(hook_state, hook) + ddp_model.train() + + for _ in range(10): + optimizer.zero_grad() + out = ddp_model(input) + loss = F.mse_loss(out, target) + loss.backward() + optimizer.step() + + state = { + "state_dict": ddp_model.state_dict(), + "comm_hook": hook, + "comm_hook_state": hook_state, + } + + if rank == 0: + with self.assertLogs("torch.distributed") as captured: + torch.save(state, chkpt_file) + + # Check that the logger has only one entry + self.assertEqual(len(captured.records), 1) + # Check that the logger has an expected entry + self.assertEqual( + captured.records[0].getMessage(), + "NOTE: Process group is not serializable and excluded from a saved state.", + ) + + dist.barrier() + map_location = {"cuda:%d" % 0: "cuda:%d" % rank} + with self.assertLogs("torch.distributed") as captured: + checkpoint = torch.load(chkpt_file, map_location=map_location) + + # Check that the logger has only one entry + self.assertEqual(len(captured.records), 1) + # Check that the logger has an expected entry + self.assertEqual( + captured.records[0].getMessage(), + "NOTE: Process group will be set to a default group (i.e. the world size).\ + If a different group is desired, please set `self.process_group` after PowerSGD state is loaded.", + ) + + dummy_ddp_model.load_state_dict(checkpoint["state_dict"]) + dummy_hook = checkpoint["comm_hook"] + dummy_hook_state = checkpoint["comm_hook_state"] + dummy_optimizer = torch.optim.SGD( + dummy_ddp_model.parameters(), lr=learning_rate + ) + + # Check that loaded function is correct + self.assertEqual(dummy_hook.__qualname__, hook.__qualname__) + + # Check that all slots' keys were restored correctly + self.assertEqual(hook_state.__slots__, dummy_hook_state.__slots__) + + # Check that all slots' attributes are restored correctly + # Excluding ``process_group`` and ``rng``. + for entry in dummy_hook_state.__slots__: + if entry != "process_group" and entry != "rng": + self.assertEqual( + getattr(dummy_hook_state, entry), getattr(hook_state, entry) + ) + + # Check that ``process_group`` was set to default + self.assertEqual(dummy_hook_state.process_group, _get_default_group()) + + # Check that a random state was restored properly: + # ``np.random.RandomState.get_state`` returns a tuple with entries: + # ``bit_generator`` - str, + # ``state.key`` - ndarray dtype[uint32], + # ``state.pos`` - int, + # ``has_gauss`` - int, + # ``gauss`` - float + # (refer to https://github.com/numpy/numpy/blob/266aad7478bc7fbcc55eea7f942a0d373b838396/numpy/random/mtrand.pyi) + # To make sure random state was restored properly, all entries should equal the original + for entry1, entry2 in zip( + hook_state.rng.get_state(), dummy_hook_state.rng.get_state() + ): + np.testing.assert_array_equal(entry1, entry2) + + dummy_ddp_model.register_comm_hook(dummy_hook_state, dummy_hook) + dummy_ddp_model.train() + + for _ in range(10): + optimizer.zero_grad() + dummy_optimizer.zero_grad() + out_origin = ddp_model(input) + out_dummy = dummy_ddp_model(input) + loss_origin = F.mse_loss(out_origin, target) + loss_dummy = F.mse_loss(out_dummy, target) + loss_origin.backward() + loss_dummy.backward() + optimizer.step() + dummy_optimizer.step() + + # Check that gradients after 10 epochs are the same + for orig_param, dummy_param in zip( + ddp_model.parameters(), dummy_ddp_model.parameters() + ): + self.assertEqual(orig_param.grad, dummy_param.grad) + + dist.barrier() + if rank == 0: + os.remove(chkpt_file) + + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["cuda"], + f"The {BACKEND} backend does not support DDP communication hook on CUDA devices", + ) + @skip_if_lt_x_gpu(int(os.environ["WORLD_SIZE"])) + @skip_but_pass_in_sandcastle_if( + True, "Skipped due to flakiness" + ) + def test_ddp_hook_pickling_powerSGD(self): + + hook = powerSGD.powerSGD_hook + powersgd_state = powerSGD.PowerSGDState( + process_group=None, + matrix_approximation_rank=1, + start_powerSGD_iter=4, + ) + self._test_hook_pickling(hook, powersgd_state) + + @require_backend_is_available(DistTestCases.backend_feature["gpu"]) + @skip_if_lt_x_gpu(2) + def test_ddp_device_mesh_initialization(self): + """ + Test DDP with device_mesh initialization. + """ + world_size = int(os.environ["WORLD_SIZE"]) + + from torch.distributed.device_mesh import init_device_mesh + device_mesh = init_device_mesh("cuda", (world_size,)) + + pg = _get_default_group() + + torch.cuda.set_device(self.rank) + model = TwoLinLayerNet().cuda() + ddp_model = torch.nn.parallel.DistributedDataParallel(model, device_mesh=device_mesh) + self.assertEqual(ddp_model.device_mesh, device_mesh) + self.assertEqual(ddp_model.device_mesh.get_group(mesh_dim=0), pg) + + with self.assertRaisesRegex( + RuntimeError, "Cannot specify both process_group and device_mesh arguments." + ): + ddp_model = torch.nn.parallel.DistributedDataParallel( + model, process_group=pg, device_mesh=device_mesh + ) + + with self.assertRaisesRegex( + RuntimeError, "Only 1D device mesh is supported," + ): + device_mesh = init_device_mesh("cuda", (2, world_size // 2)) + ddp_model = torch.nn.parallel.DistributedDataParallel( + model, device_mesh=device_mesh + ) + + @skip_if_lt_x_gpu(2) + @require_world_size(2) + @skip_but_pass_in_sandcastle_if( + BACKEND not in DistTestCases.backend_feature["ddp"], + f"The {BACKEND} backend does not support DistributedDataParallel", + ) + def test_ddp_compile_static_graph(self): + "Tests that DDP works with torch compile when static_graph=True" + model = torch.nn.Linear(10, 10).cuda(self.rank) + model_clone = copy.deepcopy(model) + ddp = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[self.rank], + ) + ddp_static = torch.nn.parallel.DistributedDataParallel( + model_clone, + device_ids=[self.rank], + static_graph=True + ) + ddp = torch.compile(ddp) + ddp_static = torch.compile(ddp_static) + input = torch.rand(10, 10).cuda(self.rank) + # verify output and gradient parity + for _ in range(6): + out_ddp = ddp(input).sum() + out_ddp_static = ddp_static(input).sum() + self.assertEqual(out_ddp, out_ddp_static) + out_ddp.backward() + out_ddp_static.backward() + for p1, p2 in zip(ddp.parameters(), ddp_static.parameters()): + self.assertEqual(p1.grad, p2.grad) + + +instantiate_parametrized_tests(DistributedTest._DistTestBase) diff --git a/shared/package-files/73/73dc54ff01624b11eb726cd81313adbf685b830fffb6d8f6bf6df30bff4cebb8/att4410v1-w b/shared/package-files/73/73dc54ff01624b11eb726cd81313adbf685b830fffb6d8f6bf6df30bff4cebb8/att4410v1-w new file mode 100644 index 0000000000000000000000000000000000000000..96225b8ef915f6e68d3e5dae17cb826d57ba66dc Binary files /dev/null and b/shared/package-files/73/73dc54ff01624b11eb726cd81313adbf685b830fffb6d8f6bf6df30bff4cebb8/att4410v1-w differ diff --git a/shared/package-files/73/73dc54ff01624b11eb726cd81313adbf685b830fffb6d8f6bf6df30bff4cebb8/att5410v1-w b/shared/package-files/73/73dc54ff01624b11eb726cd81313adbf685b830fffb6d8f6bf6df30bff4cebb8/att5410v1-w new file mode 100644 index 0000000000000000000000000000000000000000..96225b8ef915f6e68d3e5dae17cb826d57ba66dc Binary files /dev/null and b/shared/package-files/73/73dc54ff01624b11eb726cd81313adbf685b830fffb6d8f6bf6df30bff4cebb8/att5410v1-w differ diff --git a/shared/package-files/73/73dc54ff01624b11eb726cd81313adbf685b830fffb6d8f6bf6df30bff4cebb8/tty5410v1-w b/shared/package-files/73/73dc54ff01624b11eb726cd81313adbf685b830fffb6d8f6bf6df30bff4cebb8/tty5410v1-w new file mode 100644 index 0000000000000000000000000000000000000000..96225b8ef915f6e68d3e5dae17cb826d57ba66dc Binary files /dev/null and b/shared/package-files/73/73dc54ff01624b11eb726cd81313adbf685b830fffb6d8f6bf6df30bff4cebb8/tty5410v1-w differ diff --git a/shared/package-files/73/73df9ab167b832374c38761f35f916867f10c2a47c7162150d128271865dca39/slice_scatter_native.h b/shared/package-files/73/73df9ab167b832374c38761f35f916867f10c2a47c7162150d128271865dca39/slice_scatter_native.h new file mode 100644 index 0000000000000000000000000000000000000000..7778b6394ef8ceb9e7d4b92ddc572ea32030f8eb --- /dev/null +++ b/shared/package-files/73/73df9ab167b832374c38761f35f916867f10c2a47c7162150d128271865dca39/slice_scatter_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & slice_scatter_out_symint(const at::Tensor & self, const at::Tensor & src, int64_t dim, c10::optional start, c10::optional end, c10::SymInt step, at::Tensor & out); +TORCH_API at::Tensor slice_scatter(const at::Tensor & self, const at::Tensor & src, int64_t dim=0, c10::optional start=c10::nullopt, c10::optional end=c10::nullopt, int64_t step=1); +} // namespace native +} // namespace at diff --git a/shared/package-files/73/73e2155b5e1ba6a6f7aaeedbcf411a6ef3572676702405c45e842821cacbf27b/inset.pyi b/shared/package-files/73/73e2155b5e1ba6a6f7aaeedbcf411a6ef3572676702405c45e842821cacbf27b/inset.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e895fd7be27c40ad07167aeca73fc7380b4d0d23 --- /dev/null +++ b/shared/package-files/73/73e2155b5e1ba6a6f7aaeedbcf411a6ef3572676702405c45e842821cacbf27b/inset.pyi @@ -0,0 +1,25 @@ +from . import artist +from .axes import Axes +from .backend_bases import RendererBase +from .patches import ConnectionPatch, Rectangle + +from .typing import ColorType, LineStyleType + +class InsetIndicator(artist.Artist): + def __init__( + self, + bounds: tuple[float, float, float, float] | None = ..., + inset_ax: Axes | None = ..., + zorder: float | None = ..., + **kwargs + ) -> None: ... + def set_alpha(self, alpha: float | None) -> None: ... + def set_edgecolor(self, color: ColorType | None) -> None: ... + def set_color(self, c: ColorType | None) -> None: ... + def set_linewidth(self, w: float | None) -> None: ... + def set_linestyle(self, ls: LineStyleType | None) -> None: ... + @property + def rectangle(self) -> Rectangle: ... + @property + def connectors(self) -> tuple[ConnectionPatch, ConnectionPatch, ConnectionPatch, ConnectionPatch] | None: ... + def draw(self, renderer: RendererBase) -> None: ... diff --git a/shared/package-files/73/73e5f40eec532a25c152b675c6b376bf113d102d2145f1b6692ded8378a46722/validation.pyi b/shared/package-files/73/73e5f40eec532a25c152b675c6b376bf113d102d2145f1b6692ded8378a46722/validation.pyi new file mode 100644 index 0000000000000000000000000000000000000000..382f4c1adab69fb3d3196275d87d96f4ac36a273 --- /dev/null +++ b/shared/package-files/73/73e5f40eec532a25c152b675c6b376bf113d102d2145f1b6692ded8378a46722/validation.pyi @@ -0,0 +1,11 @@ +from typing import Any, List + +from django.db.backends.base.base import BaseDatabaseWrapper + +from django.db.models.fields import Field + +class BaseDatabaseValidation: + connection: Any = ... + def __init__(self, connection: BaseDatabaseWrapper) -> None: ... + def check(self, **kwargs: Any) -> List[Any]: ... + def check_field(self, field: Field, **kwargs: Any) -> List[Any]: ... diff --git a/shared/package-files/73/73e94f712ef82fff0aa07ec813a3d0179a1fca2ad140d57856191b48520f7963/top_level.txt b/shared/package-files/73/73e94f712ef82fff0aa07ec813a3d0179a1fca2ad140d57856191b48520f7963/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..dc1c9e101ad9ccd943b359338ef42c342ebc84a1 --- /dev/null +++ b/shared/package-files/73/73e94f712ef82fff0aa07ec813a3d0179a1fca2ad140d57856191b48520f7963/top_level.txt @@ -0,0 +1 @@ +pycparser diff --git a/shared/package-files/73/73e9d1608d0a1a4b8b0d2591838d432d134fe9fce3476bd5711b695949d1a9c2/_foreach_copy_native.h b/shared/package-files/73/73e9d1608d0a1a4b8b0d2591838d432d134fe9fce3476bd5711b695949d1a9c2/_foreach_copy_native.h new file mode 100644 index 0000000000000000000000000000000000000000..1977274b1218721597cb2bac2aa52c7876381384 --- /dev/null +++ b/shared/package-files/73/73e9d1608d0a1a4b8b0d2591838d432d134fe9fce3476bd5711b695949d1a9c2/_foreach_copy_native.h @@ -0,0 +1,24 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::vector _foreach_copy(at::TensorList self, at::TensorList src, bool non_blocking=false); +TORCH_API void _foreach_copy_out(at::TensorList self, at::TensorList src, bool non_blocking, at::TensorList out); +TORCH_API void foreach_tensor_copy_list_kernel_slow_(at::TensorList self, at::TensorList src, bool non_blocking=false); +TORCH_API void foreach_tensor_copy_list_kernel_cuda_(at::TensorList self, at::TensorList src, bool non_blocking=false); +} // namespace native +} // namespace at diff --git a/shared/package-files/73/73f2b76ddba22343ff9449e825435466adaa176f92bdfa3bd31bde2a0f72f5f7/Coyhaique b/shared/package-files/73/73f2b76ddba22343ff9449e825435466adaa176f92bdfa3bd31bde2a0f72f5f7/Coyhaique new file mode 100644 index 0000000000000000000000000000000000000000..26354e89460e7c9e585d62ab477cd69a5559b554 Binary files /dev/null and b/shared/package-files/73/73f2b76ddba22343ff9449e825435466adaa176f92bdfa3bd31bde2a0f72f5f7/Coyhaique differ diff --git a/shared/package-files/73/73f3c8e1bbb435001d0c886c171fe37c79085ea6416af988aee21b3a923d6886/resize_cpu_dispatch.h b/shared/package-files/73/73f3c8e1bbb435001d0c886c171fe37c79085ea6416af988aee21b3a923d6886/resize_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..8fa7d4ff0c973b2df21f6e2da3ae7eb306573bca --- /dev/null +++ b/shared/package-files/73/73f3c8e1bbb435001d0c886c171fe37c79085ea6416af988aee21b3a923d6886/resize_cpu_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API const at::Tensor & resize_(const at::Tensor & self, at::IntArrayRef size, c10::optional memory_format=c10::nullopt); +TORCH_API const at::Tensor & resize__symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::optional memory_format=c10::nullopt); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/73/73f3d7bf2385438602450276dec9d636474486e67893425b2dee79cda7a85df4/_type1font.py b/shared/package-files/73/73f3d7bf2385438602450276dec9d636474486e67893425b2dee79cda7a85df4/_type1font.py new file mode 100644 index 0000000000000000000000000000000000000000..b3e08f52c035e65837e489bf79da60d28e3ac0a8 --- /dev/null +++ b/shared/package-files/73/73f3d7bf2385438602450276dec9d636474486e67893425b2dee79cda7a85df4/_type1font.py @@ -0,0 +1,879 @@ +""" +A class representing a Type 1 font. + +This version reads pfa and pfb files and splits them for embedding in +pdf files. It also supports SlantFont and ExtendFont transformations, +similarly to pdfTeX and friends. There is no support yet for subsetting. + +Usage:: + + font = Type1Font(filename) + clear_part, encrypted_part, finale = font.parts + slanted_font = font.transform({'slant': 0.167}) + extended_font = font.transform({'extend': 1.2}) + +Sources: + +* Adobe Technical Note #5040, Supporting Downloadable PostScript + Language Fonts. + +* Adobe Type 1 Font Format, Adobe Systems Incorporated, third printing, + v1.1, 1993. ISBN 0-201-57044-0. +""" + +from __future__ import annotations + +import binascii +import functools +import logging +import re +import string +import struct +import typing as T + +import numpy as np + +from matplotlib.cbook import _format_approx +from . import _api + +_log = logging.getLogger(__name__) + + +class _Token: + """ + A token in a PostScript stream. + + Attributes + ---------- + pos : int + Position, i.e. offset from the beginning of the data. + raw : str + Raw text of the token. + kind : str + Description of the token (for debugging or testing). + """ + __slots__ = ('pos', 'raw') + kind = '?' + + def __init__(self, pos, raw): + _log.debug('type1font._Token %s at %d: %r', self.kind, pos, raw) + self.pos = pos + self.raw = raw + + def __str__(self): + return f"<{self.kind} {self.raw} @{self.pos}>" + + def endpos(self): + """Position one past the end of the token""" + return self.pos + len(self.raw) + + def is_keyword(self, *names): + """Is this a name token with one of the names?""" + return False + + def is_slash_name(self): + """Is this a name token that starts with a slash?""" + return False + + def is_delim(self): + """Is this a delimiter token?""" + return False + + def is_number(self): + """Is this a number token?""" + return False + + def value(self): + return self.raw + + +class _NameToken(_Token): + kind = 'name' + + def is_slash_name(self): + return self.raw.startswith('/') + + def value(self): + return self.raw[1:] + + +class _BooleanToken(_Token): + kind = 'boolean' + + def value(self): + return self.raw == 'true' + + +class _KeywordToken(_Token): + kind = 'keyword' + + def is_keyword(self, *names): + return self.raw in names + + +class _DelimiterToken(_Token): + kind = 'delimiter' + + def is_delim(self): + return True + + def opposite(self): + return {'[': ']', ']': '[', + '{': '}', '}': '{', + '<<': '>>', '>>': '<<' + }[self.raw] + + +class _WhitespaceToken(_Token): + kind = 'whitespace' + + +class _StringToken(_Token): + kind = 'string' + _escapes_re = re.compile(r'\\([\\()nrtbf]|[0-7]{1,3})') + _replacements = {'\\': '\\', '(': '(', ')': ')', 'n': '\n', + 'r': '\r', 't': '\t', 'b': '\b', 'f': '\f'} + _ws_re = re.compile('[\0\t\r\f\n ]') + + @classmethod + def _escape(cls, match): + group = match.group(1) + try: + return cls._replacements[group] + except KeyError: + return chr(int(group, 8)) + + @functools.lru_cache + def value(self): + if self.raw[0] == '(': + return self._escapes_re.sub(self._escape, self.raw[1:-1]) + else: + data = self._ws_re.sub('', self.raw[1:-1]) + if len(data) % 2 == 1: + data += '0' + return binascii.unhexlify(data) + + +class _BinaryToken(_Token): + kind = 'binary' + + def value(self): + return self.raw[1:] + + +class _NumberToken(_Token): + kind = 'number' + + def is_number(self): + return True + + def value(self): + if '.' not in self.raw: + return int(self.raw) + else: + return float(self.raw) + + +def _tokenize(data: bytes, skip_ws: bool) -> T.Generator[_Token, int, None]: + """ + A generator that produces _Token instances from Type-1 font code. + + The consumer of the generator may send an integer to the tokenizer to + indicate that the next token should be _BinaryToken of the given length. + + Parameters + ---------- + data : bytes + The data of the font to tokenize. + + skip_ws : bool + If true, the generator will drop any _WhitespaceTokens from the output. + """ + + text = data.decode('ascii', 'replace') + whitespace_or_comment_re = re.compile(r'[\0\t\r\f\n ]+|%[^\r\n]*') + token_re = re.compile(r'/{0,2}[^]\0\t\r\f\n ()<>{}/%[]+') + instring_re = re.compile(r'[()\\]') + hex_re = re.compile(r'^<[0-9a-fA-F\0\t\r\f\n ]*>$') + oct_re = re.compile(r'[0-7]{1,3}') + pos = 0 + next_binary: int | None = None + + while pos < len(text): + if next_binary is not None: + n = next_binary + next_binary = (yield _BinaryToken(pos, data[pos:pos+n])) + pos += n + continue + match = whitespace_or_comment_re.match(text, pos) + if match: + if not skip_ws: + next_binary = (yield _WhitespaceToken(pos, match.group())) + pos = match.end() + elif text[pos] == '(': + # PostScript string rules: + # - parentheses must be balanced + # - backslashes escape backslashes and parens + # - also codes \n\r\t\b\f and octal escapes are recognized + # - other backslashes do not escape anything + start = pos + pos += 1 + depth = 1 + while depth: + match = instring_re.search(text, pos) + if match is None: + raise ValueError( + f'Unterminated string starting at {start}') + pos = match.end() + if match.group() == '(': + depth += 1 + elif match.group() == ')': + depth -= 1 + else: # a backslash + char = text[pos] + if char in r'\()nrtbf': + pos += 1 + else: + octal = oct_re.match(text, pos) + if octal: + pos = octal.end() + else: + pass # non-escaping backslash + next_binary = (yield _StringToken(start, text[start:pos])) + elif text[pos:pos + 2] in ('<<', '>>'): + next_binary = (yield _DelimiterToken(pos, text[pos:pos + 2])) + pos += 2 + elif text[pos] == '<': + start = pos + try: + pos = text.index('>', pos) + 1 + except ValueError as e: + raise ValueError(f'Unterminated hex string starting at {start}' + ) from e + if not hex_re.match(text[start:pos]): + raise ValueError(f'Malformed hex string starting at {start}') + next_binary = (yield _StringToken(pos, text[start:pos])) + else: + match = token_re.match(text, pos) + if match: + raw = match.group() + if raw.startswith('/'): + next_binary = (yield _NameToken(pos, raw)) + elif match.group() in ('true', 'false'): + next_binary = (yield _BooleanToken(pos, raw)) + else: + try: + float(raw) + next_binary = (yield _NumberToken(pos, raw)) + except ValueError: + next_binary = (yield _KeywordToken(pos, raw)) + pos = match.end() + else: + next_binary = (yield _DelimiterToken(pos, text[pos])) + pos += 1 + + +class _BalancedExpression(_Token): + pass + + +def _expression(initial, tokens, data): + """ + Consume some number of tokens and return a balanced PostScript expression. + + Parameters + ---------- + initial : _Token + The token that triggered parsing a balanced expression. + tokens : iterator of _Token + Following tokens. + data : bytes + Underlying data that the token positions point to. + + Returns + ------- + _BalancedExpression + """ + delim_stack = [] + token = initial + while True: + if token.is_delim(): + if token.raw in ('[', '{'): + delim_stack.append(token) + elif token.raw in (']', '}'): + if not delim_stack: + raise RuntimeError(f"unmatched closing token {token}") + match = delim_stack.pop() + if match.raw != token.opposite(): + raise RuntimeError( + f"opening token {match} closed by {token}" + ) + if not delim_stack: + break + else: + raise RuntimeError(f'unknown delimiter {token}') + elif not delim_stack: + break + token = next(tokens) + return _BalancedExpression( + initial.pos, + data[initial.pos:token.endpos()].decode('ascii', 'replace') + ) + + +class Type1Font: + """ + A class representing a Type-1 font, for use by backends. + + Attributes + ---------- + parts : tuple + A 3-tuple of the cleartext part, the encrypted part, and the finale of + zeros. + + decrypted : bytes + The decrypted form of ``parts[1]``. + + prop : dict[str, Any] + A dictionary of font properties. Noteworthy keys include: + + - FontName: PostScript name of the font + - Encoding: dict from numeric codes to glyph names + - FontMatrix: bytes object encoding a matrix + - UniqueID: optional font identifier, dropped when modifying the font + - CharStrings: dict from glyph names to byte code + - Subrs: array of byte code subroutines + - OtherSubrs: bytes object encoding some PostScript code + """ + __slots__ = ('parts', 'decrypted', 'prop', '_pos', '_abbr') + # the _pos dict contains (begin, end) indices to parts[0] + decrypted + # so that they can be replaced when transforming the font; + # but since sometimes a definition appears in both parts[0] and decrypted, + # _pos[name] is an array of such pairs + # + # _abbr maps three standard abbreviations to their particular names in + # this font (e.g. 'RD' is named '-|' in some fonts) + + def __init__(self, input): + """ + Initialize a Type-1 font. + + Parameters + ---------- + input : str or 3-tuple + Either a pfb file name, or a 3-tuple of already-decoded Type-1 + font `~.Type1Font.parts`. + """ + if isinstance(input, tuple) and len(input) == 3: + self.parts = input + else: + with open(input, 'rb') as file: + data = self._read(file) + self.parts = self._split(data) + + self.decrypted = self._decrypt(self.parts[1], 'eexec') + self._abbr = {'RD': 'RD', 'ND': 'ND', 'NP': 'NP'} + self._parse() + + def _read(self, file): + """Read the font from a file, decoding into usable parts.""" + rawdata = file.read() + if not rawdata.startswith(b'\x80'): + return rawdata + + data = b'' + while rawdata: + if not rawdata.startswith(b'\x80'): + raise RuntimeError('Broken pfb file (expected byte 128, ' + 'got %d)' % rawdata[0]) + type = rawdata[1] + if type in (1, 2): + length, = struct.unpack('> 8)) + key = ((key+byte) * 52845 + 22719) & 0xffff + + return bytes(plaintext[ndiscard:]) + + @staticmethod + def _encrypt(plaintext, key, ndiscard=4): + """ + Encrypt plaintext using the Type-1 font algorithm. + + The algorithm is described in Adobe's "Adobe Type 1 Font Format". + The key argument can be an integer, or one of the strings + 'eexec' and 'charstring', which map to the key specified for the + corresponding part of Type-1 fonts. + + The ndiscard argument should be an integer, usually 4. That + number of bytes is prepended to the plaintext before encryption. + This function prepends NUL bytes for reproducibility, even though + the original algorithm uses random bytes, presumably to avoid + cryptanalysis. + """ + + key = _api.check_getitem({'eexec': 55665, 'charstring': 4330}, key=key) + ciphertext = [] + for byte in b'\0' * ndiscard + plaintext: + c = byte ^ (key >> 8) + ciphertext.append(c) + key = ((key + c) * 52845 + 22719) & 0xffff + + return bytes(ciphertext) + + def _parse(self): + """ + Find the values of various font properties. This limited kind + of parsing is described in Chapter 10 "Adobe Type Manager + Compatibility" of the Type-1 spec. + """ + # Start with reasonable defaults + prop = {'Weight': 'Regular', 'ItalicAngle': 0.0, 'isFixedPitch': False, + 'UnderlinePosition': -100, 'UnderlineThickness': 50} + pos = {} + data = self.parts[0] + self.decrypted + + source = _tokenize(data, True) + while True: + # See if there is a key to be assigned a value + # e.g. /FontName in /FontName /Helvetica def + try: + token = next(source) + except StopIteration: + break + if token.is_delim(): + # skip over this - we want top-level keys only + _expression(token, source, data) + if token.is_slash_name(): + key = token.value() + keypos = token.pos + else: + continue + + # Some values need special parsing + if key in ('Subrs', 'CharStrings', 'Encoding', 'OtherSubrs'): + prop[key], endpos = { + 'Subrs': self._parse_subrs, + 'CharStrings': self._parse_charstrings, + 'Encoding': self._parse_encoding, + 'OtherSubrs': self._parse_othersubrs + }[key](source, data) + pos.setdefault(key, []).append((keypos, endpos)) + continue + + try: + token = next(source) + except StopIteration: + break + + if isinstance(token, _KeywordToken): + # constructs like + # FontDirectory /Helvetica known {...} {...} ifelse + # mean the key was not really a key + continue + + if token.is_delim(): + value = _expression(token, source, data).raw + else: + value = token.value() + + # look for a 'def' possibly preceded by access modifiers + try: + kw = next( + kw for kw in source + if not kw.is_keyword('readonly', 'noaccess', 'executeonly') + ) + except StopIteration: + break + + # sometimes noaccess def and readonly def are abbreviated + if kw.is_keyword('def', self._abbr['ND'], self._abbr['NP']): + prop[key] = value + pos.setdefault(key, []).append((keypos, kw.endpos())) + + # detect the standard abbreviations + if value == '{noaccess def}': + self._abbr['ND'] = key + elif value == '{noaccess put}': + self._abbr['NP'] = key + elif value == '{string currentfile exch readstring pop}': + self._abbr['RD'] = key + + # Fill in the various *Name properties + if 'FontName' not in prop: + prop['FontName'] = (prop.get('FullName') or + prop.get('FamilyName') or + 'Unknown') + if 'FullName' not in prop: + prop['FullName'] = prop['FontName'] + if 'FamilyName' not in prop: + extras = ('(?i)([ -](regular|plain|italic|oblique|(semi)?bold|' + '(ultra)?light|extra|condensed))+$') + prop['FamilyName'] = re.sub(extras, '', prop['FullName']) + # Decrypt the encrypted parts + ndiscard = prop.get('lenIV', 4) + cs = prop['CharStrings'] + for key, value in cs.items(): + cs[key] = self._decrypt(value, 'charstring', ndiscard) + if 'Subrs' in prop: + prop['Subrs'] = [ + self._decrypt(value, 'charstring', ndiscard) + for value in prop['Subrs'] + ] + + self.prop = prop + self._pos = pos + + def _parse_subrs(self, tokens, _data): + count_token = next(tokens) + if not count_token.is_number(): + raise RuntimeError( + f"Token following /Subrs must be a number, was {count_token}" + ) + count = count_token.value() + array = [None] * count + next(t for t in tokens if t.is_keyword('array')) + for _ in range(count): + next(t for t in tokens if t.is_keyword('dup')) + index_token = next(tokens) + if not index_token.is_number(): + raise RuntimeError( + "Token following dup in Subrs definition must be a " + f"number, was {index_token}" + ) + nbytes_token = next(tokens) + if not nbytes_token.is_number(): + raise RuntimeError( + "Second token following dup in Subrs definition must " + f"be a number, was {nbytes_token}" + ) + token = next(tokens) + if not token.is_keyword(self._abbr['RD']): + raise RuntimeError( + f"Token preceding subr must be {self._abbr['RD']}, " + f"was {token}" + ) + binary_token = tokens.send(1+nbytes_token.value()) + array[index_token.value()] = binary_token.value() + + return array, next(tokens).endpos() + + @staticmethod + def _parse_charstrings(tokens, _data): + count_token = next(tokens) + if not count_token.is_number(): + raise RuntimeError( + "Token following /CharStrings must be a number, " + f"was {count_token}" + ) + count = count_token.value() + charstrings = {} + next(t for t in tokens if t.is_keyword('begin')) + while True: + token = next(t for t in tokens + if t.is_keyword('end') or t.is_slash_name()) + if token.raw == 'end': + return charstrings, token.endpos() + glyphname = token.value() + nbytes_token = next(tokens) + if not nbytes_token.is_number(): + raise RuntimeError( + f"Token following /{glyphname} in CharStrings definition " + f"must be a number, was {nbytes_token}" + ) + next(tokens) # usually RD or |- + binary_token = tokens.send(1+nbytes_token.value()) + charstrings[glyphname] = binary_token.value() + + @staticmethod + def _parse_encoding(tokens, _data): + # this only works for encodings that follow the Adobe manual + # but some old fonts include non-compliant data - we log a warning + # and return a possibly incomplete encoding + encoding = {} + while True: + token = next(t for t in tokens + if t.is_keyword('StandardEncoding', 'dup', 'def')) + if token.is_keyword('StandardEncoding'): + return _StandardEncoding, token.endpos() + if token.is_keyword('def'): + return encoding, token.endpos() + index_token = next(tokens) + if not index_token.is_number(): + _log.warning( + f"Parsing encoding: expected number, got {index_token}" + ) + continue + name_token = next(tokens) + if not name_token.is_slash_name(): + _log.warning( + f"Parsing encoding: expected slash-name, got {name_token}" + ) + continue + encoding[index_token.value()] = name_token.value() + + @staticmethod + def _parse_othersubrs(tokens, data): + init_pos = None + while True: + token = next(tokens) + if init_pos is None: + init_pos = token.pos + if token.is_delim(): + _expression(token, tokens, data) + elif token.is_keyword('def', 'ND', '|-'): + return data[init_pos:token.endpos()], token.endpos() + + def transform(self, effects): + """ + Return a new font that is slanted and/or extended. + + Parameters + ---------- + effects : dict + A dict with optional entries: + + - 'slant' : float, default: 0 + Tangent of the angle that the font is to be slanted to the + right. Negative values slant to the left. + - 'extend' : float, default: 1 + Scaling factor for the font width. Values less than 1 condense + the glyphs. + + Returns + ------- + `Type1Font` + """ + fontname = self.prop['FontName'] + italicangle = self.prop['ItalicAngle'] + + array = [ + float(x) for x in (self.prop['FontMatrix'] + .lstrip('[').rstrip(']').split()) + ] + oldmatrix = np.eye(3, 3) + oldmatrix[0:3, 0] = array[::2] + oldmatrix[0:3, 1] = array[1::2] + modifier = np.eye(3, 3) + + if 'slant' in effects: + slant = effects['slant'] + fontname += f'_Slant_{int(1000 * slant)}' + italicangle = round( + float(italicangle) - np.arctan(slant) / np.pi * 180, + 5 + ) + modifier[1, 0] = slant + + if 'extend' in effects: + extend = effects['extend'] + fontname += f'_Extend_{int(1000 * extend)}' + modifier[0, 0] = extend + + newmatrix = np.dot(modifier, oldmatrix) + array[::2] = newmatrix[0:3, 0] + array[1::2] = newmatrix[0:3, 1] + fontmatrix = ( + f"[{' '.join(_format_approx(x, 6) for x in array)}]" + ) + replacements = ( + [(x, f'/FontName/{fontname} def') + for x in self._pos['FontName']] + + [(x, f'/ItalicAngle {italicangle} def') + for x in self._pos['ItalicAngle']] + + [(x, f'/FontMatrix {fontmatrix} readonly def') + for x in self._pos['FontMatrix']] + + [(x, '') for x in self._pos.get('UniqueID', [])] + ) + + data = bytearray(self.parts[0]) + data.extend(self.decrypted) + len0 = len(self.parts[0]) + for (pos0, pos1), value in sorted(replacements, reverse=True): + data[pos0:pos1] = value.encode('ascii', 'replace') + if pos0 < len(self.parts[0]): + if pos1 >= len(self.parts[0]): + raise RuntimeError( + f"text to be replaced with {value} spans " + "the eexec boundary" + ) + len0 += len(value) - pos1 + pos0 + + data = bytes(data) + return Type1Font(( + data[:len0], + self._encrypt(data[len0:], 'eexec'), + self.parts[2] + )) + + +_StandardEncoding = { + **{ord(letter): letter for letter in string.ascii_letters}, + 0: '.notdef', + 32: 'space', + 33: 'exclam', + 34: 'quotedbl', + 35: 'numbersign', + 36: 'dollar', + 37: 'percent', + 38: 'ampersand', + 39: 'quoteright', + 40: 'parenleft', + 41: 'parenright', + 42: 'asterisk', + 43: 'plus', + 44: 'comma', + 45: 'hyphen', + 46: 'period', + 47: 'slash', + 48: 'zero', + 49: 'one', + 50: 'two', + 51: 'three', + 52: 'four', + 53: 'five', + 54: 'six', + 55: 'seven', + 56: 'eight', + 57: 'nine', + 58: 'colon', + 59: 'semicolon', + 60: 'less', + 61: 'equal', + 62: 'greater', + 63: 'question', + 64: 'at', + 91: 'bracketleft', + 92: 'backslash', + 93: 'bracketright', + 94: 'asciicircum', + 95: 'underscore', + 96: 'quoteleft', + 123: 'braceleft', + 124: 'bar', + 125: 'braceright', + 126: 'asciitilde', + 161: 'exclamdown', + 162: 'cent', + 163: 'sterling', + 164: 'fraction', + 165: 'yen', + 166: 'florin', + 167: 'section', + 168: 'currency', + 169: 'quotesingle', + 170: 'quotedblleft', + 171: 'guillemotleft', + 172: 'guilsinglleft', + 173: 'guilsinglright', + 174: 'fi', + 175: 'fl', + 177: 'endash', + 178: 'dagger', + 179: 'daggerdbl', + 180: 'periodcentered', + 182: 'paragraph', + 183: 'bullet', + 184: 'quotesinglbase', + 185: 'quotedblbase', + 186: 'quotedblright', + 187: 'guillemotright', + 188: 'ellipsis', + 189: 'perthousand', + 191: 'questiondown', + 193: 'grave', + 194: 'acute', + 195: 'circumflex', + 196: 'tilde', + 197: 'macron', + 198: 'breve', + 199: 'dotaccent', + 200: 'dieresis', + 202: 'ring', + 203: 'cedilla', + 205: 'hungarumlaut', + 206: 'ogonek', + 207: 'caron', + 208: 'emdash', + 225: 'AE', + 227: 'ordfeminine', + 232: 'Lslash', + 233: 'Oslash', + 234: 'OE', + 235: 'ordmasculine', + 241: 'ae', + 245: 'dotlessi', + 248: 'lslash', + 249: 'oslash', + 250: 'oe', + 251: 'germandbls', +} diff --git a/shared/package-files/73/73fd2b5e14309d8c036d334f137b9edf1f7b32dbd45491cf93184818582d0671/symbol.enc b/shared/package-files/73/73fd2b5e14309d8c036d334f137b9edf1f7b32dbd45491cf93184818582d0671/symbol.enc new file mode 100644 index 0000000000000000000000000000000000000000..ffda9e3ee606693f3cbf84b10e418ad4fef2cd05 --- /dev/null +++ b/shared/package-files/73/73fd2b5e14309d8c036d334f137b9edf1f7b32dbd45491cf93184818582d0671/symbol.enc @@ -0,0 +1,20 @@ +# Encoding file: symbol, single-byte +S +003F 1 1 +00 +0000000100020003000400050006000700080009000A000B000C000D000E000F +0010001100120013001400150016001700180019001A001B001C001D001E001F +0020002122000023220300250026220D002800292217002B002C2212002E002F +0030003100320033003400350036003700380039003A003B003C003D003E003F +22450391039203A70394039503A603930397039903D1039A039B039C039D039F +03A0039803A103A303A403A503C203A9039E03A80396005B2234005D22A5005F +F8E503B103B203C703B403B503C603B303B703B903D503BA03BB03BC03BD03BF +03C003B803C103C303C403C503D603C903BE03C803B6007B007C007D223C007F +0080008100820083008400850086008700880089008A008B008C008D008E008F +0090009100920093009400950096009700980099009A009B009C009D009E009F +000003D2203222642044221E0192266326662665266021942190219121922193 +00B000B12033226500D7221D2202202200F72260226122482026F8E6F8E721B5 +21352111211C21182297229522052229222A2283228722842282228622082209 +2220220700AE00A92122220F221A22C500AC2227222821D421D021D121D221D3 +22C42329F8E8F8E9F8EA2211F8EBF8ECF8EDF8EEF8EFF8F0F8F1F8F2F8F3F8F4 +F8FF232A222B2320F8F52321F8F6F8F7F8F8F8F9F8FAF8FBF8FCF8FDF8FE0000 diff --git a/shared/package-files/73/73ffc66e09d16b0c20a96badf20e50f76f1e9fcfbf3b7a136444156ea43c32b1/test_find_common_type.py b/shared/package-files/73/73ffc66e09d16b0c20a96badf20e50f76f1e9fcfbf3b7a136444156ea43c32b1/test_find_common_type.py new file mode 100644 index 0000000000000000000000000000000000000000..83ef7382fbe8a27ad96511a3675c51b9eadc2331 --- /dev/null +++ b/shared/package-files/73/73ffc66e09d16b0c20a96badf20e50f76f1e9fcfbf3b7a136444156ea43c32b1/test_find_common_type.py @@ -0,0 +1,175 @@ +import numpy as np +import pytest + +from pandas.core.dtypes.cast import find_common_type +from pandas.core.dtypes.common import pandas_dtype +from pandas.core.dtypes.dtypes import ( + CategoricalDtype, + DatetimeTZDtype, + IntervalDtype, + PeriodDtype, +) + +from pandas import ( + Categorical, + Index, +) + + +@pytest.mark.parametrize( + "source_dtypes,expected_common_dtype", + [ + ((np.int64,), np.int64), + ((np.uint64,), np.uint64), + ((np.float32,), np.float32), + ((object,), object), + # Into ints. + ((np.int16, np.int64), np.int64), + ((np.int32, np.uint32), np.int64), + ((np.uint16, np.uint64), np.uint64), + # Into floats. + ((np.float16, np.float32), np.float32), + ((np.float16, np.int16), np.float32), + ((np.float32, np.int16), np.float32), + ((np.uint64, np.int64), np.float64), + ((np.int16, np.float64), np.float64), + ((np.float16, np.int64), np.float64), + # Into others. + ((np.complex128, np.int32), np.complex128), + ((object, np.float32), object), + ((object, np.int16), object), + # Bool with int. + ((np.dtype("bool"), np.int64), object), + ((np.dtype("bool"), np.int32), object), + ((np.dtype("bool"), np.int16), object), + ((np.dtype("bool"), np.int8), object), + ((np.dtype("bool"), np.uint64), object), + ((np.dtype("bool"), np.uint32), object), + ((np.dtype("bool"), np.uint16), object), + ((np.dtype("bool"), np.uint8), object), + # Bool with float. + ((np.dtype("bool"), np.float64), object), + ((np.dtype("bool"), np.float32), object), + ( + (np.dtype("datetime64[ns]"), np.dtype("datetime64[ns]")), + np.dtype("datetime64[ns]"), + ), + ( + (np.dtype("timedelta64[ns]"), np.dtype("timedelta64[ns]")), + np.dtype("timedelta64[ns]"), + ), + ( + (np.dtype("datetime64[ns]"), np.dtype("datetime64[ms]")), + np.dtype("datetime64[ns]"), + ), + ( + (np.dtype("timedelta64[ms]"), np.dtype("timedelta64[ns]")), + np.dtype("timedelta64[ns]"), + ), + ((np.dtype("datetime64[ns]"), np.dtype("timedelta64[ns]")), object), + ((np.dtype("datetime64[ns]"), np.int64), object), + ], +) +def test_numpy_dtypes(source_dtypes, expected_common_dtype): + source_dtypes = [pandas_dtype(x) for x in source_dtypes] + assert find_common_type(source_dtypes) == expected_common_dtype + + +def test_raises_empty_input(): + with pytest.raises(ValueError, match="no types given"): + find_common_type([]) + + +@pytest.mark.parametrize( + "dtypes,exp_type", + [ + ([CategoricalDtype()], "category"), + ([object, CategoricalDtype()], object), + ([CategoricalDtype(), CategoricalDtype()], "category"), + ], +) +def test_categorical_dtype(dtypes, exp_type): + assert find_common_type(dtypes) == exp_type + + +def test_datetimetz_dtype_match(): + dtype = DatetimeTZDtype(unit="ns", tz="US/Eastern") + assert find_common_type([dtype, dtype]) == "datetime64[ns, US/Eastern]" + + +@pytest.mark.parametrize( + "dtype2", + [ + DatetimeTZDtype(unit="ns", tz="Asia/Tokyo"), + np.dtype("datetime64[ns]"), + object, + np.int64, + ], +) +def test_datetimetz_dtype_mismatch(dtype2): + dtype = DatetimeTZDtype(unit="ns", tz="US/Eastern") + assert find_common_type([dtype, dtype2]) == object + assert find_common_type([dtype2, dtype]) == object + + +def test_period_dtype_match(): + dtype = PeriodDtype(freq="D") + assert find_common_type([dtype, dtype]) == "period[D]" + + +@pytest.mark.parametrize( + "dtype2", + [ + DatetimeTZDtype(unit="ns", tz="Asia/Tokyo"), + PeriodDtype(freq="2D"), + PeriodDtype(freq="h"), + np.dtype("datetime64[ns]"), + object, + np.int64, + ], +) +def test_period_dtype_mismatch(dtype2): + dtype = PeriodDtype(freq="D") + assert find_common_type([dtype, dtype2]) == object + assert find_common_type([dtype2, dtype]) == object + + +interval_dtypes = [ + IntervalDtype(np.int64, "right"), + IntervalDtype(np.float64, "right"), + IntervalDtype(np.uint64, "right"), + IntervalDtype(DatetimeTZDtype(unit="ns", tz="US/Eastern"), "right"), + IntervalDtype("M8[ns]", "right"), + IntervalDtype("m8[ns]", "right"), +] + + +@pytest.mark.parametrize("left", interval_dtypes) +@pytest.mark.parametrize("right", interval_dtypes) +def test_interval_dtype(left, right): + result = find_common_type([left, right]) + + if left is right: + assert result is left + + elif left.subtype.kind in ["i", "u", "f"]: + # i.e. numeric + if right.subtype.kind in ["i", "u", "f"]: + # both numeric -> common numeric subtype + expected = IntervalDtype(np.float64, "right") + assert result == expected + else: + assert result == object + + else: + assert result == object + + +@pytest.mark.parametrize("dtype", interval_dtypes) +def test_interval_dtype_with_categorical(dtype): + obj = Index([], dtype=dtype) + + cat = Categorical([], categories=obj) + + result = find_common_type([dtype, cat.dtype]) + assert result == dtype diff --git a/shared/package-files/cc/cc077f5c47562e26c3253cd75f1d2e02016aae46caec23d83d825e5f04e7d2e7/expr.py b/shared/package-files/cc/cc077f5c47562e26c3253cd75f1d2e02016aae46caec23d83d825e5f04e7d2e7/expr.py new file mode 100644 index 0000000000000000000000000000000000000000..46a60fd8740afd4fb98997aff373b031a5addbce --- /dev/null +++ b/shared/package-files/cc/cc077f5c47562e26c3253cd75f1d2e02016aae46caec23d83d825e5f04e7d2e7/expr.py @@ -0,0 +1,736 @@ +from __future__ import annotations + +import warnings +from typing import TYPE_CHECKING, Any, cast + +import pandas as pd + +from narwhals._compliant import DepthTrackingExpr, LazyExpr +from narwhals._dask.expr_dt import DaskExprDateTimeNamespace +from narwhals._dask.expr_list import DaskExprListNamespace +from narwhals._dask.expr_str import DaskExprStringNamespace +from narwhals._dask.utils import ( + add_row_index, + align_series_full_broadcast, + make_group_by_kwargs, + narwhals_to_native_dtype, +) +from narwhals._expression_parsing import evaluate_nodes, evaluate_output_names_and_aliases +from narwhals._pandas_like.expr import window_kwargs_to_pandas_equivalent +from narwhals._pandas_like.utils import get_dtype_backend, native_to_narwhals_dtype +from narwhals._utils import ( + NO_DEFAULT, + Implementation, + generate_temporary_column_name, + length_changing_hint, + not_implemented, +) +from narwhals.exceptions import InvalidOperationError + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + import dask.dataframe.dask_expr as dx + from typing_extensions import Self + + from narwhals._compliant.typing import ( + AliasNames, + EvalNames, + EvalSeries, + NarwhalsAggregation, + ) + from narwhals._dask.dataframe import DaskLazyFrame + from narwhals._dask.namespace import DaskNamespace + from narwhals._typing import NoDefault + from narwhals._utils import Version, _LimitedContext + from narwhals.typing import ( + FillNullStrategy, + IntoDType, + ModeKeepStrategy, + RollingInterpolationMethod, + ) + + +def simple_aggregation(attr: str) -> Any: + # Translate an aggregation which differs from Dask in name only. + return lambda self, **kwargs: self._with_callable( + lambda expr: getattr(expr, attr)(**kwargs).to_series() + ) + + +def simple_method(attr: str) -> Any: + # Translate a method which differs from Dask in name only. + return lambda self, **kwargs: self._with_callable( + lambda expr: getattr(expr, attr)(**kwargs) + ) + + +def simple_binary(attr: str) -> Any: + # Translate a binary method which differs from Dask in name only. + return lambda self, other: self._binary_op(attr, other) + + +def trivial_binary_right(op: Callable[..., dx.Series]) -> Any: + # Translate a (right) binary method which differs from Dask in name only. + return lambda self, other: self._reverse_binary_op(op, other) + + +class DaskExpr( + LazyExpr["DaskLazyFrame", "dx.Series"], # pyright: ignore[reportInvalidTypeArguments] + DepthTrackingExpr["DaskLazyFrame", "dx.Series"], # pyright: ignore[reportInvalidTypeArguments] +): + _implementation: Implementation = Implementation.DASK + + # Methods which are simple Narwhals->Dask translations. + # Keep this simple, resist the temptation to do anything complex or clever. + __add__ = simple_binary("__add__") + __sub__ = simple_binary("__sub__") + __mul__ = simple_binary("__mul__") + __truediv__ = simple_binary("__truediv__") + __pow__ = simple_binary("__pow__") + __mod__ = simple_binary("__mod__") + __eq__ = simple_binary("__eq__") + __ne__ = simple_binary("__ne__") + __gt__ = simple_binary("__gt__") + __ge__ = simple_binary("__ge__") + __lt__ = simple_binary("__lt__") + __le__ = simple_binary("__le__") + __and__ = simple_binary("__and__") + __or__ = simple_binary("__or__") + __rsub__ = trivial_binary_right(lambda x, y: x - y) + __rtruediv__ = trivial_binary_right(lambda x, y: x / y) + __rpow__ = trivial_binary_right(lambda x, y: x**y) + __rmod__ = trivial_binary_right(lambda x, y: x % y) + all = simple_aggregation("all") + any = simple_aggregation("any") + count = simple_aggregation("count") + kurtosis = simple_aggregation("kurtosis") + max = simple_aggregation("max") + mean = simple_aggregation("mean") + min = simple_aggregation("min") + skew = simple_aggregation("skew") + std = simple_aggregation("std") + sum = simple_aggregation("sum") + var = simple_aggregation("var") + __invert__ = simple_method("__invert__") + __neg__ = simple_method("__neg__") + abs = simple_method("abs") + diff = simple_method("diff") + drop_nulls = simple_method("dropna") + is_null = simple_method("isna") + round = simple_method("round") + unique = simple_method("unique") + + def __init__( + self, + call: EvalSeries[DaskLazyFrame, dx.Series], # pyright: ignore[reportInvalidTypeForm] + *, + evaluate_output_names: EvalNames[DaskLazyFrame], + alias_output_names: AliasNames | None, + version: Version, + ) -> None: + self._call = call + self._evaluate_output_names = evaluate_output_names + self._alias_output_names = alias_output_names + self._version = version + + def __call__(self, df: DaskLazyFrame) -> Sequence[dx.Series]: + return self._call(df) + + def __narwhals_namespace__(self) -> DaskNamespace: # pragma: no cover + from narwhals._dask.namespace import DaskNamespace + + return DaskNamespace(version=self._version) + + def broadcast(self) -> Self: + def func(df: DaskLazyFrame) -> list[dx.Series]: + # result.loc[0][0] is a workaround for dask~<=2024.10.0/dask_expr~<=1.1.16 + # that raised a KeyError for result[0] during collection. + return [result.loc[0][0] for result in self(df)] + + return self.__class__( + func, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=self._alias_output_names, + version=self._version, + ) + + @classmethod + def from_column_names( + cls: type[Self], + evaluate_column_names: EvalNames[DaskLazyFrame], + /, + *, + context: _LimitedContext, + ) -> Self: + def func(df: DaskLazyFrame) -> list[dx.Series]: + try: + return [ + df._native_frame[column_name] + for column_name in evaluate_column_names(df) + ] + except KeyError as e: + if error := df._check_columns_exist(evaluate_column_names(df)): + raise error from e + raise + + return cls( + func, + evaluate_output_names=evaluate_column_names, + alias_output_names=None, + version=context._version, + ) + + @classmethod + def from_column_indices(cls, *column_indices: int, context: _LimitedContext) -> Self: + def func(df: DaskLazyFrame) -> list[dx.Series]: + return [df.native.iloc[:, i] for i in column_indices] + + return cls( + func, + evaluate_output_names=cls._eval_names_indices(column_indices), + alias_output_names=None, + version=context._version, + ) + + def _with_callable( + self, + # First argument to `call` should be `dx.Series` + call: Callable[..., dx.Series], + /, + expression_args: dict[str, Self] | None = None, + ) -> Self: + def func(df: DaskLazyFrame) -> list[dx.Series]: + native_results: list[dx.Series] = [] + native_series_list = self._call(df) + other_native_series = { + key: df._evaluate_single_output_expr(value) + for key, value in (expression_args or {}).items() + } + for native_series in native_series_list: + result_native = call(native_series, **other_native_series) + native_results.append(result_native) + return native_results + + return self.__class__( + func, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=self._alias_output_names, + version=self._version, + ) + + def _with_alias_output_names(self, func: AliasNames | None, /) -> Self: + current_alias_output_names = self._alias_output_names + alias_output_names = ( + None + if func is None + else func + if current_alias_output_names is None + else lambda output_names: func(current_alias_output_names(output_names)) + ) + return type(self)( + call=self._call, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=alias_output_names, + version=self._version, + ) + + def _with_binary( + self, call: Callable[[dx.Series, Any], dx.Series], other: Any + ) -> Self: + return self._with_callable(call, expression_args={"other": other}) + + def _binary_op(self, op_name: str, other: Any) -> Self: + return self._with_binary(lambda expr, other: getattr(expr, op_name)(other), other) + + def _reverse_binary_op( + self, operator_func: Callable[..., dx.Series], other: Any + ) -> Self: + return self._with_binary( + lambda expr, other: operator_func(other, expr), other + ).alias("literal") + + def __floordiv__(self, other: Any) -> Self: + def _floordiv( + df: DaskLazyFrame, series: dx.Series, other: dx.Series + ) -> dx.Series: + series, other = align_series_full_broadcast(df, series, other) + return (series.__floordiv__(other)).where(other != 0, None) + + def func(df: DaskLazyFrame) -> list[dx.Series]: + other_series = df._evaluate_single_output_expr(other) + return [_floordiv(df, series, other_series) for series in self(df)] + + return self.__class__( + func, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=self._alias_output_names, + version=self._version, + ) + + def __rfloordiv__(self, other: Any) -> Self: + def _rfloordiv( + df: DaskLazyFrame, series: dx.Series, other: dx.Series + ) -> dx.Series: + series, other = align_series_full_broadcast(df, series, other) + return (other.__floordiv__(series)).where(series != 0, None) + + def func(df: DaskLazyFrame) -> list[dx.Series]: + other_native = df._evaluate_single_output_expr(other) + return [_rfloordiv(df, series, other_native) for series in self(df)] + + return self.__class__( + func, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=self._alias_output_names, + version=self._version, + ).alias("literal") + + def median(self) -> Self: + from narwhals.exceptions import InvalidOperationError + + def func(s: dx.Series) -> dx.Series: + dtype = native_to_narwhals_dtype(s.dtype, self._version, Implementation.DASK) + if not dtype.is_numeric(): + msg = "`median` operation not supported for non-numeric input type." + raise InvalidOperationError(msg) + return s.median_approximate().to_series() + + return self._with_callable(func) + + def shift(self, n: int) -> Self: + return self._with_callable(lambda expr: expr.shift(n)) + + def cum_sum(self, *, reverse: bool) -> Self: + if reverse: # pragma: no cover + # https://github.com/dask/dask/issues/11802 + msg = "`cum_sum(reverse=True)` is not supported with Dask backend" + raise NotImplementedError(msg) + + return self._with_callable(lambda expr: expr.cumsum()) + + def cum_count(self, *, reverse: bool) -> Self: + if reverse: # pragma: no cover + msg = "`cum_count(reverse=True)` is not supported with Dask backend" + raise NotImplementedError(msg) + + return self._with_callable(lambda expr: (~expr.isna()).astype(int).cumsum()) + + def cum_min(self, *, reverse: bool) -> Self: + if reverse: # pragma: no cover + msg = "`cum_min(reverse=True)` is not supported with Dask backend" + raise NotImplementedError(msg) + + return self._with_callable(lambda expr: expr.cummin()) + + def cum_max(self, *, reverse: bool) -> Self: + if reverse: # pragma: no cover + msg = "`cum_max(reverse=True)` is not supported with Dask backend" + raise NotImplementedError(msg) + + return self._with_callable(lambda expr: expr.cummax()) + + def cum_prod(self, *, reverse: bool) -> Self: + if reverse: # pragma: no cover + msg = "`cum_prod(reverse=True)` is not supported with Dask backend" + raise NotImplementedError(msg) + + return self._with_callable(lambda expr: expr.cumprod()) + + def rolling_sum(self, window_size: int, *, min_samples: int, center: bool) -> Self: + return self._with_callable( + lambda expr: expr.rolling( + window=window_size, min_periods=min_samples, center=center + ).sum() + ) + + def rolling_mean(self, window_size: int, *, min_samples: int, center: bool) -> Self: + return self._with_callable( + lambda expr: expr.rolling( + window=window_size, min_periods=min_samples, center=center + ).mean() + ) + + def rolling_var( + self, window_size: int, *, min_samples: int, center: bool, ddof: int + ) -> Self: + if ddof == 1: + return self._with_callable( + lambda expr: expr.rolling( + window=window_size, min_periods=min_samples, center=center + ).var() + ) + msg = "Dask backend only supports `ddof=1` for `rolling_var`" + raise NotImplementedError(msg) + + def rolling_std( + self, window_size: int, *, min_samples: int, center: bool, ddof: int + ) -> Self: + if ddof == 1: + return self._with_callable( + lambda expr: expr.rolling( + window=window_size, min_periods=min_samples, center=center + ).std() + ) + msg = "Dask backend only supports `ddof=1` for `rolling_std`" + raise NotImplementedError(msg) + + def floor(self) -> Self: + import dask.array as da + + return self._with_callable(da.floor) + + def ceil(self) -> Self: + import dask.array as da + + return self._with_callable(da.ceil) + + def fill_nan(self, value: float | None) -> Self: + value_nullable = pd.NA if value is None else value + value_numpy = float("nan") if value is None else value + + def func(expr: dx.Series) -> dx.Series: + # If/when pandas exposes an API which distinguishes NaN vs null, use that. + mask = cast("dx.Series", expr != expr) # noqa: PLR0124 + mask = mask.fillna(False) + fill = ( + value_nullable + if get_dtype_backend(expr.dtype, self._implementation) + else value_numpy + ) + return expr.mask(mask, fill) # pyright: ignore[reportArgumentType] + + return self._with_callable(func) + + def fill_null( + self, value: Self | None, strategy: FillNullStrategy | None, limit: int | None + ) -> Self: + if value is None: + return self._with_callable( + lambda expr: ( + expr.ffill(limit=limit) + if strategy == "forward" + else expr.bfill(limit=limit) + ) + ) + + def func(df: DaskLazyFrame) -> list[dx.Series]: + fill_value = df._evaluate_single_output_expr(value) + aligned = (align_series_full_broadcast(df, s, fill_value) for s in self(df)) + return [series.fillna(fill) for series, fill in aligned] + + return self.__class__( + func, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=self._alias_output_names, + version=self._version, + ) + + def clip(self, lower_bound: Self, upper_bound: Self) -> Self: + return self._with_callable( + lambda expr, lower_bound, upper_bound: expr.clip( + lower=lower_bound, upper=upper_bound + ), + expression_args={"lower_bound": lower_bound, "upper_bound": upper_bound}, + ) + + def clip_lower(self, lower_bound: Self) -> Self: + return self._with_callable( + lambda expr, lower_bound: expr.clip(lower=lower_bound), + expression_args={"lower_bound": lower_bound}, + ) + + def clip_upper(self, upper_bound: Self) -> Self: + return self._with_callable( + lambda expr, upper_bound: expr.clip(upper=upper_bound), + expression_args={"upper_bound": upper_bound}, + ) + + def n_unique(self) -> Self: + return self._with_callable(lambda expr: expr.nunique(dropna=False).to_series()) + + def is_nan(self) -> Self: + def func(expr: dx.Series) -> dx.Series: + dtype = native_to_narwhals_dtype( + expr.dtype, self._version, self._implementation + ) + if dtype.is_numeric(): + return expr != expr # pyright: ignore[reportReturnType] # noqa: PLR0124 + msg = f"`.is_nan` only supported for numeric dtypes and not {dtype}, did you mean `.is_null`?" + raise InvalidOperationError(msg) + + return self._with_callable(func) + + def len(self) -> Self: + return self._with_callable(lambda expr: expr.size.to_series()) + + def quantile( + self, quantile: float, interpolation: RollingInterpolationMethod + ) -> Self: + if interpolation == "linear": + + def func(expr: dx.Series) -> dx.Series: + if expr.npartitions > 1: + msg = "`Expr.quantile` is not supported for Dask backend with multiple partitions." + raise NotImplementedError(msg) + return expr.quantile( + q=quantile, method="dask" + ).to_series() # pragma: no cover + + return self._with_callable(func) + msg = "`higher`, `lower`, `midpoint`, `nearest` - interpolation methods are not supported by Dask. Please use `linear` instead." + raise NotImplementedError(msg) + + def is_first_distinct(self) -> Self: + def func(expr: dx.Series) -> dx.Series: + _name = expr.name + col_token = generate_temporary_column_name( + n_bytes=8, columns=[_name], prefix="row_index_" + ) + frame = add_row_index(expr.to_frame(), col_token) + group_by_kwargs = make_group_by_kwargs(drop_null_keys=False) + agged = cast( + "dx.DataFrame", + frame.groupby(_name, **group_by_kwargs).agg({col_token: "min"}), + ) + first_distinct_index = agged[col_token] + return frame[col_token].isin(first_distinct_index) + + return self._with_callable(func) + + def is_last_distinct(self) -> Self: + def func(expr: dx.Series) -> dx.Series: + _name = expr.name + col_token = generate_temporary_column_name( + n_bytes=8, columns=[_name], prefix="row_index_" + ) + frame = add_row_index(expr.to_frame(), col_token) + group_by_kwargs = make_group_by_kwargs(drop_null_keys=False) + agged = cast( + "dx.DataFrame", + frame.groupby(_name, **group_by_kwargs).agg({col_token: "max"}), + ) + last_distinct_index = agged[col_token] + return frame[col_token].isin(last_distinct_index) + + return self._with_callable(func) + + def is_unique(self) -> Self: + def func(expr: dx.Series) -> dx.Series: + _name = expr.name + group_by_kwargs = make_group_by_kwargs(drop_null_keys=False) + return ( + expr.to_frame() + .groupby(_name, **group_by_kwargs) + .transform("size", meta=(_name, int)) + == 1 + ) + + return self._with_callable(func) + + def is_in(self, other: Any) -> Self: + return self._with_callable(lambda expr: expr.isin(other)) + + def null_count(self) -> Self: + return self._with_callable(lambda expr: expr.isna().sum().to_series()) + + def _over_without_partition_by(self, order_by: Sequence[str]) -> Self: + # This is something like `nw.col('a').cum_sum().order_by(key)` + # which we can always easily support, as it doesn't require grouping. + def func(df: DaskLazyFrame) -> Sequence[dx.Series]: + return self(df.sort(*order_by, descending=False, nulls_last=False)) + + return self.__class__( + func, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=self._alias_output_names, + version=self._version, + ) + + def over(self, partition_by: Sequence[str], order_by: Sequence[str]) -> Self: + if not partition_by: + assert order_by # noqa: S101 + return self._over_without_partition_by(order_by) + # pandas is a required dependency of dask so it's safe to import this + from narwhals._pandas_like.group_by import PandasLikeGroupBy + + # We have something like prev.leaf().over(...) (e.g. `nw.col('a').sum().over('b')`), where: + # - `prev` must be elementwise (in the example: `nw.col('a')`) + # - `leaf` must be a "simple" function, i.e. one that pandas supports in `transform` + # (in the example: `sum`) + # + # We first evaluate `prev` as-is, and then evaluate `leaf().over(...)`` by using `transform` + # or other DataFrameGroupBy methods. + meta = self._metadata + if partition_by and ( + meta.prev is not None and not meta.prev.is_elementwise + ): # pragma: no cover + msg = ( + "Only elementary expressions are supported for `.over` in dask backend " + "when `partition_by` is specified.\n\n" + "Please see: " + "https://narwhals-dev.github.io/narwhals/concepts/improve_group_by_operation/" + ) + raise NotImplementedError(msg) + + if order_by: + # Wrong results https://github.com/dask/dask/issues/11806. + msg = "`over` with `order_by` is not yet supported in Dask." + raise NotImplementedError(msg) + + nodes = list(reversed(list(self._metadata.iter_nodes_reversed()))) + leaf_node = nodes[-1] + function_name = cast("NarwhalsAggregation", leaf_node.name) + try: + dask_function_name = PandasLikeGroupBy._REMAP_AGGS[function_name] + except KeyError: + # window functions are unsupported: https://github.com/dask/dask/issues/11806 + msg = ( + f"Unsupported function: {function_name} in `over` context.\n\n" + f"Supported functions are {', '.join(PandasLikeGroupBy._REMAP_AGGS)}\n" + ) + raise NotImplementedError(msg) from None + dask_kwargs = window_kwargs_to_pandas_equivalent(function_name, leaf_node.kwargs) + + def func(df: DaskLazyFrame) -> Sequence[dx.Series]: + plx = self.__narwhals_namespace__() + if meta.prev is not None: + df = df.with_columns(cast("DaskExpr", evaluate_nodes(nodes[:-1], plx))) + _, aliases = evaluate_output_names_and_aliases(self, df, []) + + with warnings.catch_warnings(): + # https://github.com/dask/dask/issues/11804 + warnings.filterwarnings( + "ignore", message=".*`meta` is not specified", category=UserWarning + ) + group_by_kwargs = make_group_by_kwargs(drop_null_keys=False) + grouped = df.native.groupby(partition_by, **group_by_kwargs) + if dask_function_name == "size": + if len(aliases) != 1: # pragma: no cover + msg = "Safety check failed, please report a bug." + raise AssertionError(msg) + res_native = grouped.transform( + dask_function_name, **dask_kwargs + ).to_frame(aliases[0]) + else: + res_native = grouped[list(aliases)].transform( + dask_function_name, **dask_kwargs + ) + result_frame = df._with_native(res_native).native + return [result_frame[name] for name in aliases] + + return self.__class__( + func, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=self._alias_output_names, + version=self._version, + ) + + def cast(self, dtype: IntoDType) -> Self: + def func(expr: dx.Series) -> dx.Series: + native_dtype = narwhals_to_native_dtype(dtype, self._version) + return expr.astype(native_dtype) + + return self._with_callable(func) + + def is_finite(self) -> Self: + import dask.array as da + + return self._with_callable(da.isfinite) + + def log(self, base: float) -> Self: + import dask.array as da + + def _log(expr: dx.Series) -> dx.Series: + return da.log(expr) / da.log(base) + + return self._with_callable(_log) + + def exp(self) -> Self: + import dask.array as da + + return self._with_callable(da.exp) + + def sin(self) -> Self: + import dask.array as da + + return self._with_callable(da.sin) + + def cos(self) -> Self: + import dask.array as da + + return self._with_callable(da.cos) + + def sqrt(self) -> Self: + import dask.array as da + + return self._with_callable(da.sqrt) + + def mode(self, *, keep: ModeKeepStrategy) -> Self: + def func(expr: dx.Series) -> dx.Series: + _name = expr.name + result = expr.to_frame().mode()[_name] + return result.head(1) if keep == "any" else result + + return self._with_callable(func) + + def replace_strict( + self, + default: DaskExpr | NoDefault, + old: Sequence[Any], + new: Sequence[Any], + *, + return_dtype: IntoDType | None, + ) -> Self: + if default is NO_DEFAULT: + msg = "`replace_strict` requires an explicit value for `default` for dask backend." + raise ValueError(msg) + + mapping = dict(zip(old, new, strict=False)) + old_ = list(old) + + def func(df: DaskLazyFrame) -> list[dx.Series]: + default_series = df._evaluate_single_output_expr(default) + results = [ + series.replace(mapping).where(series.isin(old_), default_series) + for series in self(df) + ] + + if return_dtype: + native_dtype = narwhals_to_native_dtype(return_dtype, self._version) + return [res.astype(native_dtype) for res in results] + + return results + + return self.__class__( + func, + evaluate_output_names=self._evaluate_output_names, + alias_output_names=self._alias_output_names, + version=self._version, + ) + + @property + def str(self) -> DaskExprStringNamespace: + return DaskExprStringNamespace(self) + + @property + def dt(self) -> DaskExprDateTimeNamespace: + return DaskExprDateTimeNamespace(self) + + @property + def list(self) -> DaskExprListNamespace: + return DaskExprListNamespace(self) + + any_value = not_implemented() + filter = not_implemented( + hint=length_changing_hint( + instead_of="lf.select(nw.col('a').filter(nw.col('b') > 0))", + use="lf.filter(nw.col('b') > 0).select('a')", + ) + ) + first = not_implemented() + rank = not_implemented() + last = not_implemented() + + # namespaces + struct: Any = not_implemented() diff --git a/shared/package-files/cc/cc0c5ec411f87e798534ee1bbc41dbba0d4d2560b9cea7c56950e56228e8c246/test_ode.py b/shared/package-files/cc/cc0c5ec411f87e798534ee1bbc41dbba0d4d2560b9cea7c56950e56228e8c246/test_ode.py new file mode 100644 index 0000000000000000000000000000000000000000..6b6dbffa79cfd4ca6dbf14f8591296ee48b16682 --- /dev/null +++ b/shared/package-files/cc/cc0c5ec411f87e798534ee1bbc41dbba0d4d2560b9cea7c56950e56228e8c246/test_ode.py @@ -0,0 +1,73 @@ +#from mpmath.calculus import ODE_step_euler, ODE_step_rk4, odeint, arange +from mpmath import odefun, cos, sin, mpf, sinc, mp + +''' +solvers = [ODE_step_euler, ODE_step_rk4] + +def test_ode1(): + """ + Let's solve: + + x'' + w**2 * x = 0 + + i.e. x1 = x, x2 = x1': + + x1' = x2 + x2' = -x1 + """ + def derivs((x1, x2), t): + return x2, -x1 + + for solver in solvers: + t = arange(0, 3.1415926, 0.005) + sol = odeint(derivs, (0., 1.), t, solver) + x1 = [a[0] for a in sol] + x2 = [a[1] for a in sol] + # the result is x1 = sin(t), x2 = cos(t) + # let's just check the end points for t = pi + assert abs(x1[-1]) < 1e-2 + assert abs(x2[-1] - (-1)) < 1e-2 + +def test_ode2(): + """ + Let's solve: + + x' - x = 0 + + i.e. x = exp(x) + + """ + def derivs((x), t): + return x + + for solver in solvers: + t = arange(0, 1, 1e-3) + sol = odeint(derivs, (1.,), t, solver) + x = [a[0] for a in sol] + # the result is x = exp(t) + # let's just check the end point for t = 1, i.e. x = e + assert abs(x[-1] - 2.718281828) < 1e-2 +''' + +def test_odefun_rational(): + mp.dps = 15 + # A rational function + f = lambda t: 1/(1+mpf(t)**2) + g = odefun(lambda x, y: [-2*x*y[0]**2], 0, [f(0)]) + assert f(2).ae(g(2)[0]) + +def test_odefun_sinc_large(): + mp.dps = 15 + # Sinc function; test for large x + f = sinc + g = odefun(lambda x, y: [(cos(x)-y[0])/x], 1, [f(1)], tol=0.01, degree=5) + assert abs(f(100) - g(100)[0])/f(100) < 0.01 + +def test_odefun_harmonic(): + mp.dps = 15 + # Harmonic oscillator + f = odefun(lambda x, y: [-y[1], y[0]], 0, [1, 0]) + for x in [0, 1, 2.5, 8, 3.7]: # we go back to 3.7 to check caching + c, s = f(x) + assert c.ae(cos(x)) + assert s.ae(sin(x)) diff --git a/shared/package-files/cc/cc128e3b7f190e81b1f0ecbb2e8969979a50509c08e7a19b8d4bf509e7f4a691/view_cpu_dispatch.h b/shared/package-files/cc/cc128e3b7f190e81b1f0ecbb2e8969979a50509c08e7a19b8d4bf509e7f4a691/view_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..91fec458ab91b112c78fd1fd6cb18955c469d394 --- /dev/null +++ b/shared/package-files/cc/cc128e3b7f190e81b1f0ecbb2e8969979a50509c08e7a19b8d4bf509e7f4a691/view_cpu_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor view(const at::Tensor & self, at::IntArrayRef size); +TORCH_API at::Tensor view_symint(const at::Tensor & self, c10::SymIntArrayRef size); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/cc/cc1299e1de147e7d038015822018d24008528f79e3aaa537b73bb8fd229a7e3d/miopen_rnn_ops.h b/shared/package-files/cc/cc1299e1de147e7d038015822018d24008528f79e3aaa537b73bb8fd229a7e3d/miopen_rnn_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..9e84e0da22a0334484763724815c4b74531c9f90 --- /dev/null +++ b/shared/package-files/cc/cc1299e1de147e7d038015822018d24008528f79e3aaa537b73bb8fd229a7e3d/miopen_rnn_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API miopen_rnn { + using schema = ::std::tuple (const at::Tensor &, at::TensorList, int64_t, const at::Tensor &, const c10::optional &, int64_t, int64_t, int64_t, bool, double, bool, bool, at::IntArrayRef, const c10::optional &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::miopen_rnn") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "miopen_rnn(Tensor input, Tensor[] weight, int weight_stride0, Tensor hx, Tensor? cx, int mode, int hidden_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, int[] batch_sizes, Tensor? dropout_state) -> (Tensor, Tensor, Tensor, Tensor, Tensor)") + static ::std::tuple call(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const at::Tensor & hx, const c10::optional & cx, int64_t mode, int64_t hidden_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const c10::optional & dropout_state); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const at::Tensor & hx, const c10::optional & cx, int64_t mode, int64_t hidden_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const c10::optional & dropout_state); +}; + +struct TORCH_API miopen_rnn_out { + using schema = ::std::tuple (const at::Tensor &, at::TensorList, int64_t, const at::Tensor &, const c10::optional &, int64_t, int64_t, int64_t, bool, double, bool, bool, at::IntArrayRef, const c10::optional &, at::Tensor &, at::Tensor &, at::Tensor &, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::miopen_rnn") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "miopen_rnn.out(Tensor input, Tensor[] weight, int weight_stride0, Tensor hx, Tensor? cx, int mode, int hidden_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, int[] batch_sizes, Tensor? dropout_state, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3, Tensor(e!) out4) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!), Tensor(e!))") + static ::std::tuple call(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const at::Tensor & hx, const c10::optional & cx, int64_t mode, int64_t hidden_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const c10::optional & dropout_state, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const at::Tensor & hx, const c10::optional & cx, int64_t mode, int64_t hidden_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const c10::optional & dropout_state, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/cc/cc13359a564946bd0bee741af648bacab8c1ee7b57c07e53844399be5aebd5b1/bdist.py b/shared/package-files/cc/cc13359a564946bd0bee741af648bacab8c1ee7b57c07e53844399be5aebd5b1/bdist.py new file mode 100644 index 0000000000000000000000000000000000000000..71ad9cfa091ca11161f340f5ad82ee2181efdf6c --- /dev/null +++ b/shared/package-files/cc/cc13359a564946bd0bee741af648bacab8c1ee7b57c07e53844399be5aebd5b1/bdist.py @@ -0,0 +1,39 @@ +import os +import zipfile + +from .distribution import Distribution + +class BDist(Distribution): + + def __init__(self, filename, metadata_version=None): + self.filename = filename + self.metadata_version = metadata_version + self.extractMetadata() + + def read(self): + fqn = os.path.abspath( + os.path.normpath(self.filename)) + if not os.path.exists(fqn): + raise ValueError('No such file: %s' % fqn) + + if fqn.endswith('.egg'): + archive = zipfile.ZipFile(fqn) + names = archive.namelist() + def read_file(name): + return archive.read(name) + else: + raise ValueError('Not a known archive format: %s' % fqn) + + try: + tuples = [x.split('/') for x in names if 'PKG-INFO' in x] + schwarz = sorted([(len(x), x) for x in tuples]) + for path in [x[1] for x in schwarz]: + candidate = '/'.join(path) + data = read_file(candidate) + if b'Metadata-Version' in data: + return data + finally: + archive.close() + + raise ValueError('No PKG-INFO in archive: %s' % fqn) + diff --git a/shared/package-files/cc/cc14fb06a44072173d5b0e8df06d744ac98d01ad52ba40d67a93a8dd4eb6f8e9/median_ops.h b/shared/package-files/cc/cc14fb06a44072173d5b0e8df06d744ac98d01ad52ba40d67a93a8dd4eb6f8e9/median_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..e9fe7c75da3605a27d8f51896e7b5938190124f3 --- /dev/null +++ b/shared/package-files/cc/cc14fb06a44072173d5b0e8df06d744ac98d01ad52ba40d67a93a8dd4eb6f8e9/median_ops.h @@ -0,0 +1,83 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API median { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::median") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "median(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API median_dim { + using schema = ::std::tuple (const at::Tensor &, int64_t, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::median") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dim") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "median.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)") + static ::std::tuple call(const at::Tensor & self, int64_t dim, bool keepdim); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, bool keepdim); +}; + +struct TORCH_API median_dim_values { + using schema = ::std::tuple (const at::Tensor &, int64_t, bool, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::median") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dim_values") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "median.dim_values(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)") + static ::std::tuple call(const at::Tensor & self, int64_t dim, bool keepdim, at::Tensor & values, at::Tensor & indices); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, bool keepdim, at::Tensor & values, at::Tensor & indices); +}; + +struct TORCH_API median_names_dim { + using schema = ::std::tuple (const at::Tensor &, at::Dimname, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::median") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "names_dim") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "median.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices)") + static ::std::tuple call(const at::Tensor & self, at::Dimname dim, bool keepdim); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Dimname dim, bool keepdim); +}; + +struct TORCH_API median_names_dim_values { + using schema = ::std::tuple (const at::Tensor &, at::Dimname, bool, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::median") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "names_dim_values") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "median.names_dim_values(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)") + static ::std::tuple call(const at::Tensor & self, at::Dimname dim, bool keepdim, at::Tensor & values, at::Tensor & indices); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Dimname dim, bool keepdim, at::Tensor & values, at::Tensor & indices); +}; + +struct TORCH_API median_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::median") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "median.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/cc/cc15efdff75bd971b116cdd7437e5bb4d7ff92ee7668b5d7887666997e22c40b/test_tree.py b/shared/package-files/cc/cc15efdff75bd971b116cdd7437e5bb4d7ff92ee7668b5d7887666997e22c40b/test_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..643a14d89b5211f2d97b98f2e227e68361781b97 --- /dev/null +++ b/shared/package-files/cc/cc15efdff75bd971b116cdd7437e5bb4d7ff92ee7668b5d7887666997e22c40b/test_tree.py @@ -0,0 +1,48 @@ +import json + +import pytest + +import networkx as nx +from networkx.readwrite.json_graph import tree_data, tree_graph + + +def test_graph(): + G = nx.DiGraph() + G.add_nodes_from([1, 2, 3], color="red") + G.add_edge(1, 2, foo=7) + G.add_edge(1, 3, foo=10) + G.add_edge(3, 4, foo=10) + H = tree_graph(tree_data(G, 1)) + assert nx.is_isomorphic(G, H) + + +def test_graph_attributes(): + G = nx.DiGraph() + G.add_nodes_from([1, 2, 3], color="red") + G.add_edge(1, 2, foo=7) + G.add_edge(1, 3, foo=10) + G.add_edge(3, 4, foo=10) + H = tree_graph(tree_data(G, 1)) + assert H.nodes[1]["color"] == "red" + + d = json.dumps(tree_data(G, 1)) + H = tree_graph(json.loads(d)) + assert H.nodes[1]["color"] == "red" + + +def test_exceptions(): + with pytest.raises(TypeError, match="is not a tree."): + G = nx.complete_graph(3) + tree_data(G, 0) + with pytest.raises(TypeError, match="is not directed."): + G = nx.path_graph(3) + tree_data(G, 0) + with pytest.raises(TypeError, match="is not weakly connected."): + G = nx.path_graph(3, create_using=nx.DiGraph) + G.add_edge(2, 0) + G.add_node(3) + tree_data(G, 0) + with pytest.raises(nx.NetworkXError, match="must be different."): + G = nx.MultiDiGraph() + G.add_node(0) + tree_data(G, 0, ident="node", children="node") diff --git a/shared/package-files/cc/cc1bebc8f817dd51793f81ea510d61d450f6c1aac72df4af6f49c1abaaf18eb7/test_indexing.py b/shared/package-files/cc/cc1bebc8f817dd51793f81ea510d61d450f6c1aac72df4af6f49c1abaaf18eb7/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..49eb79da616e7603b70ee3189e9004dd51fb33e7 --- /dev/null +++ b/shared/package-files/cc/cc1bebc8f817dd51793f81ea510d61d450f6c1aac72df4af6f49c1abaaf18eb7/test_indexing.py @@ -0,0 +1,420 @@ +import numpy as np +import pytest + +from pandas.errors import InvalidIndexError + +import pandas as pd +from pandas import ( + CategoricalIndex, + Index, + IntervalIndex, + Timestamp, +) +import pandas._testing as tm + + +class TestTake: + def test_take_fill_value(self): + # GH 12631 + + # numeric category + idx = CategoricalIndex([1, 2, 3], name="xxx") + result = idx.take(np.array([1, 0, -1])) + expected = CategoricalIndex([2, 1, 3], name="xxx") + tm.assert_index_equal(result, expected) + tm.assert_categorical_equal(result.values, expected.values) + + # fill_value + result = idx.take(np.array([1, 0, -1]), fill_value=True) + expected = CategoricalIndex([2, 1, np.nan], categories=[1, 2, 3], name="xxx") + tm.assert_index_equal(result, expected) + tm.assert_categorical_equal(result.values, expected.values) + + # allow_fill=False + result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) + expected = CategoricalIndex([2, 1, 3], name="xxx") + tm.assert_index_equal(result, expected) + tm.assert_categorical_equal(result.values, expected.values) + + # object category + idx = CategoricalIndex( + list("CBA"), categories=list("ABC"), ordered=True, name="xxx" + ) + result = idx.take(np.array([1, 0, -1])) + expected = CategoricalIndex( + list("BCA"), categories=list("ABC"), ordered=True, name="xxx" + ) + tm.assert_index_equal(result, expected) + tm.assert_categorical_equal(result.values, expected.values) + + # fill_value + result = idx.take(np.array([1, 0, -1]), fill_value=True) + expected = CategoricalIndex( + ["B", "C", np.nan], categories=list("ABC"), ordered=True, name="xxx" + ) + tm.assert_index_equal(result, expected) + tm.assert_categorical_equal(result.values, expected.values) + + # allow_fill=False + result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) + expected = CategoricalIndex( + list("BCA"), categories=list("ABC"), ordered=True, name="xxx" + ) + tm.assert_index_equal(result, expected) + tm.assert_categorical_equal(result.values, expected.values) + + msg = ( + "When allow_fill=True and fill_value is not None, " + "all indices must be >= -1" + ) + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -2]), fill_value=True) + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -5]), fill_value=True) + + msg = "index -5 is out of bounds for (axis 0 with )?size 3" + with pytest.raises(IndexError, match=msg): + idx.take(np.array([1, -5])) + + def test_take_fill_value_datetime(self): + # datetime category + idx = pd.DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"], name="xxx") + idx = CategoricalIndex(idx) + result = idx.take(np.array([1, 0, -1])) + expected = pd.DatetimeIndex( + ["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx" + ) + expected = CategoricalIndex(expected) + tm.assert_index_equal(result, expected) + + # fill_value + result = idx.take(np.array([1, 0, -1]), fill_value=True) + expected = pd.DatetimeIndex(["2011-02-01", "2011-01-01", "NaT"], name="xxx") + exp_cats = pd.DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"]) + expected = CategoricalIndex(expected, categories=exp_cats) + tm.assert_index_equal(result, expected) + + # allow_fill=False + result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) + expected = pd.DatetimeIndex( + ["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx" + ) + expected = CategoricalIndex(expected) + tm.assert_index_equal(result, expected) + + msg = ( + "When allow_fill=True and fill_value is not None, " + "all indices must be >= -1" + ) + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -2]), fill_value=True) + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -5]), fill_value=True) + + msg = "index -5 is out of bounds for (axis 0 with )?size 3" + with pytest.raises(IndexError, match=msg): + idx.take(np.array([1, -5])) + + def test_take_invalid_kwargs(self): + idx = CategoricalIndex([1, 2, 3], name="foo") + indices = [1, 0, -1] + + msg = r"take\(\) got an unexpected keyword argument 'foo'" + with pytest.raises(TypeError, match=msg): + idx.take(indices, foo=2) + + msg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=msg): + idx.take(indices, out=indices) + + msg = "the 'mode' parameter is not supported" + with pytest.raises(ValueError, match=msg): + idx.take(indices, mode="clip") + + +class TestGetLoc: + def test_get_loc(self): + # GH 12531 + cidx1 = CategoricalIndex(list("abcde"), categories=list("edabc")) + idx1 = Index(list("abcde")) + assert cidx1.get_loc("a") == idx1.get_loc("a") + assert cidx1.get_loc("e") == idx1.get_loc("e") + + for i in [cidx1, idx1]: + with pytest.raises(KeyError, match="'NOT-EXIST'"): + i.get_loc("NOT-EXIST") + + # non-unique + cidx2 = CategoricalIndex(list("aacded"), categories=list("edabc")) + idx2 = Index(list("aacded")) + + # results in bool array + res = cidx2.get_loc("d") + tm.assert_numpy_array_equal(res, idx2.get_loc("d")) + tm.assert_numpy_array_equal( + res, np.array([False, False, False, True, False, True]) + ) + # unique element results in scalar + res = cidx2.get_loc("e") + assert res == idx2.get_loc("e") + assert res == 4 + + for i in [cidx2, idx2]: + with pytest.raises(KeyError, match="'NOT-EXIST'"): + i.get_loc("NOT-EXIST") + + # non-unique, sliceable + cidx3 = CategoricalIndex(list("aabbb"), categories=list("abc")) + idx3 = Index(list("aabbb")) + + # results in slice + res = cidx3.get_loc("a") + assert res == idx3.get_loc("a") + assert res == slice(0, 2, None) + + res = cidx3.get_loc("b") + assert res == idx3.get_loc("b") + assert res == slice(2, 5, None) + + for i in [cidx3, idx3]: + with pytest.raises(KeyError, match="'c'"): + i.get_loc("c") + + def test_get_loc_unique(self): + cidx = CategoricalIndex(list("abc")) + result = cidx.get_loc("b") + assert result == 1 + + def test_get_loc_monotonic_nonunique(self): + cidx = CategoricalIndex(list("abbc")) + result = cidx.get_loc("b") + expected = slice(1, 3, None) + assert result == expected + + def test_get_loc_nonmonotonic_nonunique(self): + cidx = CategoricalIndex(list("abcb")) + result = cidx.get_loc("b") + expected = np.array([False, True, False, True], dtype=bool) + tm.assert_numpy_array_equal(result, expected) + + def test_get_loc_nan(self): + # GH#41933 + ci = CategoricalIndex(["A", "B", np.nan]) + res = ci.get_loc(np.nan) + + assert res == 2 + + +class TestGetIndexer: + def test_get_indexer_base(self): + # Determined by cat ordering. + idx = CategoricalIndex(list("cab"), categories=list("cab")) + expected = np.arange(len(idx), dtype=np.intp) + + actual = idx.get_indexer(idx) + tm.assert_numpy_array_equal(expected, actual) + + with pytest.raises(ValueError, match="Invalid fill method"): + idx.get_indexer(idx, method="invalid") + + def test_get_indexer_requires_unique(self): + ci = CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False) + oidx = Index(np.array(ci)) + + msg = "Reindexing only valid with uniquely valued Index objects" + + for n in [1, 2, 5, len(ci)]: + finder = oidx[np.random.default_rng(2).integers(0, len(ci), size=n)] + + with pytest.raises(InvalidIndexError, match=msg): + ci.get_indexer(finder) + + # see gh-17323 + # + # Even when indexer is equal to the + # members in the index, we should + # respect duplicates instead of taking + # the fast-track path. + for finder in [list("aabbca"), list("aababca")]: + with pytest.raises(InvalidIndexError, match=msg): + ci.get_indexer(finder) + + def test_get_indexer_non_unique(self): + idx1 = CategoricalIndex(list("aabcde"), categories=list("edabc")) + idx2 = CategoricalIndex(list("abf")) + + for indexer in [idx2, list("abf"), Index(list("abf"))]: + msg = "Reindexing only valid with uniquely valued Index objects" + with pytest.raises(InvalidIndexError, match=msg): + idx1.get_indexer(indexer) + + r1, _ = idx1.get_indexer_non_unique(indexer) + expected = np.array([0, 1, 2, -1], dtype=np.intp) + tm.assert_almost_equal(r1, expected) + + def test_get_indexer_method(self): + idx1 = CategoricalIndex(list("aabcde"), categories=list("edabc")) + idx2 = CategoricalIndex(list("abf")) + + msg = "method pad not yet implemented for CategoricalIndex" + with pytest.raises(NotImplementedError, match=msg): + idx2.get_indexer(idx1, method="pad") + msg = "method backfill not yet implemented for CategoricalIndex" + with pytest.raises(NotImplementedError, match=msg): + idx2.get_indexer(idx1, method="backfill") + + msg = "method nearest not yet implemented for CategoricalIndex" + with pytest.raises(NotImplementedError, match=msg): + idx2.get_indexer(idx1, method="nearest") + + def test_get_indexer_array(self): + arr = np.array( + [Timestamp("1999-12-31 00:00:00"), Timestamp("2000-12-31 00:00:00")], + dtype=object, + ) + cats = [Timestamp("1999-12-31 00:00:00"), Timestamp("2000-12-31 00:00:00")] + ci = CategoricalIndex(cats, categories=cats, ordered=False, dtype="category") + result = ci.get_indexer(arr) + expected = np.array([0, 1], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_same_categories_same_order(self): + ci = CategoricalIndex(["a", "b"], categories=["a", "b"]) + + result = ci.get_indexer(CategoricalIndex(["b", "b"], categories=["a", "b"])) + expected = np.array([1, 1], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_same_categories_different_order(self): + # https://github.com/pandas-dev/pandas/issues/19551 + ci = CategoricalIndex(["a", "b"], categories=["a", "b"]) + + result = ci.get_indexer(CategoricalIndex(["b", "b"], categories=["b", "a"])) + expected = np.array([1, 1], dtype="intp") + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_nans_in_index_and_target(self): + # GH 45361 + ci = CategoricalIndex([1, 2, np.nan, 3]) + other1 = [2, 3, 4, np.nan] + res1 = ci.get_indexer(other1) + expected1 = np.array([1, 3, -1, 2], dtype=np.intp) + tm.assert_numpy_array_equal(res1, expected1) + other2 = [1, 4, 2, 3] + res2 = ci.get_indexer(other2) + expected2 = np.array([0, -1, 1, 3], dtype=np.intp) + tm.assert_numpy_array_equal(res2, expected2) + + +class TestWhere: + def test_where(self, listlike_box): + klass = listlike_box + + i = CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False) + cond = [True] * len(i) + expected = i + result = i.where(klass(cond)) + tm.assert_index_equal(result, expected) + + cond = [False] + [True] * (len(i) - 1) + expected = CategoricalIndex([np.nan] + i[1:].tolist(), categories=i.categories) + result = i.where(klass(cond)) + tm.assert_index_equal(result, expected) + + def test_where_non_categories(self): + ci = CategoricalIndex(["a", "b", "c", "d"]) + mask = np.array([True, False, True, False]) + + result = ci.where(mask, 2) + expected = Index(["a", 2, "c", 2], dtype=object) + tm.assert_index_equal(result, expected) + + msg = "Cannot setitem on a Categorical with a new category" + with pytest.raises(TypeError, match=msg): + # Test the Categorical method directly + ci._data._where(mask, 2) + + +class TestContains: + def test_contains(self): + ci = CategoricalIndex(list("aabbca"), categories=list("cabdef"), ordered=False) + + assert "a" in ci + assert "z" not in ci + assert "e" not in ci + assert np.nan not in ci + + # assert codes NOT in index + assert 0 not in ci + assert 1 not in ci + + def test_contains_nan(self): + ci = CategoricalIndex(list("aabbca") + [np.nan], categories=list("cabdef")) + assert np.nan in ci + + @pytest.mark.parametrize("unwrap", [True, False]) + def test_contains_na_dtype(self, unwrap): + dti = pd.date_range("2016-01-01", periods=100).insert(0, pd.NaT) + pi = dti.to_period("D") + tdi = dti - dti[-1] + ci = CategoricalIndex(dti) + + obj = ci + if unwrap: + obj = ci._data + + assert np.nan in obj + assert None in obj + assert pd.NaT in obj + assert np.datetime64("NaT") in obj + assert np.timedelta64("NaT") not in obj + + obj2 = CategoricalIndex(tdi) + if unwrap: + obj2 = obj2._data + + assert np.nan in obj2 + assert None in obj2 + assert pd.NaT in obj2 + assert np.datetime64("NaT") not in obj2 + assert np.timedelta64("NaT") in obj2 + + obj3 = CategoricalIndex(pi) + if unwrap: + obj3 = obj3._data + + assert np.nan in obj3 + assert None in obj3 + assert pd.NaT in obj3 + assert np.datetime64("NaT") not in obj3 + assert np.timedelta64("NaT") not in obj3 + + @pytest.mark.parametrize( + "item, expected", + [ + (pd.Interval(0, 1), True), + (1.5, True), + (pd.Interval(0.5, 1.5), False), + ("a", False), + (Timestamp(1), False), + (pd.Timedelta(1), False), + ], + ids=str, + ) + def test_contains_interval(self, item, expected): + # GH 23705 + ci = CategoricalIndex(IntervalIndex.from_breaks(range(3))) + result = item in ci + assert result is expected + + def test_contains_list(self): + # GH#21729 + idx = CategoricalIndex([1, 2, 3]) + + assert "a" not in idx + + with pytest.raises(TypeError, match="unhashable type"): + ["a"] in idx + + with pytest.raises(TypeError, match="unhashable type"): + ["a", "b"] in idx diff --git a/shared/package-files/cc/cc1bf9e27c2efe461f7c290acc3aa0b4d1cc886bde73ca53e858234d29e36515/_fft_c2c_native.h b/shared/package-files/cc/cc1bf9e27c2efe461f7c290acc3aa0b4d1cc886bde73ca53e858234d29e36515/_fft_c2c_native.h new file mode 100644 index 0000000000000000000000000000000000000000..38d293f0eb45c27f232262ab64187b74003ed226 --- /dev/null +++ b/shared/package-files/cc/cc1bf9e27c2efe461f7c290acc3aa0b4d1cc886bde73ca53e858234d29e36515/_fft_c2c_native.h @@ -0,0 +1,24 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor _fft_c2c_mkl(const at::Tensor & self, at::IntArrayRef dim, int64_t normalization, bool forward); +TORCH_API at::Tensor & _fft_c2c_mkl_out(const at::Tensor & self, at::IntArrayRef dim, int64_t normalization, bool forward, at::Tensor & out); +TORCH_API at::Tensor _fft_c2c_cufft(const at::Tensor & self, at::IntArrayRef dim, int64_t normalization, bool forward); +TORCH_API at::Tensor & _fft_c2c_cufft_out(const at::Tensor & self, at::IntArrayRef dim, int64_t normalization, bool forward, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/cc/cc1eb5b32f745fded8275ea62068ae68401a0488c11334402bfa9f48289c8503/conftest.py b/shared/package-files/cc/cc1eb5b32f745fded8275ea62068ae68401a0488c11334402bfa9f48289c8503/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..61c2de3e07bac4db323f8704961264d123e01544 --- /dev/null +++ b/shared/package-files/cc/cc1eb5b32f745fded8275ea62068ae68401a0488c11334402bfa9f48289c8503/conftest.py @@ -0,0 +1,2 @@ +from matplotlib.testing.conftest import (mpl_test_settings, # noqa + pytest_configure, pytest_unconfigure) diff --git a/shared/package-files/cc/cc20a6e10f82c55a053bf2379cb6fe1c0d54ad630cb7105e3fb48833b5959337/libcufile_rdma.so.1.9.1 b/shared/package-files/cc/cc20a6e10f82c55a053bf2379cb6fe1c0d54ad630cb7105e3fb48833b5959337/libcufile_rdma.so.1.9.1 new file mode 100644 index 0000000000000000000000000000000000000000..c549a078a22bb0e419326c44765d6684589d032a Binary files /dev/null and b/shared/package-files/cc/cc20a6e10f82c55a053bf2379cb6fe1c0d54ad630cb7105e3fb48833b5959337/libcufile_rdma.so.1.9.1 differ diff --git a/shared/package-files/cc/cc20c566e2fce003b30f60b9437eecec53e8f375a33136a0c716e756fc24e3d3/fbgemm_linear_int8_weight_ops.h b/shared/package-files/cc/cc20c566e2fce003b30f60b9437eecec53e8f375a33136a0c716e756fc24e3d3/fbgemm_linear_int8_weight_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..8f6d0264490c47687470764368e63e33410dc37e --- /dev/null +++ b/shared/package-files/cc/cc20c566e2fce003b30f60b9437eecec53e8f375a33136a0c716e756fc24e3d3/fbgemm_linear_int8_weight_ops.h @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API fbgemm_linear_int8_weight { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::fbgemm_linear_int8_weight") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fbgemm_linear_int8_weight(Tensor input, Tensor weight, Tensor packed, Tensor col_offsets, Scalar weight_scale, Scalar weight_zero_point, Tensor bias) -> Tensor") + static at::Tensor call(const at::Tensor & input, const at::Tensor & weight, const at::Tensor & packed, const at::Tensor & col_offsets, const at::Scalar & weight_scale, const at::Scalar & weight_zero_point, const at::Tensor & bias); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & weight, const at::Tensor & packed, const at::Tensor & col_offsets, const at::Scalar & weight_scale, const at::Scalar & weight_zero_point, const at::Tensor & bias); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/cc/cc2271d854fe5591508ee4d3acdbe80ece41b2e4d5ffd7e198b8b2bfa02b2c39/string_view.h b/shared/package-files/cc/cc2271d854fe5591508ee4d3acdbe80ece41b2e4d5ffd7e198b8b2bfa02b2c39/string_view.h new file mode 100644 index 0000000000000000000000000000000000000000..136e3cd154ecfc49192d7af85625d1e803bd989d --- /dev/null +++ b/shared/package-files/cc/cc2271d854fe5591508ee4d3acdbe80ece41b2e4d5ffd7e198b8b2bfa02b2c39/string_view.h @@ -0,0 +1,609 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace c10 { + +/** + * Port of std::string_view with methods from C++20. + * Implemented following the interface definition in + * https://en.cppreference.com/w/cpp/string/basic_string_view + * See there for the API documentation. + * + * Difference: We don't have a Traits template parameter because + * std::char_traits isn't constexpr and we'd have to reimplement + * std::char_traits if we wanted to use it with our constexpr basic_string_view. + */ +template +class basic_string_view final { + public: + using value_type = CharT; + using pointer = CharT*; + using const_pointer = const CharT*; + using reference = CharT&; + using const_reference = const CharT&; + using const_iterator = const CharT*; + using iterator = const_iterator; + using const_reverse_iterator = std::reverse_iterator; + using reverse_iterator = const_reverse_iterator; + using size_type = std::size_t; + using difference_type = std::ptrdiff_t; + + static constexpr size_type npos = size_type(-1); + + constexpr basic_string_view() noexcept : begin_(nullptr) {} + + explicit constexpr basic_string_view(const_pointer str, size_type count) + : begin_(str), size_(count) {} + + /* implicit */ constexpr basic_string_view(const_pointer str) + : basic_string_view(str, strlen_(str)) {} + + /* implicit */ basic_string_view(const ::std::basic_string& str) + : basic_string_view(str.data(), str.size()) {} + + constexpr basic_string_view(const basic_string_view&) noexcept = default; + + constexpr basic_string_view& operator=( + const basic_string_view& rhs) noexcept { + begin_ = rhs.begin_; + size_ = rhs.size_; + return *this; + } + + explicit operator ::std::basic_string() const { + return ::std::basic_string(data(), size()); + } + + constexpr const_iterator begin() const noexcept { + return cbegin(); + } + + constexpr const_iterator cbegin() const noexcept { + return begin_; + } + + constexpr const_iterator end() const noexcept { + return cend(); + } + + constexpr const_iterator cend() const noexcept { + return begin_ + size_; + } + + constexpr const_reverse_iterator rbegin() const noexcept { + return crbegin(); + } + + constexpr const_reverse_iterator crbegin() const noexcept { + return const_reverse_iterator(this->end()); + } + + constexpr const_reverse_iterator rend() const noexcept { + return crend(); + } + + constexpr const_reverse_iterator crend() const noexcept { + return const_reverse_iterator(this->begin()); + } + + friend constexpr const_iterator begin(basic_string_view sv) noexcept { + return sv.begin(); + } + + friend constexpr const_iterator end(basic_string_view sv) noexcept { + return sv.end(); + } + + constexpr const_reference operator[](size_type pos) const { + // TODO: split out + return at_(pos); + } + + constexpr const_reference at(size_type pos) const { +#if !defined( \ + __CUDA_ARCH__) // CUDA doesn't like std::out_of_range in device code + return C10_UNLIKELY(pos >= size_) + ? (throw std::out_of_range( + "string_view::operator[] or string_view::at() out of range. Index: " + + std::to_string(pos) + ", size: " + std::to_string(size())), + at_(0)) + : at_(pos); +#else + return at_(pos); +#endif + } + + constexpr const_reference front() const { + return *begin_; + } + + constexpr const_reference back() const { + return *(begin_ + size_ - 1); + } + + constexpr const_pointer data() const noexcept { + return begin_; + } + + constexpr size_type size() const noexcept { + return size_; + } + + constexpr size_type length() const noexcept { + return size(); + } + + constexpr size_type max_size() const noexcept { + return std::numeric_limits::max(); + } + + C10_NODISCARD constexpr bool empty() const noexcept { + return size() == 0; + } + + constexpr void remove_prefix(size_type n) { + if (n > size()) { + throw std::out_of_range( + "basic_string_view::remove_prefix: out of range. PrefixLength: " + + std::to_string(n) + ", size: " + std::to_string(size())); + } + begin_ += n; + size_ -= n; + } + + constexpr void remove_suffix(size_type n) { + if (n > size()) { + throw std::out_of_range( + "basic_string_view::remove_suffix: out of range. SuffixLength: " + + std::to_string(n) + ", size: " + std::to_string(size())); + } + size_ -= n; + } + + constexpr void swap(basic_string_view& sv) noexcept { + auto tmp = *this; + *this = sv; + sv = tmp; + } + + size_type copy(pointer dest, size_type count, size_type pos = 0) const { + if (pos > size_) { + throw std::out_of_range( + "basic_string_view::copy: out of range. Index: " + + std::to_string(pos) + ", size: " + std::to_string(size())); + } + size_type copy_length = std::min(count, size_ - pos); + for (auto iter = begin() + pos, end = iter + copy_length; iter != end;) { + *(dest++) = *(iter++); + } + return copy_length; + } + + constexpr basic_string_view substr(size_type pos = 0, size_type count = npos) + const { +#if !defined( \ + __CUDA_ARCH__) // CUDA doesn't like std::out_of_range in device code + return (pos > size_) + ? (throw std::out_of_range( + "basic_string_view::substr parameter out of bounds. Index: " + + std::to_string(pos) + ", size: " + std::to_string(size())), + substr_()) + : substr_(pos, count); +#else + return substr_(pos, count); +#endif + } + + constexpr int compare(basic_string_view rhs) const noexcept { + // Write it iteratively. This is faster. + for (size_t i = 0, end = std::min(size(), rhs.size()); i < end; ++i) { + if (at_(i) < rhs.at_(i)) { + return -1; + } else if (at_(i) > rhs.at_(i)) { + return 1; + } + } + if (size() < rhs.size()) { + return -1; + } else if (size() > rhs.size()) { + return 1; + } + return 0; + } + + constexpr int compare(size_type pos1, size_type count1, basic_string_view v) + const { + return substr(pos1, count1).compare(v); + } + + constexpr int compare( + size_type pos1, + size_type count1, + basic_string_view v, + size_type pos2, + size_type count2) const { + return substr(pos1, count1).compare(v.substr(pos2, count2)); + } + + constexpr int compare(const_pointer s) const { + return compare(basic_string_view(s)); + } + + constexpr int compare(size_type pos1, size_type count1, const_pointer s) + const { + return substr(pos1, count1).compare(basic_string_view(s)); + } + + constexpr int compare( + size_type pos1, + size_type count1, + const_pointer s, + size_type count2) const { + return substr(pos1, count1).compare(basic_string_view(s, count2)); + } + + friend constexpr bool operator==( + basic_string_view lhs, + basic_string_view rhs) noexcept { + return lhs.equals_(rhs); + } + + friend constexpr bool operator!=( + basic_string_view lhs, + basic_string_view rhs) noexcept { + return !(lhs == rhs); + } + + friend constexpr bool operator<( + basic_string_view lhs, + basic_string_view rhs) noexcept { + return lhs.compare(rhs) < 0; + } + + friend constexpr bool operator>=( + basic_string_view lhs, + basic_string_view rhs) noexcept { + return !(lhs < rhs); + } + + friend constexpr bool operator>( + basic_string_view lhs, + basic_string_view rhs) noexcept { + return rhs < lhs; + } + + friend constexpr bool operator<=( + basic_string_view lhs, + basic_string_view rhs) noexcept { + return !(lhs > rhs); + } + + constexpr bool starts_with(basic_string_view prefix) const noexcept { + return (prefix.size() > size()) ? false + : prefix.equals_(substr_(0, prefix.size())); + } + + constexpr bool starts_with(CharT prefix) const noexcept { + return !empty() && prefix == front(); + } + + constexpr bool starts_with(const_pointer prefix) const { + return starts_with(basic_string_view(prefix)); + } + + constexpr bool ends_with(basic_string_view suffix) const noexcept { + return (suffix.size() > size()) + ? false + : suffix.equals_(substr_(size() - suffix.size(), suffix.size())); + } + + constexpr bool ends_with(CharT suffix) const noexcept { + return !empty() && suffix == back(); + } + + constexpr bool ends_with(const_pointer suffix) const { + return ends_with(basic_string_view(suffix)); + } + + constexpr size_type find(basic_string_view v, size_type pos = 0) + const noexcept { + if (v.size() == 0) { + return pos <= size() ? pos : npos; + } + + if (pos + v.size() <= size()) { + for (size_type cur = pos, end = size() - v.size(); cur <= end; ++cur) { + if (v.at_(0) == at_(cur) && + v.substr_(1).equals_(substr_(cur + 1, v.size() - 1))) { + return cur; + } + } + } + return npos; + } + + constexpr size_type find(CharT ch, size_type pos = 0) const noexcept { + return find_first_if_(pos, charIsEqual_{ch}); + } + + constexpr size_type find(const_pointer s, size_type pos, size_type count) + const { + return find(basic_string_view(s, count), pos); + } + + constexpr size_type find(const_pointer s, size_type pos = 0) const { + return find(basic_string_view(s), pos); + } + + constexpr size_type rfind(basic_string_view v, size_type pos = npos) + const noexcept { + // Write it iteratively. This is faster. + if (v.size() == 0) { + return pos <= size() ? pos : size(); + } + + if (v.size() <= size()) { + pos = std::min(size() - v.size(), pos); + do { + if (v.at_(0) == at_(pos) && + v.substr_(1).equals_(substr_(pos + 1, v.size() - 1))) { + return pos; + } + } while (pos-- > 0); + } + return npos; + } + + constexpr size_type rfind(CharT ch, size_type pos = npos) const noexcept { + return find_last_if_(pos, charIsEqual_{ch}); + } + + constexpr size_type rfind(const_pointer s, size_type pos, size_type count) + const { + return rfind(basic_string_view(s, count), pos); + } + + constexpr size_type rfind(const_pointer s, size_type pos = npos) const { + return rfind(basic_string_view(s), pos); + } + + constexpr size_type find_first_of(basic_string_view v, size_type pos = 0) + const noexcept { + return find_first_if_(pos, stringViewContainsChar_{v}); + } + + constexpr size_type find_first_of(CharT ch, size_type pos = 0) + const noexcept { + return find_first_if_(pos, charIsEqual_{ch}); + } + + constexpr size_type find_first_of( + const_pointer s, + size_type pos, + size_type count) const { + return find_first_of(basic_string_view(s, count), pos); + } + + constexpr size_type find_first_of(const_pointer s, size_type pos = 0) const { + return find_first_of(basic_string_view(s), pos); + } + + constexpr size_type find_last_of(basic_string_view v, size_type pos = npos) + const noexcept { + return find_last_if_(pos, stringViewContainsChar_{v}); + } + + constexpr size_type find_last_of(CharT ch, size_type pos = npos) + const noexcept { + return find_last_if_(pos, charIsEqual_{ch}); + } + + constexpr size_type find_last_of( + const_pointer s, + size_type pos, + size_type count) const { + return find_last_of(basic_string_view(s, count), pos); + } + + constexpr size_type find_last_of(const_pointer s, size_type pos = npos) + const { + return find_last_of(basic_string_view(s), pos); + } + + constexpr size_type find_first_not_of(basic_string_view v, size_type pos = 0) + const noexcept { + return find_first_if_(pos, stringViewDoesNotContainChar_{v}); + } + + constexpr size_type find_first_not_of(CharT ch, size_type pos = 0) + const noexcept { + return find_first_if_(pos, charIsNotEqual_{ch}); + } + + constexpr size_type find_first_not_of( + const_pointer s, + size_type pos, + size_type count) const { + return find_first_not_of(basic_string_view(s, count), pos); + } + + constexpr size_type find_first_not_of(const_pointer s, size_type pos = 0) + const { + return find_first_not_of(basic_string_view(s), pos); + } + + constexpr size_type find_last_not_of( + basic_string_view v, + size_type pos = npos) const noexcept { + return find_last_if_(pos, stringViewDoesNotContainChar_{v}); + } + + constexpr size_type find_last_not_of(CharT ch, size_type pos = npos) + const noexcept { + return find_last_if_(pos, charIsNotEqual_{ch}); + } + + constexpr size_type find_last_not_of( + const_pointer s, + size_type pos, + size_type count) const { + return find_last_not_of(basic_string_view(s, count), pos); + } + + constexpr size_type find_last_not_of(const_pointer s, size_type pos = npos) + const { + return find_last_not_of(basic_string_view(s), pos); + } + + private: + static constexpr size_type strlen_(const_pointer str) noexcept { + const_pointer current = str; + while (*current != '\0') { + ++current; + } + return current - str; + } + + constexpr const_reference at_(size_type pos) const noexcept { + return *(begin_ + pos); + } + + constexpr basic_string_view substr_(size_type pos = 0, size_type count = npos) + const { + return basic_string_view{begin_ + pos, std::min(count, size() - pos)}; + } + + template + // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward) + constexpr size_type find_first_if_(size_type pos, Condition&& condition) + const noexcept { + if (pos + 1 <= size()) { + for (size_type cur = pos; cur < size(); ++cur) { + if (condition(at_(cur))) { + return cur; + } + } + } + return npos; + } + + template + // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward) + constexpr size_type find_last_if_(size_type pos, Condition&& condition) + const noexcept { + // Write it iteratively. This is faster. + if (size() > 0) { + pos = std::min(size() - 1, pos); + do { + if (condition(at_(pos))) { + return pos; + } + } while (pos-- > 0); + } + return npos; + } + + constexpr bool equals_(basic_string_view rhs) const { + // We don't use string_view::compare() here but implement it manually + // because only looking at equality allows for more optimized code. +#if defined(__GNUC__) && !defined(__CUDACC__) + return size() == rhs.size() && + 0 == __builtin_memcmp(data(), rhs.data(), size()); +#else + if (size() != rhs.size()) { + return false; + } + // Yes, memcmp would be laster than this loop, but memcmp isn't constexpr + // and I didn't feel like implementing a constexpr memcmp variant. + // TODO At some point this should probably be done, including tricks + // like comparing one machine word instead of a byte per iteration. + for (typename basic_string_view::size_type pos = 0; pos < size(); + ++pos) { + if (at_(pos) != rhs.at_(pos)) { + return false; + } + } + return true; +#endif + } + + struct charIsEqual_ final { + CharT expected; + constexpr bool operator()(CharT actual) const noexcept { + return expected == actual; + } + }; + + struct charIsNotEqual_ final { + CharT expected; + constexpr bool operator()(CharT actual) const noexcept { + return expected != actual; + } + }; + + struct stringViewContainsChar_ final { + basic_string_view expected; + constexpr bool operator()(CharT ch) const noexcept { + return npos != expected.find(ch); + } + }; + + struct stringViewDoesNotContainChar_ final { + basic_string_view expected; + constexpr bool operator()(CharT ch) const noexcept { + return npos == expected.find(ch); + } + }; + + const_pointer begin_; + size_type size_{}; +}; + +template +inline std::basic_ostream& operator<<( + std::basic_ostream& stream, + basic_string_view sv) { + // The rules for operator<< are quite complex, so lets defer to the + // STL implementation. + using std_string_type = ::std::basic_string_view; + return stream << std_string_type(sv.data(), sv.size()); +} + +template +constexpr inline void swap( + basic_string_view& lhs, + basic_string_view& rhs) noexcept { + lhs.swap(rhs); +} + +using string_view = basic_string_view; + +} // namespace c10 + +namespace std { +template +struct hash<::c10::basic_string_view> { + size_t operator()(::c10::basic_string_view x) const { + // The standard says that std::string_view hashing must do the same as + // std::string hashing but leaves the details of std::string hashing + // up to the implementer. So, to be conformant, we need to re-use and + // existing STL type's hash function. The std::string fallback is probably + // slow but the only way to be conformant. + + using std_string_type = ::std::basic_string_view; + return ::std::hash{}(std_string_type(x.data(), x.size())); + } +}; +} // namespace std diff --git a/shared/package-files/cc/cc228bbb4f7749f46d66a61d7c2a8150ac004af7acaf078003fc88437d3ec139/to_sparse_ops.h b/shared/package-files/cc/cc228bbb4f7749f46d66a61d7c2a8150ac004af7acaf078003fc88437d3ec139/to_sparse_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..faeb8382c43bbd7a929b558379295e3c6b5ad4a2 --- /dev/null +++ b/shared/package-files/cc/cc228bbb4f7749f46d66a61d7c2a8150ac004af7acaf078003fc88437d3ec139/to_sparse_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API to_sparse_sparse_dim { + using schema = at::Tensor (const at::Tensor &, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::to_sparse") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "sparse_dim") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "to_sparse.sparse_dim(Tensor self, int sparse_dim) -> Tensor") + static at::Tensor call(const at::Tensor & self, int64_t sparse_dim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t sparse_dim); +}; + +struct TORCH_API to_sparse { + using schema = at::Tensor (const at::Tensor &, c10::optional, at::OptionalIntArrayRef, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::to_sparse") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "to_sparse(Tensor self, *, Layout? layout=None, int[2]? blocksize=None, int? dense_dim=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, c10::optional layout, at::OptionalIntArrayRef blocksize, c10::optional dense_dim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional layout, at::OptionalIntArrayRef blocksize, c10::optional dense_dim); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/cc/cc23f0877d05d8d78396a4dada798526c3f9caaf185cc4d1332c9c93a2cfb0ff/test_agreement.py b/shared/package-files/cc/cc23f0877d05d8d78396a4dada798526c3f9caaf185cc4d1332c9c93a2cfb0ff/test_agreement.py new file mode 100644 index 0000000000000000000000000000000000000000..c1846eb3a5183624642dc84b5e58b452c96a87a7 --- /dev/null +++ b/shared/package-files/cc/cc23f0877d05d8d78396a4dada798526c3f9caaf185cc4d1332c9c93a2cfb0ff/test_agreement.py @@ -0,0 +1,73 @@ +import numpy as np +import pandas as pd +import pytest + +from statsmodels.graphics.agreement import mean_diff_plot + + +@pytest.mark.thread_unsafe(reason="Uses matplotlib") +@pytest.mark.matplotlib +def test_mean_diff_plot(close_figures): + import matplotlib.pyplot as plt + + # Seed the random number generator. + # This ensures that the results below are reproducible. + rs = np.random.RandomState(11111) + m1 = rs.random(20) + m2 = rs.random(20) + fig = plt.figure() + ax = fig.add_subplot(111) + + # basic test. + mean_diff_plot(m1, m2, ax=ax) + + # Test with pandas Series. + p1 = pd.Series(m1) + p2 = pd.Series(m2) + mean_diff_plot(p1, p2) + + # Test plotting on assigned axis. + fig, ax = plt.subplots(2) + mean_diff_plot(m1, m2, ax=ax[0]) + + # Test the setting of confidence intervals. + mean_diff_plot(m1, m2, sd_limit=0) + + # Test asethetic controls. + mean_diff_plot(m1, m2, scatter_kwds={"color": "green", "s": 10}) + + mean_diff_plot(m1, m2, mean_line_kwds={"color": "green", "lw": 5}) + + mean_diff_plot(m1, m2, limit_lines_kwds={"color": "green", "lw": 5, "ls": "dotted"}) + + +@pytest.mark.thread_unsafe(reason="Uses matplotlib") +@pytest.mark.matplotlib +def test_mean_diff_plot_linestyles(close_figures): + import matplotlib.pyplot as plt + + rs = np.random.RandomState(11111) + m1 = rs.random(20) + m2 = rs.random(20) + + # The mean line defaults to dashed and the limit lines to dotted + fig, ax = plt.subplots() + mean_diff_plot(m1, m2, ax=ax) + mean_line, lower, upper = ax.lines + assert mean_line.get_linestyle() == "--" + assert lower.get_linestyle() == ":" + assert upper.get_linestyle() == ":" + + # An explicit linestyle is used for the line it was supplied for + fig, ax = plt.subplots() + mean_diff_plot( + m1, + m2, + ax=ax, + mean_line_kwds={"linestyle": "-."}, + limit_lines_kwds={"linestyle": "-"}, + ) + mean_line, lower, upper = ax.lines + assert mean_line.get_linestyle() == "-." + assert lower.get_linestyle() == "-" + assert upper.get_linestyle() == "-" diff --git a/shared/package-files/cc/cc24239e6edd2476e66b7ae4c1362a48abc95aaeda08fbebbd25170abc9ae311/test_dynamic_factor.py b/shared/package-files/cc/cc24239e6edd2476e66b7ae4c1362a48abc95aaeda08fbebbd25170abc9ae311/test_dynamic_factor.py new file mode 100644 index 0000000000000000000000000000000000000000..abd6e1997848ee56b9f7d835ec5c6eca1caebad9 --- /dev/null +++ b/shared/package-files/cc/cc24239e6edd2476e66b7ae4c1362a48abc95aaeda08fbebbd25170abc9ae311/test_dynamic_factor.py @@ -0,0 +1,1091 @@ +""" +Tests for VARMAX models + +Author: Chad Fulton +License: Simplified-BSD +""" +from pathlib import Path +import re +import warnings + +import numpy as np +from numpy.testing import assert_allclose, assert_equal +import pandas as pd +import pytest + +from statsmodels.iolib.summary import Summary, forg +from statsmodels.tsa.statespace import dynamic_factor + +from .results import results_dynamic_factor, results_varmax + +current_path = Path(__file__).resolve().parent + +output_path = Path("results").joinpath("results_dynamic_factor_stata.csv") +output_results = pd.read_csv(Path(current_path).joinpath(output_path)) + + +class CheckDynamicFactor: + + def setup_model( + self, + true, + k_factors, + factor_order, + cov_type="approx", + included_vars=("dln_inv", "dln_inc", "dln_consump"), + demean=False, + filter=True, + **kwargs, + ): + # Recreates the model and results in each pass to allow for thread-safe testing + self.true = true + # 1960:Q1 - 1982:Q4 + dta = pd.DataFrame( + results_varmax.lutkepohl_data, + columns=["inv", "inc", "consump"], + index=pd.date_range("1960-01-01", "1982-10-01", freq="QS"), + ) + + dta["dln_inv"] = np.log(dta["inv"]).diff() + dta["dln_inc"] = np.log(dta["inc"]).diff() + dta["dln_consump"] = np.log(dta["consump"]).diff() + + endog = dta.loc["1960-04-01":"1978-10-01", list(included_vars)] + + if demean: + endog -= dta.iloc[1:][included_vars].mean() + + model = dynamic_factor.DynamicFactor( + endog, k_factors=k_factors, factor_order=factor_order, **kwargs + ) + + if filter: + results = model.smooth(true["params"], cov_type=cov_type) + else: + results = None + return model, results + + def construct_model(self): + raise NotImplementedError("subclasses must implement") + + def test_params(self): + # Smoke test to make sure the start_params are well-defined and + # lead to a well-defined model + model, result = self.construct_model() + model.filter(model.start_params) + # Similarly a smoke test for param_names + assert_equal(len(model.start_params), len(model.param_names)) + # Finally make sure the transform and untransform do their job + actual = model.transform_params(model.untransform_params(model.start_params)) + assert_allclose(actual, model.start_params) + # Also in the case of enforce stationarity = False + model.enforce_stationarity = False + actual = model.transform_params(model.untransform_params(model.start_params)) + model.enforce_stationarity = True + assert_allclose(actual, model.start_params) + + def test_results(self, close_figures): + # Smoke test for creating the summary + model, results = self.construct_model() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + results.summary() + + # Test cofficient matrix creation + # (via a different, more direct, method) + if model.factor_order > 0: + k_factors = model.k_factors + pft_params = results.params[model._params_factor_transition] + coefficients = np.array(pft_params).reshape( + k_factors, k_factors * model.factor_order + ) + coefficient_matrices = np.array( + [ + coefficients[ + : model.k_factors, + i * model.k_factors : (i + 1) * model.k_factors, + ] + for i in range(model.factor_order) + ] + ) + assert_equal(results.coefficient_matrices_var, coefficient_matrices) + else: + assert_equal(results.coefficient_matrices_var, None) + + @pytest.mark.thread_unsafe(reason="Uses matplotlib") + @pytest.mark.matplotlib + def test_plot_coefficients_of_determination(self, close_figures): + # Smoke test for plot_coefficients_of_determination + _, results = self.construct_model() + results.plot_coefficients_of_determination() + + def test_no_enforce(self): + return + # Test that nothing goes wrong when we do not enforce stationarity + # model, results = self.construct_model() + # params = model.untransform_params(self.true["params"]) + # params[model._params_transition] = self.true["params"][model._params_transition] + # model.enforce_stationarity = False + # results = model.filter(params, transformed=False) + # model.enforce_stationarity = True + # assert_allclose(results.llf, self.results.llf, rtol=1e-5) + + def test_mle(self, init_powell=True): + model, results = self.construct_model() + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + start_params = model.start_params + if init_powell: + results = model.fit(method="powell", maxiter=100, disp=False) + start_params = results.params + results = model.fit(start_params, maxiter=1000, disp=False) + results = model.fit(results.params, method="nm", maxiter=1000, disp=False) + if not results.llf > results.llf: + assert_allclose(results.llf, results.llf, rtol=1e-5) + + def test_loglike(self): + model, results = self.construct_model() + assert_allclose(results.llf, self.true["loglike"], rtol=1e-6) + + def test_aic(self): + # We only get 3 digits from Stata + model, results = self.construct_model() + assert_allclose(results.aic, self.true["aic"], atol=3) + + def test_bic(self): + # We only get 3 digits from Stata + model, results = self.construct_model() + assert_allclose(results.bic, self.true["bic"], atol=3) + + def test_predict(self, **kwargs): + # Tests predict + forecast + model, results = self.construct_model() + results.predict(end="1982-10-01", **kwargs) + assert_allclose( + results.predict(end="1982-10-01", **kwargs), + self.true["predict"], + atol=1e-6, + ) + + def test_dynamic_predict(self, **kwargs): + # Tests predict + dynamic predict + forecast + model, results = self.construct_model() + assert_allclose( + results.predict(end="1982-10-01", dynamic="1961-01-01", **kwargs), + self.true["dynamic_predict"], + atol=1e-6, + ) + + +class TestDynamicFactor(CheckDynamicFactor): + """ + Test for a dynamic factor model with 1 AR(2) factor + """ + + def construct_model(self): + true = results_dynamic_factor.lutkepohl_dfm.copy() + true["predict"] = output_results.iloc[1:][ + ["predict_dfm_1", "predict_dfm_2", "predict_dfm_3"] + ] + true["dynamic_predict"] = output_results.iloc[1:][ + ["dyn_predict_dfm_1", "dyn_predict_dfm_2", "dyn_predict_dfm_3"] + ] + return self.setup_model(true, k_factors=1, factor_order=2) + + def test_bse_approx(self): + model, results = self.construct_model() + bse = results._cov_params_approx().diagonal() ** 0.5 + assert_allclose(bse, self.true["bse_oim"], atol=1e-5) + + +class TestDynamicFactor2(CheckDynamicFactor): + """ + Test for a dynamic factor model with two VAR(1) factors + """ + + def construct_model(self): + true = results_dynamic_factor.lutkepohl_dfm2.copy() + true["predict"] = output_results.iloc[1:][ + ["predict_dfm2_1", "predict_dfm2_2", "predict_dfm2_3"] + ] + true["dynamic_predict"] = output_results.iloc[1:][ + ["dyn_predict_dfm2_1", "dyn_predict_dfm2_2", "dyn_predict_dfm2_3"] + ] + return super().setup_model(true, k_factors=2, factor_order=1) + + def test_mle(self): + # Stata's MLE on this model does not converge, so no reason to check + pass + + def test_bse(self): + # Stata's MLE on this model does not converge, and four of their + # params do not even have bse (possibly they are still at starting + # values?), so no reason to check this + pass + + def test_aic(self): + # Stata uses 9 df (i.e., 9 params) here instead of 13, because since the + # model did not coverge, 4 of the parameters are not fully estimated + # (possibly they are still at starting values?) so the AIC is off + pass + + def test_bic(self): + # Stata uses 9 df (i.e., 9 params) here instead of 13, because since the + # model did not coverge, 4 of the parameters are not fully estimated + # (possibly they are still at starting values?) so the BIC is off + pass + + def test_summary(self): + model, results = self.construct_model() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + summary = results.summary() + tables = [str(table) for table in summary.tables] + params = self.true["params"] + + # Make sure we have the right number of tables + assert_equal(len(tables), 2 + model.k_endog + model.k_factors + 1) + + # Check the model overview table + assert re.search(r"Model:.*DynamicFactor\(factors=2, order=1\)", tables[0]) + + # For each endogenous variable, check the output + for i in range(model.k_endog): + offset_loading = model.k_factors * i + table = tables[i + 2] + + # -> Make sure we have the right table / table name + name = model.endog_names[i] + assert re.search(f"Results for equation {name}", table) + + # -> Make sure it's the right size + assert_equal(len(table.split("\n")), 7) + + # -> Check that we have the right coefficients + assert re.search( + "loading.f1 +" + forg(params[offset_loading + 0], prec=4), table + ) + assert re.search( + "loading.f2 +" + forg(params[offset_loading + 1], prec=4), table + ) + + # For each factor, check the output + for i in range(model.k_factors): + offset = model.k_endog * (model.k_factors + 1) + i * model.k_factors + table = tables[model.k_endog + i + 2] + + # -> Make sure we have the right table / table name + assert re.search(f"Results for factor equation f{i + 1:d}", table) + + # -> Make sure it's the right size + assert_equal(len(table.split("\n")), 7) + + # -> Check that we have the right coefficients + assert re.search("L1.f1 +" + forg(params[offset + 0], prec=4), table) + assert re.search("L1.f2 +" + forg(params[offset + 1], prec=4), table) + + # Check the Error covariance matrix output + table = tables[2 + model.k_endog + model.k_factors] + + # -> Make sure we have the right table / table name + assert re.search("Error covariance matrix", table) + + # -> Make sure it's the right size + assert_equal(len(table.split("\n")), 8) + + # -> Check that we have the right coefficients + offset = model.k_endog * model.k_factors + for i in range(model.k_endog): + iname = model.endog_names[i] + iparam = forg(params[offset + i], prec=4) + assert re.search(f"sigma2.{iname} +{iparam}", table) + + +class TestDynamicFactor_exog1(CheckDynamicFactor): + """ + Test for a dynamic factor model with 1 exogenous regressor: a constant + """ + + def construct_model(self): + true = results_dynamic_factor.lutkepohl_dfm_exog1.copy() + true["predict"] = output_results.iloc[1:][ + ["predict_dfm_exog1_1", "predict_dfm_exog1_2", "predict_dfm_exog1_3"] + ] + true["dynamic_predict"] = output_results.iloc[1:][ + [ + "dyn_predict_dfm_exog1_1", + "dyn_predict_dfm_exog1_2", + "dyn_predict_dfm_exog1_3", + ] + ] + exog = np.ones((75, 1)) + return super().setup_model(true, k_factors=1, factor_order=1, exog=exog) + + def test_predict(self): + exog = np.ones((16, 1)) + super().test_predict(exog=exog) + + def test_dynamic_predict(self): + exog = np.ones((16, 1)) + super().test_dynamic_predict(exog=exog) + + def test_bse_approx(self): + model, results = self.construct_model() + bse = results._cov_params_approx().diagonal() ** 0.5 + assert_allclose(bse**2, self.true["var_oim"], atol=1e-5) + + +class TestDynamicFactor_exog2(CheckDynamicFactor): + """ + Test for a dynamic factor model with 2 exogenous regressors: a constant + and a time-trend + """ + + def construct_model(self): + true = results_dynamic_factor.lutkepohl_dfm_exog2.copy() + true["predict"] = output_results.iloc[1:][ + ["predict_dfm_exog2_1", "predict_dfm_exog2_2", "predict_dfm_exog2_3"] + ] + true["dynamic_predict"] = output_results.iloc[1:][ + [ + "dyn_predict_dfm_exog2_1", + "dyn_predict_dfm_exog2_2", + "dyn_predict_dfm_exog2_3", + ] + ] + exog = np.c_[np.ones((75, 1)), (np.arange(75) + 2)[:, np.newaxis]] + return super().setup_model(true, k_factors=1, factor_order=1, exog=exog) + + def test_bse_approx(self): + model, results = self.construct_model() + bse = results._cov_params_approx().diagonal() ** 0.5 + assert_allclose(bse**2, self.true["var_oim"], atol=1e-5) + + def test_predict(self): + exog = np.c_[np.ones((16, 1)), (np.arange(75, 75 + 16) + 2)[:, np.newaxis]] + super().test_predict(exog=exog) + + def test_dynamic_predict(self): + exog = np.c_[np.ones((16, 1)), (np.arange(75, 75 + 16) + 2)[:, np.newaxis]] + super().test_dynamic_predict(exog=exog) + + def test_summary(self): + model, results = self.construct_model() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + summary = results.summary() + tables = [str(table) for table in summary.tables] + params = self.true["params"] + + # Make sure we have the right number of tables + assert_equal(len(tables), 2 + model.k_endog + model.k_factors + 1) + + # Check the model overview table + assert re.search(r"Model:.*DynamicFactor\(factors=1, order=1\)", tables[0]) + assert_equal(re.search(r".*2 regressors", tables[0]) is None, False) + + # For each endogenous variable, check the output + for i in range(model.k_endog): + offset_loading = model.k_factors * i + offset_exog = model.k_factors * model.k_endog + table = tables[i + 2] + + # -> Make sure we have the right table / table name + name = model.endog_names[i] + assert re.search(f"Results for equation {name}", table) + + # -> Make sure it's the right size + assert_equal(len(table.split("\n")), 8) + + # -> Check that we have the right coefficients + assert re.search( + "loading.f1 +" + forg(params[offset_loading + 0], prec=4), table + ) + assert re.search( + "beta.const +" + forg(params[offset_exog + i * 2 + 0], prec=4), table + ) + assert re.search( + "beta.x1 +" + forg(params[offset_exog + i * 2 + 1], prec=4), table + ) + + # For each factor, check the output + for i in range(model.k_factors): + offset = model.k_endog * (model.k_factors + 3) + i * model.k_factors + table = tables[model.k_endog + i + 2] + + # -> Make sure we have the right table / table name + assert re.search(f"Results for factor equation f{i + 1:d}", table) + + # -> Make sure it's the right size + assert_equal(len(table.split("\n")), 6) + + # -> Check that we have the right coefficients + assert re.search("L1.f1 +" + forg(params[offset + 0], prec=4), table) + + # Check the Error covariance matrix output + table = tables[2 + model.k_endog + model.k_factors] + + # -> Make sure we have the right table / table name + assert re.search("Error covariance matrix", table) + + # -> Make sure it's the right size + assert_equal(len(table.split("\n")), 8) + + # -> Check that we have the right coefficients + offset = model.k_endog * (model.k_factors + 2) + for i in range(model.k_endog): + iname = model.endog_names[i] + iparam = forg(params[offset + i], prec=4) + assert re.search(f"sigma2.{iname} +{iparam}", table) + + +class TestDynamicFactor_general_errors(CheckDynamicFactor): + """ + Test for a dynamic factor model where errors are as general as possible, + meaning: + + - Errors are vector autocorrelated, VAR(1) + - Innovations are correlated + """ + + def construct_model(self): + true = results_dynamic_factor.lutkepohl_dfm_gen.copy() + true["predict"] = output_results.iloc[1:][ + ["predict_dfm_gen_1", "predict_dfm_gen_2", "predict_dfm_gen_3"] + ] + true["dynamic_predict"] = output_results.iloc[1:][ + ["dyn_predict_dfm_gen_1", "dyn_predict_dfm_gen_2", "dyn_predict_dfm_gen_3"] + ] + return super().setup_model( + true, + k_factors=1, + factor_order=1, + error_var=True, + error_order=1, + error_cov_type="unstructured", + ) + + def test_bse_approx(self): + model, results = self.construct_model() + bse = results._cov_params_approx().diagonal() + assert_allclose(bse[:3], self.true["var_oim"][:3], atol=1e-5) + assert_allclose(bse[-10:], self.true["var_oim"][-10:], atol=3e-4) + + @pytest.mark.skip( + "Known failure, no sequence of optimizers has been " + "found which can achieve the maximum." + ) + def test_mle(self): + # The following gets us to llf=546.53, which is still not good enough + # llf = 300.842477412 + # res = mod.fit(method='lbfgs', maxiter=10000) + # llf = 460.26576722 + # res = mod.fit(res.params, method='nm', maxiter=10000, maxfev=10000) + # llf = 542.245718508 + # res = mod.fit(res.params, method='lbfgs', maxiter=10000) + # llf = 544.035160955 + # res = mod.fit(res.params, method='nm', maxiter=10000, maxfev=10000) + # llf = 557.442240083 + # res = mod.fit(res.params, method='lbfgs', maxiter=10000) + # llf = 558.199513262 + # res = mod.fit(res.params, method='nm', maxiter=10000, maxfev=10000) + # llf = 559.049076604 + # res = mod.fit(res.params, method='nm', maxiter=10000, maxfev=10000) + # llf = 559.049076604 + # ... + pass + + def test_summary(self): + model, results = self.construct_model() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + summary = results.summary() + tables = [str(table) for table in summary.tables] + params = self.true["params"] + + # Make sure we have the right number of tables + assert_equal( + len(tables), + 2 + model.k_endog + model.k_factors + model.k_endog + 1, + ) + + # Check the model overview table + assert re.search(r"Model:.*DynamicFactor\(factors=1, order=1\)", tables[0]) + assert re.search(r".*VAR\(1\) errors", tables[0]) + + # For each endogenous variable, check the output + for i in range(model.k_endog): + offset_loading = model.k_factors * i + table = tables[i + 2] + + # -> Make sure we have the right table / table name + name = model.endog_names[i] + assert re.search(f"Results for equation {name}", table) + + # -> Make sure it's the right size + assert_equal(len(table.split("\n")), 6) + + # -> Check that we have the right coefficients + pattern = "loading.f1 +" + forg(params[offset_loading + 0], prec=4) + assert re.search(pattern, table) + + # For each factor, check the output + for i in range(model.k_factors): + offset = model.k_endog * model.k_factors + 6 + i * model.k_factors + table = tables[2 + model.k_endog + i] + + # -> Make sure we have the right table / table name + assert re.search(f"Results for factor equation f{i + 1:d}", table) + + # -> Make sure it's the right size + assert_equal(len(table.split("\n")), 6) + + # -> Check that we have the right coefficients + assert re.search("L1.f1 +" + forg(params[offset + 0], prec=4), table) + + # For each error equation, check the output + for i in range(model.k_endog): + offset = model.k_endog * (model.k_factors + i) + 6 + model.k_factors + table = tables[2 + model.k_endog + model.k_factors + i] + + # -> Make sure we have the right table / table name + name = model.endog_names[i] + assert re.search(fr"Results for error equation e\({name}\)", table) + + # -> Make sure it's the right size + assert_equal(len(table.split("\n")), 8) + + # -> Check that we have the right coefficients + for j in range(model.k_endog): + name = model.endog_names[j] + pattern = rf"L1.e\({name}\) +{forg(params[offset + j], prec=4)}" + assert re.search(pattern, table) + + # Check the Error covariance matrix output + table = tables[2 + model.k_endog + model.k_factors + model.k_endog] + + # -> Make sure we have the right table / table name + assert re.search("Error covariance matrix", table) + + # -> Make sure it's the right size + assert_equal(len(table.split("\n")), 11) + + # -> Check that we have the right coefficients + offset = model.k_endog * model.k_factors + assert re.search(r"cov.chol\[1,1\] +" + forg(params[offset + 0], prec=4), table) + assert re.search(r"cov.chol\[2,1\] +" + forg(params[offset + 1], prec=4), table) + assert re.search(r"cov.chol\[2,2\] +" + forg(params[offset + 2], prec=4), table) + assert re.search(r"cov.chol\[3,1\] +" + forg(params[offset + 3], prec=4), table) + assert re.search(r"cov.chol\[3,2\] +" + forg(params[offset + 4], prec=4), table) + assert re.search(r"cov.chol\[3,3\] +" + forg(params[offset + 5], prec=4), table) + + +class TestDynamicFactor_ar2_errors(CheckDynamicFactor): + """ + Test for a dynamic factor model where errors are as general as possible, + meaning: + + - Errors are vector autocorrelated, VAR(1) + - Innovations are correlated + """ + + def construct_model(self): + true = results_dynamic_factor.lutkepohl_dfm_ar2.copy() + true["predict"] = output_results.iloc[1:][ + ["predict_dfm_ar2_1", "predict_dfm_ar2_2", "predict_dfm_ar2_3"] + ] + true["dynamic_predict"] = output_results.iloc[1:][ + ["dyn_predict_dfm_ar2_1", "dyn_predict_dfm_ar2_2", "dyn_predict_dfm_ar2_3"] + ] + return super().setup_model(true, k_factors=1, factor_order=1, error_order=2) + + def test_bse_approx(self): + model, results = self.construct_model() + bse = results._cov_params_approx().diagonal() + assert_allclose(bse, self.true["var_oim"], atol=1e-5) + + def test_mle(self): + with warnings.catch_warnings(record=True): + # Depending on the system, this test can reach a greater precision, + # but for cross-platform results keep it at 1e-2 + mod, results = self.construct_model() + res1 = mod.fit(maxiter=100, optim_score="approx", disp=False) + res = mod.fit( + res1.params, + method="nm", + maxiter=10000, + optim_score="approx", + disp=False, + ) + # Added rtol to catch spurious failures on some platforms + model, results = self.construct_model() + assert_allclose(res.llf, results.llf, atol=1e-2, rtol=1e-3) + + +class TestDynamicFactor_scalar_error(CheckDynamicFactor): + """ + Test for a dynamic factor model where innovations are uncorrelated and + are forced to have the same variance. + """ + + def construct_model(self): + true = results_dynamic_factor.lutkepohl_dfm_scalar.copy() + true["predict"] = output_results.iloc[1:][ + ["predict_dfm_scalar_1", "predict_dfm_scalar_2", "predict_dfm_scalar_3"] + ] + true["dynamic_predict"] = output_results.iloc[1:][ + [ + "dyn_predict_dfm_scalar_1", + "dyn_predict_dfm_scalar_2", + "dyn_predict_dfm_scalar_3", + ] + ] + exog = np.ones((75, 1)) + return super().setup_model( + true, k_factors=1, factor_order=1, exog=exog, error_cov_type="scalar" + ) + + def test_bse_approx(self): + model, results = self.construct_model() + bse = results._cov_params_approx().diagonal() + assert_allclose(bse, self.true["var_oim"], atol=1e-5) + + def test_predict(self): + exog = np.ones((16, 1)) + super().test_predict(exog=exog) + + def test_dynamic_predict(self): + exog = np.ones((16, 1)) + super().test_dynamic_predict(exog=exog) + + +class TestStaticFactor(CheckDynamicFactor): + """ + Test for a static factor model (i.e., factors are not autocorrelated). + """ + + def construct_model(self): + true = results_dynamic_factor.lutkepohl_sfm.copy() + true["predict"] = output_results.iloc[1:][ + ["predict_sfm_1", "predict_sfm_2", "predict_sfm_3"] + ] + true["dynamic_predict"] = output_results.iloc[1:][ + ["dyn_predict_sfm_1", "dyn_predict_sfm_2", "dyn_predict_sfm_3"] + ] + return super().setup_model(true, k_factors=1, factor_order=0) + + def test_bse_approx(self): + model, results = self.construct_model() + bse = results._cov_params_approx().diagonal() + assert_allclose(bse, self.true["var_oim"], atol=1e-5) + + def test_bic(self): + # Stata uses 5 df (i.e., 5 params) here instead of 6, because one param + # is basically zero. + pass + + +class TestSUR(CheckDynamicFactor): + """ + Test for a seemingly unrelated regression model (i.e., no factors) with + errors cross-sectionally, but not auto-, correlated + """ + + def construct_model(self): + true = results_dynamic_factor.lutkepohl_sur.copy() + true["predict"] = output_results.iloc[1:][ + ["predict_sur_1", "predict_sur_2", "predict_sur_3"] + ] + true["dynamic_predict"] = output_results.iloc[1:][ + ["dyn_predict_sur_1", "dyn_predict_sur_2", "dyn_predict_sur_3"] + ] + exog = np.c_[np.ones((75, 1)), (np.arange(75) + 2)[:, np.newaxis]] + return super().setup_model( + true, k_factors=0, factor_order=0, exog=exog, error_cov_type="unstructured" + ) + + def test_bse_approx(self): + model, results = self.construct_model() + bse = results._cov_params_approx().diagonal() + assert_allclose(bse[:6], self.true["var_oim"][:6], atol=1e-5) + + def test_predict(self): + exog = np.c_[np.ones((16, 1)), (np.arange(75, 75 + 16) + 2)[:, np.newaxis]] + super().test_predict(exog=exog) + + def test_dynamic_predict(self): + exog = np.c_[np.ones((16, 1)), (np.arange(75, 75 + 16) + 2)[:, np.newaxis]] + super().test_dynamic_predict(exog=exog) + + +class TestSUR_autocorrelated_errors(CheckDynamicFactor): + """ + Test for a seemingly unrelated regression model (i.e., no factors) where + the errors are vector autocorrelated, but innovations are uncorrelated. + """ + + def construct_model(self): + true = results_dynamic_factor.lutkepohl_sur_auto.copy() + true["predict"] = output_results.iloc[1:][ + ["predict_sur_auto_1", "predict_sur_auto_2"] + ] + true["dynamic_predict"] = output_results.iloc[1:][ + ["dyn_predict_sur_auto_1", "dyn_predict_sur_auto_2"] + ] + exog = np.c_[np.ones((75, 1)), (np.arange(75) + 2)[:, np.newaxis]] + return super().setup_model( + true, + k_factors=0, + factor_order=0, + exog=exog, + error_order=1, + error_var=True, + error_cov_type="diagonal", + included_vars=["dln_inv", "dln_inc"], + ) + + def test_bse_approx(self): + model, results = self.construct_model() + bse = results._cov_params_approx().diagonal() + assert_allclose(bse, self.true["var_oim"], atol=1e-5) + + def test_predict(self): + exog = np.c_[np.ones((16, 1)), (np.arange(75, 75 + 16) + 2)[:, np.newaxis]] + super().test_predict(exog=exog) + + def test_dynamic_predict(self): + exog = np.c_[np.ones((16, 1)), (np.arange(75, 75 + 16) + 2)[:, np.newaxis]] + super().test_dynamic_predict(exog=exog) + + def test_mle(self): + super().test_mle(init_powell=False) + + +def test_misspecification(): + # Tests for model specification and misspecification exceptions + endog = np.arange(20).reshape(10, 2) + + # Too few endog + with pytest.raises(ValueError): + dynamic_factor.DynamicFactor(endog[:, 0], k_factors=0, factor_order=0) + + # Too many factors + with pytest.raises(ValueError): + dynamic_factor.DynamicFactor(endog, k_factors=2, factor_order=1) + + # Bad error_cov_type specification + with pytest.raises(ValueError): + dynamic_factor.DynamicFactor( + endog, k_factors=1, factor_order=1, order=(1, 0), error_cov_type="" + ) + + +def test_miscellaneous(): + # Initialization with 1-dimensional exog array + exog = np.arange(75) + mod = CheckDynamicFactor() + mod.setup_model(true=None, k_factors=1, factor_order=1, exog=exog, filter=False) + exog = pd.Series( + np.arange(75), + index=pd.date_range(start="1960-04-01", end="1978-10-01", freq="QS"), + ) + mod = CheckDynamicFactor() + mod.setup_model(true=None, k_factors=1, factor_order=1, exog=exog, filter=False) + + +def test_predict_custom_index(): + rs = np.random.RandomState(328423) + endog = pd.DataFrame(rs.normal(size=(50, 2))) + mod = dynamic_factor.DynamicFactor(endog, k_factors=1, factor_order=1) + res = mod.smooth(mod.start_params) + out = res.predict(start=1, end=1, index=["a"]) + assert_equal(out.index.equals(pd.Index(["a"])), True) + + +def test_forecast_exog(): + # Test forecasting with various shapes of `exog` + nobs = 100 + endog = np.ones((nobs, 2)) * 2.0 + exog = np.ones(nobs) + + mod = dynamic_factor.DynamicFactor(endog, exog=exog, k_factors=1, factor_order=1) + res = mod.smooth(np.r_[[0] * 2, 2.0, 2.0, 1, 1.0, 0.0]) + + # 1-step-ahead, valid + exog_fcast_scalar = 1.0 + exog_fcast_1dim = np.ones(1) + exog_fcast_2dim = np.ones((1, 1)) + + assert_allclose(res.forecast(1, exog=exog_fcast_scalar), 2.0) + assert_allclose(res.forecast(1, exog=exog_fcast_1dim), 2.0) + assert_allclose(res.forecast(1, exog=exog_fcast_2dim), 2.0) + + # h-steps-ahead, valid + h = 10 + exog_fcast_1dim = np.ones(h) + exog_fcast_2dim = np.ones((h, 1)) + + assert_allclose(res.forecast(h, exog=exog_fcast_1dim), 2.0) + assert_allclose(res.forecast(h, exog=exog_fcast_2dim), 2.0) + + # h-steps-ahead, invalid + with pytest.raises(ValueError): + res.forecast(h, exog=1.0) + with pytest.raises(ValueError): + res.forecast(h, exog=[1, 2]) + with pytest.raises(ValueError): + res.forecast(h, exog=np.ones((h, 2))) + + +def check_equivalent_models(mod, mod2): + attrs = [ + "k_factors", + "factor_order", + "error_order", + "error_var", + "error_cov_type", + "enforce_stationarity", + "mle_regression", + "k_params", + ] + + ssm_attrs = [ + "nobs", + "k_endog", + "k_states", + "k_posdef", + "obs_intercept", + "design", + "obs_cov", + "state_intercept", + "transition", + "selection", + "state_cov", + ] + + for attr in attrs: + assert_equal(getattr(mod2, attr), getattr(mod, attr)) + + for attr in ssm_attrs: + assert_equal(getattr(mod2.ssm, attr), getattr(mod.ssm, attr)) + + assert_equal(mod2._get_init_kwds(), mod._get_init_kwds()) + + +def test_recreate_model(): + nobs = 100 + endog = np.ones((nobs, 3)) * 2.0 + exog = np.ones(nobs) + + k_factors = [0, 1, 2] + factor_orders = [0, 1, 2] + error_orders = [0, 1] + error_vars = [False, True] + error_cov_types = ["diagonal", "scalar"] + + import itertools + + names = ["k_factors", "factor_order", "error_order", "error_var", "error_cov_type"] + for element in itertools.product( + k_factors, factor_orders, error_orders, error_vars, error_cov_types + ): + kwargs = dict(zip(names, element, strict=True)) + + mod = dynamic_factor.DynamicFactor(endog, exog=exog, **kwargs) + mod2 = dynamic_factor.DynamicFactor(endog, exog=exog, **mod._get_init_kwds()) + check_equivalent_models(mod, mod2) + + +def test_append_results(): + endog = np.arange(200).reshape(100, 2) + exog = np.ones(100) + params = [0.1, -0.2, 1.0, 2.0, 1.0, 1.0, 0.5, 0.1] + + mod1 = dynamic_factor.DynamicFactor(endog, k_factors=1, factor_order=2, exog=exog) + res1 = mod1.smooth(params) + + mod2 = dynamic_factor.DynamicFactor( + endog[:50], k_factors=1, factor_order=2, exog=exog[:50] + ) + res2 = mod2.smooth(params) + res3 = res2.append(endog[50:], exog=exog[50:]) + + assert_equal(res1.specification, res3.specification) + + assert_allclose(res3.cov_params_default, res2.cov_params_default) + for attr in ["nobs", "llf", "llf_obs", "loglikelihood_burn"]: + assert_equal(getattr(res3, attr), getattr(res1, attr)) + + for attr in [ + "filtered_state", + "filtered_state_cov", + "predicted_state", + "predicted_state_cov", + "forecasts", + "forecasts_error", + "forecasts_error_cov", + "standardized_forecasts_error", + "forecasts_error_diffuse_cov", + "predicted_diffuse_state_cov", + "scaled_smoothed_estimator", + "scaled_smoothed_estimator_cov", + "smoothing_error", + "smoothed_state", + "smoothed_state_cov", + "smoothed_state_autocov", + "smoothed_measurement_disturbance", + "smoothed_state_disturbance", + "smoothed_measurement_disturbance_cov", + "smoothed_state_disturbance_cov", + ]: + assert_equal(getattr(res3, attr), getattr(res1, attr)) + + assert_allclose( + res3.forecast(10, exog=np.ones(10)), res1.forecast(10, exog=np.ones(10)) + ) + + +def test_extend_results(): + endog = np.arange(200).reshape(100, 2) + exog = np.ones(100) + params = [0.1, -0.2, 1.0, 2.0, 1.0, 1.0, 0.5, 0.1] + + mod1 = dynamic_factor.DynamicFactor(endog, k_factors=1, factor_order=2, exog=exog) + res1 = mod1.smooth(params) + + mod2 = dynamic_factor.DynamicFactor( + endog[:50], k_factors=1, factor_order=2, exog=exog[:50] + ) + res2 = mod2.smooth(params) + res3 = res2.extend(endog[50:], exog=exog[50:]) + + assert_allclose(res3.llf_obs, res1.llf_obs[50:]) + + for attr in [ + "filtered_state", + "filtered_state_cov", + "predicted_state", + "predicted_state_cov", + "forecasts", + "forecasts_error", + "forecasts_error_cov", + "standardized_forecasts_error", + "forecasts_error_diffuse_cov", + "predicted_diffuse_state_cov", + "scaled_smoothed_estimator", + "scaled_smoothed_estimator_cov", + "smoothing_error", + "smoothed_state", + "smoothed_state_cov", + "smoothed_state_autocov", + "smoothed_measurement_disturbance", + "smoothed_state_disturbance", + "smoothed_measurement_disturbance_cov", + "smoothed_state_disturbance_cov", + ]: + desired = getattr(res1, attr) + if desired is not None: + desired = desired[..., 50:] + assert_equal(getattr(res3, attr), desired) + + assert_allclose( + res3.forecast(10, exog=np.ones(10)), res1.forecast(10, exog=np.ones(10)) + ) + + +def test_apply_results(): + endog = np.arange(200).reshape(100, 2) + exog = np.ones(100) + params = [0.1, -0.2, 1.0, 2.0, 1.0, 1.0, 0.5, 0.1] + + mod1 = dynamic_factor.DynamicFactor( + endog[:50], k_factors=1, factor_order=2, exog=exog[:50] + ) + res1 = mod1.smooth(params) + + mod2 = dynamic_factor.DynamicFactor( + endog[50:], k_factors=1, factor_order=2, exog=exog[50:] + ) + res2 = mod2.smooth(params) + + res3 = res2.apply(endog[:50], exog=exog[:50]) + + assert_equal(res1.specification, res3.specification) + + assert_allclose(res3.cov_params_default, res2.cov_params_default) + for attr in ["nobs", "llf", "llf_obs", "loglikelihood_burn"]: + assert_equal(getattr(res3, attr), getattr(res1, attr)) + + for attr in [ + "filtered_state", + "filtered_state_cov", + "predicted_state", + "predicted_state_cov", + "forecasts", + "forecasts_error", + "forecasts_error_cov", + "standardized_forecasts_error", + "forecasts_error_diffuse_cov", + "predicted_diffuse_state_cov", + "scaled_smoothed_estimator", + "scaled_smoothed_estimator_cov", + "smoothing_error", + "smoothed_state", + "smoothed_state_cov", + "smoothed_state_autocov", + "smoothed_measurement_disturbance", + "smoothed_state_disturbance", + "smoothed_measurement_disturbance_cov", + "smoothed_state_disturbance_cov", + ]: + assert_equal(getattr(res3, attr), getattr(res1, attr)) + + assert_allclose( + res3.forecast(10, exog=np.ones(10)), res1.forecast(10, exog=np.ones(10)) + ) + + +def test_start_params_nans(): + ix = pd.date_range("1960-01-01", "1982-10-01", freq="QS") + dta = ( + np.log( + pd.DataFrame( + results_varmax.lutkepohl_data, + columns=["inv", "inc", "consump"], + index=ix, + ) + ) + .diff() + .iloc[1:] + ) + + endog1 = dta.iloc[:-1] + mod1 = dynamic_factor.DynamicFactor(endog1, k_factors=1, factor_order=1) + endog2 = dta.copy() + endog2.iloc[-1:] = np.nan + mod2 = dynamic_factor.DynamicFactor(endog2, k_factors=1, factor_order=1) + + assert_allclose(mod2.start_params, mod1.start_params) + + +def test_summary_after_remove_data(): + # summary() must still work after remove_data() has been called + dta = pd.DataFrame( + results_varmax.lutkepohl_data, + columns=["inv", "inc", "consump"], + index=pd.date_range("1960-01-01", "1982-10-01", freq="QS"), + ) + dta["dln_inv"] = np.log(dta["inv"]).diff() + dta["dln_inc"] = np.log(dta["inc"]).diff() + dta["dln_consump"] = np.log(dta["consump"]).diff() + endog = dta.loc[ + "1960-04-01":"1978-10-01", ["dln_inv", "dln_inc", "dln_consump"] + ] + + true = results_dynamic_factor.lutkepohl_sfm.copy() + mod = dynamic_factor.DynamicFactor(endog, k_factors=1, factor_order=0) + res = mod.smooth(true["params"], cov_type="approx") + + assert isinstance(res.summary(), Summary) + res.remove_data() + assert isinstance(res.summary(), Summary) diff --git a/shared/package-files/cc/cc2ace11447e68e2684db343949425625162d95f35c5cc166c2ae5e4e2db7e00/memory_tracker.py b/shared/package-files/cc/cc2ace11447e68e2684db343949425625162d95f35c5cc166c2ae5e4e2db7e00/memory_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..96a3fa497c04c6419b74d8095ac4d3b4f1f41fa2 --- /dev/null +++ b/shared/package-files/cc/cc2ace11447e68e2684db343949425625162d95f35c5cc166c2ae5e4e2db7e00/memory_tracker.py @@ -0,0 +1,299 @@ +from collections import defaultdict + +from itertools import chain + +import pickle + +from typing import ( + Any, + Callable, + Dict, + List, + no_type_check, + Sequence, +) + +import torch +import torch.nn as nn +from torch.utils.hooks import RemovableHandle +from torch.utils._python_dispatch import TorchDispatchMode + + +BYTES_PER_MB = 1024 * 1024.0 + + +class MemoryProfileDispatchMode(TorchDispatchMode): + """Run in ``TorchDispatchMode`` to get memory stats at operator level.""" + + def __init__(self, memory_tracker) -> None: + self.memory_tracker = memory_tracker + + def __torch_dispatch__(self, func, types, args=..., kwargs=None): + rs = func(*args, **kwargs) + if func == torch.ops.aten.detach.default: + return rs + func_name: str = ( + self.memory_tracker._cur_module_name + + "." + + func.__name__ + + "_" + + str(self.memory_tracker._operator_names[func.__name__]) + ) + self.memory_tracker._operator_names[func.__name__] = ( + self.memory_tracker._operator_names[func.__name__] + 1 + ) + self.memory_tracker._record_memory_stats(func_name) + + return rs + + +class MemoryTracker: + """ + Collect and plot the memory stats at operator level. + + Includes ``memories_allocated``, ``memories_active`` and ``memories_reserved``. + It also prints a summary for the top 20 operators that generate the most memories. + + Example usage: + + >>> # xdoctest: +SKIP(failing) + >>> net.cuda() + >>> input = input.cuda() + + >>> mem_tracker = MemoryTracker() + >>> mem_tracker.start_monitor(net) + + >>> net.zero_grad(True) + >>> loss = net(input) + >>> if isinstance(loss, dict): + >>> loss = loss['out'] + >>> loss.sum().backward() + >>> net.zero_grad(set_to_none=True) + + >>> mem_tracker.stop() + >>> mem_tracker.summary() + >>> mem_tracker.show_traces() + """ + + def __init__(self) -> None: + torch._C._log_api_usage_once("torch.distributed.memory_tracker") + self._hooks: List[RemovableHandle] = [] + self._operator_names: Dict[str, int] = defaultdict(int) + self.memories_allocated: Dict[int, Dict[str, float]] = defaultdict() + self.memories_active: Dict[int, Dict[str, float]] = defaultdict() + self.memories_reserved: Dict[int, Dict[str, float]] = defaultdict() + self._markers: Dict[str, int] = defaultdict(int) + self._cur_module_name: str = "" + self._op_index: int = 0 + self._num_cuda_retries: int = 0 + + @no_type_check + def start_monitor(self, root_module: nn.Module) -> None: + """ + Register module hooks and entering ``MemoryProfileDispatchMode``. + + This enables operator level memory stats can be tracked during module runtime. + """ + self._clear_state() + root_module.__setattr__("_memory_tracker_is_root", True) + for name, m in root_module.named_modules(): + if m is not root_module: + m.__setattr__("_memory_tracker_is_root", False) + # fused_proxy_group does not support hooks + if ".fused_proxy_grouped_embedding_bag" in name: + continue + # hook ordering with other hooks added by users is not managed, so + # the memory stats tracked here may not completely accurate. + h1 = m.register_forward_pre_hook(self._create_pre_forward_hook(name)) + h2 = m.register_forward_hook(self._create_post_forward_hook(name)) + # it does not work well with jagged tensor somehow, the root cause is not + # clear and remove it for now as it does not really capture important info. + # h3 = m.register_backward_hook(self._create_backward_hook(name)) + self._hooks.extend([h1, h2]) + torch.cuda.empty_cache() + assert getattr(self, "profile_mode", None) is None + self.profile_mode = MemoryProfileDispatchMode(self) + self.profile_mode.__enter__() + + @no_type_check + def stop(self) -> None: + """ + Remove module hooks and exit ``MemoryProfileDispatchMode`` to stop tracking memory stats at operator level. + + Get some aggregated stats when the memory_tracker() is enabled, like cuda ``num_alloc_retries``. + """ + self._num_cuda_retries = torch.cuda.memory_stats().get("num_alloc_retries", 0) + + for h in self._hooks: + h.remove() + self._hooks.clear() + assert getattr(self, "profile_mode", None) is not None + self.profile_mode.__exit__(None, None, None) + self.profile_mode = None + + @no_type_check + def summary(self, top: int = 20) -> None: + """ + Print out the top operators that generate the most memories. + + The number of the top operators can be configured. + """ + op_diff: Dict[str, float] = defaultdict(float) + op_name, previous_allocated_memory = self.memories_allocated[0] + for i in range(1, self._op_index): + op_name, current_allocated_memory = self.memories_allocated[i] + op_diff[op_name] = current_allocated_memory - previous_allocated_memory + previous_allocated_memory = current_allocated_memory + + print("------------------------------------------------") + print(f"The number of cuda retries are: {self._num_cuda_retries}") + print(f"Top {top} ops that generates memory are:") + for k, v in sorted(op_diff.items(), key=lambda item: item[1], reverse=True)[ + :top + ]: + print(f"{k}: {v}MB") + print("------------------------------------------------") + + @no_type_check + def show_traces(self, path: str = "") -> None: + import matplotlib.pyplot as plt + + def _plot_figure(x, y_values, labels): + min_val = min(list(chain(*y_values))) * 0.999 + max_val = max(list(chain(*y_values))) * 1.001 + plt.figure() + for y, label in zip(y_values, labels): + plt.plot(x, y, label=label) + plt.xlabel("# Operator Calls") + plt.ylabel("Memory (MB)") + plt.legend() + for marker_name, marker in self._markers.items(): + if marker_name == "fw_bw_boundary": + plt.plot( + [marker, marker], + [min_val, max_val], + "r", + lw=2, + label=marker_name, + ) + else: + plt.plot( + [marker, marker], + [min_val, max_val], + "k-", + lw=2, + label=marker_name, + ) + + if path != "": + self.load(path) + + y_1 = [gb for (name, gb) in self.memories_allocated.values()] + y_2 = [gb for (name, gb) in self.memories_active.values()] + y_3 = [gb for (name, gb) in self.memories_reserved.values()] + x = list(range(len(y_1))) + # Split figures when there is big difference between + # "reserved_memory" and "allocated_memory" or "active_memory". + _plot_figure( + x, + [list(y_1), list(y_2), list(y_3)], + ["allocated_memory", "active_memory", "reserved_memory"], + ) + _plot_figure(x, [list(y_1)], ["allocated_memory"]) + _plot_figure(x, [list(y_2)], ["active_memory"]) + _plot_figure(x, [list(y_3)], ["reserved_memory"]) + + def save_stats(self, path: str) -> None: + """Save the stats using pickle during runtime if users want to plot the traces in other places like notebook.""" + stats = { + "memories_allocated": self.memories_allocated, + "memories_active": self.memories_active, + "memories_reserved": self.memories_reserved, + "markers": self._markers, + "num_alloc_retries": self._num_cuda_retries, + } + + with open(path, "wb") as f: + pickle.dump(stats, f, pickle.HIGHEST_PROTOCOL) + + def load(self, path: str) -> None: + """Load the pickled memory stats to plot the traces or print the summary.""" + with open(path, "rb") as f: + stats = pickle.load(f) + + self.memories_allocated = stats["memories_allocated"] + self.memories_active = stats["memories_active"] + self.memories_reserved = stats["memories_reserved"] + self._markers = stats["markers"] + self._num_cuda_retries = stats["num_alloc_retries"] + + def _create_pre_forward_hook(self, name: str) -> Callable: + """Prefix operator name with current module and 'forward', and insert 'fw_start' marker at forward pass start.""" + def _pre_forward_hook(module: nn.Module, inputs: Any) -> None: + self._cur_module_name = f"{name}.forward" + if ( + hasattr(module, "_memory_tracker_is_root") + and module._memory_tracker_is_root + ): + self._add_marker("fw_start") + + return _pre_forward_hook + + def _create_post_forward_hook(self, name: str) -> Callable: + """Insert the marker 'fw_bw_boundary' at the boundary of forward and backward pass.""" + + def _post_forward_hook( + module: nn.Module, + inputs: Sequence[torch.Tensor], + outputs: Sequence[torch.Tensor], + ) -> None: + if ( + hasattr(module, "_memory_tracker_is_root") + and module._memory_tracker_is_root + ): + self._add_marker("fw_bw_boundary") + + return _post_forward_hook + + def _create_backward_hook(self, name: str) -> Callable: + """Insert the current module name with backward prefix for the operator name.""" + + def _backward_hook( + module: nn.Module, grad_input: torch.Tensor, grad_output: torch.Tensor + ) -> None: + self._cur_module_name = f"{name}.backward" + + return _backward_hook + + @no_type_check + def _record_memory_stats(self, fn_name: str) -> None: + """ + Record current memory allocated, current memory active and current memory reserved. + + The memory stats dict is indexed with ``self._op_index``. + """ + memory_allocated: float = torch.cuda.memory_allocated() / BYTES_PER_MB + memory_reserved: float = torch.cuda.memory_reserved() / BYTES_PER_MB + memory_active: float = ( + torch.cuda.memory_stats().get("active_bytes.all.current", 0) / BYTES_PER_MB + ) + self.memories_allocated[self._op_index] = (fn_name, memory_allocated) + self.memories_reserved[self._op_index] = (fn_name, memory_reserved) + self.memories_active[self._op_index] = (fn_name, memory_active) + self._op_index += 1 + + def _add_marker(self, marker_name: str) -> None: + """Set the marker's x-axis value.""" + marker_val = len(self.memories_allocated.values()) + self._markers[marker_name] = marker_val + + def _clear_state(self) -> None: + """Clear states when start_monitor() is called.""" + self._operator_names.clear() + self.memories_allocated.clear() + self.memories_active.clear() + self.memories_reserved.clear() + self._markers.clear() + self._cur_module_name = "" + self._op_index = 0 + self._num_cuda_retries = 0 diff --git a/shared/package-files/cc/cc2bbd7006c57ff2150dbd6c7f98ff5b0e4b612173195c0c86965950fdfbd24c/timestamps.pyi b/shared/package-files/cc/cc2bbd7006c57ff2150dbd6c7f98ff5b0e4b612173195c0c86965950fdfbd24c/timestamps.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c769b09d1b7a1adc4532dd367bcbc4cf522419cd --- /dev/null +++ b/shared/package-files/cc/cc2bbd7006c57ff2150dbd6c7f98ff5b0e4b612173195c0c86965950fdfbd24c/timestamps.pyi @@ -0,0 +1,241 @@ +from datetime import ( + date as _date, + datetime, + time as _time, + timedelta, + tzinfo as _tzinfo, +) +from time import struct_time +from typing import ( + ClassVar, + Literal, + TypeAlias, + overload, +) + +import numpy as np + +from pandas._libs.tslibs import ( + BaseOffset, + NaTType, + Period, + Tick, + Timedelta, +) +from pandas._typing import ( + Self, + TimestampNonexistent, +) + +_TimeZones: TypeAlias = str | _tzinfo | None | int + +def integer_op_not_supported(obj: object) -> TypeError: ... + +class Timestamp(datetime): + _creso: int + min: ClassVar[Timestamp] + max: ClassVar[Timestamp] + + resolution: ClassVar[Timedelta] + _value: int # np.int64 + # error: "__new__" must return a class instance (got "Union[Timestamp, NaTType]") + def __new__( # type: ignore[misc] + cls: type[Self], + ts_input: np.integer | float | str | _date | datetime | np.datetime64 = ..., + year: int | None = ..., + month: int | None = ..., + day: int | None = ..., + hour: int | None = ..., + minute: int | None = ..., + second: int | None = ..., + microsecond: int | None = ..., + tzinfo: _tzinfo | None = ..., + *, + nanosecond: int | None = ..., + tz: _TimeZones = ..., + unit: str | int | None = ..., + fold: int | None = ..., + ) -> Self | NaTType: ... + @classmethod + def _from_value_and_reso( + cls, value: int, reso: int, tz: _TimeZones + ) -> Timestamp: ... + @property + def value(self) -> int: ... # np.int64 + @property + def year(self) -> int: ... + @property + def month(self) -> int: ... + @property + def day(self) -> int: ... + @property + def hour(self) -> int: ... + @property + def minute(self) -> int: ... + @property + def second(self) -> int: ... + @property + def microsecond(self) -> int: ... + @property + def nanosecond(self) -> int: ... + @property + def tzinfo(self) -> _tzinfo | None: ... + @property + def tz(self) -> _tzinfo | None: ... + @property + def fold(self) -> int: ... + @classmethod + def fromtimestamp(cls, ts: float, tz: _TimeZones = ...) -> Self: ... + @classmethod + def utcfromtimestamp(cls, ts: float) -> Self: ... + @classmethod + def today(cls, tz: _TimeZones = ...) -> Self: ... + @classmethod + def fromordinal( + cls, + ordinal: int, + tz: _TimeZones = ..., + ) -> Self: ... + @classmethod + def now(cls, tz: _TimeZones = ...) -> Self: ... + @classmethod + def utcnow(cls) -> Self: ... + # error: Signature of "combine" incompatible with supertype "datetime" + @classmethod + def combine( # type: ignore[override] + cls, date: _date, time: _time + ) -> datetime: ... + @classmethod + def fromisoformat(cls, date_string: str) -> Self: ... + def strftime(self, format: str) -> str: ... + def __format__(self, fmt: str) -> str: ... + def toordinal(self) -> int: ... + def timetuple(self) -> struct_time: ... + def timestamp(self) -> float: ... + def utctimetuple(self) -> struct_time: ... + def date(self) -> _date: ... + def time(self) -> _time: ... + def timetz(self) -> _time: ... + # LSP violation: nanosecond is not present in datetime.datetime.replace + # and has positional args following it + def replace( # type: ignore[override] + self, + year: int | None = ..., + month: int | None = ..., + day: int | None = ..., + hour: int | None = ..., + minute: int | None = ..., + second: int | None = ..., + microsecond: int | None = ..., + nanosecond: int | None = ..., + tzinfo: _tzinfo | type[object] | None = ..., + fold: int | None = ..., + ) -> Self: ... + # LSP violation: datetime.datetime.astimezone has a default value for tz + def astimezone(self, tz: _TimeZones) -> Self: ... # type: ignore[override] + def ctime(self) -> str: ... + def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... + @classmethod + def strptime( + # Note: strptime is actually disabled and raises NotImplementedError + cls, + date_string: str, + format: str, + ) -> Self: ... + def utcoffset(self) -> timedelta | None: ... + def tzname(self) -> str | None: ... + def dst(self) -> timedelta | None: ... + def __le__(self, other: datetime) -> bool: ... # type: ignore[override] + def __lt__(self, other: datetime) -> bool: ... # type: ignore[override] + def __ge__(self, other: datetime) -> bool: ... # type: ignore[override] + def __gt__(self, other: datetime) -> bool: ... # type: ignore[override] + # error: Signature of "__add__" incompatible with supertype "date"/"datetime" + @overload # type: ignore[override] + def __add__(self, other: np.ndarray) -> np.ndarray: ... + @overload + def __add__(self, other: timedelta | np.timedelta64 | Tick) -> Self: ... + def __radd__(self, other: timedelta) -> Self: ... + @overload # type: ignore[override] + def __sub__(self, other: datetime) -> Timedelta: ... + @overload + def __sub__(self, other: timedelta | np.timedelta64 | Tick) -> Self: ... + def __hash__(self) -> int: ... + def weekday(self) -> int: ... + def isoweekday(self) -> int: ... + # Return type "Tuple[int, int, int]" of "isocalendar" incompatible with return + # type "_IsoCalendarDate" in supertype "date" + def isocalendar(self) -> tuple[int, int, int]: ... # type: ignore[override] + @property + def is_leap_year(self) -> bool: ... + @property + def is_month_start(self) -> bool: ... + @property + def is_quarter_start(self) -> bool: ... + @property + def is_year_start(self) -> bool: ... + @property + def is_month_end(self) -> bool: ... + @property + def is_quarter_end(self) -> bool: ... + @property + def is_year_end(self) -> bool: ... + def to_pydatetime(self, warn: bool = ...) -> datetime: ... + def to_datetime64(self) -> np.datetime64: ... + def to_period(self, freq: BaseOffset | str | None = None) -> Period: ... + def to_julian_date(self) -> np.float64: ... + @property + def asm8(self) -> np.datetime64: ... + def tz_convert(self, tz: _TimeZones) -> Self: ... + # TODO: could return NaT? + def tz_localize( + self, + tz: _TimeZones, + ambiguous: bool | Literal["raise", "NaT"] = ..., + nonexistent: TimestampNonexistent = ..., + ) -> Self: ... + def normalize(self) -> Self: ... + # TODO: round/floor/ceil could return NaT? + def round( + self, + freq: str, + ambiguous: bool | Literal["raise", "NaT"] = ..., + nonexistent: TimestampNonexistent = ..., + ) -> Self: ... + def floor( + self, + freq: str, + ambiguous: bool | Literal["raise", "NaT"] = ..., + nonexistent: TimestampNonexistent = ..., + ) -> Self: ... + def ceil( + self, + freq: str, + ambiguous: bool | Literal["raise", "NaT"] = ..., + nonexistent: TimestampNonexistent = ..., + ) -> Self: ... + def day_name(self, locale: str | None = ...) -> str: ... + def month_name(self, locale: str | None = ...) -> str: ... + @property + def day_of_week(self) -> int: ... + @property + def dayofweek(self) -> int: ... + @property + def day_of_year(self) -> int: ... + @property + def dayofyear(self) -> int: ... + @property + def quarter(self) -> int: ... + @property + def week(self) -> int: ... + def to_numpy( + self, dtype: np.dtype | None = ..., copy: bool = ... + ) -> np.datetime64: ... + @property + def _date_repr(self) -> str: ... + @property + def days_in_month(self) -> int: ... + @property + def daysinmonth(self) -> int: ... + @property + def unit(self) -> str: ... + def as_unit(self, unit: str, round_ok: bool = ...) -> Timestamp: ... diff --git a/shared/package-files/cc/cc303d26340b6d599bc2878899f8c50c12323dc04b52a26ad047965ea2b9d2a3/sunspots_monthly.dat b/shared/package-files/cc/cc303d26340b6d599bc2878899f8c50c12323dc04b52a26ad047965ea2b9d2a3/sunspots_monthly.dat new file mode 100644 index 0000000000000000000000000000000000000000..577ce4d8e92b6f68418e4b72f10bad644733b800 --- /dev/null +++ b/shared/package-files/cc/cc303d26340b6d599bc2878899f8c50c12323dc04b52a26ad047965ea2b9d2a3/sunspots_monthly.dat @@ -0,0 +1,323 @@ + MONTHLY MEAN SUNSPOT NUMBERS +=============================================================================== +Year Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec +------------------------------------------------------------------------------- +1749 58.0 62.6 70.0 55.7 85.0 83.5 94.8 66.3 75.9 75.5 158.6 85.2 +1750 73.3 75.9 89.2 88.3 90.0 100.0 85.4 103.0 91.2 65.7 63.3 75.4 + +1751 70.0 43.5 45.3 56.4 60.7 50.7 66.3 59.8 23.5 23.2 28.5 44.0 +1752 35.0 50.0 71.0 59.3 59.7 39.6 78.4 29.3 27.1 46.6 37.6 40.0 +1753 44.0 32.0 45.7 38.0 36.0 31.7 22.0 39.0 28.0 25.0 20.0 6.7 +1754 0.0 3.0 1.7 13.7 20.7 26.7 18.8 12.3 8.2 24.1 13.2 4.2 +1755 10.2 11.2 6.8 6.5 0.0 0.0 8.6 3.2 17.8 23.7 6.8 20.0 + +1756 12.5 7.1 5.4 9.4 12.5 12.9 3.6 6.4 11.8 14.3 17.0 9.4 +1757 14.1 21.2 26.2 30.0 38.1 12.8 25.0 51.3 39.7 32.5 64.7 33.5 +1758 37.6 52.0 49.0 72.3 46.4 45.0 44.0 38.7 62.5 37.7 43.0 43.0 +1759 48.3 44.0 46.8 47.0 49.0 50.0 51.0 71.3 77.2 59.7 46.3 57.0 +1760 67.3 59.5 74.7 58.3 72.0 48.3 66.0 75.6 61.3 50.6 59.7 61.0 + +1761 70.0 91.0 80.7 71.7 107.2 99.3 94.1 91.1 100.7 88.7 89.7 46.0 +1762 43.8 72.8 45.7 60.2 39.9 77.1 33.8 67.7 68.5 69.3 77.8 77.2 +1763 56.5 31.9 34.2 32.9 32.7 35.8 54.2 26.5 68.1 46.3 60.9 61.4 +1764 59.7 59.7 40.2 34.4 44.3 30.0 30.0 30.0 28.2 28.0 26.0 25.7 +1765 24.0 26.0 25.0 22.0 20.2 20.0 27.0 29.7 16.0 14.0 14.0 13.0 + +1766 12.0 11.0 36.6 6.0 26.8 3.0 3.3 4.0 4.3 5.0 5.7 19.2 +1767 27.4 30.0 43.0 32.9 29.8 33.3 21.9 40.8 42.7 44.1 54.7 53.3 +1768 53.5 66.1 46.3 42.7 77.7 77.4 52.6 66.8 74.8 77.8 90.6 111.8 +1769 73.9 64.2 64.3 96.7 73.6 94.4 118.6 120.3 148.8 158.2 148.1 112.0 +1770 104.0 142.5 80.1 51.0 70.1 83.3 109.8 126.3 104.4 103.6 132.2 102.3 + +1771 36.0 46.2 46.7 64.9 152.7 119.5 67.7 58.5 101.4 90.0 99.7 95.7 +1772 100.9 90.8 31.1 92.2 38.0 57.0 77.3 56.2 50.5 78.6 61.3 64.0 +1773 54.6 29.0 51.2 32.9 41.1 28.4 27.7 12.7 29.3 26.3 40.9 43.2 +1774 46.8 65.4 55.7 43.8 51.3 28.5 17.5 6.6 7.9 14.0 17.7 12.2 +1775 4.4 0.0 11.6 11.2 3.9 12.3 1.0 7.9 3.2 5.6 15.1 7.9 + +1776 21.7 11.6 6.3 21.8 11.2 19.0 1.0 24.2 16.0 30.0 35.0 40.0 +1777 45.0 36.5 39.0 95.5 80.3 80.7 95.0 112.0 116.2 106.5 146.0 157.3 +1778 177.3 109.3 134.0 145.0 238.9 171.6 153.0 140.0 171.7 156.3 150.3 105.0 +1779 114.7 165.7 118.0 145.0 140.0 113.7 143.0 112.0 111.0 124.0 114.0 110.0 +1780 70.0 98.0 98.0 95.0 107.2 88.0 86.0 86.0 93.7 77.0 60.0 58.7 + +1781 98.7 74.7 53.0 68.3 104.7 97.7 73.5 66.0 51.0 27.3 67.0 35.2 +1782 54.0 37.5 37.0 41.0 54.3 38.0 37.0 44.0 34.0 23.2 31.5 30.0 +1783 28.0 38.7 26.7 28.3 23.0 25.2 32.2 20.0 18.0 8.0 15.0 10.5 +1784 13.0 8.0 11.0 10.0 6.0 9.0 6.0 10.0 10.0 8.0 17.0 14.0 +1785 6.5 8.0 9.0 15.7 20.7 26.3 36.3 20.0 32.0 47.2 40.2 27.3 + +1786 37.2 47.6 47.7 85.4 92.3 59.0 83.0 89.7 111.5 112.3 116.0 112.7 +1787 134.7 106.0 87.4 127.2 134.8 99.2 128.0 137.2 157.3 157.0 141.5 174.0 +1788 138.0 129.2 143.3 108.5 113.0 154.2 141.5 136.0 141.0 142.0 94.7 129.5 +1789 114.0 125.3 120.0 123.3 123.5 120.0 117.0 103.0 112.0 89.7 134.0 135.5 +1790 103.0 127.5 96.3 94.0 93.0 91.0 69.3 87.0 77.3 84.3 82.0 74.0 + +1791 72.7 62.0 74.0 77.2 73.7 64.2 71.0 43.0 66.5 61.7 67.0 66.0 +1792 58.0 64.0 63.0 75.7 62.0 61.0 45.8 60.0 59.0 59.0 57.0 56.0 +1793 56.0 55.0 55.5 53.0 52.3 51.0 50.0 29.3 24.0 47.0 44.0 45.7 +1794 45.0 44.0 38.0 28.4 55.7 41.5 41.0 40.0 11.1 28.5 67.4 51.4 +1795 21.4 39.9 12.6 18.6 31.0 17.1 12.9 25.7 13.5 19.5 25.0 18.0 + +1796 22.0 23.8 15.7 31.7 21.0 6.7 26.9 1.5 18.4 11.0 8.4 5.1 +1797 14.4 4.2 4.0 4.0 7.3 11.1 4.3 6.0 5.7 6.9 5.8 3.0 +1798 2.0 4.0 12.4 1.1 0.0 0.0 0.0 3.0 2.4 1.5 12.5 9.9 +1799 1.6 12.6 21.7 8.4 8.2 10.6 2.1 0.0 0.0 4.6 2.7 8.6 +1800 6.9 9.3 13.9 0.0 5.0 23.7 21.0 19.5 11.5 12.3 10.5 40.1 + +1801 27.0 29.0 30.0 31.0 32.0 31.2 35.0 38.7 33.5 32.6 39.8 48.2 +1802 47.8 47.0 40.8 42.0 44.0 46.0 48.0 50.0 51.8 38.5 34.5 50.0 +1803 50.0 50.8 29.5 25.0 44.3 36.0 48.3 34.1 45.3 54.3 51.0 48.0 +1804 45.3 48.3 48.0 50.6 33.4 34.8 29.8 43.1 53.0 62.3 61.0 60.0 +1805 61.0 44.1 51.4 37.5 39.0 40.5 37.6 42.7 44.4 29.4 41.0 38.3 + +1806 39.0 29.6 32.7 27.7 26.4 25.6 30.0 26.3 24.0 27.0 25.0 24.0 +1807 12.0 12.2 9.6 23.8 10.0 12.0 12.7 12.0 5.7 8.0 2.6 0.0 +1808 0.0 4.5 0.0 12.3 13.5 13.5 6.7 8.0 11.7 4.7 10.5 12.3 +1809 7.2 9.2 0.9 2.5 2.0 7.7 0.3 0.2 0.4 0.0 0.0 0.0 +1810 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 + +1811 0.0 0.0 0.0 0.0 0.0 0.0 6.6 0.0 2.4 6.1 0.8 1.1 +1812 11.3 1.9 0.7 0.0 1.0 1.3 0.5 15.6 5.2 3.9 7.9 10.1 +1813 0.0 10.3 1.9 16.6 5.5 11.2 18.3 8.4 15.3 27.8 16.7 14.3 +1814 22.2 12.0 5.7 23.8 5.8 14.9 18.5 2.3 8.1 19.3 14.5 20.1 +1815 19.2 32.2 26.2 31.6 9.8 55.9 35.5 47.2 31.5 33.5 37.2 65.0 + +1816 26.3 68.8 73.7 58.8 44.3 43.6 38.8 23.2 47.8 56.4 38.1 29.9 +1817 36.4 57.9 96.2 26.4 21.2 40.0 50.0 45.0 36.7 25.6 28.9 28.4 +1818 34.9 22.4 25.4 34.5 53.1 36.4 28.0 31.5 26.1 31.6 10.9 25.8 +1819 32.8 20.7 3.7 20.2 19.6 35.0 31.4 26.1 14.9 27.5 25.1 30.6 +1820 19.2 26.6 4.5 19.4 29.3 10.8 20.6 25.9 5.2 8.9 7.9 9.1 + +1821 21.5 4.2 5.7 9.2 1.7 1.8 2.5 4.8 4.4 18.8 4.4 0.2 +1822 0.0 0.9 16.1 13.5 1.5 5.6 7.9 2.1 0.0 0.4 0.0 0.0 +1823 0.0 0.0 0.6 0.0 0.0 0.0 0.5 0.0 0.0 0.0 0.0 20.4 +1824 21.7 10.8 0.0 19.4 2.8 0.0 0.0 1.4 20.5 25.2 0.0 0.8 +1825 5.0 15.5 22.4 3.8 15.5 15.4 30.9 25.7 15.7 15.6 11.7 22.0 + +1826 17.7 18.2 36.7 24.0 32.4 37.1 52.5 39.6 18.9 50.6 39.5 68.1 +1827 34.6 47.4 57.8 46.0 56.3 56.7 42.3 53.7 49.6 56.1 48.2 46.1 +1828 52.8 64.4 65.0 61.1 89.1 98.0 54.2 76.4 50.4 54.7 57.0 46.9 +1829 43.0 49.4 72.3 95.0 67.4 73.9 90.8 77.6 52.8 57.2 67.6 56.5 +1830 52.2 72.1 84.6 106.3 66.3 65.1 43.9 50.7 62.1 84.4 81.2 82.1 + +1831 47.5 50.1 93.4 54.5 38.1 33.4 45.2 55.0 37.9 46.3 43.5 28.9 +1832 30.9 55.6 55.1 26.9 41.3 26.7 14.0 8.9 8.2 21.1 14.3 27.5 +1833 11.3 14.9 11.8 2.8 12.9 1.0 7.0 5.7 11.6 7.5 5.9 9.9 +1834 4.9 18.1 3.9 1.4 8.8 7.8 8.7 4.0 11.5 24.8 30.5 34.5 +1835 7.5 24.5 19.7 61.5 43.6 33.2 59.8 59.0 100.8 95.2 100.0 77.5 + +1836 88.6 107.6 98.2 142.9 111.4 124.7 116.7 107.8 95.1 137.4 120.9 206.2 +1837 188.0 175.6 134.6 138.2 111.7 158.0 162.8 134.0 96.3 123.7 107.0 129.8 +1838 144.9 84.8 140.8 126.6 137.6 94.5 108.2 78.8 73.6 90.8 77.4 79.8 +1839 105.6 102.5 77.7 61.8 53.8 54.6 84.8 131.2 132.7 90.9 68.8 63.7 +1840 81.2 87.7 67.8 65.9 69.2 48.5 60.7 57.8 74.0 55.0 54.3 53.7 + +1841 24.1 29.9 29.7 40.2 67.5 55.7 30.8 39.3 36.5 28.5 19.8 38.8 +1842 20.4 22.1 21.7 26.9 24.9 20.5 12.6 26.6 18.4 38.1 40.5 17.6 +1843 13.3 3.5 8.3 9.5 21.1 10.5 9.5 11.8 4.2 5.3 19.1 12.7 +1844 9.4 14.7 13.6 20.8 11.6 3.7 21.2 23.9 7.0 21.5 10.7 21.6 +1845 25.7 43.6 43.3 57.0 47.8 31.1 30.6 32.3 29.6 40.7 39.4 59.7 + +1846 38.7 51.0 63.9 69.3 59.9 65.1 46.5 54.8 107.1 55.9 60.4 65.5 +1847 62.6 44.9 85.7 44.7 75.4 85.3 52.2 140.6 160.9 180.4 138.9 109.6 +1848 159.1 111.8 108.6 107.1 102.2 129.0 139.2 132.6 100.3 132.4 114.6 159.5 +1849 157.0 131.7 96.2 102.5 80.6 81.1 78.0 67.7 93.7 71.5 99.0 97.0 +1850 78.0 89.4 82.6 44.1 61.6 70.0 39.1 61.6 86.2 71.0 54.8 61.0 + +1851 75.5 105.4 64.6 56.5 62.6 63.2 36.1 57.4 67.9 62.5 51.0 71.4 +1852 68.4 66.4 61.2 65.4 54.9 46.9 42.1 39.7 37.5 67.3 54.3 45.4 +1853 41.1 42.9 37.7 47.6 34.7 40.0 45.9 50.4 33.5 42.3 28.8 23.4 +1854 15.4 20.0 20.7 26.5 24.0 21.1 18.7 15.8 22.4 12.6 28.2 21.6 +1855 12.3 11.4 17.4 4.4 9.1 5.3 0.4 3.1 0.0 9.6 4.2 3.1 + +1856 0.5 4.9 0.4 6.5 0.0 5.2 4.6 5.9 4.4 4.5 7.7 7.2 +1857 13.7 7.4 5.2 11.1 28.6 16.0 22.2 16.9 42.4 40.6 31.4 37.2 +1858 39.0 34.9 57.5 38.3 41.4 44.5 56.7 55.3 80.1 91.2 51.9 66.9 +1859 83.7 87.6 90.3 85.7 91.0 87.1 95.2 106.8 105.8 114.6 97.2 81.0 +1860 82.4 88.3 98.9 71.4 107.1 108.6 116.7 100.3 92.2 90.1 97.9 95.6 + +1861 62.3 77.7 101.0 98.5 56.8 88.1 78.0 82.5 79.9 67.2 53.7 80.5 +1862 63.1 64.5 43.6 53.7 64.4 84.0 73.4 62.5 66.6 41.9 50.6 40.9 +1863 48.3 56.7 66.4 40.6 53.8 40.8 32.7 48.1 22.0 39.9 37.7 41.2 +1864 57.7 47.1 66.3 35.8 40.6 57.8 54.7 54.8 28.5 33.9 57.6 28.6 +1865 48.7 39.3 39.5 29.4 34.5 33.6 26.8 37.8 21.6 17.1 24.6 12.8 + +1866 31.6 38.4 24.6 17.6 12.9 16.5 9.3 12.7 7.3 14.1 9.0 1.5 +1867 0.0 0.7 9.2 5.1 2.9 1.5 5.0 4.8 9.8 13.5 9.6 25.2 +1868 15.6 15.7 26.5 36.6 26.7 31.1 29.0 34.4 47.2 61.6 59.1 67.6 +1869 60.9 59.9 52.7 41.0 103.9 108.4 59.2 79.6 80.6 59.3 78.1 104.3 +1870 77.3 114.9 157.6 160.0 176.0 135.6 132.4 153.8 136.0 146.4 147.5 130.0 + +1871 88.3 125.3 143.2 162.4 145.5 91.7 103.0 110.1 80.3 89.0 105.4 90.4 +1872 79.5 120.1 88.4 102.1 107.6 109.9 105.5 92.9 114.6 102.6 112.0 83.9 +1873 86.7 107.0 98.3 76.2 47.9 44.8 66.9 68.2 47.1 47.1 55.4 49.2 +1874 60.8 64.2 46.4 32.0 44.6 38.2 67.8 61.3 28.0 34.3 28.9 29.3 +1875 14.6 21.5 33.8 29.1 11.5 23.9 12.5 14.6 2.4 12.7 17.7 9.9 + +1876 14.3 15.0 30.6 2.3 5.1 1.6 15.2 8.8 9.9 14.3 9.9 8.2 +1877 24.4 8.7 11.9 15.8 21.6 14.2 6.0 6.3 16.9 6.7 14.2 2.2 +1878 3.3 6.6 7.8 0.1 5.9 6.4 0.1 0.0 5.3 1.1 4.1 0.5 +1879 1.0 0.6 0.0 6.2 2.4 4.8 7.5 10.7 6.1 12.3 13.1 7.3 +1880 24.0 27.2 19.3 19.5 23.5 34.1 21.9 48.1 66.0 43.0 30.7 29.6 + +1881 36.4 53.2 51.5 51.6 43.5 60.5 76.9 58.4 53.2 64.4 54.8 47.3 +1882 45.0 69.5 66.8 95.8 64.1 45.2 45.4 40.4 57.7 59.2 84.4 41.8 +1883 60.6 46.9 42.8 82.1 31.5 76.3 80.6 46.0 52.6 83.8 84.5 75.9 +1884 91.5 86.9 87.5 76.1 66.5 51.2 53.1 55.8 61.9 47.8 36.6 47.2 +1885 42.8 71.8 49.8 55.0 73.0 83.7 66.5 50.0 39.6 38.7 30.9 21.7 + +1886 29.9 25.9 57.3 43.7 30.7 27.1 30.3 16.9 21.4 8.6 0.3 13.0 +1887 10.3 13.2 4.2 6.9 20.0 15.7 23.3 21.4 7.4 6.6 6.9 20.7 +1888 12.7 7.1 7.8 5.1 7.0 7.1 3.1 2.8 8.8 2.1 10.7 6.7 +1889 0.8 8.5 6.7 4.3 2.4 6.4 9.4 20.6 6.5 2.1 0.2 6.7 +1890 5.3 0.6 5.1 1.6 4.8 1.3 11.6 8.5 17.2 11.2 9.6 7.8 + +1891 13.5 22.2 10.4 20.5 41.1 48.3 58.8 33.0 53.8 51.5 41.9 32.5 +1892 69.1 75.6 49.9 69.6 79.6 76.3 76.5 101.4 62.8 70.5 65.4 78.6 +1893 75.0 73.0 65.7 88.1 84.7 89.9 88.6 129.2 77.9 80.0 75.1 93.8 +1894 83.2 84.6 52.3 81.6 101.2 98.9 106.0 70.3 65.9 75.5 56.6 60.0 +1895 63.3 67.2 61.0 76.9 67.5 71.5 47.8 68.9 57.7 67.9 47.2 70.7 + +1896 29.0 57.4 52.0 43.8 27.7 49.0 45.0 27.2 61.3 28.7 38.0 42.6 +1897 40.6 29.4 29.1 31.0 20.0 11.3 27.6 21.8 48.1 14.3 8.4 33.3 +1898 30.2 36.4 38.3 14.5 25.8 22.3 9.0 31.4 34.8 34.4 30.9 12.6 +1899 19.5 9.2 18.1 14.2 7.7 20.5 13.5 2.9 8.4 13.0 7.8 10.5 +1900 9.4 13.6 8.6 16.0 15.2 12.1 8.3 4.3 8.3 12.9 4.5 0.3 + +1901 0.2 2.4 4.5 0.0 10.2 5.8 0.7 1.0 0.6 3.7 3.8 0.0 +1902 5.5 0.0 12.4 0.0 2.8 1.4 0.9 2.3 7.6 16.3 10.3 1.1 +1903 8.3 17.0 13.5 26.1 14.6 16.3 27.9 28.8 11.1 38.9 44.5 45.6 +1904 31.6 24.5 37.2 43.0 39.5 41.9 50.6 58.2 30.1 54.2 38.0 54.6 +1905 54.8 85.8 56.5 39.3 48.0 49.0 73.0 58.8 55.0 78.7 107.2 55.5 + +1906 45.5 31.3 64.5 55.3 57.7 63.2 103.6 47.7 56.1 17.8 38.9 64.7 +1907 76.4 108.2 60.7 52.6 42.9 40.4 49.7 54.3 85.0 65.4 61.5 47.3 +1908 39.2 33.9 28.7 57.6 40.8 48.1 39.5 90.5 86.9 32.3 45.5 39.5 +1909 56.7 46.6 66.3 32.3 36.0 22.6 35.8 23.1 38.8 58.4 55.8 54.2 +1910 26.4 31.5 21.4 8.4 22.2 12.3 14.1 11.5 26.2 38.3 4.9 5.8 + +1911 3.4 9.0 7.8 16.5 9.0 2.2 3.5 4.0 4.0 2.6 4.2 2.2 +1912 0.3 0.0 4.9 4.5 4.4 4.1 3.0 0.3 9.5 4.6 1.1 6.4 +1913 2.3 2.9 0.5 0.9 0.0 0.0 1.7 0.2 1.2 3.1 0.7 3.8 +1914 2.8 2.6 3.1 17.3 5.2 11.4 5.4 7.7 12.7 8.2 16.4 22.3 +1915 23.0 42.3 38.8 41.3 33.0 68.8 71.6 69.6 49.5 53.5 42.5 34.5 + +1916 45.3 55.4 67.0 71.8 74.5 67.7 53.5 35.2 45.1 50.7 65.6 53.0 +1917 74.7 71.9 94.8 74.7 114.1 114.9 119.8 154.5 129.4 72.2 96.4 129.3 +1918 96.0 65.3 72.2 80.5 76.7 59.4 107.6 101.7 79.9 85.0 83.4 59.2 +1919 48.1 79.5 66.5 51.8 88.1 111.2 64.7 69.0 54.7 52.8 42.0 34.9 +1920 51.1 53.9 70.2 14.8 33.3 38.7 27.5 19.2 36.3 49.6 27.2 29.9 + +1921 31.5 28.3 26.7 32.4 22.2 33.7 41.9 22.8 17.8 18.2 17.8 20.3 +1922 11.8 26.4 54.7 11.0 8.0 5.8 10.9 6.5 4.7 6.2 7.4 17.5 +1923 4.5 1.5 3.3 6.1 3.2 9.1 3.5 0.5 13.2 11.6 10.0 2.8 +1924 0.5 5.1 1.8 11.3 20.8 24.0 28.1 19.3 25.1 25.6 22.5 16.5 +1925 5.5 23.2 18.0 31.7 42.8 47.5 38.5 37.9 60.2 69.2 58.6 98.6 + +1926 71.8 69.9 62.5 38.5 64.3 73.5 52.3 61.6 60.8 71.5 60.5 79.4 +1927 81.6 93.0 69.6 93.5 79.1 59.1 54.9 53.8 68.4 63.1 67.2 45.2 +1928 83.5 73.5 85.4 80.6 77.0 91.4 98.0 83.8 89.7 61.4 50.3 59.0 +1929 68.9 62.8 50.2 52.8 58.2 71.9 70.2 65.8 34.4 54.0 81.1 108.0 +1930 65.3 49.9 35.0 38.2 36.8 28.8 21.9 24.9 32.1 34.4 35.6 25.8 + +1931 14.6 43.1 30.0 31.2 24.6 15.3 17.4 13.0 19.0 10.0 18.7 17.8 +1932 12.1 10.6 11.2 11.2 17.9 22.2 9.6 6.8 4.0 8.9 8.2 11.0 +1933 12.3 22.2 10.1 2.9 3.2 5.2 2.8 0.2 5.1 3.0 0.6 0.3 +1934 3.4 7.8 4.3 11.3 19.7 6.7 9.3 8.3 4.0 5.7 8.7 15.4 +1935 18.6 20.5 23.1 12.2 27.3 45.7 33.9 30.1 42.1 53.2 64.2 61.5 + +1936 62.8 74.3 77.1 74.9 54.6 70.0 52.3 87.0 76.0 89.0 115.4 123.4 +1937 132.5 128.5 83.9 109.3 116.7 130.3 145.1 137.7 100.7 124.9 74.4 88.8 +1938 98.4 119.2 86.5 101.0 127.4 97.5 165.3 115.7 89.6 99.1 122.2 92.7 +1939 80.3 77.4 64.6 109.1 118.3 101.0 97.6 105.8 112.6 88.1 68.1 42.1 +1940 50.5 59.4 83.3 60.7 54.4 83.9 67.5 105.5 66.5 55.0 58.4 68.3 + +1941 45.6 44.5 46.4 32.8 29.5 59.8 66.9 60.0 65.9 46.3 38.4 33.7 +1942 35.6 52.8 54.2 60.7 25.0 11.4 17.7 20.2 17.2 19.2 30.7 22.5 +1943 12.4 28.9 27.4 26.1 14.1 7.6 13.2 19.4 10.0 7.8 10.2 18.8 +1944 3.7 0.5 11.0 0.3 2.5 5.0 5.0 16.7 14.3 16.9 10.8 28.4 +1945 18.5 12.7 21.5 32.0 30.6 36.2 42.6 25.9 34.9 68.8 46.0 27.4 + +1946 47.6 86.2 76.6 75.7 84.9 73.5 116.2 107.2 94.4 102.3 123.8 121.7 +1947 115.7 133.4 129.8 149.8 201.3 163.9 157.9 188.8 169.4 163.6 128.0 116.5 +1948 108.5 86.1 94.8 189.7 174.0 167.8 142.2 157.9 143.3 136.3 95.8 138.0 +1949 119.1 182.3 157.5 147.0 106.2 121.7 125.8 123.8 145.3 131.6 143.5 117.6 +1950 101.6 94.8 109.7 113.4 106.2 83.6 91.0 85.2 51.3 61.4 54.8 54.1 + +1951 59.9 59.9 55.9 92.9 108.5 100.6 61.5 61.0 83.1 51.6 52.4 45.8 +1952 40.7 22.7 22.0 29.1 23.4 36.4 39.3 54.9 28.2 23.8 22.1 34.3 +1953 26.5 3.9 10.0 27.8 12.5 21.8 8.6 23.5 19.3 8.2 1.6 2.5 +1954 0.2 0.5 10.9 1.8 0.8 0.2 4.8 8.4 1.5 7.0 9.2 7.6 +1955 23.1 20.8 4.9 11.3 28.9 31.7 26.7 40.7 42.7 58.5 89.2 76.9 + +1956 73.6 124.0 118.4 110.7 136.6 116.6 129.1 169.6 173.2 155.3 201.3 192.1 +1957 165.0 130.2 157.4 175.2 164.6 200.7 187.2 158.0 235.8 253.8 210.9 239.4 +1958 202.5 164.9 190.7 196.0 175.3 171.5 191.4 200.2 201.2 181.5 152.3 187.6 +1959 217.4 143.1 185.7 163.3 172.0 168.7 149.6 199.6 145.2 111.4 124.0 125.0 +1960 146.3 106.0 102.2 122.0 119.6 110.2 121.7 134.1 127.2 82.8 89.6 85.6 + +1961 57.9 46.1 53.0 61.4 51.0 77.4 70.2 55.8 63.6 37.7 32.6 39.9 +1962 38.7 50.3 45.6 46.4 43.7 42.0 21.8 21.8 51.3 39.5 26.9 23.2 +1963 19.8 24.4 17.1 29.3 43.0 35.9 19.6 33.2 38.8 35.3 23.4 14.9 +1964 15.3 17.7 16.5 8.6 9.5 9.1 3.1 9.3 4.7 6.1 7.4 15.1 +1965 17.5 14.2 11.7 6.8 24.1 15.9 11.9 8.9 16.8 20.1 15.8 17.0 + +1966 28.2 24.4 25.3 48.7 45.3 47.7 56.7 51.2 50.2 57.2 57.2 70.4 +1967 110.9 93.6 111.8 69.5 86.5 67.3 91.5 107.2 76.8 88.2 94.3 126.4 +1968 121.8 111.9 92.2 81.2 127.2 110.3 96.1 109.3 117.2 107.7 86.0 109.8 +1969 104.4 120.5 135.8 106.8 120.0 106.0 96.8 98.0 91.3 95.7 93.5 97.9 +1970 111.5 127.8 102.9 109.5 127.5 106.8 112.5 93.0 99.5 86.6 95.2 83.5 + +1971 91.3 79.0 60.7 71.8 57.5 49.8 81.0 61.4 50.2 51.7 63.2 82.2 +1972 61.5 88.4 80.1 63.2 80.5 88.0 76.5 76.8 64.0 61.3 41.6 45.3 +1973 43.4 42.9 46.0 57.7 42.4 37.5 23.1 25.6 59.3 30.7 23.9 23.3 +1974 27.6 26.0 21.3 40.3 39.5 36.0 55.8 33.6 40.2 47.1 25.0 20.5 +1975 18.9 11.5 11.5 5.1 9.0 11.4 28.2 39.7 13.9 9.1 19.4 7.8 + +1976 8.1 4.3 21.9 18.8 12.4 12.2 1.9 16.4 13.5 20.6 5.2 15.3 +1977 16.4 23.1 8.7 12.9 18.6 38.5 21.4 30.1 44.0 43.8 29.1 43.2 +1978 51.9 93.6 76.5 99.7 82.7 95.1 70.4 58.1 138.2 125.1 97.9 122.7 +1979 166.6 137.5 138.0 101.5 134.4 149.5 159.4 142.2 188.4 186.2 183.3 176.3 +1980 159.6 155.0 126.2 164.1 179.9 157.3 136.3 135.4 155.0 164.7 147.9 174.4 + +1981 114.0 141.3 135.5 156.4 127.5 90.9 143.8 158.7 167.3 162.4 137.5 150.1 +1982 111.2 163.6 153.8 122.0 82.2 110.4 106.1 107.6 118.8 94.7 98.1 127.0 +1983 84.3 51.0 66.5 80.7 99.2 91.1 82.2 71.8 50.3 55.8 33.3 33.4 +1984 57.0 85.4 83.5 69.7 76.4 46.1 37.4 25.5 15.7 12.0 22.8 18.7 +1985 16.5 15.9 17.2 16.2 27.5 24.2 30.7 11.1 3.9 18.6 16.2 17.3 + +1986 2.5 23.2 15.1 18.5 13.7 1.1 18.1 7.4 3.8 35.4 15.2 6.8 +1987 10.4 2.4 14.7 39.6 33.0 17.4 33.0 38.7 33.9 60.6 39.9 27.1 +1988 59.0 40.0 76.2 88.0 60.1 101.8 113.8 111.6 120.1 125.1 125.1 179.2 +1989 161.3 165.1 131.4 130.6 138.5 196.2 126.9 168.9 176.7 159.4 173.0 165.5 +1990 177.3 130.5 140.3 140.3 132.2 105.4 149.4 200.3 125.2 145.5 131.4 129.7 + +1991 136.9 167.5 141.9 140.0 121.3 169.7 173.7 176.3 125.3 144.1 108.2 144.4 +1992 150.0 161.1 106.7 99.8 73.8 65.2 85.7 64.5 63.9 88.7 91.8 82.6 +1993 59.3 91.0 69.8 62.2 61.3 49.8 57.9 42.2 22.4 56.4 35.6 48.9 +1994 57.8 35.5 31.7 16.1 17.8 28.0 35.1 22.5 25.7 44.0 18.0 26.2 +1995 24.2 29.9 31.1 14.0 14.5 15.6 14.5 14.3 11.8 21.1 9.0 10.0 + +1996 11.5 4.4 9.2 4.8 5.5 11.8 8.2 14.4 1.6 0.9 17.9 13.3 +1997 5.7 7.6 8.7 15.5 18.5 12.7 10.4 24.4 51.3 23.8 39.0 41.2 +1998 31.9 40.3 54.8 53.4 56.3 70.7 66.6 92.2 92.9 55.5 74.0 81.9 +1999 62.0 66.3 68.8 63.7 106.4 137.7 113.5 93.7 71.5 116.7 133.2 84.6 +2000 90.1 112.9 138.5 125.5 121.6 124.9 170.1 130.5 109.7 99.4 106.8 104.4 + +2001 95.6 80.6 113.5 107.7 96.6 134.0 81.8 106.4 150.7 125.5 106.5 132.2 +2002 114.1 107.4 98.4 120.7 120.8 88.3 99.6 116.4 109.6 97.5 95.5 80.8 +2003 79.7 46.0 61.1 60.0 54.6 77.4 83.3 72.7 48.7 65.5 67.3 46.5 +2004 37.3 45.8 49.1 39.3 41.5 43.2 51.1 40.9 27.7 48.0 43.5 17.9 +2005 31.3 29.2 24.5 24.2 42.7 39.3 40.1 36.4 21.9 8.7 18.0 41.1 +2006 15.3 4.9 10.6 30.2 22.3 13.9 12.2 12.9 14.4 10.5 21.4 13.6 +2007 16.8 10.7 4.5 3.4 11.7 12.1 9.7 6.0 2.4 0.9 1.7 10.1 +2008 3.3 2.1 9.3 2.9 3.2 3.4 0.8 0.5 1.1 2.9 4.1 0.8 +2009 1.5 1.4 0.7 1.2 2.9 2.6 +------------------------------------------------------------------------------- +No observations were available during February 1824. The value shown was +interpolated from the January and March monthly means of that year. + + +Note: Data are preliminary after Dec 08. + diff --git a/shared/package-files/cc/cc3133c70548d2525480c85f1c58c9388ed1caeb2aca60ca979314497a2bb5d1/cloneable.h b/shared/package-files/cc/cc3133c70548d2525480c85f1c58c9388ed1caeb2aca60ca979314497a2bb5d1/cloneable.h new file mode 100644 index 0000000000000000000000000000000000000000..aaf30d90974b11bd97dfa7617bc78faf13ded068 --- /dev/null +++ b/shared/package-files/cc/cc3133c70548d2525480c85f1c58c9388ed1caeb2aca60ca979314497a2bb5d1/cloneable.h @@ -0,0 +1,98 @@ +#pragma once + +#include +#include +#include + +#include +#include + +#include +#include + +namespace torch { +namespace nn { +/// The `clone()` method in the base `Module` class does not have knowledge of +/// the concrete runtime type of its subclasses. Therefore, `clone()` must +/// either be called from within the subclass, or from a base class that has +/// knowledge of the concrete type. `Cloneable` uses the CRTP to gain +/// knowledge of the subclass' static type and provide an implementation of the +/// `clone()` method. We do not want to use this pattern in the base class, +/// because then storing a module would always require templatizing it. +template +// NOLINTNEXTLINE(bugprone-exception-escape) +class Cloneable : public Module { + public: + using Module::Module; + + /// `reset()` must perform initialization of all members with reference + /// semantics, most importantly parameters, buffers and submodules. + virtual void reset() = 0; + + /// Performs a recursive "deep copy" of the `Module`, such that all parameters + /// and submodules in the cloned module are different from those in the + /// original module. + std::shared_ptr clone( + const optional& device = nullopt) const override { + NoGradGuard no_grad; + + const auto& self = static_cast(*this); + auto copy = std::make_shared(self); + copy->parameters_.clear(); + copy->buffers_.clear(); + copy->children_.clear(); + copy->reset(); + TORCH_CHECK( + copy->parameters_.size() == parameters_.size(), + "The cloned module does not have the same number of " + "parameters as the original module after calling reset(). " + "Are you sure you called register_parameter() inside reset() " + "and not the constructor?"); + for (const auto& parameter : named_parameters(/*recurse=*/false)) { + auto& tensor = *parameter; + auto data = device && tensor.device() != *device + ? tensor.to(*device) + : autograd::Variable(tensor).clone(); + copy->parameters_[parameter.key()].set_data(data); + } + TORCH_CHECK( + copy->buffers_.size() == buffers_.size(), + "The cloned module does not have the same number of " + "buffers as the original module after calling reset(). " + "Are you sure you called register_buffer() inside reset() " + "and not the constructor?"); + for (const auto& buffer : named_buffers(/*recurse=*/false)) { + auto& tensor = *buffer; + auto data = device && tensor.device() != *device + ? tensor.to(*device) + : autograd::Variable(tensor).clone(); + copy->buffers_[buffer.key()].set_data(data); + } + TORCH_CHECK( + copy->children_.size() == children_.size(), + "The cloned module does not have the same number of " + "child modules as the original module after calling reset(). " + "Are you sure you called register_module() inside reset() " + "and not the constructor?"); + for (const auto& child : children_) { + copy->children_[child.key()]->clone_(*child.value(), device); + } + return copy; + } + + private: + void clone_(Module& other, const optional& device) final { + // Here we are *pretty* certain that `other's` type is `Derived` (because it + // was registered under the same name as `this`), but you never know what + // crazy things `reset()` does, so `dynamic_cast` just to be safe. + auto clone = std::dynamic_pointer_cast(other.clone(device)); + TORCH_CHECK( + clone != nullptr, + "Attempted to clone submodule, but it is of a " + "different type than the submodule it was to be cloned into"); + static_cast(*this) = *clone; + } +}; + +} // namespace nn +} // namespace torch diff --git a/shared/package-files/cc/cc3672969c1dd223eadd9a226e00cac731d8245532408b75ab9a70e9edd28673/de.msg b/shared/package-files/cc/cc3672969c1dd223eadd9a226e00cac731d8245532408b75ab9a70e9edd28673/de.msg new file mode 100644 index 0000000000000000000000000000000000000000..9eb31454b5ce32f90f68e6518378c008a662f5f1 --- /dev/null +++ b/shared/package-files/cc/cc3672969c1dd223eadd9a226e00cac731d8245532408b75ab9a70e9edd28673/de.msg @@ -0,0 +1,54 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset de DAYS_OF_WEEK_ABBREV [list \ + "So"\ + "Mo"\ + "Di"\ + "Mi"\ + "Do"\ + "Fr"\ + "Sa"] + ::msgcat::mcset de DAYS_OF_WEEK_FULL [list \ + "Sonntag"\ + "Montag"\ + "Dienstag"\ + "Mittwoch"\ + "Donnerstag"\ + "Freitag"\ + "Samstag"] + ::msgcat::mcset de MONTHS_ABBREV [list \ + "Jan"\ + "Feb"\ + "Mrz"\ + "Apr"\ + "Mai"\ + "Jun"\ + "Jul"\ + "Aug"\ + "Sep"\ + "Okt"\ + "Nov"\ + "Dez"\ + ""] + ::msgcat::mcset de MONTHS_FULL [list \ + "Januar"\ + "Februar"\ + "M\u00e4rz"\ + "April"\ + "Mai"\ + "Juni"\ + "Juli"\ + "August"\ + "September"\ + "Oktober"\ + "November"\ + "Dezember"\ + ""] + ::msgcat::mcset de BCE "v. Chr." + ::msgcat::mcset de CE "n. Chr." + ::msgcat::mcset de AM "vorm." + ::msgcat::mcset de PM "nachm." + ::msgcat::mcset de DATE_FORMAT "%d.%m.%Y" + ::msgcat::mcset de TIME_FORMAT "%H:%M:%S" + ::msgcat::mcset de DATE_TIME_FORMAT "%d.%m.%Y %H:%M:%S %z" +} diff --git a/shared/package-files/cc/cc3855b7024992bf948ce63c8c686ebcf43b6ff323bdeed7a4b34d03823670ba/harary_graph.py b/shared/package-files/cc/cc3855b7024992bf948ce63c8c686ebcf43b6ff323bdeed7a4b34d03823670ba/harary_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..7af21b3384f24d676d06e1645a8d3dd111914a22 --- /dev/null +++ b/shared/package-files/cc/cc3855b7024992bf948ce63c8c686ebcf43b6ff323bdeed7a4b34d03823670ba/harary_graph.py @@ -0,0 +1,197 @@ +"""Generators for Harary graphs + +This module gives two generators for the Harary graph, which was +introduced by the famous mathematician Frank Harary in his 1962 work [H]_. +The first generator gives the Harary graph that maximizes the node +connectivity with given number of nodes and given number of edges. +The second generator gives the Harary graph that minimizes +the number of edges in the graph with given node connectivity and +number of nodes. + +References +---------- +.. [H] Harary, F. "The Maximum Connectivity of a Graph." + Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962. + +""" + +import networkx as nx +from networkx.exception import NetworkXError + +__all__ = ["hnm_harary_graph", "hkn_harary_graph"] + + +def hnm_harary_graph(n, m, create_using=None): + """Returns the Harary graph with given numbers of nodes and edges. + + The Harary graph $H_{n,m}$ is the graph that maximizes node connectivity + with $n$ nodes and $m$ edges. + + This maximum node connectivity is known to be floor($2m/n$). [1]_ + + Parameters + ---------- + n: integer + The number of nodes the generated graph is to contain + + m: integer + The number of edges the generated graph is to contain + + create_using : NetworkX graph constructor, optional Graph type + to create (default=nx.Graph). If graph instance, then cleared + before populated. + + Returns + ------- + NetworkX graph + The Harary graph $H_{n,m}$. + + See Also + -------- + hkn_harary_graph + + Notes + ----- + This algorithm runs in $O(m)$ time. + It is implemented by following the Reference [2]_. + + References + ---------- + .. [1] F. T. Boesch, A. Satyanarayana, and C. L. Suffel, + "A Survey of Some Network Reliability Analysis and Synthesis Results," + Networks, pp. 99-107, 2009. + + .. [2] Harary, F. "The Maximum Connectivity of a Graph." + Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962. + """ + + if n < 1: + raise NetworkXError("The number of nodes must be >= 1!") + if m < n - 1: + raise NetworkXError("The number of edges must be >= n - 1 !") + if m > n * (n - 1) // 2: + raise NetworkXError("The number of edges must be <= n(n-1)/2") + + # Construct an empty graph with n nodes first + H = nx.empty_graph(n, create_using) + # Get the floor of average node degree + d = 2 * m // n + + # Test the parity of n and d + if (n % 2 == 0) or (d % 2 == 0): + # Start with a regular graph of d degrees + offset = d // 2 + for i in range(n): + for j in range(1, offset + 1): + H.add_edge(i, (i - j) % n) + H.add_edge(i, (i + j) % n) + if d & 1: + # in case d is odd; n must be even in this case + half = n // 2 + for i in range(0, half): + # add edges diagonally + H.add_edge(i, i + half) + # Get the remainder of 2*m modulo n + r = 2 * m % n + if r > 0: + # add remaining edges at offset+1 + for i in range(0, r // 2): + H.add_edge(i, i + offset + 1) + else: + # Start with a regular graph of (d - 1) degrees + offset = (d - 1) // 2 + for i in range(n): + for j in range(1, offset + 1): + H.add_edge(i, (i - j) % n) + H.add_edge(i, (i + j) % n) + half = n // 2 + for i in range(0, m - n * offset): + # add the remaining m - n*offset edges between i and i+half + H.add_edge(i, (i + half) % n) + + return H + + +def hkn_harary_graph(k, n, create_using=None): + """Returns the Harary graph with given node connectivity and node number. + + The Harary graph $H_{k,n}$ is the graph that minimizes the number of + edges needed with given node connectivity $k$ and node number $n$. + + This smallest number of edges is known to be ceil($kn/2$) [1]_. + + Parameters + ---------- + k: integer + The node connectivity of the generated graph + + n: integer + The number of nodes the generated graph is to contain + + create_using : NetworkX graph constructor, optional Graph type + to create (default=nx.Graph). If graph instance, then cleared + before populated. + + Returns + ------- + NetworkX graph + The Harary graph $H_{k,n}$. + + See Also + -------- + hnm_harary_graph + + Notes + ----- + This algorithm runs in $O(kn)$ time. + It is implemented by following the Reference [2]_. + + References + ---------- + .. [1] Weisstein, Eric W. "Harary Graph." From MathWorld--A Wolfram Web + Resource. http://mathworld.wolfram.com/HararyGraph.html. + + .. [2] Harary, F. "The Maximum Connectivity of a Graph." + Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962. + """ + + if k < 1: + raise NetworkXError("The node connectivity must be >= 1!") + if n < k + 1: + raise NetworkXError("The number of nodes must be >= k+1 !") + + # in case of connectivity 1, simply return the path graph + if k == 1: + H = nx.path_graph(n, create_using) + return H + + # Construct an empty graph with n nodes first + H = nx.empty_graph(n, create_using) + + # Test the parity of k and n + if (k % 2 == 0) or (n % 2 == 0): + # Construct a regular graph with k degrees + offset = k // 2 + for i in range(n): + for j in range(1, offset + 1): + H.add_edge(i, (i - j) % n) + H.add_edge(i, (i + j) % n) + if k & 1: + # odd degree; n must be even in this case + half = n // 2 + for i in range(0, half): + # add edges diagonally + H.add_edge(i, i + half) + else: + # Construct a regular graph with (k - 1) degrees + offset = (k - 1) // 2 + for i in range(n): + for j in range(1, offset + 1): + H.add_edge(i, (i - j) % n) + H.add_edge(i, (i + j) % n) + half = n // 2 + for i in range(0, half + 1): + # add half+1 edges between i and i+half + H.add_edge(i, (i + half) % n) + + return H diff --git a/shared/package-files/cc/cc3a2e9d503eeb0384652ed6c24a03bb13a97f67a69049e9db5a530c7b58ef55/libtdbcstub1.1.3.a b/shared/package-files/cc/cc3a2e9d503eeb0384652ed6c24a03bb13a97f67a69049e9db5a530c7b58ef55/libtdbcstub1.1.3.a new file mode 100644 index 0000000000000000000000000000000000000000..655d87eaa6051e972553bef48916752dc9e15ea2 Binary files /dev/null and b/shared/package-files/cc/cc3a2e9d503eeb0384652ed6c24a03bb13a97f67a69049e9db5a530c7b58ef55/libtdbcstub1.1.3.a differ diff --git a/shared/package-files/cc/cc3f54e41502075b908204b17d9693197fee0761e4a7be6cb6d1a665b0868012/linalg.pyi b/shared/package-files/cc/cc3f54e41502075b908204b17d9693197fee0761e4a7be6cb6d1a665b0868012/linalg.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c0b2f29b28d9528556151bb0139e671c5ecbb4c4 --- /dev/null +++ b/shared/package-files/cc/cc3f54e41502075b908204b17d9693197fee0761e4a7be6cb6d1a665b0868012/linalg.pyi @@ -0,0 +1,297 @@ +from collections.abc import Iterable +from typing import ( + Literal as L, + overload, + TypeVar, + Any, + SupportsIndex, + SupportsInt, + NamedTuple, + Generic, +) + +from numpy import ( + generic, + floating, + complexfloating, + int32, + float64, + complex128, +) + +from numpy.linalg import LinAlgError as LinAlgError + +from numpy._typing import ( + NDArray, + ArrayLike, + _ArrayLikeInt_co, + _ArrayLikeFloat_co, + _ArrayLikeComplex_co, + _ArrayLikeTD64_co, + _ArrayLikeObject_co, +) + +_T = TypeVar("_T") +_ArrayType = TypeVar("_ArrayType", bound=NDArray[Any]) +_SCT = TypeVar("_SCT", bound=generic, covariant=True) +_SCT2 = TypeVar("_SCT2", bound=generic, covariant=True) + +_2Tuple = tuple[_T, _T] +_ModeKind = L["reduced", "complete", "r", "raw"] + +__all__: list[str] + +class EigResult(NamedTuple): + eigenvalues: NDArray[Any] + eigenvectors: NDArray[Any] + +class EighResult(NamedTuple): + eigenvalues: NDArray[Any] + eigenvectors: NDArray[Any] + +class QRResult(NamedTuple): + Q: NDArray[Any] + R: NDArray[Any] + +class SlogdetResult(NamedTuple): + # TODO: `sign` and `logabsdet` are scalars for input 2D arrays and + # a `(x.ndim - 2)`` dimensionl arrays otherwise + sign: Any + logabsdet: Any + +class SVDResult(NamedTuple): + U: NDArray[Any] + S: NDArray[Any] + Vh: NDArray[Any] + +@overload +def tensorsolve( + a: _ArrayLikeInt_co, + b: _ArrayLikeInt_co, + axes: None | Iterable[int] =..., +) -> NDArray[float64]: ... +@overload +def tensorsolve( + a: _ArrayLikeFloat_co, + b: _ArrayLikeFloat_co, + axes: None | Iterable[int] =..., +) -> NDArray[floating[Any]]: ... +@overload +def tensorsolve( + a: _ArrayLikeComplex_co, + b: _ArrayLikeComplex_co, + axes: None | Iterable[int] =..., +) -> NDArray[complexfloating[Any, Any]]: ... + +@overload +def solve( + a: _ArrayLikeInt_co, + b: _ArrayLikeInt_co, +) -> NDArray[float64]: ... +@overload +def solve( + a: _ArrayLikeFloat_co, + b: _ArrayLikeFloat_co, +) -> NDArray[floating[Any]]: ... +@overload +def solve( + a: _ArrayLikeComplex_co, + b: _ArrayLikeComplex_co, +) -> NDArray[complexfloating[Any, Any]]: ... + +@overload +def tensorinv( + a: _ArrayLikeInt_co, + ind: int = ..., +) -> NDArray[float64]: ... +@overload +def tensorinv( + a: _ArrayLikeFloat_co, + ind: int = ..., +) -> NDArray[floating[Any]]: ... +@overload +def tensorinv( + a: _ArrayLikeComplex_co, + ind: int = ..., +) -> NDArray[complexfloating[Any, Any]]: ... + +@overload +def inv(a: _ArrayLikeInt_co) -> NDArray[float64]: ... +@overload +def inv(a: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... +@overload +def inv(a: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ... + +# TODO: The supported input and output dtypes are dependent on the value of `n`. +# For example: `n < 0` always casts integer types to float64 +def matrix_power( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + n: SupportsIndex, +) -> NDArray[Any]: ... + +@overload +def cholesky(a: _ArrayLikeInt_co) -> NDArray[float64]: ... +@overload +def cholesky(a: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... +@overload +def cholesky(a: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ... + +@overload +def qr(a: _ArrayLikeInt_co, mode: _ModeKind = ...) -> QRResult: ... +@overload +def qr(a: _ArrayLikeFloat_co, mode: _ModeKind = ...) -> QRResult: ... +@overload +def qr(a: _ArrayLikeComplex_co, mode: _ModeKind = ...) -> QRResult: ... + +@overload +def eigvals(a: _ArrayLikeInt_co) -> NDArray[float64] | NDArray[complex128]: ... +@overload +def eigvals(a: _ArrayLikeFloat_co) -> NDArray[floating[Any]] | NDArray[complexfloating[Any, Any]]: ... +@overload +def eigvals(a: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ... + +@overload +def eigvalsh(a: _ArrayLikeInt_co, UPLO: L["L", "U", "l", "u"] = ...) -> NDArray[float64]: ... +@overload +def eigvalsh(a: _ArrayLikeComplex_co, UPLO: L["L", "U", "l", "u"] = ...) -> NDArray[floating[Any]]: ... + +@overload +def eig(a: _ArrayLikeInt_co) -> EigResult: ... +@overload +def eig(a: _ArrayLikeFloat_co) -> EigResult: ... +@overload +def eig(a: _ArrayLikeComplex_co) -> EigResult: ... + +@overload +def eigh( + a: _ArrayLikeInt_co, + UPLO: L["L", "U", "l", "u"] = ..., +) -> EighResult: ... +@overload +def eigh( + a: _ArrayLikeFloat_co, + UPLO: L["L", "U", "l", "u"] = ..., +) -> EighResult: ... +@overload +def eigh( + a: _ArrayLikeComplex_co, + UPLO: L["L", "U", "l", "u"] = ..., +) -> EighResult: ... + +@overload +def svd( + a: _ArrayLikeInt_co, + full_matrices: bool = ..., + compute_uv: L[True] = ..., + hermitian: bool = ..., +) -> SVDResult: ... +@overload +def svd( + a: _ArrayLikeFloat_co, + full_matrices: bool = ..., + compute_uv: L[True] = ..., + hermitian: bool = ..., +) -> SVDResult: ... +@overload +def svd( + a: _ArrayLikeComplex_co, + full_matrices: bool = ..., + compute_uv: L[True] = ..., + hermitian: bool = ..., +) -> SVDResult: ... +@overload +def svd( + a: _ArrayLikeInt_co, + full_matrices: bool = ..., + compute_uv: L[False] = ..., + hermitian: bool = ..., +) -> NDArray[float64]: ... +@overload +def svd( + a: _ArrayLikeComplex_co, + full_matrices: bool = ..., + compute_uv: L[False] = ..., + hermitian: bool = ..., +) -> NDArray[floating[Any]]: ... + +# TODO: Returns a scalar for 2D arrays and +# a `(x.ndim - 2)`` dimensionl array otherwise +def cond(x: _ArrayLikeComplex_co, p: None | float | L["fro", "nuc"] = ...) -> Any: ... + +# TODO: Returns `int` for <2D arrays and `intp` otherwise +def matrix_rank( + A: _ArrayLikeComplex_co, + tol: None | _ArrayLikeFloat_co = ..., + hermitian: bool = ..., +) -> Any: ... + +@overload +def pinv( + a: _ArrayLikeInt_co, + rcond: _ArrayLikeFloat_co = ..., + hermitian: bool = ..., +) -> NDArray[float64]: ... +@overload +def pinv( + a: _ArrayLikeFloat_co, + rcond: _ArrayLikeFloat_co = ..., + hermitian: bool = ..., +) -> NDArray[floating[Any]]: ... +@overload +def pinv( + a: _ArrayLikeComplex_co, + rcond: _ArrayLikeFloat_co = ..., + hermitian: bool = ..., +) -> NDArray[complexfloating[Any, Any]]: ... + +# TODO: Returns a 2-tuple of scalars for 2D arrays and +# a 2-tuple of `(a.ndim - 2)`` dimensionl arrays otherwise +def slogdet(a: _ArrayLikeComplex_co) -> SlogdetResult: ... + +# TODO: Returns a 2-tuple of scalars for 2D arrays and +# a 2-tuple of `(a.ndim - 2)`` dimensionl arrays otherwise +def det(a: _ArrayLikeComplex_co) -> Any: ... + +@overload +def lstsq(a: _ArrayLikeInt_co, b: _ArrayLikeInt_co, rcond: None | float = ...) -> tuple[ + NDArray[float64], + NDArray[float64], + int32, + NDArray[float64], +]: ... +@overload +def lstsq(a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co, rcond: None | float = ...) -> tuple[ + NDArray[floating[Any]], + NDArray[floating[Any]], + int32, + NDArray[floating[Any]], +]: ... +@overload +def lstsq(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co, rcond: None | float = ...) -> tuple[ + NDArray[complexfloating[Any, Any]], + NDArray[floating[Any]], + int32, + NDArray[floating[Any]], +]: ... + +@overload +def norm( + x: ArrayLike, + ord: None | float | L["fro", "nuc"] = ..., + axis: None = ..., + keepdims: bool = ..., +) -> floating[Any]: ... +@overload +def norm( + x: ArrayLike, + ord: None | float | L["fro", "nuc"] = ..., + axis: SupportsInt | SupportsIndex | tuple[int, ...] = ..., + keepdims: bool = ..., +) -> Any: ... + +# TODO: Returns a scalar or array +def multi_dot( + arrays: Iterable[_ArrayLikeComplex_co | _ArrayLikeObject_co | _ArrayLikeTD64_co], + *, + out: None | NDArray[Any] = ..., +) -> Any: ... diff --git a/shared/package-files/cc/cc3f7d4ecd36540e2238409e1e91e508fdc308e4fde4da1b13437f1ee03f61d1/rsub_cuda_dispatch.h b/shared/package-files/cc/cc3f7d4ecd36540e2238409e1e91e508fdc308e4fde4da1b13437f1ee03f61d1/rsub_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..4d4b1869672c3d5a60321f426b23293f334fb4a5 --- /dev/null +++ b/shared/package-files/cc/cc3f7d4ecd36540e2238409e1e91e508fdc308e4fde4da1b13437f1ee03f61d1/rsub_cuda_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor rsub(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha=1); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/cc/cc3fd14d1c5fa891d5653000c9d7732c30db842cca49fc051abde1c19d67ab7d/Norris.dat b/shared/package-files/cc/cc3fd14d1c5fa891d5653000c9d7732c30db842cca49fc051abde1c19d67ab7d/Norris.dat new file mode 100644 index 0000000000000000000000000000000000000000..4bf8ed911cae75824b27e5f5d5e444e17fa8eae8 --- /dev/null +++ b/shared/package-files/cc/cc3fd14d1c5fa891d5653000c9d7732c30db842cca49fc051abde1c19d67ab7d/Norris.dat @@ -0,0 +1,97 @@ +NIST/ITL StRD +Dataset Name: Norris (Norris.dat) + +File Format: ASCII + Certified Values (lines 31 to 46) + Data (lines 61 to 96) + +Procedure: Linear Least Squares Regression + +Reference: Norris, J., NIST. + Calibration of Ozone Monitors. + +Data: 1 Response Variable (y) + 1 Predictor Variable (x) + 36 Observations + Lower Level of Difficulty + Observed Data + +Model: Linear Class + 2 Parameters (B0,B1) + + y = B0 + B1*x + e + + + + Certified Regression Statistics + + Standard Deviation + Parameter Estimate of Estimate + + B0 -0.262323073774029 0.232818234301152 + B1 1.00211681802045 0.429796848199937E-03 + + Residual + Standard Deviation 0.884796396144373 + + R-Squared 0.999993745883712 + + + Certified Analysis of Variance Table + +Source of Degrees of Sums of Mean +Variation Freedom Squares Squares F Statistic + +Regression 1 4255954.13232369 4255954.13232369 5436385.54079785 +Residual 34 26.6173985294224 0.782864662630069 + + + + + + + + + + + + + +Data: y x + 0.1 0.2 + 338.8 337.4 + 118.1 118.2 + 888.0 884.6 + 9.2 10.1 + 228.1 226.5 + 668.5 666.3 + 998.5 996.3 + 449.1 448.6 + 778.9 777.0 + 559.2 558.2 + 0.3 0.4 + 0.1 0.6 + 778.1 775.5 + 668.8 666.9 + 339.3 338.0 + 448.9 447.5 + 10.8 11.6 + 557.7 556.0 + 228.3 228.1 + 998.0 995.8 + 888.8 887.6 + 119.6 120.2 + 0.3 0.3 + 0.6 0.3 + 557.6 556.8 + 339.3 339.1 + 888.0 887.2 + 998.5 999.0 + 778.9 779.0 + 10.2 11.1 + 117.6 118.3 + 228.9 229.2 + 668.4 669.1 + 449.2 448.9 + 0.2 0.5 + diff --git a/shared/package-files/cc/cc42ce2a5f770de0898bb32bbf6874a3bf97d601fcd7a26134926def2e98bc0f/_to_sparse_bsr_cuda_dispatch.h b/shared/package-files/cc/cc42ce2a5f770de0898bb32bbf6874a3bf97d601fcd7a26134926def2e98bc0f/_to_sparse_bsr_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..e9549aa51d2747be887ba7bba1ec101c0ce5b02f --- /dev/null +++ b/shared/package-files/cc/cc42ce2a5f770de0898bb32bbf6874a3bf97d601fcd7a26134926def2e98bc0f/_to_sparse_bsr_cuda_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor _to_sparse_bsr(const at::Tensor & self, at::IntArrayRef blocksize, c10::optional dense_dim=c10::nullopt); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/cc/cc4859a92c7e00c521fa57949f50d420aadee0f3a1051a1c9545f6d38c74627c/dnnl_ocl.h b/shared/package-files/cc/cc4859a92c7e00c521fa57949f50d420aadee0f3a1051a1c9545f6d38c74627c/dnnl_ocl.h new file mode 100644 index 0000000000000000000000000000000000000000..ad731150b28babe7bd5a911acd8de70c57e85254 --- /dev/null +++ b/shared/package-files/cc/cc4859a92c7e00c521fa57949f50d420aadee0f3a1051a1c9545f6d38c74627c/dnnl_ocl.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef DNNL_OCL_H +#define DNNL_OCL_H + +#include "oneapi/dnnl/dnnl_ocl.h" + +#endif /* DNNL_OCL_H */ diff --git a/shared/package-files/cc/cc4966dcfadf488be339c7b6f331131cc2147fda45612500e68d007e58143fae/live_render.py b/shared/package-files/cc/cc4966dcfadf488be339c7b6f331131cc2147fda45612500e68d007e58143fae/live_render.py new file mode 100644 index 0000000000000000000000000000000000000000..b90fbf7f35097694f727e201b0b378942d70a443 --- /dev/null +++ b/shared/package-files/cc/cc4966dcfadf488be339c7b6f331131cc2147fda45612500e68d007e58143fae/live_render.py @@ -0,0 +1,113 @@ +import sys +from typing import Optional, Tuple + +if sys.version_info >= (3, 8): + from typing import Literal +else: + from pip._vendor.typing_extensions import Literal # pragma: no cover + + +from ._loop import loop_last +from .console import Console, ConsoleOptions, RenderableType, RenderResult +from .control import Control +from .segment import ControlType, Segment +from .style import StyleType +from .text import Text + +VerticalOverflowMethod = Literal["crop", "ellipsis", "visible"] + + +class LiveRender: + """Creates a renderable that may be updated. + + Args: + renderable (RenderableType): Any renderable object. + style (StyleType, optional): An optional style to apply to the renderable. Defaults to "". + """ + + def __init__( + self, + renderable: RenderableType, + style: StyleType = "", + vertical_overflow: VerticalOverflowMethod = "ellipsis", + ) -> None: + self.renderable = renderable + self.style = style + self.vertical_overflow = vertical_overflow + self._shape: Optional[Tuple[int, int]] = None + + def set_renderable(self, renderable: RenderableType) -> None: + """Set a new renderable. + + Args: + renderable (RenderableType): Any renderable object, including str. + """ + self.renderable = renderable + + def position_cursor(self) -> Control: + """Get control codes to move cursor to beginning of live render. + + Returns: + Control: A control instance that may be printed. + """ + if self._shape is not None: + _, height = self._shape + return Control( + ControlType.CARRIAGE_RETURN, + (ControlType.ERASE_IN_LINE, 2), + *( + ( + (ControlType.CURSOR_UP, 1), + (ControlType.ERASE_IN_LINE, 2), + ) + * (height - 1) + ) + ) + return Control() + + def restore_cursor(self) -> Control: + """Get control codes to clear the render and restore the cursor to its previous position. + + Returns: + Control: A Control instance that may be printed. + """ + if self._shape is not None: + _, height = self._shape + return Control( + ControlType.CARRIAGE_RETURN, + *((ControlType.CURSOR_UP, 1), (ControlType.ERASE_IN_LINE, 2)) * height + ) + return Control() + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + + renderable = self.renderable + style = console.get_style(self.style) + lines = console.render_lines(renderable, options, style=style, pad=False) + shape = Segment.get_shape(lines) + + _, height = shape + if height > options.size.height: + if self.vertical_overflow == "crop": + lines = lines[: options.size.height] + shape = Segment.get_shape(lines) + elif self.vertical_overflow == "ellipsis": + lines = lines[: (options.size.height - 1)] + overflow_text = Text( + "...", + overflow="crop", + justify="center", + end="", + style="live.ellipsis", + ) + lines.append(list(console.render(overflow_text))) + shape = Segment.get_shape(lines) + self._shape = shape + + new_line = Segment.line() + for last, line in loop_last(lines): + yield from line + if not last: + yield new_line diff --git a/shared/package-files/cc/cc55685b7826bd9149e4fe6dd24f4214268a542caa39a663b8ad3bd9547ce1a1/library.h b/shared/package-files/cc/cc55685b7826bd9149e4fe6dd24f4214268a542caa39a663b8ad3bd9547ce1a1/library.h new file mode 100644 index 0000000000000000000000000000000000000000..793c87544233acccb2e08f1626d892896de3b5ce --- /dev/null +++ b/shared/package-files/cc/cc55685b7826bd9149e4fe6dd24f4214268a542caa39a663b8ad3bd9547ce1a1/library.h @@ -0,0 +1,1050 @@ +#pragma once + +/// \file +/// +/// This header provides an API for extending PyTorch's core library +/// of operators with user defined operators and data types. This +/// API can be used in a few ways: +/// +/// * You can define new custom operators and classes with TORCH_LIBRARY(), +/// making them available for use in both eager Python as well as in +/// TorchScript. This API is modeled off of pybind11's `PYBIND11_MODULE` +/// macro, as the provided functionality is similar (pybind11 lets you bind +/// C++ to Python only; `torch/library.h` lets you bind C++ simultaneously to +/// Python and TorchScript). +/// +/// * You can override existing operators with TORCH_LIBRARY_IMPL(), +/// providing a new implementation for these operators for a custom +/// backend (e.g., XLA). When you pass operators with tensors of your custom +/// backend, your overridden implementations will be called instead +/// of the standard implementations. +/// +/// * You can use both capabilities at the same time, allowing you +/// to write custom operators that register CPU/CUDA/Autograd +/// implementations without having to write the boilerplate +/// conditionals yourself. +/// +/// For a tutorial style introduction to the library API, check +/// out the [Extending TorchScript with Custom C++ +/// Operators](https://pytorch.org/tutorials/advanced/torch_script_custom_ops.html) +/// tutorial. +/// +/// ``` +/// // Define a library whose operators live in the namespace 'myops'. +/// // You must define all of the operators for this library in +/// // this namespace. +/// TORCH_LIBRARY(myops, m) { +/// // Define a operator with exactly one implementation for all backends. +/// m.def("add(Tensor self, Tensor other) -> Tensor", &add_impl); +/// +/// // Define a schema for an operator, but provide no implementation +/// // (use this syntax if you want to use the dispatcher) +/// m.def("mul(Tensor self, Tensor other) -> Tensor"); +/// +/// // Provide an implementation for a defined operator (you can +/// // provide multiple; one per backend). The dispatcher takes care of +/// // calling the correct implementation depending on if we get a CPU +/// // tensor or a CUDA tensor +/// m.impl("mul", torch::kCPU, &mul_cpu_impl); +/// m.impl("mul", torch::kCUDA, &mul_cuda_impl); +/// } +/// +/// // Define implementations for operators for a non-standard backend, +/// // e.g., XLA (valid values are entries of DispatchKey). This can +/// // be used to define operators in a different file than the initial +/// // TORCH_LIBRARY definition (e.g., if it is in an external library) +/// TORCH_LIBRARY_IMPL(myops, XLA, m) { +/// m.impl("mul", &mul_xla_impl); +/// } +/// ``` + +#include +#include +#include +#include +#include + +// Just for inferFunctionSchemaFromFunctor +#include +#include + +namespace torch { + +#if defined C10_MOBILE +/** + * The NoInferSchemaTag is a type name used to indicate that this call to the + * CppFunction constructor should not trigger schema inference from functor. + * Schema inference from functor utilizes template meta-programming, and is + * costly from a size perspective. Ideally, one would expect that the schema + * inference would require very little binary size since most of the + * computation can be done by the compiler at build time, but that isn't + * necessarily the case. + * + * Schema inference is elided only for mobile use-cases where we don't need + * the additional runtime cost or size overhead on client devices. + * + */ +struct NoInferSchemaTag {}; +#endif + +#define HAS_PT2_COMPLIANT_TAG + +// For multipy/torchdeploy use case +enum class _RegisterOrVerify { REGISTER, VERIFY }; + +template +class class_; + +#define HAS_IMPL_ABSTRACT_PYSTUB + +/// Represents a C++ function that implements an operator. Most users won't +/// interact directly with this class, except via error messages: the +/// constructors this function define the set of permissible "function"-like +/// things you can bind via the interface. +/// +/// This class erases the type of the passed in function, but durably records +/// the type via an inferred schema for the function. +class TORCH_API CppFunction final { + // TODO: This is morally the same thing as KernelRegistrationConfig, but it's + // opaque to the user. + + public: + /// This overload accepts function pointers, e.g., `CppFunction(&add_impl)` + template + explicit CppFunction( + Func* f, + std::enable_if_t< + c10::guts::is_function_type::value, + std::nullptr_t> = nullptr) + : func_(c10::KernelFunction::makeFromUnboxedRuntimeFunction(f)), + cpp_signature_(c10::impl::CppSignature::make()), + schema_( + c10::detail::inferFunctionSchemaFromFunctor>()), + debug_() {} + + /// This overload accepts compile time function pointers, e.g., + /// `CppFunction(TORCH_FN(add_impl))` + template + explicit CppFunction( + FuncPtr f, + std::enable_if_t< + c10::is_compile_time_function_pointer::value, + std::nullptr_t> = nullptr) + : func_(c10::KernelFunction::makeFromUnboxedFunction(f)), + cpp_signature_( + c10::impl::CppSignature::make()), + schema_(c10::detail::inferFunctionSchemaFromFunctor< + typename FuncPtr::FuncType>()), + debug_() {} + + /// This overload accepts lambdas, e.g., `CppFunction([](const Tensor& self) { + /// ... })` + template + explicit CppFunction( + Lambda&& f, + std::enable_if_t< + c10::guts::is_functor>::value, + std::nullptr_t> = nullptr) + : func_(c10::KernelFunction::makeFromUnboxedLambda( + std::forward(f))), + cpp_signature_(c10::impl::CppSignature::make()), + schema_(c10::detail::inferFunctionSchemaFromFunctor< + std::decay_t>()), + debug_() {} + +#if defined C10_MOBILE + /// This overload accepts function pointers, e.g., `CppFunction(&add_impl, + /// NoInferSchemaTag())` + template + explicit CppFunction( + Func* f, + NoInferSchemaTag, + std::enable_if_t< + c10::guts::is_function_type::value, + std::nullptr_t> = nullptr) + : func_(c10::KernelFunction::makeFromUnboxedRuntimeFunction(f)), + cpp_signature_(c10::impl::CppSignature::make()) + // TODO: Don't go through WrapRuntimeKernelFunctor + , + schema_(nullptr), + debug_() {} + + /// This overload accepts compile time function pointers, e.g., + /// `CppFunction(TORCH_FN(add_impl), NoInferSchemaTag())` + template + explicit CppFunction( + FuncPtr f, + NoInferSchemaTag, + std::enable_if_t< + c10::is_compile_time_function_pointer::value, + std::nullptr_t> = nullptr) + : func_(c10::KernelFunction::makeFromUnboxedFunction(f)), + cpp_signature_( + c10::impl::CppSignature::make()) + // TODO: Don't go through WrapRuntimeKernelFunctor + , + schema_(nullptr), + debug_() {} + + /// This overload accepts lambdas, e.g., `CppFunction([](const Tensor& self) { + /// ... }. NoInferSchemaTag())` + template + explicit CppFunction( + Lambda&& f, + NoInferSchemaTag, + std::enable_if_t< + c10::guts::is_functor>::value, + std::nullptr_t> = nullptr) + : func_(c10::KernelFunction::makeFromUnboxedLambda( + std::forward(f))), + cpp_signature_(c10::impl::CppSignature::make()) + // TODO: Don't go through WrapRuntimeKernelFunctor + , + schema_(nullptr), + debug_() {} +#endif + + ~CppFunction(); + + CppFunction(CppFunction&&) noexcept = default; + + CppFunction& operator=(CppFunction&&) = default; + + /// \private + /// Creates a function from a type-erased boxed kernel. + static CppFunction makeFromBoxedKernel(c10::BoxedKernel kernel) { + return CppFunction( + c10::KernelFunction::makeFromBoxedKernel(std::move(kernel)), + /* cpp_signature */ c10::nullopt, // not known for boxed functions + /* schema */ nullptr); + } + + /// This creates a fallthrough function. Fallthrough functions + /// immediately redispatch to the next available dispatch key, + /// but are implemented more efficiently than a hand written + /// function done in the same way. + static CppFunction makeFallthrough() { + return makeFromBoxedKernel(c10::BoxedKernel::makeFallthrough()); + } + + /// \private + /// + /// Creates a function that raises an error saying that named tensors + /// are not supported when called. + static CppFunction makeNamedNotSupported() { + return makeFromBoxedKernel(c10::BoxedKernel::makeNamedNotSupported()); + } + + /// Create a function from a boxed kernel function with signature + /// `void(const OperatorHandle&, Stack*)`; i.e., they receive a + /// stack of arguments in a boxed calling convention, rather than + /// in the native C++ calling convention. Boxed functions are + /// typically only used to register backend fallbacks via + /// torch::Library::fallback(). + template + static CppFunction makeFromBoxedFunction() { + return makeFromBoxedKernel(c10::BoxedKernel::makeFromFunction()); + } + + // Variant that takes in a boxed kernel function with a plumbed + // DispatchKeySet. See Note [Plumbing Keys Through The Dispatcher] for + // details. + template + static CppFunction makeFromBoxedFunction() { + return makeFromBoxedKernel(c10::BoxedKernel::makeFromFunction()); + } + + /// Create a function from a boxed kernel functor which defines + /// `operator()(const OperatorHandle&, DispatchKeySet, Stack*)` + /// (receiving arguments from boxed calling convention) and inherits + /// from `c10::OperatorKernel`. Unlike makeFromBoxedFunction, functions + /// registered in this way can also carry additional state which + /// is managed by the functor; this is useful if you're writing an + /// adapter to some other implementation, e.g., a Python callable, which + /// is dynamically associated with the registered kernel. + template + static CppFunction makeFromBoxedFunctor( + std::unique_ptr kernelFunctor) { + return makeFromBoxedKernel( + c10::BoxedKernel::makeFromFunctor(std::move(kernelFunctor))); + } + + /// Create a function from an unboxed kernel function. + /// This is typically used to register common operators. + template < + typename FuncPtr, + std::enable_if_t< + c10::guts::is_function_type::value, + std::nullptr_t> = nullptr> + static CppFunction makeFromUnboxedFunction(FuncPtr* f) { + return CppFunction(f); + } + + /// Create a function from a compile time unboxed kernel function pointer. + /// This is typically used to register common operators. + /// Compile time function pointers can be used to allow the compiler + /// to optimize (e.g. inline) calls to it. + template < + typename FuncPtr, + std::enable_if_t< + c10::is_compile_time_function_pointer::value, + std::nullptr_t> = nullptr> + static CppFunction makeFromUnboxedFunction(FuncPtr f) { + return CppFunction(f); + } + + CppFunction&& debug(std::string d) && { + debug_ = std::move(d); + return std::move(*this); + } + + private: + c10::optional dispatch_key_; + c10::KernelFunction func_; + c10::optional cpp_signature_; + std::unique_ptr schema_; + std::string debug_; + + // The "setter" for dispatch_key_ + template + friend CppFunction dispatch(c10::DispatchKey, Func&&); + + // The only class which actually pulls out values from CppFunction (does so + // destructively, felt too lazy to write accessors that I don't even + // want users to use) + friend class Library; + + CppFunction( + c10::KernelFunction func, + c10::optional cpp_signature, + std::unique_ptr schema); +}; + +/// \defgroup torch-dispatch-overloads torch::dispatch overloads + +/// Create a torch::CppFunction which is associated with a specific +/// dispatch key. torch::CppFunctions that are tagged with a +/// c10::DispatchKey don't get invoked unless the dispatcher determines +/// that this particular c10::DispatchKey is the one that should be +/// dispatched to. +/// +/// This function is generally not used directly, instead, prefer using +/// TORCH_LIBRARY_IMPL(), which will implicitly set the c10::DispatchKey +/// for all registration calls inside of its body. +/// +/// \ingroup torch-dispatch-overloads +template +inline CppFunction dispatch(c10::DispatchKey k, Func&& raw_f) { + CppFunction f(std::forward(raw_f)); + if (k == c10::DispatchKey::CatchAll) { + f.dispatch_key_ = c10::nullopt; + } else { + f.dispatch_key_ = k; + } + return f; +} + +/// Convenience overload of dispatch() which accepts c10::DeviceType +/// +/// \ingroup torch-dispatch-overloads +template +inline CppFunction dispatch(c10::DeviceType type, Func&& raw_f) { + auto deviceTypeToDispatchKey = [](c10::DeviceType t) { + switch (t) { + // This list is synchronized with the k-constants in c10/core/DeviceType.h + case c10::DeviceType::CPU: + return c10::DispatchKey::CPU; + case c10::DeviceType::CUDA: + return c10::DispatchKey::CUDA; + case c10::DeviceType::IPU: + return c10::DispatchKey::IPU; + case c10::DeviceType::XLA: + return c10::DispatchKey::XLA; + case c10::DeviceType::Lazy: + return c10::DispatchKey::Lazy; + case c10::DeviceType::XPU: + return c10::DispatchKey::XPU; + case c10::DeviceType::MPS: + return c10::DispatchKey::MPS; + case c10::DeviceType::Meta: + return c10::DispatchKey::Meta; + case c10::DeviceType::HIP: + return c10::DispatchKey::HIP; + case c10::DeviceType::ORT: + return c10::DispatchKey::ORT; + case c10::DeviceType::HPU: + return c10::DispatchKey::HPU; + case c10::DeviceType::MTIA: + return c10::DispatchKey::MTIA; + case c10::DeviceType::PrivateUse1: + return c10::DispatchKey::PrivateUse1; + default: + TORCH_CHECK( + false, + "Device type ", + t, + " cannot be overloaded at dispatch time, " + "please file a bug report explaining what you were trying to do."); + } + }; + return dispatch(deviceTypeToDispatchKey(type), std::forward(raw_f)); +} + +/// \defgroup torch-schema-overloads torch::schema overloads + +/// Construct a c10::FunctionSchema from a string, with an explicitly +/// specified c10::AliasAnalysisKind. Ordinarily, schemas are simply +/// passed in as strings, but if you need to specify a custom alias +/// analysis, you can replace the string with a call to this function. +/// +/// ``` +/// // Default alias analysis (FROM_SCHEMA) +/// m.def("def3(Tensor self) -> Tensor"); +/// // Pure function alias analysis +/// m.def(torch::schema("def3(Tensor self) -> Tensor", +/// c10::AliasAnalysisKind::PURE_FUNCTION)); +/// ``` +/// +/// \ingroup torch-schema-overloads +inline c10::FunctionSchema schema(const char* str, c10::AliasAnalysisKind k) { + c10::FunctionSchema s = torch::jit::parseSchema(str); + s.setAliasAnalysis(k); + return s; +} + +/// Function schemas can be directly constructed from string literals. +/// +/// \ingroup torch-schema-overloads +inline c10::FunctionSchema schema(const char* s) { + return schema(s, c10::AliasAnalysisKind::FROM_SCHEMA); +} + +/// \private +/// +/// Already constructed function schemas are accepted if they are +/// rvalues. +/// +/// \ingroup torch-schema-overloads +inline c10::FunctionSchema&& schema(c10::FunctionSchema&& s) { + return std::move(s); +} + +namespace detail { + +inline std::variant constructSchemaOrName( + c10::FunctionSchema&& s) { + return std::move(s); +} +inline std::variant constructSchemaOrName( + c10::OperatorName&& n) { + return std::move(n); +} +inline std::variant +constructSchemaOrName(const char* str) { + auto s = torch::jit::parseSchemaOrName(str); + if (std::holds_alternative(s)) { + std::get(s).setAliasAnalysis( + c10::AliasAnalysisKind::FROM_SCHEMA); + } + return s; +} + +class TorchLibraryInit; + +} // namespace detail + +// Note [Selective build] +// ~~~~~~~~~~~~~~~~~~~~~~ +// In some settings, especially mobile, it is important to avoid compiling any +// references to functions that you aren't actually going to use, so that they +// can be eliminated by the linker. We call this capability "selective build". +// +// A very easy way to implement selective build which results in a lot of +// boilerplate is to just add ifdef's around every registration call, but this +// means you have to write a lot of extra lines of code at every registration +// site, and it also means you have to define some munging scheme to map +// operators to macros. +// +// Instead of doing this, we have a different mechanism centered around the +// concept of a SelectiveStr. A selective name is like a const char* string, +// except it also carries at compile time a boolean saying whether or not a +// registration should actually happen or not. We then have extra overloads +// which bypass registration entirely if a selective name is disabled. We do a +// constexpr test to see if a operator should be enabled or not; this is +// currently implemented in ATen/core/op_registration/op_allowlist.h + +namespace detail { + +// dummy class for non selected custom torchbind classes +class ClassNotSelected { + public: + ClassNotSelected& def_pickle(...) { + return *this; + } + ClassNotSelected& def(...) { + return *this; + } +}; + +// A SelectiveStr is like a const char*, except that it also comes +// with a type brand that says whether or not the name is enabled or +// not. If the string is disabled, then (at compile time) we DON'T generate +// a registration call for it. This class is not intended to be called +// directly; use TORCH_SELECTIVE_NAME or TORCH_SELECTIVE_SCHEMA macros below +// to create it. +template +class SelectiveStr { + public: + constexpr explicit SelectiveStr(const char* name) : name_(name) {} + constexpr operator const char*() { + return name_; + } + + private: + const char* name_; +}; + +#define TORCH_SELECTIVE_CLASS(n) \ + torch::detail::SelectiveStr(n) +#define TORCH_SELECTIVE_NAME(n) \ + torch::detail::SelectiveStr(n) +#define TORCH_SELECTIVE_SCHEMA(n) \ + torch::detail::SelectiveStr(n) + +} // namespace detail + +/// This object provides the API for defining operators and providing +/// implementations at dispatch keys. Typically, a torch::Library +/// is not allocated directly; instead it is created by the +/// TORCH_LIBRARY() or TORCH_LIBRARY_IMPL() macros. +/// +/// Most methods on torch::Library return a reference to itself, +/// supporting method chaining. +/// +/// ``` +/// // Examples: +/// +/// TORCH_LIBRARY(torchvision, m) { +/// // m is a torch::Library +/// m.def("roi_align", ...); +/// ... +/// } +/// +/// TORCH_LIBRARY_IMPL(aten, XLA, m) { +/// // m is a torch::Library +/// m.impl("add", ...); +/// ... +/// } +/// ``` +/// +class TORCH_API Library final { + public: + /// \private + /// + /// Which type of macro produced this Library + enum Kind { + DEF, // from TORCH_LIBRARY (no qualifier) + IMPL, + FRAGMENT, + }; + + /// \private + /// + /// Use TORCH_LIBRARY() or TORCH_LIBRARY_IMPL() instead of using these + /// constructors directly + Library( + Kind kind, + std::string ns, + c10::optional k, + const char* file, + uint32_t line); + + Library(const Library&) = delete; + Library& operator=(const Library&) = delete; + Library(Library&&) = default; + Library& operator=(Library&&) = default; + + // Some notes about the API design here. We had the following constraints: + // + // - We need to support multiple "types" of arguments for schema and + // functions (e.g., unnamed lambda types, regular functions, const char*, + // fully instantiated schemas) + // - We don't want to write exponentially many overloads + // - We don't want to rely on implicit conversion to a common type, + // because the C++ compiler will only be willing to do a single + // implicit conversion (reducing the set of valid types which you + // can invoke with); also error messages are worse when an implicit + // conversion is not selected (as the compiler will not explain + // why it didn't select an implicit conversion; this is different + // from overloads where it will explain each candidate overload and + // why it didn't apply) + // + // To solve all of these constraints at the same time, we use a trick taken + // from the pybind11 library: template over the argument in the user visible + // API, and inside of the templated function explicitly call an overloaded + // function to resolve the argument to a real type. You get the good error + // messages from overloads, but at the same time you only need to write the + // overload for any given argument type once. + + /// Declare an operator with a schema, but don't provide any implementations + /// for it. You're expected to then provide implementations using the + /// impl() method. All template arguments are inferred. + /// + /// \param raw_schema The schema of the operator to be defined. + /// Typically, this is a `const char*` string literal, but any type + /// accepted by torch::schema() is accepted here. + /// + /// ``` + /// // Example: + /// TORCH_LIBRARY(myops, m) { + /// m.def("add(Tensor self, Tensor other) -> Tensor"); + /// } + /// ``` + + template + Library& def( + Schema&& raw_schema, + const std::vector& tags = {}, + _RegisterOrVerify rv = _RegisterOrVerify::REGISTER) & { + c10::FunctionSchema s = schema(std::forward(raw_schema)); + return _def(std::move(s), nullptr, tags, rv); + } + + /// Declares that for all operators that are subsequently def'ed, their + /// abstract impls may be found in the given Python module (pymodule). + /// This registers some help text that is used if the abstract impl + /// cannot be found. + /// + /// Args: + /// - pymodule: the python module + /// - context: We may include this in the error message. + Library& impl_abstract_pystub(const char* pymodule, const char* context = "") { + impl_abstract_pystub_ = {pymodule, context}; + return *this; + } + + /// Define an operator for a schema and then register an implementation for + /// it. This is typically what you would use if you aren't planning + /// on making use of the dispatcher to structure your operator + /// implementation. It's roughly equivalent to calling def() and + /// then impl(), but if you omit the schema of the operator, we will + /// infer it from the type of your C++ function. All template + /// arguments are inferred. + /// + /// \param raw_name_or_schema The schema of the operator to be + /// defined, or just the name of the operator if the schema is to be + /// inferred from `raw_f`. Typically a `const char*` literal. + /// \param raw_f The C++ function that implements this operator. + /// Any valid constructor of torch::CppFunction is accepted here; + /// typically you provide a function pointer or lambda. + /// + /// ``` + /// // Example: + /// TORCH_LIBRARY(myops, m) { + /// m.def("add", add_fn); + /// } + /// ``` + template + Library& def(NameOrSchema&& raw_name_or_schema, Func&& raw_f, + const std::vector& tags = {}) & { + CppFunction f(std::forward(raw_f)); + return _def( + detail::constructSchemaOrName( + ::std::forward(raw_name_or_schema)), + ::std::move(f), tags); + } + + /// Register an implementation for an operator. You may register multiple + /// implementations for a single operator at different dispatch keys + /// (see torch::dispatch()). Implementations must have a corresponding + /// declaration (from def()), otherwise they are invalid. If you plan + /// to register multiple implementations, DO NOT provide a function + /// implementation when you def() the operator. + /// + /// \param name The name of the operator to implement. Do NOT provide + /// schema here. + /// \param raw_f The C++ function that implements this operator. Any + /// valid constructor of torch::CppFunction is accepted here; + /// typically you provide a function pointer or lambda. + /// + /// ``` + /// // Example: + /// TORCH_LIBRARY_IMPL(myops, CUDA, m) { + /// m.impl("add", add_cuda); + /// } + /// ``` + template + Library& impl( + Name name, + Func&& raw_f, + _RegisterOrVerify rv = _RegisterOrVerify::REGISTER) & { + // TODO: need to raise an error when you impl a function that has a + // catch all def +#if defined C10_MOBILE + CppFunction f(std::forward(raw_f), NoInferSchemaTag()); +#else + CppFunction f(std::forward(raw_f)); +#endif + return _impl(name, std::move(f), rv); + } + +#if defined C10_MOBILE + // Note: This overload is needed only for C10_MOBILE, since the automatically + // defined copy constructor for the CppFunction doesn't have the additional + // NoInferSchemaTag argument. We define the overload for the impl() function + // to accept a CppFunction&& argument. The already constructed CppFunction + // object may or may not have the inferred schema, but it doesn't matter + // for our purposes since if it already has the inferred schema, then we + // might as well just pass it through directly. + // + template + Library& impl(Name name, CppFunction&& raw_f) & { + // TODO: need to raise an error when you impl a function that has a + // catch all def + CppFunction f(std::forward(raw_f)); + return _impl(name, std::move(f)); + } +#endif + + // Helper for getting an OperatorName for a const char*. You probably + // don't need this. + c10::OperatorName _resolve(const char* name) const; + + /// \private + /// + /// Convenience overload for directly specifying the dispatch key when + /// impl(). You probably don't need this; instead, prefer specifying + /// the dispatch key for the entire block in TORCH_LIBRARY_IMPL() + template + Library& impl(Name name, Dispatch&& key, Func&& raw_f) & { + return impl( + name, dispatch(std::forward(key), std::forward(raw_f))); + } + + template + Library& impl_UNBOXED(Name /*name*/, Func* /*raw_f*/) & { + static_assert( + c10::guts::false_t(), + ".impl_UNBOXED(...) was removed. Please use .impl(...) instead."); + return *this; + } + + // These overloads cover cases when a SelectiveStr (see Note [Selective + // build]) has been disabled at compile time. In that case, don't generate + // any code referencing the passed in functions at all. + Library& def(detail::SelectiveStr, const std::vector& tags = {}) & { + return *this; + } + Library& def(detail::SelectiveStr raw_schema, const std::vector& tags = {}) & { + return def(raw_schema.operator const char*(), tags); + } + template + Library& def(detail::SelectiveStr, Func&& /*raw_f*/, const std::vector& tags = {}) & { + return *this; + } + template + Library& def(detail::SelectiveStr raw_name_or_schema, Func&& raw_f, const std::vector& tags = {}) & { + return def( + raw_name_or_schema.operator const char*(), std::forward(raw_f), tags); + } + + template + Library& impl(detail::SelectiveStr, Func&& /*raw_f*/) & { + return *this; + } + template + Library& impl( + detail::SelectiveStr, + Dispatch&& /*key*/, + Func&& /*raw_f*/) & { + return *this; + } + template + Library& impl_UNBOXED( + detail::SelectiveStr /*name*/, + Func* /*raw_f*/) & { + static_assert( + c10::guts::false_t(), + ".impl_UNBOXED(...) was removed. Please use .impl(...) instead."); + return *this; + } + + template + Library& impl(detail::SelectiveStr name, Func&& raw_f) & { + return impl(name.operator const char*(), std::forward(raw_f)); + } + template + Library& impl( + detail::SelectiveStr name, + Dispatch&& key, + Func&& raw_f) & { + return impl( + name.operator const char*(), + std::forward(key), + std::forward(raw_f)); + } + template + Library& impl_UNBOXED( + detail::SelectiveStr /*name*/, + Func* /*raw_f*/) & { + static_assert( + c10::guts::false_t(), + ".impl_UNBOXED(...) was removed. Please use .impl(...) instead."); + return *this; + } + + /// Register a fallback implementation for all operators which will be used + /// if there is not a specific implementation for an operator available. + /// There MUST be a DispatchKey associated with a fallback; e.g., + /// only call this from TORCH_LIBRARY_IMPL() with namespace `_`. + /// + /// \param raw_f The function that implements the fallback. Unboxed + /// functions typically do not work as fallback functions, as + /// fallback functions must work for every operator (even though + /// they have varying type signatures). Typical arguments are + /// CppFunction::makeFallthrough() or + /// CppFunction::makeFromBoxedFunction() + /// + /// ``` + /// // Example: + /// + /// TORCH_LIBRARY_IMPL(_, AutogradXLA, m) { + /// // If there is not a kernel explicitly registered + /// // for AutogradXLA, fallthrough to the next + /// // available kernel + /// m.fallback(torch::CppFunction::makeFallthrough()); + /// } + /// + /// // See aten/src/ATen/core/dispatch/backend_fallback_test.cpp + /// // for a full example of boxed fallback + /// ``` + template + Library& fallback(Func&& raw_f) & { + CppFunction f((std::forward(raw_f))); + return _fallback(std::move(f)); + } + + template + inline torch::class_ class_(const std::string& className); + + // These overloads enable the use of selective build on classes registered + // within a library. The API is the same as before with 1 minor change. + // Instead of m.class_("foo") you instead do + // m.class_(TORCH_SELECTIVE_CLASS("foo")) + template + inline torch::class_ class_(detail::SelectiveStr className); + + template + inline detail::ClassNotSelected class_(detail::SelectiveStr className); + + // De-registers all registrations created with this Library + void reset(); + + private: + Kind kind_; + c10::optional ns_; + c10::optional dispatch_key_; + c10::optional> impl_abstract_pystub_; + const char* file_; + uint32_t line_; + + std::vector registrars_; + + friend class detail::TorchLibraryInit; + + // Non-user visible actual implementations of functions. These aren't + // public because we only implement & qualifier and not && qualifier + Library& _def( + c10::FunctionSchema&& schema, + c10::OperatorName* out_name = nullptr, + const std::vector& tags = {}, + _RegisterOrVerify rv = _RegisterOrVerify::REGISTER) &; + Library& _def( + std::variant&&, + CppFunction&& f, + const std::vector& tags = {}) &; + Library& _impl( + const char* name, + CppFunction&& f, + _RegisterOrVerify rv = _RegisterOrVerify::REGISTER) &; + Library& _fallback(CppFunction&& f) &; + + at::OperatorName _parseNameForLib(const char* name_str) const; +}; + +namespace detail { + +class TorchLibraryInit final { + private: + using InitFn = void(Library&); + Library lib_; + + public: + TorchLibraryInit( + Library::Kind kind, + InitFn* fn, + const char* ns, + c10::optional k, + const char* file, + uint32_t line) + : lib_(kind, ns, k, file, line) { + fn(lib_); + } +}; + +} // namespace detail + +} // namespace torch + +// NB: The EXACT NAMING of the initializer functions (e.g., +// TORCH_LIBRARY_init_aten) matters for the code analyzer; +// see the regexes at tools/code_analyzer/run_analyzer.sh + +/// Macro for defining a function that will be run at static +/// initialization time to define a library of operators in the +/// namespace `ns` (must be a valid C++ identifier, no quotes). +/// Use this macro when you want to define a new set of custom operators +/// that do not already exist in PyTorch. +/// +/// Example usage: +/// +/// ``` +/// TORCH_LIBRARY(myops, m) { +/// // m is a torch::Library; methods on it will define +/// // operators in the myops namespace +/// m.def("add", add_impl); +/// } +/// ``` +/// +/// The `m` argument is bound to a torch::Library that is used to +/// register operators. There may only be one TORCH_LIBRARY() +/// for any given namespace. +#define TORCH_LIBRARY(ns, m) \ + static void TORCH_LIBRARY_init_##ns(torch::Library&); \ + static const torch::detail::TorchLibraryInit TORCH_LIBRARY_static_init_##ns( \ + torch::Library::DEF, \ + &TORCH_LIBRARY_init_##ns, \ + #ns, \ + c10::nullopt, \ + __FILE__, \ + __LINE__); \ + void TORCH_LIBRARY_init_##ns(torch::Library& m) + +/// \private +/// +/// This macro is a version of TORCH_LIBRARY() that doesn't enforce that there +/// is only one library (it is a "fragment"). This is used inside the +/// PerOpRegistration.cpp file, as well as in places where all op registrations +/// within the same namespace cannot be easily put into one macro block +/// (this is mostly the case for custom ops in fbcode that were ported from +/// the old API) +#define TORCH_LIBRARY_FRAGMENT(ns, m) _TORCH_LIBRARY_FRAGMENT(ns, m, C10_UID) + +/// \private +/// +/// The above macro requires an extra unique identifier (uid) to prevent +/// variable name collisions This can happen if TORCH_LIBRARY_FRAGMENT is called +/// multiple times with the same namespace in the same translation unit. Note +/// that the TORCH_LIBRARY variant doesn't run into this problem, because it +/// enforces that it can only be called once for a given namespace. +#define _TORCH_LIBRARY_FRAGMENT(ns, m, uid) \ + static void C10_CONCATENATE( \ + TORCH_LIBRARY_FRAGMENT_init_##ns##_, uid)(torch::Library&); \ + static const torch::detail::TorchLibraryInit C10_CONCATENATE( \ + TORCH_LIBRARY_FRAGMENT_static_init_##ns##_, uid)( \ + torch::Library::FRAGMENT, \ + &C10_CONCATENATE(TORCH_LIBRARY_FRAGMENT_init_##ns##_, uid), \ + #ns, \ + c10::nullopt, \ + __FILE__, \ + __LINE__); \ + void C10_CONCATENATE( \ + TORCH_LIBRARY_FRAGMENT_init_##ns##_, uid)(torch::Library & m) + +/// Macro for defining a function that will be run at static +/// initialization time to define operator overrides for dispatch key +/// `k` (must be an unqualified enum member of c10::DispatchKey) in +/// namespace `ns` (must be a valid C++ identifer, no quotes). Use this +/// macro when you want to implement a preexisting set of custom +/// operators on a new dispatch key (e.g., you want to provide CUDA +/// implementations of already existing operators). One common usage +/// pattern is to use TORCH_LIBRARY() to define schema for all new +/// operators you want to define, and then use several +/// TORCH_LIBRARY_IMPL() blocks to provide implementations of the +/// operator for CPU, CUDA and Autograd. +/// +/// In some cases, you need to define something that applies to all namespaces, +/// not just one namespace (usually a fallback). In that case, use the reserved +/// namespace _, e.g., +/// +/// ``` +/// TORCH_LIBRARY_IMPL(_, XLA, m) { +/// m.fallback(xla_fallback); +/// } +/// ``` +/// +/// Example usage: +/// +/// ``` +/// TORCH_LIBRARY_IMPL(myops, CPU, m) { +/// // m is a torch::Library; methods on it will define +/// // CPU implementations of operators in the myops namespace. +/// // It is NOT valid to call torch::Library::def() +/// // in this context. +/// m.impl("add", add_cpu_impl); +/// } +/// ``` +/// +/// If ``add_cpu_impl`` is an overloaded function, use a +/// ``static_cast`` to specify which overload you want +/// (by providing the full type). +/// +// NB: if the dispatch key is not whitelisted, we simply omit the Library +// call entirely +#define TORCH_LIBRARY_IMPL(ns, k, m) _TORCH_LIBRARY_IMPL(ns, k, m, C10_UID) + +/// \private +/// +/// The above macro requires an extra unique identifier (uid) to prevent +/// variable name collisions. This can happen if TORCH_LIBRARY_IMPL is called +/// multiple times with the same namespace and dispatch key in the same +/// translation unit. +#define _TORCH_LIBRARY_IMPL(ns, k, m, uid) \ + static void C10_CONCATENATE( \ + TORCH_LIBRARY_IMPL_init_##ns##_##k##_, uid)(torch::Library&); \ + static const torch::detail::TorchLibraryInit C10_CONCATENATE( \ + TORCH_LIBRARY_IMPL_static_init_##ns##_##k##_, uid)( \ + torch::Library::IMPL, \ + (c10::impl::dispatch_key_allowlist_check(c10::DispatchKey::k) \ + ? &C10_CONCATENATE(TORCH_LIBRARY_IMPL_init_##ns##_##k##_, uid) \ + : [](torch::Library&) -> void {}), \ + #ns, \ + c10::make_optional(c10::DispatchKey::k), \ + __FILE__, \ + __LINE__); \ + void C10_CONCATENATE( \ + TORCH_LIBRARY_IMPL_init_##ns##_##k##_, uid)(torch::Library & m) + +// These are variants of the macros above which are to be used for testing (they +// don't setup the static initializer, so you can control the visibility of +// the allocated library yourself). +// +// DO NOT use these in production code, they are NOT understood by the +// code analyzer and will be incorrectly analyzed in those situations. + +/// \private +#define MAKE_TORCH_LIBRARY(ns) \ + torch::Library(torch::Library::DEF, #ns, c10::nullopt, __FILE__, __LINE__) +/// \private +#define MAKE_TORCH_LIBRARY_IMPL(ns, k) \ + torch::Library( \ + torch::Library::IMPL, \ + #ns, \ + c10::make_optional(c10::DispatchKey::k), \ + __FILE__, \ + __LINE__) + +// Make the custom class API visible, so it is available from +// torch::Library. + +#include diff --git a/shared/package-files/cc/cc568eaaebec0f1fdc56a9e1c51641b4f813a9f90c7759378e8dcae83ff86013/test_loc.py b/shared/package-files/cc/cc568eaaebec0f1fdc56a9e1c51641b4f813a9f90c7759378e8dcae83ff86013/test_loc.py new file mode 100644 index 0000000000000000000000000000000000000000..8697103dd6f1a8c6f048fc701d2b650b2f249503 --- /dev/null +++ b/shared/package-files/cc/cc568eaaebec0f1fdc56a9e1c51641b4f813a9f90c7759378e8dcae83ff86013/test_loc.py @@ -0,0 +1,1000 @@ +import numpy as np +import pytest + +from pandas.errors import ( + IndexingError, + PerformanceWarning, +) + +import pandas as pd +from pandas import ( + DataFrame, + Index, + MultiIndex, + Series, +) +import pandas._testing as tm + + +@pytest.fixture +def single_level_multiindex(): + """single level MultiIndex""" + return MultiIndex( + levels=[["foo", "bar", "baz", "qux"]], codes=[[0, 1, 2, 3]], names=["first"] + ) + + +@pytest.fixture +def frame_random_data_integer_multi_index(): + levels = [[0, 1], [0, 1, 2]] + codes = [[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]] + index = MultiIndex(levels=levels, codes=codes) + return DataFrame(np.random.default_rng(2).standard_normal((6, 2)), index=index) + + +class TestMultiIndexLoc: + @pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning") + @pytest.mark.parametrize("has_ref", [True, False]) + def test_loc_setitem_frame_with_multiindex( + self, multiindex_dataframe_random_data, has_ref + ): + frame = multiindex_dataframe_random_data + if has_ref: + view = frame[:] + frame.loc[("bar", "two"), "B"] = 5 + assert frame.loc[("bar", "two"), "B"] == 5 + + # with integer labels + df = frame.copy() + df.columns = list(range(3)) + if has_ref: + view = df[:] # noqa: F841 + df.loc[("bar", "two"), 1] = 7 + assert df.loc[("bar", "two"), 1] == 7 + + def test_loc_getitem_general(self, any_real_numpy_dtype): + # GH#2817 + dtype = any_real_numpy_dtype + data = { + "amount": {0: 700, 1: 600, 2: 222, 3: 333, 4: 444}, + "col": {0: 3.5, 1: 3.5, 2: 4.0, 3: 4.0, 4: 4.0}, + "num": {0: 12, 1: 11, 2: 12, 3: 12, 4: 12}, + } + df = DataFrame(data) + df = df.astype({"col": dtype, "num": dtype}) + df = df.set_index(keys=["col", "num"]) + key = 4.0, 12 + + # emits a PerformanceWarning, ok + with tm.assert_produces_warning(PerformanceWarning): + tm.assert_frame_equal(df.loc[key], df.iloc[2:]) + + # this is ok + return_value = df.sort_index(inplace=True) + assert return_value is None + res = df.loc[key] + + # col has float dtype, result should be float64 Index + col_arr = np.array([4.0] * 3, dtype=dtype) + year_arr = np.array([12] * 3, dtype=dtype) + index = MultiIndex.from_arrays([col_arr, year_arr], names=["col", "num"]) + expected = DataFrame({"amount": [222, 333, 444]}, index=index) + tm.assert_frame_equal(res, expected) + + def test_loc_getitem_multiindex_missing_label_raises(self): + # GH#21593 + df = DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + columns=[[2, 2, 4], [6, 8, 10]], + index=[[4, 4, 8], [8, 10, 12]], + ) + + with pytest.raises(KeyError, match=r"^2$"): + df.loc[2] + + def test_loc_getitem_list_of_tuples_with_multiindex( + self, multiindex_year_month_day_dataframe_random_data + ): + ser = multiindex_year_month_day_dataframe_random_data["A"] + expected = ser.reindex(ser.index[49:51]) + result = ser.loc[[(2000, 3, 10), (2000, 3, 13)]] + tm.assert_series_equal(result, expected) + + def test_loc_getitem_series(self): + # GH14730 + # passing a series as a key with a MultiIndex + index = MultiIndex.from_product([[1, 2, 3], ["A", "B", "C"]]) + x = Series(index=index, data=range(9), dtype=np.float64) + y = Series([1, 3]) + expected = Series( + data=[0, 1, 2, 6, 7, 8], + index=MultiIndex.from_product([[1, 3], ["A", "B", "C"]]), + dtype=np.float64, + ) + result = x.loc[y] + tm.assert_series_equal(result, expected) + + result = x.loc[[1, 3]] + tm.assert_series_equal(result, expected) + + # GH15424 + y1 = Series([1, 3], index=[1, 2]) + result = x.loc[y1] + tm.assert_series_equal(result, expected) + + empty = Series(data=[], dtype=np.float64) + expected = Series( + [], + index=MultiIndex(levels=index.levels, codes=[[], []], dtype=np.float64), + dtype=np.float64, + ) + result = x.loc[empty] + tm.assert_series_equal(result, expected) + + def test_loc_getitem_array(self): + # GH15434 + # passing an array as a key with a MultiIndex + index = MultiIndex.from_product([[1, 2, 3], ["A", "B", "C"]]) + x = Series(index=index, data=range(9), dtype=np.float64) + y = np.array([1, 3]) + expected = Series( + data=[0, 1, 2, 6, 7, 8], + index=MultiIndex.from_product([[1, 3], ["A", "B", "C"]]), + dtype=np.float64, + ) + result = x.loc[y] + tm.assert_series_equal(result, expected) + + # empty array: + empty = np.array([]) + expected = Series( + [], + index=MultiIndex(levels=index.levels, codes=[[], []], dtype=np.float64), + dtype="float64", + ) + result = x.loc[empty] + tm.assert_series_equal(result, expected) + + # 0-dim array (scalar): + scalar = np.int64(1) + expected = Series(data=[0, 1, 2], index=["A", "B", "C"], dtype=np.float64) + result = x.loc[scalar] + tm.assert_series_equal(result, expected) + + def test_loc_multiindex_labels(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + columns=[["i", "i", "j"], ["A", "A", "B"]], + index=[["i", "i", "j"], ["X", "X", "Y"]], + ) + + # the first 2 rows + expected = df.iloc[[0, 1]].droplevel(0) + result = df.loc["i"] + tm.assert_frame_equal(result, expected) + + # 2nd (last) column + expected = df.iloc[:, [2]].droplevel(0, axis=1) + result = df.loc[:, "j"] + tm.assert_frame_equal(result, expected) + + # bottom right corner + expected = df.iloc[[2], [2]].droplevel(0).droplevel(0, axis=1) + result = df.loc["j"].loc[:, "j"] + tm.assert_frame_equal(result, expected) + + # with a tuple + expected = df.iloc[[0, 1]] + result = df.loc[("i", "X")] + tm.assert_frame_equal(result, expected) + + def test_loc_multiindex_ints(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + columns=[[2, 2, 4], [6, 8, 10]], + index=[[4, 4, 8], [8, 10, 12]], + ) + expected = df.iloc[[0, 1]].droplevel(0) + result = df.loc[4] + tm.assert_frame_equal(result, expected) + + def test_loc_multiindex_missing_label_raises(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + columns=[[2, 2, 4], [6, 8, 10]], + index=[[4, 4, 8], [8, 10, 12]], + ) + + with pytest.raises(KeyError, match=r"^2$"): + df.loc[2] + + @pytest.mark.parametrize("key, pos", [([2, 4], [0, 1]), ([2], []), ([2, 3], [])]) + def test_loc_multiindex_list_missing_label(self, key, pos): + # GH 27148 - lists with missing labels _do_ raise + df = DataFrame( + np.random.default_rng(2).standard_normal((3, 3)), + columns=[[2, 2, 4], [6, 8, 10]], + index=[[4, 4, 8], [8, 10, 12]], + ) + + with pytest.raises(KeyError, match="not in index"): + df.loc[key] + + def test_loc_multiindex_too_many_dims_raises(self): + # GH 14885 + s = Series( + range(8), + index=MultiIndex.from_product([["a", "b"], ["c", "d"], ["e", "f"]]), + ) + + with pytest.raises(KeyError, match=r"^\('a', 'b'\)$"): + s.loc["a", "b"] + with pytest.raises(KeyError, match=r"^\('a', 'd', 'g'\)$"): + s.loc["a", "d", "g"] + with pytest.raises(IndexingError, match="Too many indexers"): + s.loc["a", "d", "g", "j"] + + def test_loc_multiindex_indexer_none(self): + # GH6788 + # multi-index indexer is None (meaning take all) + attributes = ["Attribute" + str(i) for i in range(1)] + attribute_values = ["Value" + str(i) for i in range(5)] + + index = MultiIndex.from_product([attributes, attribute_values]) + df = 0.1 * np.random.default_rng(2).standard_normal((10, 1 * 5)) + 0.5 + df = DataFrame(df, columns=index) + result = df[attributes] + tm.assert_frame_equal(result, df) + + # GH 7349 + # loc with a multi-index seems to be doing fallback + df = DataFrame( + np.arange(12).reshape(-1, 1), + index=MultiIndex.from_product([[1, 2, 3, 4], [1, 2, 3]]), + ) + + expected = df.loc[([1, 2],), :] + result = df.loc[[1, 2]] + tm.assert_frame_equal(result, expected) + + def test_loc_multiindex_incomplete(self): + # GH 7399 + # incomplete indexers + s = Series( + np.arange(15, dtype="int64"), + MultiIndex.from_product([range(5), ["a", "b", "c"]]), + ) + expected = s.loc[:, "a":"c"] + + result = s.loc[0:4, "a":"c"] + tm.assert_series_equal(result, expected) + + result = s.loc[:4, "a":"c"] + tm.assert_series_equal(result, expected) + + result = s.loc[0:, "a":"c"] + tm.assert_series_equal(result, expected) + + # GH 7400 + # multiindexer getitem with list of indexers skips wrong element + s = Series( + np.arange(15, dtype="int64"), + MultiIndex.from_product([range(5), ["a", "b", "c"]]), + ) + expected = s.iloc[[6, 7, 8, 12, 13, 14]] + result = s.loc[2:4:2, "a":"c"] + tm.assert_series_equal(result, expected) + + def test_get_loc_single_level(self, single_level_multiindex): + single_level = single_level_multiindex + s = Series( + np.random.default_rng(2).standard_normal(len(single_level)), + index=single_level, + ) + for k in single_level.values: + s[k] + + def test_loc_getitem_int_slice(self): + # GH 3053 + # loc should treat integer slices like label slices + + index = MultiIndex.from_product([[6, 7, 8], ["a", "b"]]) + df = DataFrame(np.random.default_rng(2).standard_normal((6, 6)), index, index) + result = df.loc[6:8, :] + expected = df + tm.assert_frame_equal(result, expected) + + index = MultiIndex.from_product([[10, 20, 30], ["a", "b"]]) + df = DataFrame(np.random.default_rng(2).standard_normal((6, 6)), index, index) + result = df.loc[20:30, :] + expected = df.iloc[2:] + tm.assert_frame_equal(result, expected) + + # doc examples + result = df.loc[10, :] + expected = df.iloc[0:2] + expected.index = ["a", "b"] + tm.assert_frame_equal(result, expected) + + result = df.loc[:, 10] + expected = df[10] + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "indexer_type_1", (list, tuple, set, slice, np.ndarray, Series, Index) + ) + @pytest.mark.parametrize( + "indexer_type_2", (list, tuple, set, slice, np.ndarray, Series, Index) + ) + def test_loc_getitem_nested_indexer(self, indexer_type_1, indexer_type_2): + # GH #19686 + # .loc should work with nested indexers which can be + # any list-like objects (see `is_list_like` (`pandas.api.types`)) or slices + + def convert_nested_indexer(indexer_type, keys): + if indexer_type == np.ndarray: + return np.array(keys) + if indexer_type == slice: + return slice(*keys) + return indexer_type(keys) + + a = [10, 20, 30] + b = [1, 2, 3] + index = MultiIndex.from_product([a, b]) + df = DataFrame( + np.arange(len(index), dtype="int64"), index=index, columns=["Data"] + ) + + keys = ([10, 20], [2, 3]) + types = (indexer_type_1, indexer_type_2) + + # check indexers with all the combinations of nested objects + # of all the valid types + indexer = tuple( + convert_nested_indexer(indexer_type, k) + for indexer_type, k in zip(types, keys) + ) + if indexer_type_1 is set or indexer_type_2 is set: + with pytest.raises(TypeError, match="as an indexer is not supported"): + df.loc[indexer, "Data"] + + return + else: + result = df.loc[indexer, "Data"] + expected = Series( + [1, 2, 4, 5], name="Data", index=MultiIndex.from_product(keys) + ) + + tm.assert_series_equal(result, expected) + + def test_multiindex_loc_one_dimensional_tuple(self, frame_or_series): + # GH#37711 + mi = MultiIndex.from_tuples([("a", "A"), ("b", "A")]) + obj = frame_or_series([1, 2], index=mi) + obj.loc[("a",)] = 0 + expected = frame_or_series([0, 2], index=mi) + tm.assert_equal(obj, expected) + + @pytest.mark.parametrize("indexer", [("a",), ("a")]) + def test_multiindex_one_dimensional_tuple_columns(self, indexer): + # GH#37711 + mi = MultiIndex.from_tuples([("a", "A"), ("b", "A")]) + obj = DataFrame([1, 2], index=mi) + obj.loc[indexer, :] = 0 + expected = DataFrame([0, 2], index=mi) + tm.assert_frame_equal(obj, expected) + + @pytest.mark.parametrize( + "indexer, exp_value", [(slice(None), 1.0), ((1, 2), np.nan)] + ) + def test_multiindex_setitem_columns_enlarging(self, indexer, exp_value): + # GH#39147 + mi = MultiIndex.from_tuples([(1, 2), (3, 4)]) + df = DataFrame([[1, 2], [3, 4]], index=mi, columns=["a", "b"]) + df.loc[indexer, ["c", "d"]] = 1.0 + expected = DataFrame( + [[1, 2, 1.0, 1.0], [3, 4, exp_value, exp_value]], + index=mi, + columns=["a", "b", "c", "d"], + ) + tm.assert_frame_equal(df, expected) + + def test_sorted_multiindex_after_union(self): + # GH#44752 + midx = MultiIndex.from_product( + [pd.date_range("20110101", periods=2), Index(["a", "b"])] + ) + ser1 = Series(1, index=midx) + ser2 = Series(1, index=midx[:2]) + df = pd.concat([ser1, ser2], axis=1) + expected = df.copy() + result = df.loc["2011-01-01":"2011-01-02"] + tm.assert_frame_equal(result, expected) + + df = DataFrame({0: ser1, 1: ser2}) + result = df.loc["2011-01-01":"2011-01-02"] + tm.assert_frame_equal(result, expected) + + df = pd.concat([ser1, ser2.reindex(ser1.index)], axis=1) + result = df.loc["2011-01-01":"2011-01-02"] + tm.assert_frame_equal(result, expected) + + def test_loc_no_second_level_index(self): + # GH#43599 + df = DataFrame( + index=MultiIndex.from_product([list("ab"), list("cd"), list("e")]), + columns=["Val"], + ) + res = df.loc[np.s_[:, "c", :]] + expected = DataFrame( + index=MultiIndex.from_product([list("ab"), list("e")]), columns=["Val"] + ) + tm.assert_frame_equal(res, expected) + + def test_loc_multi_index_key_error(self): + # GH 51892 + df = DataFrame( + { + (1, 2): ["a", "b", "c"], + (1, 3): ["d", "e", "f"], + (2, 2): ["g", "h", "i"], + (2, 4): ["j", "k", "l"], + } + ) + with pytest.raises(KeyError, match=r"(1, 4)"): + df.loc[0, (1, 4)] + + +@pytest.mark.parametrize( + "indexer, pos", + [ + ([], []), # empty ok + (["A"], slice(3)), + (["A", "D"], []), # "D" isn't present -> raise + (["D", "E"], []), # no values found -> raise + (["D"], []), # same, with single item list: GH 27148 + (pd.IndexSlice[:, ["foo"]], slice(2, None, 3)), + (pd.IndexSlice[:, ["foo", "bah"]], slice(2, None, 3)), + ], +) +def test_loc_getitem_duplicates_multiindex_missing_indexers(indexer, pos): + # GH 7866 + # multi-index slicing with missing indexers + idx = MultiIndex.from_product( + [["A", "B", "C"], ["foo", "bar", "baz"]], names=["one", "two"] + ) + ser = Series(np.arange(9, dtype="int64"), index=idx).sort_index() + expected = ser.iloc[pos] + + if expected.size == 0 and indexer != []: + with pytest.raises(KeyError, match=str(indexer)): + ser.loc[indexer] + elif indexer == (slice(None), ["foo", "bah"]): + # "bah" is not in idx.levels[1], raising KeyError enforced in 2.0 + with pytest.raises(KeyError, match="'bah'"): + ser.loc[indexer] + else: + result = ser.loc[indexer] + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("columns_indexer", [([], slice(None)), (["foo"], [])]) +def test_loc_getitem_duplicates_multiindex_empty_indexer(columns_indexer): + # GH 8737 + # empty indexer + multi_index = MultiIndex.from_product((["foo", "bar", "baz"], ["alpha", "beta"])) + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 6)), + index=range(5), + columns=multi_index, + ) + df = df.sort_index(level=0, axis=1) + + expected = DataFrame(index=range(5), columns=multi_index.reindex([])[0]) + result = df.loc[:, columns_indexer] + tm.assert_frame_equal(result, expected) + + +def test_loc_getitem_duplicates_multiindex_non_scalar_type_object(): + # regression from < 0.14.0 + # GH 7914 + df = DataFrame( + [[np.mean, np.median], ["mean", "median"]], + columns=MultiIndex.from_tuples([("functs", "mean"), ("functs", "median")]), + index=["function", "name"], + ) + result = df.loc["function", ("functs", "mean")] + expected = np.mean + assert result == expected + + +def test_loc_getitem_tuple_plus_slice(): + # GH 671 + df = DataFrame( + { + "a": np.arange(10), + "b": np.arange(10), + "c": np.random.default_rng(2).standard_normal(10), + "d": np.random.default_rng(2).standard_normal(10), + } + ).set_index(["a", "b"]) + expected = df.loc[0, 0] + result = df.loc[(0, 0), :] + tm.assert_series_equal(result, expected) + + +def test_loc_getitem_int(frame_random_data_integer_multi_index): + df = frame_random_data_integer_multi_index + result = df.loc[1] + expected = df[-3:] + expected.index = expected.index.droplevel(0) + tm.assert_frame_equal(result, expected) + + +def test_loc_getitem_int_raises_exception(frame_random_data_integer_multi_index): + df = frame_random_data_integer_multi_index + with pytest.raises(KeyError, match=r"^3$"): + df.loc[3] + + +def test_loc_getitem_lowerdim_corner(multiindex_dataframe_random_data): + df = multiindex_dataframe_random_data + + # test setup - check key not in dataframe + with pytest.raises(KeyError, match=r"^\('bar', 'three'\)$"): + df.loc[("bar", "three"), "B"] + + # in theory should be inserting in a sorted space???? + df.loc[("bar", "three"), "B"] = 0 + expected = 0 + result = df.sort_index().loc[("bar", "three"), "B"] + assert result == expected + + +def test_loc_setitem_single_column_slice(): + # case from https://github.com/pandas-dev/pandas/issues/27841 + df = DataFrame( + "string", + index=list("abcd"), + columns=MultiIndex.from_product([["Main"], ("another", "one")]), + ) + df["labels"] = "a" + df.loc[:, "labels"] = df.index + tm.assert_numpy_array_equal(np.asarray(df["labels"]), np.asarray(df.index)) + + # test with non-object block + df = DataFrame( + np.nan, + index=range(4), + columns=MultiIndex.from_tuples([("A", "1"), ("A", "2"), ("B", "1")]), + ) + expected = df.copy() + df.loc[:, "B"] = np.arange(4) + expected.iloc[:, 2] = np.arange(4) + tm.assert_frame_equal(df, expected) + + +def test_loc_nan_multiindex(using_infer_string): + # GH 5286 + tups = [ + ("Good Things", "C", np.nan), + ("Good Things", "R", np.nan), + ("Bad Things", "C", np.nan), + ("Bad Things", "T", np.nan), + ("Okay Things", "N", "B"), + ("Okay Things", "N", "D"), + ("Okay Things", "B", np.nan), + ("Okay Things", "D", np.nan), + ] + df = DataFrame( + np.ones((8, 4)), + columns=Index(["d1", "d2", "d3", "d4"]), + index=MultiIndex.from_tuples(tups, names=["u1", "u2", "u3"]), + ) + result = df.loc["Good Things"].loc["C"] + expected = DataFrame( + np.ones((1, 4)), + index=Index( + [np.nan], + dtype="object" if not using_infer_string else "str", + name="u3", + ), + columns=Index(["d1", "d2", "d3", "d4"]), + ) + tm.assert_frame_equal(result, expected) + + +def test_loc_period_string_indexing(): + # GH 9892 + a = pd.period_range("2013Q1", "2013Q4", freq="Q") + i = (1111, 2222, 3333) + idx = MultiIndex.from_product((a, i), names=("Period", "CVR")) + df = DataFrame( + index=idx, + columns=( + "OMS", + "OMK", + "RES", + "DRIFT_IND", + "OEVRIG_IND", + "FIN_IND", + "VARE_UD", + "LOEN_UD", + "FIN_UD", + ), + ) + result = df.loc[("2013Q1", 1111), "OMS"] + + alt = df.loc[(a[0], 1111), "OMS"] + assert np.isnan(alt) + + # Because the resolution of the string matches, it is an exact lookup, + # not a slice + assert np.isnan(result) + + alt = df.loc[("2013Q1", 1111), "OMS"] + assert np.isnan(alt) + + +def test_loc_datetime_mask_slicing(): + # GH 16699 + dt_idx = pd.to_datetime(["2017-05-04", "2017-05-05"]) + m_idx = MultiIndex.from_product([dt_idx, dt_idx], names=["Idx1", "Idx2"]) + df = DataFrame( + data=[[1, 2], [3, 4], [5, 6], [7, 6]], index=m_idx, columns=["C1", "C2"] + ) + result = df.loc[(dt_idx[0], (df.index.get_level_values(1) > "2017-05-04")), "C1"] + expected = Series( + [3], + name="C1", + index=MultiIndex.from_tuples( + [(pd.Timestamp("2017-05-04"), pd.Timestamp("2017-05-05"))], + names=["Idx1", "Idx2"], + ), + ) + tm.assert_series_equal(result, expected) + + +def test_loc_datetime_series_tuple_slicing(): + # https://github.com/pandas-dev/pandas/issues/35858 + date = pd.Timestamp("2000") + ser = Series( + 1, + index=MultiIndex.from_tuples([("a", date)], names=["a", "b"]), + name="c", + ) + result = ser.loc[:, [date]] + tm.assert_series_equal(result, ser) + + +def test_loc_with_mi_indexer(): + # https://github.com/pandas-dev/pandas/issues/35351 + df = DataFrame( + data=[["a", 1], ["a", 0], ["b", 1], ["c", 2]], + index=MultiIndex.from_tuples( + [(0, 1), (1, 0), (1, 1), (1, 1)], names=["index", "date"] + ), + columns=["author", "price"], + ) + idx = MultiIndex.from_tuples([(0, 1), (1, 1)], names=["index", "date"]) + result = df.loc[idx, :] + expected = DataFrame( + [["a", 1], ["b", 1], ["c", 2]], + index=MultiIndex.from_tuples([(0, 1), (1, 1), (1, 1)], names=["index", "date"]), + columns=["author", "price"], + ) + tm.assert_frame_equal(result, expected) + + +def test_loc_mi_with_level1_named_0(): + # GH#37194 + dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific") + + ser = Series(range(3), index=dti) + df = ser.to_frame() + df[1] = dti + + df2 = df.set_index(0, append=True) + assert df2.index.names == (None, 0) + df2.index.get_loc(dti[0]) # smoke test + + result = df2.loc[dti[0]] + expected = df2.iloc[[0]].droplevel(None) + tm.assert_frame_equal(result, expected) + + ser2 = df2[1] + assert ser2.index.names == (None, 0) + + result = ser2.loc[dti[0]] + expected = ser2.iloc[[0]].droplevel(None) + tm.assert_series_equal(result, expected) + + +def test_getitem_str_slice(): + # GH#15928 + df = DataFrame( + [ + ["20160525 13:30:00.023", "MSFT", "51.95", "51.95"], + ["20160525 13:30:00.048", "GOOG", "720.50", "720.93"], + ["20160525 13:30:00.076", "AAPL", "98.55", "98.56"], + ["20160525 13:30:00.131", "AAPL", "98.61", "98.62"], + ["20160525 13:30:00.135", "MSFT", "51.92", "51.95"], + ["20160525 13:30:00.135", "AAPL", "98.61", "98.62"], + ], + columns="time,ticker,bid,ask".split(","), + ) + df2 = df.set_index(["ticker", "time"]).sort_index() + + res = df2.loc[("AAPL", slice("2016-05-25 13:30:00")), :].droplevel(0) + expected = df2.loc["AAPL"].loc[slice("2016-05-25 13:30:00"), :] + tm.assert_frame_equal(res, expected) + + +def test_3levels_leading_period_index(): + # GH#24091 + pi = pd.PeriodIndex( + ["20181101 1100", "20181101 1200", "20181102 1300", "20181102 1400"], + name="datetime", + freq="D", + ) + lev2 = ["A", "A", "Z", "W"] + lev3 = ["B", "C", "Q", "F"] + mi = MultiIndex.from_arrays([pi, lev2, lev3]) + + ser = Series(range(4), index=mi, dtype=np.float64) + result = ser.loc[(pi[0], "A", "B")] + assert result == 0.0 + + +class TestKeyErrorsWithMultiIndex: + def test_missing_keys_raises_keyerror(self): + # GH#27420 KeyError, not TypeError + df = DataFrame(np.arange(12).reshape(4, 3), columns=["A", "B", "C"]) + df2 = df.set_index(["A", "B"]) + + with pytest.raises(KeyError, match="1"): + df2.loc[(1, 6)] + + def test_missing_key_raises_keyerror2(self): + # GH#21168 KeyError, not "IndexingError: Too many indexers" + ser = Series(-1, index=MultiIndex.from_product([[0, 1]] * 2)) + + with pytest.raises(KeyError, match=r"\(0, 3\)"): + ser.loc[0, 3] + + def test_missing_key_combination(self): + # GH: 19556 + mi = MultiIndex.from_arrays( + [ + np.array(["a", "a", "b", "b"]), + np.array(["1", "2", "2", "3"]), + np.array(["c", "d", "c", "d"]), + ], + names=["one", "two", "three"], + ) + df = DataFrame(np.random.default_rng(2).random((4, 3)), index=mi) + msg = r"\('b', '1', slice\(None, None, None\)\)" + with pytest.raises(KeyError, match=msg): + df.loc[("b", "1", slice(None)), :] + with pytest.raises(KeyError, match=msg): + df.index.get_locs(("b", "1", slice(None))) + with pytest.raises(KeyError, match=r"\('b', '1'\)"): + df.loc[("b", "1"), :] + + +def test_getitem_loc_commutability(multiindex_year_month_day_dataframe_random_data): + df = multiindex_year_month_day_dataframe_random_data + ser = df["A"] + result = ser[2000, 5] + expected = df.loc[2000, 5]["A"] + tm.assert_series_equal(result, expected) + + +def test_loc_with_nan(): + # GH: 27104 + df = DataFrame( + {"col": [1, 2, 5], "ind1": ["a", "d", np.nan], "ind2": [1, 4, 5]} + ).set_index(["ind1", "ind2"]) + result = df.loc[["a"]] + expected = DataFrame( + {"col": [1]}, index=MultiIndex.from_tuples([("a", 1)], names=["ind1", "ind2"]) + ) + tm.assert_frame_equal(result, expected) + + result = df.loc["a"] + expected = DataFrame({"col": [1]}, index=Index([1], name="ind2")) + tm.assert_frame_equal(result, expected) + + +def test_getitem_non_found_tuple(): + # GH: 25236 + df = DataFrame([[1, 2, 3, 4]], columns=["a", "b", "c", "d"]).set_index( + ["a", "b", "c"] + ) + with pytest.raises(KeyError, match=r"\(2\.0, 2\.0, 3\.0\)"): + df.loc[(2.0, 2.0, 3.0)] + + +def test_get_loc_datetime_index(): + # GH#24263 + index = pd.date_range("2001-01-01", periods=100) + mi = MultiIndex.from_arrays([index]) + # Check if get_loc matches for Index and MultiIndex + assert mi.get_loc("2001-01") == slice(0, 31, None) + assert index.get_loc("2001-01") == slice(0, 31, None) + + loc = mi[::2].get_loc("2001-01") + expected = index[::2].get_loc("2001-01") + assert loc == expected + + loc = mi.repeat(2).get_loc("2001-01") + expected = index.repeat(2).get_loc("2001-01") + assert loc == expected + + loc = mi.append(mi).get_loc("2001-01") + expected = index.append(index).get_loc("2001-01") + # TODO: standardize return type for MultiIndex.get_loc + tm.assert_numpy_array_equal(loc.nonzero()[0], expected) + + +def test_loc_setitem_indexer_differently_ordered(): + # GH#34603 + mi = MultiIndex.from_product([["a", "b"], [0, 1]]) + df = DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]], index=mi) + + indexer = ("a", [1, 0]) + df.loc[indexer, :] = np.array([[9, 10], [11, 12]]) + expected = DataFrame([[11, 12], [9, 10], [5, 6], [7, 8]], index=mi) + tm.assert_frame_equal(df, expected) + + +def test_loc_getitem_index_differently_ordered_slice_none(): + # GH#31330 + df = DataFrame( + [[1, 2], [3, 4], [5, 6], [7, 8]], + index=[["a", "a", "b", "b"], [1, 2, 1, 2]], + columns=["a", "b"], + ) + result = df.loc[(slice(None), [2, 1]), :] + expected = DataFrame( + [[3, 4], [7, 8], [1, 2], [5, 6]], + index=[["a", "b", "a", "b"], [2, 2, 1, 1]], + columns=["a", "b"], + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("indexer", [[1, 2, 7, 6, 2, 3, 8, 7], [1, 2, 7, 6, 3, 8]]) +def test_loc_getitem_index_differently_ordered_slice_none_duplicates(indexer): + # GH#40978 + df = DataFrame( + [1] * 8, + index=MultiIndex.from_tuples( + [(1, 1), (1, 2), (1, 7), (1, 6), (2, 2), (2, 3), (2, 8), (2, 7)] + ), + columns=["a"], + ) + result = df.loc[(slice(None), indexer), :] + expected = DataFrame( + [1] * 8, + index=[[1, 1, 2, 1, 2, 1, 2, 2], [1, 2, 2, 7, 7, 6, 3, 8]], + columns=["a"], + ) + tm.assert_frame_equal(result, expected) + + result = df.loc[df.index.isin(indexer, level=1), :] + tm.assert_frame_equal(result, df) + + +def test_loc_getitem_drops_levels_for_one_row_dataframe(): + # GH#10521 "x" and "z" are both scalar indexing, so those levels are dropped + mi = MultiIndex.from_arrays([["x"], ["y"], ["z"]], names=["a", "b", "c"]) + df = DataFrame({"d": [0]}, index=mi) + expected = df.droplevel([0, 2]) + result = df.loc["x", :, "z"] + tm.assert_frame_equal(result, expected) + + ser = Series([0], index=mi) + result = ser.loc["x", :, "z"] + expected = Series([0], index=Index(["y"], name="b")) + tm.assert_series_equal(result, expected) + + +def test_mi_columns_loc_list_label_order(): + # GH 10710 + cols = MultiIndex.from_product([["A", "B", "C"], [1, 2]]) + df = DataFrame(np.zeros((5, 6)), columns=cols) + result = df.loc[:, ["B", "A"]] + expected = DataFrame( + np.zeros((5, 4)), + columns=MultiIndex.from_tuples([("B", 1), ("B", 2), ("A", 1), ("A", 2)]), + ) + tm.assert_frame_equal(result, expected) + + +def test_mi_partial_indexing_list_raises(): + # GH 13501 + frame = DataFrame( + np.arange(12).reshape((4, 3)), + index=[["a", "a", "b", "b"], [1, 2, 1, 2]], + columns=[["Ohio", "Ohio", "Colorado"], ["Green", "Red", "Green"]], + ) + frame.index.names = ["key1", "key2"] + frame.columns.names = ["state", "color"] + with pytest.raises(KeyError, match="\\[2\\] not in index"): + frame.loc[["b", 2], "Colorado"] + + +def test_mi_indexing_list_nonexistent_raises(): + # GH 15452 + s = Series(range(4), index=MultiIndex.from_product([[1, 2], ["a", "b"]])) + with pytest.raises(KeyError, match="\\['not' 'found'\\] not in index"): + s.loc[["not", "found"]] + + +def test_mi_add_cell_missing_row_non_unique(): + # GH 16018 + result = DataFrame( + [[1, 2, 5, 6], [3, 4, 7, 8]], + index=["a", "a"], + columns=MultiIndex.from_product([[1, 2], ["A", "B"]]), + ) + result.loc["c"] = -1 + result.loc["c", (1, "A")] = 3 + result.loc["d", (1, "A")] = 3 + expected = DataFrame( + [ + [1.0, 2.0, 5.0, 6.0], + [3.0, 4.0, 7.0, 8.0], + [3.0, -1.0, -1, -1], + [3.0, np.nan, np.nan, np.nan], + ], + index=["a", "a", "c", "d"], + columns=MultiIndex.from_product([[1, 2], ["A", "B"]]), + ) + tm.assert_frame_equal(result, expected) + + +def test_loc_get_scalar_casting_to_float(): + # GH#41369 + df = DataFrame( + {"a": 1.0, "b": 2}, index=MultiIndex.from_arrays([[3], [4]], names=["c", "d"]) + ) + result = df.loc[(3, 4), "b"] + assert result == 2 + assert isinstance(result, np.int64) + result = df.loc[[(3, 4)], "b"].iloc[0] + assert result == 2 + assert isinstance(result, np.int64) + + +def test_loc_empty_single_selector_with_names(): + # GH 19517 + idx = MultiIndex.from_product([["a", "b"], ["A", "B"]], names=[1, 0]) + s2 = Series(index=idx, dtype=np.float64) + result = s2.loc["a"] + expected = Series([np.nan, np.nan], index=Index(["A", "B"], name=0)) + tm.assert_series_equal(result, expected) + + +def test_loc_keyerror_rightmost_key_missing(): + # GH 20951 + + df = DataFrame( + { + "A": [100, 100, 200, 200, 300, 300], + "B": [10, 10, 20, 21, 31, 33], + "C": range(6), + } + ) + df = df.set_index(["A", "B"]) + with pytest.raises(KeyError, match="^1$"): + df.loc[(100, 1)] + + +def test_multindex_series_loc_with_tuple_label(): + # GH#43908 + mi = MultiIndex.from_tuples([(1, 2), (3, (4, 5))]) + ser = Series([1, 2], index=mi) + result = ser.loc[(3, (4, 5))] + assert result == 2 diff --git a/shared/package-files/cc/cc57ba2d749fba82631ac9984cc1a326d05c00c2e2285903ee3efe55aa8ac07f/Baghdad b/shared/package-files/cc/cc57ba2d749fba82631ac9984cc1a326d05c00c2e2285903ee3efe55aa8ac07f/Baghdad new file mode 100644 index 0000000000000000000000000000000000000000..a3ce97599100c0e514afa0764879c3f104be87e9 Binary files /dev/null and b/shared/package-files/cc/cc57ba2d749fba82631ac9984cc1a326d05c00c2e2285903ee3efe55aa8ac07f/Baghdad differ diff --git a/shared/package-files/cc/cc59009fbd58a8b1a0e2b0ee7e39711738675e71ccb8bb890a6230355435186d/_differentiate.py b/shared/package-files/cc/cc59009fbd58a8b1a0e2b0ee7e39711738675e71ccb8bb890a6230355435186d/_differentiate.py new file mode 100644 index 0000000000000000000000000000000000000000..0e104a071055161b69f62cec317e8a07b4466653 --- /dev/null +++ b/shared/package-files/cc/cc59009fbd58a8b1a0e2b0ee7e39711738675e71ccb8bb890a6230355435186d/_differentiate.py @@ -0,0 +1,1129 @@ +# mypy: disable-error-code="attr-defined" +import warnings +import numpy as np +import scipy._lib._elementwise_iterative_method as eim +from scipy._lib._util import _RichResult +from scipy._lib._array_api import array_namespace, xp_sign, xp_copy, xp_take_along_axis + +_EERRORINCREASE = -1 # used in derivative + +def _derivative_iv(f, x, args, tolerances, maxiter, order, initial_step, + step_factor, step_direction, preserve_shape, callback): + # Input validation for `derivative` + xp = array_namespace(x) + + if not callable(f): + raise ValueError('`f` must be callable.') + + if not np.iterable(args): + args = (args,) + + tolerances = {} if tolerances is None else tolerances + atol = tolerances.get('atol', None) + rtol = tolerances.get('rtol', None) + + # tolerances are floats, not arrays; OK to use NumPy + message = 'Tolerances and step parameters must be non-negative scalars.' + tols = np.asarray([atol if atol is not None else 1, + rtol if rtol is not None else 1, + step_factor]) + if (not np.issubdtype(tols.dtype, np.number) or np.any(tols < 0) + or np.any(np.isnan(tols)) or tols.shape != (3,)): + raise ValueError(message) + step_factor = float(tols[2]) + + maxiter_int = int(maxiter) + if maxiter != maxiter_int or maxiter <= 0: + raise ValueError('`maxiter` must be a positive integer.') + + order_int = int(order) + if order_int != order or order <= 0: + raise ValueError('`order` must be a positive integer.') + + step_direction = xp.asarray(step_direction) + initial_step = xp.asarray(initial_step) + temp = xp.broadcast_arrays(x, step_direction, initial_step) + x, step_direction, initial_step = temp + + message = '`preserve_shape` must be True or False.' + if preserve_shape not in {True, False}: + raise ValueError(message) + + if callback is not None and not callable(callback): + raise ValueError('`callback` must be callable.') + + return (f, x, args, atol, rtol, maxiter_int, order_int, initial_step, + step_factor, step_direction, preserve_shape, callback) + + +def derivative(f, x, *, args=(), tolerances=None, maxiter=10, + order=8, initial_step=0.5, step_factor=2.0, + step_direction=0, preserve_shape=False, callback=None): + """Evaluate the derivative of a elementwise, real scalar function numerically. + + For each element of the output of `f`, `derivative` approximates the first + derivative of `f` at the corresponding element of `x` using finite difference + differentiation. + + This function works elementwise when `x`, `step_direction`, and `args` contain + (broadcastable) arrays. + + Parameters + ---------- + f : callable + The function whose derivative is desired. The signature must be:: + + f(xi: ndarray, *argsi) -> ndarray + + where each element of ``xi`` is a finite real number and ``argsi`` is a tuple, + which may contain an arbitrary number of arrays that are broadcastable with + ``xi``. `f` must be an elementwise function: each scalar element ``f(xi)[j]`` + must equal ``f(xi[j])`` for valid indices ``j``. It must not mutate the array + ``xi`` or the arrays in ``argsi``. + x : float array_like + Abscissae at which to evaluate the derivative. Must be broadcastable with + `args` and `step_direction`. + args : tuple of array_like, optional + Additional positional array arguments to be passed to `f`. Arrays + must be broadcastable with one another and the arrays of `init`. + If the callable for which the root is desired requires arguments that are + not broadcastable with `x`, wrap that callable with `f` such that `f` + accepts only `x` and broadcastable ``*args``. + tolerances : dictionary of floats, optional + Absolute and relative tolerances. Valid keys of the dictionary are: + + - ``atol`` - absolute tolerance on the derivative + - ``rtol`` - relative tolerance on the derivative + + Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default + `atol` is the smallest normal number of the appropriate dtype, and + the default `rtol` is the square root of the precision of the + appropriate dtype. + order : int, default: 8 + The (positive integer) order of the finite difference formula to be + used. Odd integers will be rounded up to the next even integer. + initial_step : float array_like, default: 0.5 + The (absolute) initial step size for the finite difference derivative + approximation. + step_factor : float, default: 2.0 + The factor by which the step size is *reduced* in each iteration; i.e. + the step size in iteration 1 is ``initial_step/step_factor``. If + ``step_factor < 1``, subsequent steps will be greater than the initial + step; this may be useful if steps smaller than some threshold are + undesirable (e.g. due to subtractive cancellation error). + maxiter : int, default: 10 + The maximum number of iterations of the algorithm to perform. See + Notes. + step_direction : integer array_like + An array representing the direction of the finite difference steps (for + use when `x` lies near to the boundary of the domain of the function.) + Must be broadcastable with `x` and all `args`. + Where 0 (default), central differences are used; where negative (e.g. + -1), steps are non-positive; and where positive (e.g. 1), all steps are + non-negative. + preserve_shape : bool, default: False + In the following, "arguments of `f`" refers to the array ``xi`` and + any arrays within ``argsi``. Let ``shape`` be the broadcasted shape + of `x` and all elements of `args` (which is conceptually + distinct from ``xi` and ``argsi`` passed into `f`). + + - When ``preserve_shape=False`` (default), `f` must accept arguments + of *any* broadcastable shapes. + + - When ``preserve_shape=True``, `f` must accept arguments of shape + ``shape`` *or* ``shape + (n,)``, where ``(n,)`` is the number of + abscissae at which the function is being evaluated. + + In either case, for each scalar element ``xi[j]`` within ``xi``, the array + returned by `f` must include the scalar ``f(xi[j])`` at the same index. + Consequently, the shape of the output is always the shape of the input + ``xi``. + + See Examples. + callback : callable, optional + An optional user-supplied function to be called before the first + iteration and after each iteration. + Called as ``callback(res)``, where ``res`` is a ``_RichResult`` + similar to that returned by `derivative` (but containing the current + iterate's values of all variables). If `callback` raises a + ``StopIteration``, the algorithm will terminate immediately and + `derivative` will return a result. `callback` must not mutate + `res` or its attributes. + + Returns + ------- + res : _RichResult + An object similar to an instance of `scipy.optimize.OptimizeResult` with the + following attributes. The descriptions are written as though the values will + be scalars; however, if `f` returns an array, the outputs will be + arrays of the same shape. + + success : bool array + ``True`` where the algorithm terminated successfully (status ``0``); + ``False`` otherwise. + status : int array + An integer representing the exit status of the algorithm. + + - ``0`` : The algorithm converged to the specified tolerances. + - ``-1`` : The error estimate increased, so iteration was terminated. + - ``-2`` : The maximum number of iterations was reached. + - ``-3`` : A non-finite value was encountered. + - ``-4`` : Iteration was terminated by `callback`. + - ``1`` : The algorithm is proceeding normally (in `callback` only). + + df : float array + The derivative of `f` at `x`, if the algorithm terminated + successfully. + error : float array + An estimate of the error: the magnitude of the difference between + the current estimate of the derivative and the estimate in the + previous iteration. + nit : int array + The number of iterations of the algorithm that were performed. + nfev : int array + The number of points at which `f` was evaluated. + x : float array + The value at which the derivative of `f` was evaluated + (after broadcasting with `args` and `step_direction`). + + See Also + -------- + jacobian, hessian + + Notes + ----- + The implementation was inspired by jacobi [1]_, numdifftools [2]_, and + DERIVEST [3]_, but the implementation follows the theory of Taylor series + more straightforwardly (and arguably naively so). + In the first iteration, the derivative is estimated using a finite + difference formula of order `order` with maximum step size `initial_step`. + Each subsequent iteration, the maximum step size is reduced by + `step_factor`, and the derivative is estimated again until a termination + condition is reached. The error estimate is the magnitude of the difference + between the current derivative approximation and that of the previous + iteration. + + The stencils of the finite difference formulae are designed such that + abscissae are "nested": after `f` is evaluated at ``order + 1`` + points in the first iteration, `f` is evaluated at only two new points + in each subsequent iteration; ``order - 1`` previously evaluated function + values required by the finite difference formula are reused, and two + function values (evaluations at the points furthest from `x`) are unused. + + Step sizes are absolute. When the step size is small relative to the + magnitude of `x`, precision is lost; for example, if `x` is ``1e20``, the + default initial step size of ``0.5`` cannot be resolved. Accordingly, + consider using larger initial step sizes for large magnitudes of `x`. + + The default tolerances are challenging to satisfy at points where the + true derivative is exactly zero. If the derivative may be exactly zero, + consider specifying an absolute tolerance (e.g. ``atol=1e-12``) to + improve convergence. + + References + ---------- + .. [1] Hans Dembinski (@HDembinski). jacobi. + https://github.com/HDembinski/jacobi + .. [2] Per A. Brodtkorb and John D'Errico. numdifftools. + https://numdifftools.readthedocs.io/en/latest/ + .. [3] John D'Errico. DERIVEST: Adaptive Robust Numerical Differentiation. + https://www.mathworks.com/matlabcentral/fileexchange/13490-adaptive-robust-numerical-differentiation + .. [4] Numerical Differentition. Wikipedia. + https://en.wikipedia.org/wiki/Numerical_differentiation + + Examples + -------- + Evaluate the derivative of ``np.exp`` at several points ``x``. + + >>> import numpy as np + >>> from scipy.differentiate import derivative + >>> f = np.exp + >>> df = np.exp # true derivative + >>> x = np.linspace(1, 2, 5) + >>> res = derivative(f, x) + >>> res.df # approximation of the derivative + array([2.71828183, 3.49034296, 4.48168907, 5.75460268, 7.3890561 ]) + >>> res.error # estimate of the error + array([7.13740178e-12, 9.16600129e-12, 1.17594823e-11, 1.51061386e-11, + 1.94262384e-11]) + >>> abs(res.df - df(x)) # true error + array([2.53130850e-14, 3.55271368e-14, 5.77315973e-14, 5.59552404e-14, + 6.92779167e-14]) + + Show the convergence of the approximation as the step size is reduced. + Each iteration, the step size is reduced by `step_factor`, so for + sufficiently small initial step, each iteration reduces the error by a + factor of ``1/step_factor**order`` until finite precision arithmetic + inhibits further improvement. + + >>> import matplotlib.pyplot as plt + >>> iter = list(range(1, 12)) # maximum iterations + >>> hfac = 2 # step size reduction per iteration + >>> hdir = [-1, 0, 1] # compare left-, central-, and right- steps + >>> order = 4 # order of differentiation formula + >>> x = 1 + >>> ref = df(x) + >>> errors = [] # true error + >>> for i in iter: + ... res = derivative(f, x, maxiter=i, step_factor=hfac, + ... step_direction=hdir, order=order, + ... # prevent early termination + ... tolerances=dict(atol=0, rtol=0)) + ... errors.append(abs(res.df - ref)) + >>> errors = np.array(errors) + >>> plt.semilogy(iter, errors[:, 0], label='left differences') + >>> plt.semilogy(iter, errors[:, 1], label='central differences') + >>> plt.semilogy(iter, errors[:, 2], label='right differences') + >>> plt.xlabel('iteration') + >>> plt.ylabel('error') + >>> plt.legend() + >>> plt.show() + >>> (errors[1, 1] / errors[0, 1], 1 / hfac**order) + (0.06215223140159822, 0.0625) + + The implementation is vectorized over `x`, `step_direction`, and `args`. + The function is evaluated once before the first iteration to perform input + validation and standardization, and once per iteration thereafter. + + >>> def f(x, p): + ... f.nit += 1 + ... return x**p + >>> f.nit = 0 + >>> def df(x, p): + ... return p*x**(p-1) + >>> x = np.arange(1, 5) + >>> p = np.arange(1, 6).reshape((-1, 1)) + >>> hdir = np.arange(-1, 2).reshape((-1, 1, 1)) + >>> res = derivative(f, x, args=(p,), step_direction=hdir, maxiter=1) + >>> np.allclose(res.df, df(x, p)) + True + >>> res.df.shape + (3, 5, 4) + >>> f.nit + 2 + + By default, `preserve_shape` is False, and therefore the callable + `f` may be called with arrays of any broadcastable shapes. + For example: + + >>> shapes = [] + >>> def f(x, c): + ... shape = np.broadcast_shapes(x.shape, c.shape) + ... shapes.append(shape) + ... return np.sin(c*x) + >>> + >>> c = [1, 5, 10, 20] + >>> res = derivative(f, 0, args=(c,)) + >>> shapes + [(4,), (4, 8), (4, 2), (3, 2), (2, 2), (1, 2)] + + To understand where these shapes are coming from - and to better + understand how `derivative` computes accurate results - note that + higher values of ``c`` correspond with higher frequency sinusoids. + The higher frequency sinusoids make the function's derivative change + faster, so more function evaluations are required to achieve the target + accuracy: + + >>> res.nfev + array([11, 13, 15, 17], dtype=int32) + + The initial ``shape``, ``(4,)``, corresponds with evaluating the + function at a single abscissa and all four frequencies; this is used + for input validation and to determine the size and dtype of the arrays + that store results. The next shape corresponds with evaluating the + function at an initial grid of abscissae and all four frequencies. + Successive calls to the function evaluate the function at two more + abscissae, increasing the effective order of the approximation by two. + However, in later function evaluations, the function is evaluated at + fewer frequencies because the corresponding derivative has already + converged to the required tolerance. This saves function evaluations to + improve performance, but it requires the function to accept arguments of + any shape. + + "Vector-valued" functions are unlikely to satisfy this requirement. + For example, consider + + >>> def f(x): + ... return [x, np.sin(3*x), x+np.sin(10*x), np.sin(20*x)*(x-1)**2] + + This integrand is not compatible with `derivative` as written; for instance, + the shape of the output will not be the same as the shape of ``x``. Such a + function *could* be converted to a compatible form with the introduction of + additional parameters, but this would be inconvenient. In such cases, + a simpler solution would be to use `preserve_shape`. + + >>> shapes = [] + >>> def f(x): + ... shapes.append(x.shape) + ... x0, x1, x2, x3 = x + ... return [x0, np.sin(3*x1), x2+np.sin(10*x2), np.sin(20*x3)*(x3-1)**2] + >>> + >>> x = np.zeros(4) + >>> res = derivative(f, x, preserve_shape=True) + >>> shapes + [(4,), (4, 8), (4, 2), (4, 2), (4, 2), (4, 2)] + + Here, the shape of ``x`` is ``(4,)``. With ``preserve_shape=True``, the + function may be called with argument ``x`` of shape ``(4,)`` or ``(4, n)``, + and this is what we observe. + + """ + # TODO (followup): + # - investigate behavior at saddle points + # - multivariate functions? + # - relative steps? + # - show example of `np.vectorize` + + res = _derivative_iv(f, x, args, tolerances, maxiter, order, initial_step, + step_factor, step_direction, preserve_shape, callback) + (func, x, args, atol, rtol, maxiter, order, + h0, fac, hdir, preserve_shape, callback) = res + + # Initialization + # Since f(x) (no step) is not needed for central differences, it may be + # possible to eliminate this function evaluation. However, it's useful for + # input validation and standardization, and everything else is designed to + # reduce function calls, so let's keep it simple. + temp = eim._initialize(func, (x,), args, preserve_shape=preserve_shape) + func, xs, fs, args, shape, dtype, xp = temp + + finfo = xp.finfo(dtype) + atol = finfo.smallest_normal if atol is None else atol + rtol = finfo.eps**0.5 if rtol is None else rtol # keep same as `hessian` + + x, f = xs[0], fs[0] + df = xp.full_like(f, xp.nan) + + # Ideally we'd broadcast the shape of `hdir` in `_elementwise_algo_init`, but + # it's simpler to do it here than to generalize `_elementwise_algo_init` further. + # `hdir` and `x` are already broadcasted in `_derivative_iv`, so we know + # that `hdir` can be broadcasted to the final shape. Same with `h0`. + hdir = xp.broadcast_to(hdir, shape) + hdir = xp.reshape(hdir, (-1,)) + hdir = xp.astype(xp_sign(hdir), dtype) + h0 = xp.broadcast_to(h0, shape) + h0 = xp.reshape(h0, (-1,)) + h0 = xp.astype(h0, dtype) + h0[h0 <= 0] = xp.asarray(xp.nan, dtype=dtype) + + status = xp.full_like(x, eim._EINPROGRESS, dtype=xp.int32) # in progress + nit, nfev = 0, 1 # one function evaluations performed above + # Boolean indices of left, central, right, and (all) one-sided steps + il = hdir < 0 + ic = hdir == 0 + ir = hdir > 0 + io = il | ir + + # Most of these attributes are reasonably obvious, but: + # - `fs` holds all the function values of all active `x`. The zeroth + # axis corresponds with active points `x`, the first axis corresponds + # with the different steps (in the order described in + # `_derivative_weights`). + # - `terms` (which could probably use a better name) is half the `order`, + # which is always even. + work = _RichResult(x=x, df=df, fs=f[:, xp.newaxis], error=xp.nan, h=h0, + df_last=xp.nan, error_last=xp.nan, fac=fac, + atol=atol, rtol=rtol, nit=nit, nfev=nfev, + status=status, dtype=dtype, terms=(order+1)//2, + hdir=hdir, il=il, ic=ic, ir=ir, io=io, + # Store the weights in an object so they can't get compressed + # Using RichResult to allow dot notation, but a dict would work + diff_state=_RichResult(central=[], right=[], fac=None)) + + # This is the correspondence between terms in the `work` object and the + # final result. In this case, the mapping is trivial. Note that `success` + # is prepended automatically. + res_work_pairs = [('status', 'status'), ('df', 'df'), ('error', 'error'), + ('nit', 'nit'), ('nfev', 'nfev'), ('x', 'x')] + + def pre_func_eval(work): + """Determine the abscissae at which the function needs to be evaluated. + + See `_derivative_weights` for a description of the stencil (pattern + of the abscissae). + + In the first iteration, there is only one stored function value in + `work.fs`, `f(x)`, so we need to evaluate at `order` new points. In + subsequent iterations, we evaluate at two new points. Note that + `work.x` is always flattened into a 1D array after broadcasting with + all `args`, so we add a new axis at the end and evaluate all point + in one call to the function. + + For improvement: + - Consider measuring the step size actually taken, since ``(x + h) - x`` + is not identically equal to `h` with floating point arithmetic. + - Adjust the step size automatically if `x` is too big to resolve the + step. + - We could probably save some work if there are no central difference + steps or no one-sided steps. + """ + n = work.terms # half the order + h = work.h[:, xp.newaxis] # step size + c = work.fac # step reduction factor + d = c**0.5 # square root of step reduction factor (one-sided stencil) + # Note - no need to be careful about dtypes until we allocate `x_eval` + + if work.nit == 0: + hc = h / c**xp.arange(n, dtype=work.dtype) + hc = xp.concat((-xp.flip(hc, axis=-1), hc), axis=-1) + else: + hc = xp.concat((-h, h), axis=-1) / c**(n-1) + + if work.nit == 0: + hr = h / d**xp.arange(2*n, dtype=work.dtype) + else: + hr = xp.concat((h, h/d), axis=-1) / c**(n-1) + + n_new = 2*n if work.nit == 0 else 2 # number of new abscissae + x_eval = xp.zeros((work.hdir.shape[0], n_new), dtype=work.dtype) + il, ic, ir = work.il, work.ic, work.ir + x_eval[ir] = work.x[ir][:, xp.newaxis] + hr[ir] + x_eval[ic] = work.x[ic][:, xp.newaxis] + hc[ic] + x_eval[il] = work.x[il][:, xp.newaxis] - hr[il] + return x_eval + + def post_func_eval(x, f, work): + """ Estimate the derivative and error from the function evaluations + + As in `pre_func_eval`: in the first iteration, there is only one stored + function value in `work.fs`, `f(x)`, so we need to add the `order` new + points. In subsequent iterations, we add two new points. The tricky + part is getting the order to match that of the weights, which is + described in `_derivative_weights`. + + For improvement: + - Change the order of the weights (and steps in `pre_func_eval`) to + simplify `work_fc` concatenation and eliminate `fc` concatenation. + - It would be simple to do one-step Richardson extrapolation with `df` + and `df_last` to increase the order of the estimate and/or improve + the error estimate. + - Process the function evaluations in a more numerically favorable + way. For instance, combining the pairs of central difference evals + into a second-order approximation and using Richardson extrapolation + to produce a higher order approximation seemed to retain accuracy up + to very high order. + - Alternatively, we could use `polyfit` like Jacobi. An advantage of + fitting polynomial to more points than necessary is improved noise + tolerance. + """ + n = work.terms + n_new = n if work.nit == 0 else 1 + il, ic, io = work.il, work.ic, work.io + + # Central difference + # `work_fc` is *all* the points at which the function has been evaluated + # `fc` is the points we're using *this iteration* to produce the estimate + work_fc = (f[ic][:, :n_new], work.fs[ic], f[ic][:, -n_new:]) + work_fc = xp.concat(work_fc, axis=-1) + if work.nit == 0: + fc = work_fc + else: + fc = (work_fc[:, :n], work_fc[:, n:n+1], work_fc[:, -n:]) + fc = xp.concat(fc, axis=-1) + + # One-sided difference + work_fo = xp.concat((work.fs[io], f[io]), axis=-1) + if work.nit == 0: + fo = work_fo + else: + fo = xp.concat((work_fo[:, 0:1], work_fo[:, -2*n:]), axis=-1) + + work.fs = xp.zeros((ic.shape[0], work.fs.shape[-1] + 2*n_new), dtype=work.dtype) + work.fs[ic] = work_fc + work.fs[io] = work_fo + + wc, wo = _derivative_weights(work, n, xp) + work.df_last = xp.asarray(work.df, copy=True) + work.df[ic] = fc @ wc / work.h[ic] + work.df[io] = fo @ wo / work.h[io] + work.df[il] *= -1 + + work.h /= work.fac + work.error_last = work.error + # Simple error estimate - the difference in derivative estimates between + # this iteration and the last. This is typically conservative because if + # convergence has begin, the true error is much closer to the difference + # between the current estimate and the *next* error estimate. However, + # we could use Richarson extrapolation to produce an error estimate that + # is one order higher, and take the difference between that and + # `work.df` (which would just be constant factor that depends on `fac`.) + work.error = xp.abs(work.df - work.df_last) + + def check_termination(work): + """Terminate due to convergence, non-finite values, or error increase""" + stop = xp.astype(xp.zeros_like(work.df), xp.bool) + + i = work.error < work.atol + work.rtol*abs(work.df) + work.status[i] = eim._ECONVERGED + stop[i] = True + + if work.nit > 0: + i = ~((xp.isfinite(work.x) & xp.isfinite(work.df)) | stop) + work.df[i], work.status[i] = xp.nan, eim._EVALUEERR + stop[i] = True + + # With infinite precision, there is a step size below which + # all smaller step sizes will reduce the error. But in floating point + # arithmetic, catastrophic cancellation will begin to cause the error + # to increase again. This heuristic tries to avoid step sizes that are + # too small. There may be more theoretically sound approaches for + # detecting a step size that minimizes the total error, but this + # heuristic seems simple and effective. + i = (work.error > work.error_last*10) & ~stop + work.status[i] = _EERRORINCREASE + stop[i] = True + + return stop + + def post_termination_check(work): + return + + def customize_result(res, shape): + return shape + + return eim._loop(work, callback, shape, maxiter, func, args, dtype, + pre_func_eval, post_func_eval, check_termination, + post_termination_check, customize_result, res_work_pairs, + xp, preserve_shape) + + +def _derivative_weights(work, n, xp): + # This produces the weights of the finite difference formula for a given + # stencil. In experiments, use of a second-order central difference formula + # with Richardson extrapolation was more accurate numerically, but it was + # more complicated, and it would have become even more complicated when + # adding support for one-sided differences. However, now that all the + # function evaluation values are stored, they can be processed in whatever + # way is desired to produce the derivative estimate. We leave alternative + # approaches to future work. To be more self-contained, here is the theory + # for deriving the weights below. + # + # Recall that the Taylor expansion of a univariate, scalar-values function + # about a point `x` may be expressed as: + # f(x + h) = f(x) + f'(x)*h + f''(x)/2!*h**2 + O(h**3) + # Suppose we evaluate f(x), f(x+h), and f(x-h). We have: + # f(x) = f(x) + # f(x + h) = f(x) + f'(x)*h + f''(x)/2!*h**2 + O(h**3) + # f(x - h) = f(x) - f'(x)*h + f''(x)/2!*h**2 + O(h**3) + # We can solve for weights `wi` such that: + # w1*f(x) = w1*(f(x)) + # + w2*f(x + h) = w2*(f(x) + f'(x)*h + f''(x)/2!*h**2) + O(h**3) + # + w3*f(x - h) = w3*(f(x) - f'(x)*h + f''(x)/2!*h**2) + O(h**3) + # = 0 + f'(x)*h + 0 + O(h**3) + # Then + # f'(x) ~ (w1*f(x) + w2*f(x+h) + w3*f(x-h))/h + # is a finite difference derivative approximation with error O(h**2), + # and so it is said to be a "second-order" approximation. Under certain + # conditions (e.g. well-behaved function, `h` sufficiently small), the + # error in the approximation will decrease with h**2; that is, if `h` is + # reduced by a factor of 2, the error is reduced by a factor of 4. + # + # By default, we use eighth-order formulae. Our central-difference formula + # uses abscissae: + # x-h/c**3, x-h/c**2, x-h/c, x-h, x, x+h, x+h/c, x+h/c**2, x+h/c**3 + # where `c` is the step factor. (Typically, the step factor is greater than + # one, so the outermost points - as written above - are actually closest to + # `x`.) This "stencil" is chosen so that each iteration, the step can be + # reduced by the factor `c`, and most of the function evaluations can be + # reused with the new step size. For example, in the next iteration, we + # will have: + # x-h/c**4, x-h/c**3, x-h/c**2, x-h/c, x, x+h/c, x+h/c**2, x+h/c**3, x+h/c**4 + # We do not reuse `x-h` and `x+h` for the new derivative estimate. + # While this would increase the order of the formula and thus the + # theoretical convergence rate, it is also less stable numerically. + # (As noted above, there are other ways of processing the values that are + # more stable. Thus, even now we store `f(x-h)` and `f(x+h)` in `work.fs` + # to simplify future development of this sort of improvement.) + # + # The (right) one-sided formula is produced similarly using abscissae + # x, x+h, x+h/d, x+h/d**2, ..., x+h/d**6, x+h/d**7, x+h/d**7 + # where `d` is the square root of `c`. (The left one-sided formula simply + # uses -h.) When the step size is reduced by factor `c = d**2`, we have + # abscissae: + # x, x+h/d**2, x+h/d**3..., x+h/d**8, x+h/d**9, x+h/d**9 + # `d` is chosen as the square root of `c` so that the rate of the step-size + # reduction is the same per iteration as in the central difference case. + # Note that because the central difference formulas are inherently of even + # order, for simplicity, we use only even-order formulas for one-sided + # differences, too. + + # It's possible for the user to specify `fac` in, say, double precision but + # `x` and `args` in single precision. `fac` gets converted to single + # precision, but we should always use double precision for the intermediate + # calculations here to avoid additional error in the weights. + fac = float(work.fac) + + # Note that if the user switches back to floating point precision with + # `x` and `args`, then `fac` will not necessarily equal the (lower + # precision) cached `_derivative_weights.fac`, and the weights will + # need to be recalculated. This could be fixed, but it's late, and of + # low consequence. + + diff_state = work.diff_state + if fac != diff_state.fac: + diff_state.central = [] + diff_state.right = [] + diff_state.fac = fac + + if len(diff_state.central) != 2*n + 1: + # Central difference weights. Consider refactoring this; it could + # probably be more compact. + # Note: Using NumPy here is OK; we convert to xp-type at the end + i = np.arange(-n, n + 1) + p = np.abs(i) - 1. # center point has power `p` -1, but sign `s` is 0 + s = np.sign(i) + + h = s / fac ** p + A = np.vander(h, increasing=True).T + b = np.zeros(2*n + 1) + b[1] = 1 + weights = np.linalg.solve(A, b) + + # Enforce identities to improve accuracy + weights[n] = 0 + for i in range(n): + weights[-i-1] = -weights[i] + + # Cache the weights. We only need to calculate them once unless + # the step factor changes. + diff_state.central = weights + + # One-sided difference weights. The left one-sided weights (with + # negative steps) are simply the negative of the right one-sided + # weights, so no need to compute them separately. + i = np.arange(2*n + 1) + p = i - 1. + s = np.sign(i) + + h = s / np.sqrt(fac) ** p + A = np.vander(h, increasing=True).T + b = np.zeros(2 * n + 1) + b[1] = 1 + weights = np.linalg.solve(A, b) + + diff_state.right = weights + + return (xp.asarray(diff_state.central, dtype=work.dtype), + xp.asarray(diff_state.right, dtype=work.dtype)) + + +def jacobian(f, x, *, tolerances=None, maxiter=10, order=8, initial_step=0.5, + step_factor=2.0, step_direction=0): + r"""Evaluate the Jacobian of a function numerically. + + Parameters + ---------- + f : callable + The function whose Jacobian is desired. The signature must be:: + + f(xi: ndarray) -> ndarray + + where each element of ``xi`` is a finite real. If the function to be + differentiated accepts additional arguments, wrap it (e.g. using + `functools.partial` or ``lambda``) and pass the wrapped callable + into `jacobian`. `f` must not mutate the array ``xi``. See Notes + regarding vectorization and the dimensionality of the input and output. + x : float array_like + Points at which to evaluate the Jacobian. Must have at least one dimension. + See Notes regarding the dimensionality and vectorization. + tolerances : dictionary of floats, optional + Absolute and relative tolerances. Valid keys of the dictionary are: + + - ``atol`` - absolute tolerance on the derivative + - ``rtol`` - relative tolerance on the derivative + + Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default + `atol` is the smallest normal number of the appropriate dtype, and + the default `rtol` is the square root of the precision of the + appropriate dtype. + maxiter : int, default: 10 + The maximum number of iterations of the algorithm to perform. See + Notes. + order : int, default: 8 + The (positive integer) order of the finite difference formula to be + used. Odd integers will be rounded up to the next even integer. + initial_step : float array_like, default: 0.5 + The (absolute) initial step size for the finite difference derivative + approximation. Must be broadcastable with `x` and `step_direction`. + step_factor : float, default: 2.0 + The factor by which the step size is *reduced* in each iteration; i.e. + the step size in iteration 1 is ``initial_step/step_factor``. If + ``step_factor < 1``, subsequent steps will be greater than the initial + step; this may be useful if steps smaller than some threshold are + undesirable (e.g. due to subtractive cancellation error). + step_direction : integer array_like + An array representing the direction of the finite difference steps (e.g. + for use when `x` lies near to the boundary of the domain of the function.) + Must be broadcastable with `x` and `initial_step`. + Where 0 (default), central differences are used; where negative (e.g. + -1), steps are non-positive; and where positive (e.g. 1), all steps are + non-negative. + + Returns + ------- + res : _RichResult + An object similar to an instance of `scipy.optimize.OptimizeResult` with the + following attributes. The descriptions are written as though the values will + be scalars; however, if `f` returns an array, the outputs will be + arrays of the same shape. + + success : bool array + ``True`` where the algorithm terminated successfully (status ``0``); + ``False`` otherwise. + status : int array + An integer representing the exit status of the algorithm. + + - ``0`` : The algorithm converged to the specified tolerances. + - ``-1`` : The error estimate increased, so iteration was terminated. + - ``-2`` : The maximum number of iterations was reached. + - ``-3`` : A non-finite value was encountered. + + df : float array + The Jacobian of `f` at `x`, if the algorithm terminated + successfully. + error : float array + An estimate of the error: the magnitude of the difference between + the current estimate of the Jacobian and the estimate in the + previous iteration. + nit : int array + The number of iterations of the algorithm that were performed. + nfev : int array + The number of points at which `f` was evaluated. + + Each element of an attribute is associated with the corresponding + element of `df`. For instance, element ``i`` of `nfev` is the + number of points at which `f` was evaluated for the sake of + computing element ``i`` of `df`. + + See Also + -------- + derivative, hessian + + Notes + ----- + Suppose we wish to evaluate the Jacobian of a function + :math:`f: \mathbf{R}^m \rightarrow \mathbf{R}^n`. Assign to variables + ``m`` and ``n`` the positive integer values of :math:`m` and :math:`n`, + respectively, and let ``...`` represent an arbitrary tuple of integers. + If we wish to evaluate the Jacobian at a single point, then: + + - argument `x` must be an array of shape ``(m,)`` + - argument `f` must be vectorized to accept an array of shape ``(m, ...)``. + The first axis represents the :math:`m` inputs of :math:`f`; the remainder + are for evaluating the function at multiple points in a single call. + - argument `f` must return an array of shape ``(n, ...)``. The first + axis represents the :math:`n` outputs of :math:`f`; the remainder + are for the result of evaluating the function at multiple points. + - attribute ``df`` of the result object will be an array of shape ``(n, m)``, + the Jacobian. + + This function is also vectorized in the sense that the Jacobian can be + evaluated at ``k`` points in a single call. In this case, `x` would be an + array of shape ``(m, k)``, `f` would accept an array of shape + ``(m, k, ...)`` and return an array of shape ``(n, k, ...)``, and the ``df`` + attribute of the result would have shape ``(n, m, k)``. + + Suppose the desired callable ``f_not_vectorized`` is not vectorized; it can + only accept an array of shape ``(m,)``. A simple solution to satisfy the required + interface is to wrap ``f_not_vectorized`` as follows:: + + def f(x): + return np.apply_along_axis(f_not_vectorized, axis=0, arr=x) + + Alternatively, suppose the desired callable ``f_vec_q`` is vectorized, but + only for 2-D arrays of shape ``(m, q)``. To satisfy the required interface, + consider:: + + def f(x): + m, batch = x.shape[0], x.shape[1:] # x.shape is (m, ...) + x = np.reshape(x, (m, -1)) # `-1` is short for q = prod(batch) + res = f_vec_q(x) # pass shape (m, q) to function + n = res.shape[0] + return np.reshape(res, (n,) + batch) # return shape (n, ...) + + Then pass the wrapped callable ``f`` as the first argument of `jacobian`. + + References + ---------- + .. [1] Jacobian matrix and determinant, *Wikipedia*, + https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant + + Examples + -------- + The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`; + the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an + array of shape ``(m, p)`` and return an array of shape ``p``. Suppose we wish + to evaluate the Jacobian (AKA the gradient because the function returns a scalar) + at ``[0.5, 0.5, 0.5]``. + + >>> import numpy as np + >>> from scipy.differentiate import jacobian + >>> from scipy.optimize import rosen, rosen_der + >>> m = 3 + >>> x = np.full(m, 0.5) + >>> res = jacobian(rosen, x) + >>> ref = rosen_der(x) # reference value of the gradient + >>> res.df, ref + (array([-51., -1., 50.]), array([-51., -1., 50.])) + + As an example of a function with multiple outputs, consider Example 4 + from [1]_. + + >>> def f(x): + ... x1, x2, x3 = x + ... return [x1, 5*x3, 4*x2**2 - 2*x3, x3*np.sin(x1)] + + The true Jacobian is given by: + + >>> def df(x): + ... x1, x2, x3 = x + ... one = np.ones_like(x1) + ... return [[one, 0*one, 0*one], + ... [0*one, 0*one, 5*one], + ... [0*one, 8*x2, -2*one], + ... [x3*np.cos(x1), 0*one, np.sin(x1)]] + + Evaluate the Jacobian at an arbitrary point. + + >>> rng = np.random.default_rng(389252938452) + >>> x = rng.random(size=3) + >>> res = jacobian(f, x) + >>> ref = df(x) + >>> res.df.shape == (4, 3) + True + >>> np.allclose(res.df, ref) + True + + Evaluate the Jacobian at 10 arbitrary points in a single call. + + >>> x = rng.random(size=(3, 10)) + >>> res = jacobian(f, x) + >>> ref = df(x) + >>> res.df.shape == (4, 3, 10) + True + >>> np.allclose(res.df, ref) + True + + """ + xp = array_namespace(x) + x = xp.asarray(x) + int_dtype = xp.isdtype(x.dtype, 'integral') + x0 = xp.asarray(x, dtype=xp.asarray(1.0).dtype) if int_dtype else x + + if x0.ndim < 1: + message = "Argument `x` must be at least 1-D." + raise ValueError(message) + + m = x0.shape[0] + i = xp.arange(m) + + def wrapped(x): + p = () if x.ndim == x0.ndim else (x.shape[-1],) # number of abscissae + + new_shape = (m, m) + x0.shape[1:] + p + xph = xp.expand_dims(x0, axis=1) + if x.ndim != x0.ndim: + xph = xp.expand_dims(xph, axis=-1) + xph = xp_copy(xp.broadcast_to(xph, new_shape), xp=xp) + xph[i, i] = x + return f(xph) + + res = derivative(wrapped, x, tolerances=tolerances, + maxiter=maxiter, order=order, initial_step=initial_step, + step_factor=step_factor, preserve_shape=True, + step_direction=step_direction) + + del res.x # the user knows `x`, and the way it gets broadcasted is meaningless here + return res + + +def hessian(f, x, *, tolerances=None, maxiter=10, + order=8, initial_step=0.5, step_factor=2.0): + r"""Evaluate the Hessian of a function numerically. + + Parameters + ---------- + f : callable + The function whose Hessian is desired. The signature must be:: + + f(xi: ndarray) -> ndarray + + where each element of ``xi`` is a finite real. If the function to be + differentiated accepts additional arguments, wrap it (e.g. using + `functools.partial` or ``lambda``) and pass the wrapped callable + into `hessian`. `f` must not mutate the array ``xi``. See Notes + regarding vectorization and the dimensionality of the input and output. + x : float array_like + Points at which to evaluate the Hessian. Must have at least one dimension. + See Notes regarding the dimensionality and vectorization. + tolerances : dictionary of floats, optional + Absolute and relative tolerances. Valid keys of the dictionary are: + + - ``atol`` - absolute tolerance on the derivative + - ``rtol`` - relative tolerance on the derivative + + Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default + `atol` is the smallest normal number of the appropriate dtype, and + the default `rtol` is the square root of the precision of the + appropriate dtype. + order : int, default: 8 + The (positive integer) order of the finite difference formula to be + used. Odd integers will be rounded up to the next even integer. + initial_step : float, default: 0.5 + The (absolute) initial step size for the finite difference derivative + approximation. + step_factor : float, default: 2.0 + The factor by which the step size is *reduced* in each iteration; i.e. + the step size in iteration 1 is ``initial_step/step_factor``. If + ``step_factor < 1``, subsequent steps will be greater than the initial + step; this may be useful if steps smaller than some threshold are + undesirable (e.g. due to subtractive cancellation error). + maxiter : int, default: 10 + The maximum number of iterations of the algorithm to perform. See + Notes. + + Returns + ------- + res : _RichResult + An object similar to an instance of `scipy.optimize.OptimizeResult` with the + following attributes. The descriptions are written as though the values will + be scalars; however, if `f` returns an array, the outputs will be + arrays of the same shape. + + success : bool array + ``True`` where the algorithm terminated successfully (status ``0``); + ``False`` otherwise. + status : int array + An integer representing the exit status of the algorithm. + + - ``0`` : The algorithm converged to the specified tolerances. + - ``-1`` : The error estimate increased, so iteration was terminated. + - ``-2`` : The maximum number of iterations was reached. + - ``-3`` : A non-finite value was encountered. + + ddf : float array + The Hessian of `f` at `x`, if the algorithm terminated + successfully. + error : float array + An estimate of the error: the magnitude of the difference between + the current estimate of the Hessian and the estimate in the + previous iteration. + nfev : int array + The number of points at which `f` was evaluated. + + Each element of an attribute is associated with the corresponding + element of `ddf`. For instance, element ``[i, j]`` of `nfev` is the + number of points at which `f` was evaluated for the sake of + computing element ``[i, j]`` of `ddf`. + + See Also + -------- + derivative, jacobian + + Notes + ----- + Suppose we wish to evaluate the Hessian of a function + :math:`f: \mathbf{R}^m \rightarrow \mathbf{R}`, and we assign to variable + ``m`` the positive integer value of :math:`m`. If we wish to evaluate + the Hessian at a single point, then: + + - argument `x` must be an array of shape ``(m,)`` + - argument `f` must be vectorized to accept an array of shape + ``(m, ...)``. The first axis represents the :math:`m` inputs of + :math:`f`; the remaining axes indicated by ellipses are for evaluating + the function at several abscissae in a single call. + - argument `f` must return an array of shape ``(...)``. + - attribute ``dff`` of the result object will be an array of shape ``(m, m)``, + the Hessian. + + This function is also vectorized in the sense that the Hessian can be + evaluated at ``k`` points in a single call. In this case, `x` would be an + array of shape ``(m, k)``, `f` would accept an array of shape + ``(m, ...)`` and return an array of shape ``(...)``, and the ``ddf`` + attribute of the result would have shape ``(m, m, k)``. Note that the + axis associated with the ``k`` points is included within the axes + denoted by ``(...)``. + + Currently, `hessian` is implemented by nesting calls to `jacobian`. + All options passed to `hessian` are used for both the inner and outer + calls with one exception: the `rtol` used in the inner `jacobian` call + is tightened by a factor of 100 with the expectation that the inner + error can be ignored. A consequence is that `rtol` should not be set + less than 100 times the precision of the dtype of `x`; a warning is + emitted otherwise. + + References + ---------- + .. [1] Hessian matrix, *Wikipedia*, + https://en.wikipedia.org/wiki/Hessian_matrix + + Examples + -------- + The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`; + the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an + array of shape ``(m, ...)`` and return an array of shape ``...``. Suppose we + wish to evaluate the Hessian at ``[0.5, 0.5, 0.5]``. + + >>> import numpy as np + >>> from scipy.differentiate import hessian + >>> from scipy.optimize import rosen, rosen_hess + >>> m = 3 + >>> x = np.full(m, 0.5) + >>> res = hessian(rosen, x) + >>> ref = rosen_hess(x) # reference value of the Hessian + >>> np.allclose(res.ddf, ref) + True + + `hessian` is vectorized to evaluate the Hessian at multiple points + in a single call. + + >>> rng = np.random.default_rng(4589245925010) + >>> x = rng.random((m, 10)) + >>> res = hessian(rosen, x) + >>> ref = [rosen_hess(xi) for xi in x.T] + >>> ref = np.moveaxis(ref, 0, -1) + >>> np.allclose(res.ddf, ref) + True + + """ + # todo: + # - add ability to vectorize over additional parameters (*args?) + # - error estimate stack with inner jacobian (or use legit 2D stencil) + + kwargs = dict(maxiter=maxiter, order=order, initial_step=initial_step, + step_factor=step_factor) + tolerances = {} if tolerances is None else tolerances + atol = tolerances.get('atol', None) + rtol = tolerances.get('rtol', None) + + xp = array_namespace(x) + x = xp.asarray(x) + dtype = x.dtype if not xp.isdtype(x.dtype, 'integral') else xp.asarray(1.).dtype + finfo = xp.finfo(dtype) + rtol = finfo.eps**0.5 if rtol is None else rtol # keep same as `derivative` + + # tighten the inner tolerance to make the inner error negligible + rtol_min = finfo.eps * 100 + message = (f"The specified `{rtol=}`, but error estimates are likely to be " + f"unreliable when `rtol < {rtol_min}`.") + if 0 < rtol < rtol_min: # rtol <= 0 is an error + warnings.warn(message, RuntimeWarning, stacklevel=2) + rtol = rtol_min + + def df(x): + tolerances = dict(rtol=rtol/100, atol=atol) + temp = jacobian(f, x, tolerances=tolerances, **kwargs) + nfev.append(temp.nfev if len(nfev) == 0 else temp.nfev.sum(axis=-1)) + return temp.df + + nfev = [] # track inner function evaluations + res = jacobian(df, x, tolerances=tolerances, **kwargs) # jacobian of jacobian + + nfev = xp.cumulative_sum(xp.stack(nfev), axis=0) + res_nit = xp.astype(res.nit[xp.newaxis, ...], xp.int64) # appease torch + res.nfev = xp_take_along_axis(nfev, res_nit, axis=0)[0] + res.ddf = res.df + del res.df # this is renamed to ddf + del res.nit # this is only the outer-jacobian nit + + return res diff --git a/shared/package-files/cc/cc5cd54af3a98c7900f7fb4407698f9dfabd3c9201b816b89428ba06f5db0431/test_size.py b/shared/package-files/cc/cc5cd54af3a98c7900f7fb4407698f9dfabd3c9201b816b89428ba06f5db0431/test_size.py new file mode 100644 index 0000000000000000000000000000000000000000..0c8b6473c85ea8e4a9749e79c8b4459afe6637d8 --- /dev/null +++ b/shared/package-files/cc/cc5cd54af3a98c7900f7fb4407698f9dfabd3c9201b816b89428ba06f5db0431/test_size.py @@ -0,0 +1,21 @@ +import numpy as np +import pytest + +from pandas import DataFrame + + +@pytest.mark.parametrize( + "data, index, expected", + [ + ({"col1": [1], "col2": [3]}, None, 2), + ({}, None, 0), + ({"col1": [1, np.nan], "col2": [3, 4]}, None, 4), + ({"col1": [1, 2], "col2": [3, 4]}, [["a", "b"], [1, 2]], 4), + ({"col1": [1, 2, 3, 4], "col2": [3, 4, 5, 6]}, ["x", "y", "a", "b"], 8), + ], +) +def test_size(data, index, expected): + # GH#52897 + df = DataFrame(data, index=index) + assert df.size == expected + assert isinstance(df.size, int) diff --git a/shared/package-files/cc/cc5ef39d76939f933970c4691ebeab358965668683e0e864e885ce13eb243411/_passive_aggressive.py b/shared/package-files/cc/cc5ef39d76939f933970c4691ebeab358965668683e0e864e885ce13eb243411/_passive_aggressive.py new file mode 100644 index 0000000000000000000000000000000000000000..61eb06edae85f9c6d04a94c070cd71c1bbbcaa3b --- /dev/null +++ b/shared/package-files/cc/cc5ef39d76939f933970c4691ebeab358965668683e0e864e885ce13eb243411/_passive_aggressive.py @@ -0,0 +1,573 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from numbers import Real + +from ..base import _fit_context +from ..utils._param_validation import Interval, StrOptions +from ._stochastic_gradient import DEFAULT_EPSILON, BaseSGDClassifier, BaseSGDRegressor + + +class PassiveAggressiveClassifier(BaseSGDClassifier): + """Passive Aggressive Classifier. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + C : float, default=1.0 + Maximum step size (regularization). Defaults to 1.0. + + fit_intercept : bool, default=True + Whether the intercept should be estimated or not. If False, the + data is assumed to be already centered. + + max_iter : int, default=1000 + The maximum number of passes over the training data (aka epochs). + It only impacts the behavior in the ``fit`` method, and not the + :meth:`~sklearn.linear_model.PassiveAggressiveClassifier.partial_fit` method. + + .. versionadded:: 0.19 + + tol : float or None, default=1e-3 + The stopping criterion. If it is not None, the iterations will stop + when (loss > previous_loss - tol). + + .. versionadded:: 0.19 + + early_stopping : bool, default=False + Whether to use early stopping to terminate training when validation + score is not improving. If set to True, it will automatically set aside + a stratified fraction of training data as validation and terminate + training when validation score is not improving by at least `tol` for + `n_iter_no_change` consecutive epochs. + + .. versionadded:: 0.20 + + validation_fraction : float, default=0.1 + The proportion of training data to set aside as validation set for + early stopping. Must be between 0 and 1. + Only used if early_stopping is True. + + .. versionadded:: 0.20 + + n_iter_no_change : int, default=5 + Number of iterations with no improvement to wait before early stopping. + + .. versionadded:: 0.20 + + shuffle : bool, default=True + Whether or not the training data should be shuffled after each epoch. + + verbose : int, default=0 + The verbosity level. + + loss : str, default="hinge" + The loss function to be used: + hinge: equivalent to PA-I in the reference paper. + squared_hinge: equivalent to PA-II in the reference paper. + + n_jobs : int or None, default=None + The number of CPUs to use to do the OVA (One Versus All, for + multi-class problems) computation. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + random_state : int, RandomState instance, default=None + Used to shuffle the training data, when ``shuffle`` is set to + ``True``. Pass an int for reproducible output across multiple + function calls. + See :term:`Glossary `. + + warm_start : bool, default=False + When set to True, reuse the solution of the previous call to fit as + initialization, otherwise, just erase the previous solution. + See :term:`the Glossary `. + + Repeatedly calling fit or partial_fit when warm_start is True can + result in a different solution than when calling fit a single time + because of the way the data is shuffled. + + class_weight : dict, {class_label: weight} or "balanced" or None, \ + default=None + Preset for the class_weight fit parameter. + + Weights associated with classes. If not given, all classes + are supposed to have weight one. + + The "balanced" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data + as ``n_samples / (n_classes * np.bincount(y))``. + + .. versionadded:: 0.17 + parameter *class_weight* to automatically weight samples. + + average : bool or int, default=False + When set to True, computes the averaged SGD weights and stores the + result in the ``coef_`` attribute. If set to an int greater than 1, + averaging will begin once the total number of samples seen reaches + average. So average=10 will begin averaging after seeing 10 samples. + + .. versionadded:: 0.19 + parameter *average* to use weights averaging in SGD. + + Attributes + ---------- + coef_ : ndarray of shape (1, n_features) if n_classes == 2 else \ + (n_classes, n_features) + Weights assigned to the features. + + intercept_ : ndarray of shape (1,) if n_classes == 2 else (n_classes,) + Constants in decision function. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_iter_ : int + The actual number of iterations to reach the stopping criterion. + For multiclass fits, it is the maximum over every binary fit. + + classes_ : ndarray of shape (n_classes,) + The unique classes labels. + + t_ : int + Number of weight updates performed during training. + Same as ``(n_iter_ * n_samples + 1)``. + + See Also + -------- + SGDClassifier : Incrementally trained logistic regression. + Perceptron : Linear perceptron classifier. + + References + ---------- + Online Passive-Aggressive Algorithms + + K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR (2006) + + Examples + -------- + >>> from sklearn.linear_model import PassiveAggressiveClassifier + >>> from sklearn.datasets import make_classification + >>> X, y = make_classification(n_features=4, random_state=0) + >>> clf = PassiveAggressiveClassifier(max_iter=1000, random_state=0, + ... tol=1e-3) + >>> clf.fit(X, y) + PassiveAggressiveClassifier(random_state=0) + >>> print(clf.coef_) + [[0.26642044 0.45070924 0.67251877 0.64185414]] + >>> print(clf.intercept_) + [1.84127814] + >>> print(clf.predict([[0, 0, 0, 0]])) + [1] + """ + + _parameter_constraints: dict = { + **BaseSGDClassifier._parameter_constraints, + "loss": [StrOptions({"hinge", "squared_hinge"})], + "C": [Interval(Real, 0, None, closed="right")], + } + + def __init__( + self, + *, + C=1.0, + fit_intercept=True, + max_iter=1000, + tol=1e-3, + early_stopping=False, + validation_fraction=0.1, + n_iter_no_change=5, + shuffle=True, + verbose=0, + loss="hinge", + n_jobs=None, + random_state=None, + warm_start=False, + class_weight=None, + average=False, + ): + super().__init__( + penalty=None, + fit_intercept=fit_intercept, + max_iter=max_iter, + tol=tol, + early_stopping=early_stopping, + validation_fraction=validation_fraction, + n_iter_no_change=n_iter_no_change, + shuffle=shuffle, + verbose=verbose, + random_state=random_state, + eta0=1.0, + warm_start=warm_start, + class_weight=class_weight, + average=average, + n_jobs=n_jobs, + ) + + self.C = C + self.loss = loss + + @_fit_context(prefer_skip_nested_validation=True) + def partial_fit(self, X, y, classes=None): + """Fit linear model with Passive Aggressive algorithm. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Subset of the training data. + + y : array-like of shape (n_samples,) + Subset of the target values. + + classes : ndarray of shape (n_classes,) + Classes across all calls to partial_fit. + Can be obtained by via `np.unique(y_all)`, where y_all is the + target vector of the entire dataset. + This argument is required for the first call to partial_fit + and can be omitted in the subsequent calls. + Note that y doesn't need to contain all labels in `classes`. + + Returns + ------- + self : object + Fitted estimator. + """ + if not hasattr(self, "classes_"): + self._more_validate_params(for_partial_fit=True) + + if self.class_weight == "balanced": + raise ValueError( + "class_weight 'balanced' is not supported for " + "partial_fit. For 'balanced' weights, use " + "`sklearn.utils.compute_class_weight` with " + "`class_weight='balanced'`. In place of y you " + "can use a large enough subset of the full " + "training set target to properly estimate the " + "class frequency distributions. Pass the " + "resulting weights as the class_weight " + "parameter." + ) + + lr = "pa1" if self.loss == "hinge" else "pa2" + return self._partial_fit( + X, + y, + alpha=1.0, + C=self.C, + loss="hinge", + learning_rate=lr, + max_iter=1, + classes=classes, + sample_weight=None, + coef_init=None, + intercept_init=None, + ) + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, coef_init=None, intercept_init=None): + """Fit linear model with Passive Aggressive algorithm. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) + Target values. + + coef_init : ndarray of shape (n_classes, n_features) + The initial coefficients to warm-start the optimization. + + intercept_init : ndarray of shape (n_classes,) + The initial intercept to warm-start the optimization. + + Returns + ------- + self : object + Fitted estimator. + """ + self._more_validate_params() + + lr = "pa1" if self.loss == "hinge" else "pa2" + return self._fit( + X, + y, + alpha=1.0, + C=self.C, + loss="hinge", + learning_rate=lr, + coef_init=coef_init, + intercept_init=intercept_init, + ) + + +class PassiveAggressiveRegressor(BaseSGDRegressor): + """Passive Aggressive Regressor. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + + C : float, default=1.0 + Maximum step size (regularization). Defaults to 1.0. + + fit_intercept : bool, default=True + Whether the intercept should be estimated or not. If False, the + data is assumed to be already centered. Defaults to True. + + max_iter : int, default=1000 + The maximum number of passes over the training data (aka epochs). + It only impacts the behavior in the ``fit`` method, and not the + :meth:`~sklearn.linear_model.PassiveAggressiveRegressor.partial_fit` method. + + .. versionadded:: 0.19 + + tol : float or None, default=1e-3 + The stopping criterion. If it is not None, the iterations will stop + when (loss > previous_loss - tol). + + .. versionadded:: 0.19 + + early_stopping : bool, default=False + Whether to use early stopping to terminate training when validation. + score is not improving. If set to True, it will automatically set aside + a fraction of training data as validation and terminate + training when validation score is not improving by at least tol for + n_iter_no_change consecutive epochs. + + .. versionadded:: 0.20 + + validation_fraction : float, default=0.1 + The proportion of training data to set aside as validation set for + early stopping. Must be between 0 and 1. + Only used if early_stopping is True. + + .. versionadded:: 0.20 + + n_iter_no_change : int, default=5 + Number of iterations with no improvement to wait before early stopping. + + .. versionadded:: 0.20 + + shuffle : bool, default=True + Whether or not the training data should be shuffled after each epoch. + + verbose : int, default=0 + The verbosity level. + + loss : str, default="epsilon_insensitive" + The loss function to be used: + epsilon_insensitive: equivalent to PA-I in the reference paper. + squared_epsilon_insensitive: equivalent to PA-II in the reference + paper. + + epsilon : float, default=0.1 + If the difference between the current prediction and the correct label + is below this threshold, the model is not updated. + + random_state : int, RandomState instance, default=None + Used to shuffle the training data, when ``shuffle`` is set to + ``True``. Pass an int for reproducible output across multiple + function calls. + See :term:`Glossary `. + + warm_start : bool, default=False + When set to True, reuse the solution of the previous call to fit as + initialization, otherwise, just erase the previous solution. + See :term:`the Glossary `. + + Repeatedly calling fit or partial_fit when warm_start is True can + result in a different solution than when calling fit a single time + because of the way the data is shuffled. + + average : bool or int, default=False + When set to True, computes the averaged SGD weights and stores the + result in the ``coef_`` attribute. If set to an int greater than 1, + averaging will begin once the total number of samples seen reaches + average. So average=10 will begin averaging after seeing 10 samples. + + .. versionadded:: 0.19 + parameter *average* to use weights averaging in SGD. + + Attributes + ---------- + coef_ : array, shape = [1, n_features] if n_classes == 2 else [n_classes,\ + n_features] + Weights assigned to the features. + + intercept_ : array, shape = [1] if n_classes == 2 else [n_classes] + Constants in decision function. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_iter_ : int + The actual number of iterations to reach the stopping criterion. + + t_ : int + Number of weight updates performed during training. + Same as ``(n_iter_ * n_samples + 1)``. + + See Also + -------- + SGDRegressor : Linear model fitted by minimizing a regularized + empirical loss with SGD. + + References + ---------- + Online Passive-Aggressive Algorithms + + K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR (2006). + + Examples + -------- + >>> from sklearn.linear_model import PassiveAggressiveRegressor + >>> from sklearn.datasets import make_regression + + >>> X, y = make_regression(n_features=4, random_state=0) + >>> regr = PassiveAggressiveRegressor(max_iter=100, random_state=0, + ... tol=1e-3) + >>> regr.fit(X, y) + PassiveAggressiveRegressor(max_iter=100, random_state=0) + >>> print(regr.coef_) + [20.48736655 34.18818427 67.59122734 87.94731329] + >>> print(regr.intercept_) + [-0.02306214] + >>> print(regr.predict([[0, 0, 0, 0]])) + [-0.02306214] + """ + + _parameter_constraints: dict = { + **BaseSGDRegressor._parameter_constraints, + "loss": [StrOptions({"epsilon_insensitive", "squared_epsilon_insensitive"})], + "C": [Interval(Real, 0, None, closed="right")], + "epsilon": [Interval(Real, 0, None, closed="left")], + } + + def __init__( + self, + *, + C=1.0, + fit_intercept=True, + max_iter=1000, + tol=1e-3, + early_stopping=False, + validation_fraction=0.1, + n_iter_no_change=5, + shuffle=True, + verbose=0, + loss="epsilon_insensitive", + epsilon=DEFAULT_EPSILON, + random_state=None, + warm_start=False, + average=False, + ): + super().__init__( + penalty=None, + l1_ratio=0, + epsilon=epsilon, + eta0=1.0, + fit_intercept=fit_intercept, + max_iter=max_iter, + tol=tol, + early_stopping=early_stopping, + validation_fraction=validation_fraction, + n_iter_no_change=n_iter_no_change, + shuffle=shuffle, + verbose=verbose, + random_state=random_state, + warm_start=warm_start, + average=average, + ) + self.C = C + self.loss = loss + + @_fit_context(prefer_skip_nested_validation=True) + def partial_fit(self, X, y): + """Fit linear model with Passive Aggressive algorithm. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Subset of training data. + + y : numpy array of shape [n_samples] + Subset of target values. + + Returns + ------- + self : object + Fitted estimator. + """ + if not hasattr(self, "coef_"): + self._more_validate_params(for_partial_fit=True) + + lr = "pa1" if self.loss == "epsilon_insensitive" else "pa2" + return self._partial_fit( + X, + y, + alpha=1.0, + C=self.C, + loss="epsilon_insensitive", + learning_rate=lr, + max_iter=1, + sample_weight=None, + coef_init=None, + intercept_init=None, + ) + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, coef_init=None, intercept_init=None): + """Fit linear model with Passive Aggressive algorithm. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : numpy array of shape [n_samples] + Target values. + + coef_init : array, shape = [n_features] + The initial coefficients to warm-start the optimization. + + intercept_init : array, shape = [1] + The initial intercept to warm-start the optimization. + + Returns + ------- + self : object + Fitted estimator. + """ + self._more_validate_params() + + lr = "pa1" if self.loss == "epsilon_insensitive" else "pa2" + return self._fit( + X, + y, + alpha=1.0, + C=self.C, + loss="epsilon_insensitive", + learning_rate=lr, + coef_init=coef_init, + intercept_init=intercept_init, + ) diff --git a/shared/package-files/cc/cc64cdd4d7e2e1006513bbcc1ca96d6fc152bc3a5e4bfcb64d200f0f7f7ef107/strides.h b/shared/package-files/cc/cc64cdd4d7e2e1006513bbcc1ca96d6fc152bc3a5e4bfcb64d200f0f7f7ef107/strides.h new file mode 100644 index 0000000000000000000000000000000000000000..980540b5b97a4d2ad8fae0c0ea5364078eab860f --- /dev/null +++ b/shared/package-files/cc/cc64cdd4d7e2e1006513bbcc1ca96d6fc152bc3a5e4bfcb64d200f0f7f7ef107/strides.h @@ -0,0 +1,24 @@ +#pragma once +#include +#include +#include + +namespace c10 { + +// Computes the contiguous strides of a tensor, given its sizes. +static inline DimVector contiguous_strides(const IntArrayRef sizes) { + using Int = IntArrayRef::value_type; + const Int dims = static_cast(sizes.size()); + + // With this initialisation we get the case dim == 0 or 1 right + DimVector strides(dims, 1); + + for (auto i = dims - 2; i >= 0; --i) { + // Strides can't be 0 even if sizes are 0. + strides[i] = strides[i + 1] * std::max(sizes[i + 1], Int{1}); + } + + return strides; +} + +} // namespace c10 diff --git a/shared/package-files/cc/cc67fb32687b5cfb70ba73a87937e08880a77ec55e0846cca29dcdac38087ea6/test_regular.py b/shared/package-files/cc/cc67fb32687b5cfb70ba73a87937e08880a77ec55e0846cca29dcdac38087ea6/test_regular.py new file mode 100644 index 0000000000000000000000000000000000000000..0c8e4e465824310f0b950c1db972336f0bb8c9ca --- /dev/null +++ b/shared/package-files/cc/cc67fb32687b5cfb70ba73a87937e08880a77ec55e0846cca29dcdac38087ea6/test_regular.py @@ -0,0 +1,86 @@ +import pytest + +import networkx +import networkx as nx +import networkx.algorithms.regular as reg +import networkx.generators as gen + + +class TestKFactor: + def test_k_factor_trivial(self): + g = gen.cycle_graph(4) + f = reg.k_factor(g, 2) + assert g.edges == f.edges + + def test_k_factor1(self): + g = gen.grid_2d_graph(4, 4) + g_kf = reg.k_factor(g, 2) + for edge in g_kf.edges(): + assert g.has_edge(edge[0], edge[1]) + for _, degree in g_kf.degree(): + assert degree == 2 + + def test_k_factor2(self): + g = gen.complete_graph(6) + g_kf = reg.k_factor(g, 3) + for edge in g_kf.edges(): + assert g.has_edge(edge[0], edge[1]) + for _, degree in g_kf.degree(): + assert degree == 3 + + def test_k_factor3(self): + g = gen.grid_2d_graph(4, 4) + with pytest.raises(nx.NetworkXUnfeasible): + reg.k_factor(g, 3) + + def test_k_factor4(self): + g = gen.lattice.hexagonal_lattice_graph(4, 4) + # Perfect matching doesn't exist for 4,4 hexagonal lattice graph + with pytest.raises(nx.NetworkXUnfeasible): + reg.k_factor(g, 2) + + def test_k_factor5(self): + g = gen.complete_graph(6) + # small k to exercise SmallKGadget + g_kf = reg.k_factor(g, 2) + for edge in g_kf.edges(): + assert g.has_edge(edge[0], edge[1]) + for _, degree in g_kf.degree(): + assert degree == 2 + + +class TestIsRegular: + def test_is_regular1(self): + g = gen.cycle_graph(4) + assert reg.is_regular(g) + + def test_is_regular2(self): + g = gen.complete_graph(5) + assert reg.is_regular(g) + + def test_is_regular3(self): + g = gen.lollipop_graph(5, 5) + assert not reg.is_regular(g) + + def test_is_regular4(self): + g = nx.DiGraph() + g.add_edges_from([(0, 1), (1, 2), (2, 0)]) + assert reg.is_regular(g) + + +class TestIsKRegular: + def test_is_k_regular1(self): + g = gen.cycle_graph(4) + assert reg.is_k_regular(g, 2) + assert not reg.is_k_regular(g, 3) + + def test_is_k_regular2(self): + g = gen.complete_graph(5) + assert reg.is_k_regular(g, 4) + assert not reg.is_k_regular(g, 3) + assert not reg.is_k_regular(g, 6) + + def test_is_k_regular3(self): + g = gen.lollipop_graph(5, 5) + assert not reg.is_k_regular(g, 5) + assert not reg.is_k_regular(g, 6) diff --git a/shared/package-files/cc/cc6a054c25cd9d66c759d90b44a63122fd97838d6512fedebcef1622f8352ca2/context.py b/shared/package-files/cc/cc6a054c25cd9d66c759d90b44a63122fd97838d6512fedebcef1622f8352ca2/context.py new file mode 100644 index 0000000000000000000000000000000000000000..d838aa3c77bbbc0f37cd7fa6e005d85c9e9dd624 --- /dev/null +++ b/shared/package-files/cc/cc6a054c25cd9d66c759d90b44a63122fd97838d6512fedebcef1622f8352ca2/context.py @@ -0,0 +1,31 @@ +import functools +from typing import Callable + +from torchgen.api.autograd import NativeFunctionWithDifferentiabilityInfo as NFWDI +from torchgen.context import native_function_manager +from torchgen.utils import T + + +# Like tools.api.context.with_native_function, but for +# NativeFunctionWithDifferentiabilityInfo. +def with_native_function_with_differentiability_info( + func: Callable[[NFWDI], T] +) -> Callable[[NFWDI], T]: + @functools.wraps(func) + def wrapper(f: NFWDI) -> T: + with native_function_manager(f.func): + return func(f) + + return wrapper + + +# Like the above but with an additional dispatch key string argument +def with_native_function_with_differentiability_info_and_key( + func: Callable[[NFWDI, str], T] +) -> Callable[[NFWDI, str], T]: + @functools.wraps(func) + def wrapper(f: NFWDI, key: str) -> T: + with native_function_manager(f.func): + return func(f, key) + + return wrapper diff --git a/shared/package-files/cc/cc6faaa9dc4a933127da0aaacd1dc7a44c09266051af56bfe3215ff228636b6b/cp852.py b/shared/package-files/cc/cc6faaa9dc4a933127da0aaacd1dc7a44c09266051af56bfe3215ff228636b6b/cp852.py new file mode 100644 index 0000000000000000000000000000000000000000..34d8a0ea5acc4b7f97cf4f943cfc4a78bb3d4247 --- /dev/null +++ b/shared/package-files/cc/cc6faaa9dc4a933127da0aaacd1dc7a44c09266051af56bfe3215ff228636b6b/cp852.py @@ -0,0 +1,698 @@ +""" Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP852.TXT' with gencodec.py. + +"""#" + +import codecs + +### Codec APIs + +class Codec(codecs.Codec): + + def encode(self,input,errors='strict'): + return codecs.charmap_encode(input,errors,encoding_map) + + def decode(self,input,errors='strict'): + return codecs.charmap_decode(input,errors,decoding_table) + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input, final=False): + return codecs.charmap_encode(input,self.errors,encoding_map)[0] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input, final=False): + return codecs.charmap_decode(input,self.errors,decoding_table)[0] + +class StreamWriter(Codec,codecs.StreamWriter): + pass + +class StreamReader(Codec,codecs.StreamReader): + pass + +### encodings module API + +def getregentry(): + return codecs.CodecInfo( + name='cp852', + encode=Codec().encode, + decode=Codec().decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamreader=StreamReader, + streamwriter=StreamWriter, + ) + +### Decoding Map + +decoding_map = codecs.make_identity_dict(range(256)) +decoding_map.update({ + 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA + 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS + 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE + 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX + 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS + 0x0085: 0x016f, # LATIN SMALL LETTER U WITH RING ABOVE + 0x0086: 0x0107, # LATIN SMALL LETTER C WITH ACUTE + 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA + 0x0088: 0x0142, # LATIN SMALL LETTER L WITH STROKE + 0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS + 0x008a: 0x0150, # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE + 0x008b: 0x0151, # LATIN SMALL LETTER O WITH DOUBLE ACUTE + 0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX + 0x008d: 0x0179, # LATIN CAPITAL LETTER Z WITH ACUTE + 0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS + 0x008f: 0x0106, # LATIN CAPITAL LETTER C WITH ACUTE + 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE + 0x0091: 0x0139, # LATIN CAPITAL LETTER L WITH ACUTE + 0x0092: 0x013a, # LATIN SMALL LETTER L WITH ACUTE + 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX + 0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS + 0x0095: 0x013d, # LATIN CAPITAL LETTER L WITH CARON + 0x0096: 0x013e, # LATIN SMALL LETTER L WITH CARON + 0x0097: 0x015a, # LATIN CAPITAL LETTER S WITH ACUTE + 0x0098: 0x015b, # LATIN SMALL LETTER S WITH ACUTE + 0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS + 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS + 0x009b: 0x0164, # LATIN CAPITAL LETTER T WITH CARON + 0x009c: 0x0165, # LATIN SMALL LETTER T WITH CARON + 0x009d: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE + 0x009e: 0x00d7, # MULTIPLICATION SIGN + 0x009f: 0x010d, # LATIN SMALL LETTER C WITH CARON + 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE + 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE + 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE + 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE + 0x00a4: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK + 0x00a5: 0x0105, # LATIN SMALL LETTER A WITH OGONEK + 0x00a6: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON + 0x00a7: 0x017e, # LATIN SMALL LETTER Z WITH CARON + 0x00a8: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK + 0x00a9: 0x0119, # LATIN SMALL LETTER E WITH OGONEK + 0x00aa: 0x00ac, # NOT SIGN + 0x00ab: 0x017a, # LATIN SMALL LETTER Z WITH ACUTE + 0x00ac: 0x010c, # LATIN CAPITAL LETTER C WITH CARON + 0x00ad: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA + 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + 0x00b0: 0x2591, # LIGHT SHADE + 0x00b1: 0x2592, # MEDIUM SHADE + 0x00b2: 0x2593, # DARK SHADE + 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL + 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT + 0x00b5: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE + 0x00b6: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX + 0x00b7: 0x011a, # LATIN CAPITAL LETTER E WITH CARON + 0x00b8: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA + 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT + 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL + 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT + 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT + 0x00bd: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE + 0x00be: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE + 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT + 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT + 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL + 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL + 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT + 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL + 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL + 0x00c6: 0x0102, # LATIN CAPITAL LETTER A WITH BREVE + 0x00c7: 0x0103, # LATIN SMALL LETTER A WITH BREVE + 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT + 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT + 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL + 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL + 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT + 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL + 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL + 0x00cf: 0x00a4, # CURRENCY SIGN + 0x00d0: 0x0111, # LATIN SMALL LETTER D WITH STROKE + 0x00d1: 0x0110, # LATIN CAPITAL LETTER D WITH STROKE + 0x00d2: 0x010e, # LATIN CAPITAL LETTER D WITH CARON + 0x00d3: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS + 0x00d4: 0x010f, # LATIN SMALL LETTER D WITH CARON + 0x00d5: 0x0147, # LATIN CAPITAL LETTER N WITH CARON + 0x00d6: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE + 0x00d7: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX + 0x00d8: 0x011b, # LATIN SMALL LETTER E WITH CARON + 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT + 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT + 0x00db: 0x2588, # FULL BLOCK + 0x00dc: 0x2584, # LOWER HALF BLOCK + 0x00dd: 0x0162, # LATIN CAPITAL LETTER T WITH CEDILLA + 0x00de: 0x016e, # LATIN CAPITAL LETTER U WITH RING ABOVE + 0x00df: 0x2580, # UPPER HALF BLOCK + 0x00e0: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE + 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S + 0x00e2: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX + 0x00e3: 0x0143, # LATIN CAPITAL LETTER N WITH ACUTE + 0x00e4: 0x0144, # LATIN SMALL LETTER N WITH ACUTE + 0x00e5: 0x0148, # LATIN SMALL LETTER N WITH CARON + 0x00e6: 0x0160, # LATIN CAPITAL LETTER S WITH CARON + 0x00e7: 0x0161, # LATIN SMALL LETTER S WITH CARON + 0x00e8: 0x0154, # LATIN CAPITAL LETTER R WITH ACUTE + 0x00e9: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE + 0x00ea: 0x0155, # LATIN SMALL LETTER R WITH ACUTE + 0x00eb: 0x0170, # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE + 0x00ec: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE + 0x00ed: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE + 0x00ee: 0x0163, # LATIN SMALL LETTER T WITH CEDILLA + 0x00ef: 0x00b4, # ACUTE ACCENT + 0x00f0: 0x00ad, # SOFT HYPHEN + 0x00f1: 0x02dd, # DOUBLE ACUTE ACCENT + 0x00f2: 0x02db, # OGONEK + 0x00f3: 0x02c7, # CARON + 0x00f4: 0x02d8, # BREVE + 0x00f5: 0x00a7, # SECTION SIGN + 0x00f6: 0x00f7, # DIVISION SIGN + 0x00f7: 0x00b8, # CEDILLA + 0x00f8: 0x00b0, # DEGREE SIGN + 0x00f9: 0x00a8, # DIAERESIS + 0x00fa: 0x02d9, # DOT ABOVE + 0x00fb: 0x0171, # LATIN SMALL LETTER U WITH DOUBLE ACUTE + 0x00fc: 0x0158, # LATIN CAPITAL LETTER R WITH CARON + 0x00fd: 0x0159, # LATIN SMALL LETTER R WITH CARON + 0x00fe: 0x25a0, # BLACK SQUARE + 0x00ff: 0x00a0, # NO-BREAK SPACE +}) + +### Decoding Table + +decoding_table = ( + '\x00' # 0x0000 -> NULL + '\x01' # 0x0001 -> START OF HEADING + '\x02' # 0x0002 -> START OF TEXT + '\x03' # 0x0003 -> END OF TEXT + '\x04' # 0x0004 -> END OF TRANSMISSION + '\x05' # 0x0005 -> ENQUIRY + '\x06' # 0x0006 -> ACKNOWLEDGE + '\x07' # 0x0007 -> BELL + '\x08' # 0x0008 -> BACKSPACE + '\t' # 0x0009 -> HORIZONTAL TABULATION + '\n' # 0x000a -> LINE FEED + '\x0b' # 0x000b -> VERTICAL TABULATION + '\x0c' # 0x000c -> FORM FEED + '\r' # 0x000d -> CARRIAGE RETURN + '\x0e' # 0x000e -> SHIFT OUT + '\x0f' # 0x000f -> SHIFT IN + '\x10' # 0x0010 -> DATA LINK ESCAPE + '\x11' # 0x0011 -> DEVICE CONTROL ONE + '\x12' # 0x0012 -> DEVICE CONTROL TWO + '\x13' # 0x0013 -> DEVICE CONTROL THREE + '\x14' # 0x0014 -> DEVICE CONTROL FOUR + '\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE + '\x16' # 0x0016 -> SYNCHRONOUS IDLE + '\x17' # 0x0017 -> END OF TRANSMISSION BLOCK + '\x18' # 0x0018 -> CANCEL + '\x19' # 0x0019 -> END OF MEDIUM + '\x1a' # 0x001a -> SUBSTITUTE + '\x1b' # 0x001b -> ESCAPE + '\x1c' # 0x001c -> FILE SEPARATOR + '\x1d' # 0x001d -> GROUP SEPARATOR + '\x1e' # 0x001e -> RECORD SEPARATOR + '\x1f' # 0x001f -> UNIT SEPARATOR + ' ' # 0x0020 -> SPACE + '!' # 0x0021 -> EXCLAMATION MARK + '"' # 0x0022 -> QUOTATION MARK + '#' # 0x0023 -> NUMBER SIGN + '$' # 0x0024 -> DOLLAR SIGN + '%' # 0x0025 -> PERCENT SIGN + '&' # 0x0026 -> AMPERSAND + "'" # 0x0027 -> APOSTROPHE + '(' # 0x0028 -> LEFT PARENTHESIS + ')' # 0x0029 -> RIGHT PARENTHESIS + '*' # 0x002a -> ASTERISK + '+' # 0x002b -> PLUS SIGN + ',' # 0x002c -> COMMA + '-' # 0x002d -> HYPHEN-MINUS + '.' # 0x002e -> FULL STOP + '/' # 0x002f -> SOLIDUS + '0' # 0x0030 -> DIGIT ZERO + '1' # 0x0031 -> DIGIT ONE + '2' # 0x0032 -> DIGIT TWO + '3' # 0x0033 -> DIGIT THREE + '4' # 0x0034 -> DIGIT FOUR + '5' # 0x0035 -> DIGIT FIVE + '6' # 0x0036 -> DIGIT SIX + '7' # 0x0037 -> DIGIT SEVEN + '8' # 0x0038 -> DIGIT EIGHT + '9' # 0x0039 -> DIGIT NINE + ':' # 0x003a -> COLON + ';' # 0x003b -> SEMICOLON + '<' # 0x003c -> LESS-THAN SIGN + '=' # 0x003d -> EQUALS SIGN + '>' # 0x003e -> GREATER-THAN SIGN + '?' # 0x003f -> QUESTION MARK + '@' # 0x0040 -> COMMERCIAL AT + 'A' # 0x0041 -> LATIN CAPITAL LETTER A + 'B' # 0x0042 -> LATIN CAPITAL LETTER B + 'C' # 0x0043 -> LATIN CAPITAL LETTER C + 'D' # 0x0044 -> LATIN CAPITAL LETTER D + 'E' # 0x0045 -> LATIN CAPITAL LETTER E + 'F' # 0x0046 -> LATIN CAPITAL LETTER F + 'G' # 0x0047 -> LATIN CAPITAL LETTER G + 'H' # 0x0048 -> LATIN CAPITAL LETTER H + 'I' # 0x0049 -> LATIN CAPITAL LETTER I + 'J' # 0x004a -> LATIN CAPITAL LETTER J + 'K' # 0x004b -> LATIN CAPITAL LETTER K + 'L' # 0x004c -> LATIN CAPITAL LETTER L + 'M' # 0x004d -> LATIN CAPITAL LETTER M + 'N' # 0x004e -> LATIN CAPITAL LETTER N + 'O' # 0x004f -> LATIN CAPITAL LETTER O + 'P' # 0x0050 -> LATIN CAPITAL LETTER P + 'Q' # 0x0051 -> LATIN CAPITAL LETTER Q + 'R' # 0x0052 -> LATIN CAPITAL LETTER R + 'S' # 0x0053 -> LATIN CAPITAL LETTER S + 'T' # 0x0054 -> LATIN CAPITAL LETTER T + 'U' # 0x0055 -> LATIN CAPITAL LETTER U + 'V' # 0x0056 -> LATIN CAPITAL LETTER V + 'W' # 0x0057 -> LATIN CAPITAL LETTER W + 'X' # 0x0058 -> LATIN CAPITAL LETTER X + 'Y' # 0x0059 -> LATIN CAPITAL LETTER Y + 'Z' # 0x005a -> LATIN CAPITAL LETTER Z + '[' # 0x005b -> LEFT SQUARE BRACKET + '\\' # 0x005c -> REVERSE SOLIDUS + ']' # 0x005d -> RIGHT SQUARE BRACKET + '^' # 0x005e -> CIRCUMFLEX ACCENT + '_' # 0x005f -> LOW LINE + '`' # 0x0060 -> GRAVE ACCENT + 'a' # 0x0061 -> LATIN SMALL LETTER A + 'b' # 0x0062 -> LATIN SMALL LETTER B + 'c' # 0x0063 -> LATIN SMALL LETTER C + 'd' # 0x0064 -> LATIN SMALL LETTER D + 'e' # 0x0065 -> LATIN SMALL LETTER E + 'f' # 0x0066 -> LATIN SMALL LETTER F + 'g' # 0x0067 -> LATIN SMALL LETTER G + 'h' # 0x0068 -> LATIN SMALL LETTER H + 'i' # 0x0069 -> LATIN SMALL LETTER I + 'j' # 0x006a -> LATIN SMALL LETTER J + 'k' # 0x006b -> LATIN SMALL LETTER K + 'l' # 0x006c -> LATIN SMALL LETTER L + 'm' # 0x006d -> LATIN SMALL LETTER M + 'n' # 0x006e -> LATIN SMALL LETTER N + 'o' # 0x006f -> LATIN SMALL LETTER O + 'p' # 0x0070 -> LATIN SMALL LETTER P + 'q' # 0x0071 -> LATIN SMALL LETTER Q + 'r' # 0x0072 -> LATIN SMALL LETTER R + 's' # 0x0073 -> LATIN SMALL LETTER S + 't' # 0x0074 -> LATIN SMALL LETTER T + 'u' # 0x0075 -> LATIN SMALL LETTER U + 'v' # 0x0076 -> LATIN SMALL LETTER V + 'w' # 0x0077 -> LATIN SMALL LETTER W + 'x' # 0x0078 -> LATIN SMALL LETTER X + 'y' # 0x0079 -> LATIN SMALL LETTER Y + 'z' # 0x007a -> LATIN SMALL LETTER Z + '{' # 0x007b -> LEFT CURLY BRACKET + '|' # 0x007c -> VERTICAL LINE + '}' # 0x007d -> RIGHT CURLY BRACKET + '~' # 0x007e -> TILDE + '\x7f' # 0x007f -> DELETE + '\xc7' # 0x0080 -> LATIN CAPITAL LETTER C WITH CEDILLA + '\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS + '\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE + '\xe2' # 0x0083 -> LATIN SMALL LETTER A WITH CIRCUMFLEX + '\xe4' # 0x0084 -> LATIN SMALL LETTER A WITH DIAERESIS + '\u016f' # 0x0085 -> LATIN SMALL LETTER U WITH RING ABOVE + '\u0107' # 0x0086 -> LATIN SMALL LETTER C WITH ACUTE + '\xe7' # 0x0087 -> LATIN SMALL LETTER C WITH CEDILLA + '\u0142' # 0x0088 -> LATIN SMALL LETTER L WITH STROKE + '\xeb' # 0x0089 -> LATIN SMALL LETTER E WITH DIAERESIS + '\u0150' # 0x008a -> LATIN CAPITAL LETTER O WITH DOUBLE ACUTE + '\u0151' # 0x008b -> LATIN SMALL LETTER O WITH DOUBLE ACUTE + '\xee' # 0x008c -> LATIN SMALL LETTER I WITH CIRCUMFLEX + '\u0179' # 0x008d -> LATIN CAPITAL LETTER Z WITH ACUTE + '\xc4' # 0x008e -> LATIN CAPITAL LETTER A WITH DIAERESIS + '\u0106' # 0x008f -> LATIN CAPITAL LETTER C WITH ACUTE + '\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE + '\u0139' # 0x0091 -> LATIN CAPITAL LETTER L WITH ACUTE + '\u013a' # 0x0092 -> LATIN SMALL LETTER L WITH ACUTE + '\xf4' # 0x0093 -> LATIN SMALL LETTER O WITH CIRCUMFLEX + '\xf6' # 0x0094 -> LATIN SMALL LETTER O WITH DIAERESIS + '\u013d' # 0x0095 -> LATIN CAPITAL LETTER L WITH CARON + '\u013e' # 0x0096 -> LATIN SMALL LETTER L WITH CARON + '\u015a' # 0x0097 -> LATIN CAPITAL LETTER S WITH ACUTE + '\u015b' # 0x0098 -> LATIN SMALL LETTER S WITH ACUTE + '\xd6' # 0x0099 -> LATIN CAPITAL LETTER O WITH DIAERESIS + '\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS + '\u0164' # 0x009b -> LATIN CAPITAL LETTER T WITH CARON + '\u0165' # 0x009c -> LATIN SMALL LETTER T WITH CARON + '\u0141' # 0x009d -> LATIN CAPITAL LETTER L WITH STROKE + '\xd7' # 0x009e -> MULTIPLICATION SIGN + '\u010d' # 0x009f -> LATIN SMALL LETTER C WITH CARON + '\xe1' # 0x00a0 -> LATIN SMALL LETTER A WITH ACUTE + '\xed' # 0x00a1 -> LATIN SMALL LETTER I WITH ACUTE + '\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE + '\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE + '\u0104' # 0x00a4 -> LATIN CAPITAL LETTER A WITH OGONEK + '\u0105' # 0x00a5 -> LATIN SMALL LETTER A WITH OGONEK + '\u017d' # 0x00a6 -> LATIN CAPITAL LETTER Z WITH CARON + '\u017e' # 0x00a7 -> LATIN SMALL LETTER Z WITH CARON + '\u0118' # 0x00a8 -> LATIN CAPITAL LETTER E WITH OGONEK + '\u0119' # 0x00a9 -> LATIN SMALL LETTER E WITH OGONEK + '\xac' # 0x00aa -> NOT SIGN + '\u017a' # 0x00ab -> LATIN SMALL LETTER Z WITH ACUTE + '\u010c' # 0x00ac -> LATIN CAPITAL LETTER C WITH CARON + '\u015f' # 0x00ad -> LATIN SMALL LETTER S WITH CEDILLA + '\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + '\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + '\u2591' # 0x00b0 -> LIGHT SHADE + '\u2592' # 0x00b1 -> MEDIUM SHADE + '\u2593' # 0x00b2 -> DARK SHADE + '\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL + '\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT + '\xc1' # 0x00b5 -> LATIN CAPITAL LETTER A WITH ACUTE + '\xc2' # 0x00b6 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX + '\u011a' # 0x00b7 -> LATIN CAPITAL LETTER E WITH CARON + '\u015e' # 0x00b8 -> LATIN CAPITAL LETTER S WITH CEDILLA + '\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT + '\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL + '\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT + '\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT + '\u017b' # 0x00bd -> LATIN CAPITAL LETTER Z WITH DOT ABOVE + '\u017c' # 0x00be -> LATIN SMALL LETTER Z WITH DOT ABOVE + '\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT + '\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT + '\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL + '\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL + '\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT + '\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL + '\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL + '\u0102' # 0x00c6 -> LATIN CAPITAL LETTER A WITH BREVE + '\u0103' # 0x00c7 -> LATIN SMALL LETTER A WITH BREVE + '\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT + '\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT + '\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL + '\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL + '\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT + '\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL + '\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL + '\xa4' # 0x00cf -> CURRENCY SIGN + '\u0111' # 0x00d0 -> LATIN SMALL LETTER D WITH STROKE + '\u0110' # 0x00d1 -> LATIN CAPITAL LETTER D WITH STROKE + '\u010e' # 0x00d2 -> LATIN CAPITAL LETTER D WITH CARON + '\xcb' # 0x00d3 -> LATIN CAPITAL LETTER E WITH DIAERESIS + '\u010f' # 0x00d4 -> LATIN SMALL LETTER D WITH CARON + '\u0147' # 0x00d5 -> LATIN CAPITAL LETTER N WITH CARON + '\xcd' # 0x00d6 -> LATIN CAPITAL LETTER I WITH ACUTE + '\xce' # 0x00d7 -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX + '\u011b' # 0x00d8 -> LATIN SMALL LETTER E WITH CARON + '\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT + '\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT + '\u2588' # 0x00db -> FULL BLOCK + '\u2584' # 0x00dc -> LOWER HALF BLOCK + '\u0162' # 0x00dd -> LATIN CAPITAL LETTER T WITH CEDILLA + '\u016e' # 0x00de -> LATIN CAPITAL LETTER U WITH RING ABOVE + '\u2580' # 0x00df -> UPPER HALF BLOCK + '\xd3' # 0x00e0 -> LATIN CAPITAL LETTER O WITH ACUTE + '\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S + '\xd4' # 0x00e2 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX + '\u0143' # 0x00e3 -> LATIN CAPITAL LETTER N WITH ACUTE + '\u0144' # 0x00e4 -> LATIN SMALL LETTER N WITH ACUTE + '\u0148' # 0x00e5 -> LATIN SMALL LETTER N WITH CARON + '\u0160' # 0x00e6 -> LATIN CAPITAL LETTER S WITH CARON + '\u0161' # 0x00e7 -> LATIN SMALL LETTER S WITH CARON + '\u0154' # 0x00e8 -> LATIN CAPITAL LETTER R WITH ACUTE + '\xda' # 0x00e9 -> LATIN CAPITAL LETTER U WITH ACUTE + '\u0155' # 0x00ea -> LATIN SMALL LETTER R WITH ACUTE + '\u0170' # 0x00eb -> LATIN CAPITAL LETTER U WITH DOUBLE ACUTE + '\xfd' # 0x00ec -> LATIN SMALL LETTER Y WITH ACUTE + '\xdd' # 0x00ed -> LATIN CAPITAL LETTER Y WITH ACUTE + '\u0163' # 0x00ee -> LATIN SMALL LETTER T WITH CEDILLA + '\xb4' # 0x00ef -> ACUTE ACCENT + '\xad' # 0x00f0 -> SOFT HYPHEN + '\u02dd' # 0x00f1 -> DOUBLE ACUTE ACCENT + '\u02db' # 0x00f2 -> OGONEK + '\u02c7' # 0x00f3 -> CARON + '\u02d8' # 0x00f4 -> BREVE + '\xa7' # 0x00f5 -> SECTION SIGN + '\xf7' # 0x00f6 -> DIVISION SIGN + '\xb8' # 0x00f7 -> CEDILLA + '\xb0' # 0x00f8 -> DEGREE SIGN + '\xa8' # 0x00f9 -> DIAERESIS + '\u02d9' # 0x00fa -> DOT ABOVE + '\u0171' # 0x00fb -> LATIN SMALL LETTER U WITH DOUBLE ACUTE + '\u0158' # 0x00fc -> LATIN CAPITAL LETTER R WITH CARON + '\u0159' # 0x00fd -> LATIN SMALL LETTER R WITH CARON + '\u25a0' # 0x00fe -> BLACK SQUARE + '\xa0' # 0x00ff -> NO-BREAK SPACE +) + +### Encoding Map + +encoding_map = { + 0x0000: 0x0000, # NULL + 0x0001: 0x0001, # START OF HEADING + 0x0002: 0x0002, # START OF TEXT + 0x0003: 0x0003, # END OF TEXT + 0x0004: 0x0004, # END OF TRANSMISSION + 0x0005: 0x0005, # ENQUIRY + 0x0006: 0x0006, # ACKNOWLEDGE + 0x0007: 0x0007, # BELL + 0x0008: 0x0008, # BACKSPACE + 0x0009: 0x0009, # HORIZONTAL TABULATION + 0x000a: 0x000a, # LINE FEED + 0x000b: 0x000b, # VERTICAL TABULATION + 0x000c: 0x000c, # FORM FEED + 0x000d: 0x000d, # CARRIAGE RETURN + 0x000e: 0x000e, # SHIFT OUT + 0x000f: 0x000f, # SHIFT IN + 0x0010: 0x0010, # DATA LINK ESCAPE + 0x0011: 0x0011, # DEVICE CONTROL ONE + 0x0012: 0x0012, # DEVICE CONTROL TWO + 0x0013: 0x0013, # DEVICE CONTROL THREE + 0x0014: 0x0014, # DEVICE CONTROL FOUR + 0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE + 0x0016: 0x0016, # SYNCHRONOUS IDLE + 0x0017: 0x0017, # END OF TRANSMISSION BLOCK + 0x0018: 0x0018, # CANCEL + 0x0019: 0x0019, # END OF MEDIUM + 0x001a: 0x001a, # SUBSTITUTE + 0x001b: 0x001b, # ESCAPE + 0x001c: 0x001c, # FILE SEPARATOR + 0x001d: 0x001d, # GROUP SEPARATOR + 0x001e: 0x001e, # RECORD SEPARATOR + 0x001f: 0x001f, # UNIT SEPARATOR + 0x0020: 0x0020, # SPACE + 0x0021: 0x0021, # EXCLAMATION MARK + 0x0022: 0x0022, # QUOTATION MARK + 0x0023: 0x0023, # NUMBER SIGN + 0x0024: 0x0024, # DOLLAR SIGN + 0x0025: 0x0025, # PERCENT SIGN + 0x0026: 0x0026, # AMPERSAND + 0x0027: 0x0027, # APOSTROPHE + 0x0028: 0x0028, # LEFT PARENTHESIS + 0x0029: 0x0029, # RIGHT PARENTHESIS + 0x002a: 0x002a, # ASTERISK + 0x002b: 0x002b, # PLUS SIGN + 0x002c: 0x002c, # COMMA + 0x002d: 0x002d, # HYPHEN-MINUS + 0x002e: 0x002e, # FULL STOP + 0x002f: 0x002f, # SOLIDUS + 0x0030: 0x0030, # DIGIT ZERO + 0x0031: 0x0031, # DIGIT ONE + 0x0032: 0x0032, # DIGIT TWO + 0x0033: 0x0033, # DIGIT THREE + 0x0034: 0x0034, # DIGIT FOUR + 0x0035: 0x0035, # DIGIT FIVE + 0x0036: 0x0036, # DIGIT SIX + 0x0037: 0x0037, # DIGIT SEVEN + 0x0038: 0x0038, # DIGIT EIGHT + 0x0039: 0x0039, # DIGIT NINE + 0x003a: 0x003a, # COLON + 0x003b: 0x003b, # SEMICOLON + 0x003c: 0x003c, # LESS-THAN SIGN + 0x003d: 0x003d, # EQUALS SIGN + 0x003e: 0x003e, # GREATER-THAN SIGN + 0x003f: 0x003f, # QUESTION MARK + 0x0040: 0x0040, # COMMERCIAL AT + 0x0041: 0x0041, # LATIN CAPITAL LETTER A + 0x0042: 0x0042, # LATIN CAPITAL LETTER B + 0x0043: 0x0043, # LATIN CAPITAL LETTER C + 0x0044: 0x0044, # LATIN CAPITAL LETTER D + 0x0045: 0x0045, # LATIN CAPITAL LETTER E + 0x0046: 0x0046, # LATIN CAPITAL LETTER F + 0x0047: 0x0047, # LATIN CAPITAL LETTER G + 0x0048: 0x0048, # LATIN CAPITAL LETTER H + 0x0049: 0x0049, # LATIN CAPITAL LETTER I + 0x004a: 0x004a, # LATIN CAPITAL LETTER J + 0x004b: 0x004b, # LATIN CAPITAL LETTER K + 0x004c: 0x004c, # LATIN CAPITAL LETTER L + 0x004d: 0x004d, # LATIN CAPITAL LETTER M + 0x004e: 0x004e, # LATIN CAPITAL LETTER N + 0x004f: 0x004f, # LATIN CAPITAL LETTER O + 0x0050: 0x0050, # LATIN CAPITAL LETTER P + 0x0051: 0x0051, # LATIN CAPITAL LETTER Q + 0x0052: 0x0052, # LATIN CAPITAL LETTER R + 0x0053: 0x0053, # LATIN CAPITAL LETTER S + 0x0054: 0x0054, # LATIN CAPITAL LETTER T + 0x0055: 0x0055, # LATIN CAPITAL LETTER U + 0x0056: 0x0056, # LATIN CAPITAL LETTER V + 0x0057: 0x0057, # LATIN CAPITAL LETTER W + 0x0058: 0x0058, # LATIN CAPITAL LETTER X + 0x0059: 0x0059, # LATIN CAPITAL LETTER Y + 0x005a: 0x005a, # LATIN CAPITAL LETTER Z + 0x005b: 0x005b, # LEFT SQUARE BRACKET + 0x005c: 0x005c, # REVERSE SOLIDUS + 0x005d: 0x005d, # RIGHT SQUARE BRACKET + 0x005e: 0x005e, # CIRCUMFLEX ACCENT + 0x005f: 0x005f, # LOW LINE + 0x0060: 0x0060, # GRAVE ACCENT + 0x0061: 0x0061, # LATIN SMALL LETTER A + 0x0062: 0x0062, # LATIN SMALL LETTER B + 0x0063: 0x0063, # LATIN SMALL LETTER C + 0x0064: 0x0064, # LATIN SMALL LETTER D + 0x0065: 0x0065, # LATIN SMALL LETTER E + 0x0066: 0x0066, # LATIN SMALL LETTER F + 0x0067: 0x0067, # LATIN SMALL LETTER G + 0x0068: 0x0068, # LATIN SMALL LETTER H + 0x0069: 0x0069, # LATIN SMALL LETTER I + 0x006a: 0x006a, # LATIN SMALL LETTER J + 0x006b: 0x006b, # LATIN SMALL LETTER K + 0x006c: 0x006c, # LATIN SMALL LETTER L + 0x006d: 0x006d, # LATIN SMALL LETTER M + 0x006e: 0x006e, # LATIN SMALL LETTER N + 0x006f: 0x006f, # LATIN SMALL LETTER O + 0x0070: 0x0070, # LATIN SMALL LETTER P + 0x0071: 0x0071, # LATIN SMALL LETTER Q + 0x0072: 0x0072, # LATIN SMALL LETTER R + 0x0073: 0x0073, # LATIN SMALL LETTER S + 0x0074: 0x0074, # LATIN SMALL LETTER T + 0x0075: 0x0075, # LATIN SMALL LETTER U + 0x0076: 0x0076, # LATIN SMALL LETTER V + 0x0077: 0x0077, # LATIN SMALL LETTER W + 0x0078: 0x0078, # LATIN SMALL LETTER X + 0x0079: 0x0079, # LATIN SMALL LETTER Y + 0x007a: 0x007a, # LATIN SMALL LETTER Z + 0x007b: 0x007b, # LEFT CURLY BRACKET + 0x007c: 0x007c, # VERTICAL LINE + 0x007d: 0x007d, # RIGHT CURLY BRACKET + 0x007e: 0x007e, # TILDE + 0x007f: 0x007f, # DELETE + 0x00a0: 0x00ff, # NO-BREAK SPACE + 0x00a4: 0x00cf, # CURRENCY SIGN + 0x00a7: 0x00f5, # SECTION SIGN + 0x00a8: 0x00f9, # DIAERESIS + 0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + 0x00ac: 0x00aa, # NOT SIGN + 0x00ad: 0x00f0, # SOFT HYPHEN + 0x00b0: 0x00f8, # DEGREE SIGN + 0x00b4: 0x00ef, # ACUTE ACCENT + 0x00b8: 0x00f7, # CEDILLA + 0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + 0x00c1: 0x00b5, # LATIN CAPITAL LETTER A WITH ACUTE + 0x00c2: 0x00b6, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX + 0x00c4: 0x008e, # LATIN CAPITAL LETTER A WITH DIAERESIS + 0x00c7: 0x0080, # LATIN CAPITAL LETTER C WITH CEDILLA + 0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE + 0x00cb: 0x00d3, # LATIN CAPITAL LETTER E WITH DIAERESIS + 0x00cd: 0x00d6, # LATIN CAPITAL LETTER I WITH ACUTE + 0x00ce: 0x00d7, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX + 0x00d3: 0x00e0, # LATIN CAPITAL LETTER O WITH ACUTE + 0x00d4: 0x00e2, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX + 0x00d6: 0x0099, # LATIN CAPITAL LETTER O WITH DIAERESIS + 0x00d7: 0x009e, # MULTIPLICATION SIGN + 0x00da: 0x00e9, # LATIN CAPITAL LETTER U WITH ACUTE + 0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS + 0x00dd: 0x00ed, # LATIN CAPITAL LETTER Y WITH ACUTE + 0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S + 0x00e1: 0x00a0, # LATIN SMALL LETTER A WITH ACUTE + 0x00e2: 0x0083, # LATIN SMALL LETTER A WITH CIRCUMFLEX + 0x00e4: 0x0084, # LATIN SMALL LETTER A WITH DIAERESIS + 0x00e7: 0x0087, # LATIN SMALL LETTER C WITH CEDILLA + 0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE + 0x00eb: 0x0089, # LATIN SMALL LETTER E WITH DIAERESIS + 0x00ed: 0x00a1, # LATIN SMALL LETTER I WITH ACUTE + 0x00ee: 0x008c, # LATIN SMALL LETTER I WITH CIRCUMFLEX + 0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE + 0x00f4: 0x0093, # LATIN SMALL LETTER O WITH CIRCUMFLEX + 0x00f6: 0x0094, # LATIN SMALL LETTER O WITH DIAERESIS + 0x00f7: 0x00f6, # DIVISION SIGN + 0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE + 0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS + 0x00fd: 0x00ec, # LATIN SMALL LETTER Y WITH ACUTE + 0x0102: 0x00c6, # LATIN CAPITAL LETTER A WITH BREVE + 0x0103: 0x00c7, # LATIN SMALL LETTER A WITH BREVE + 0x0104: 0x00a4, # LATIN CAPITAL LETTER A WITH OGONEK + 0x0105: 0x00a5, # LATIN SMALL LETTER A WITH OGONEK + 0x0106: 0x008f, # LATIN CAPITAL LETTER C WITH ACUTE + 0x0107: 0x0086, # LATIN SMALL LETTER C WITH ACUTE + 0x010c: 0x00ac, # LATIN CAPITAL LETTER C WITH CARON + 0x010d: 0x009f, # LATIN SMALL LETTER C WITH CARON + 0x010e: 0x00d2, # LATIN CAPITAL LETTER D WITH CARON + 0x010f: 0x00d4, # LATIN SMALL LETTER D WITH CARON + 0x0110: 0x00d1, # LATIN CAPITAL LETTER D WITH STROKE + 0x0111: 0x00d0, # LATIN SMALL LETTER D WITH STROKE + 0x0118: 0x00a8, # LATIN CAPITAL LETTER E WITH OGONEK + 0x0119: 0x00a9, # LATIN SMALL LETTER E WITH OGONEK + 0x011a: 0x00b7, # LATIN CAPITAL LETTER E WITH CARON + 0x011b: 0x00d8, # LATIN SMALL LETTER E WITH CARON + 0x0139: 0x0091, # LATIN CAPITAL LETTER L WITH ACUTE + 0x013a: 0x0092, # LATIN SMALL LETTER L WITH ACUTE + 0x013d: 0x0095, # LATIN CAPITAL LETTER L WITH CARON + 0x013e: 0x0096, # LATIN SMALL LETTER L WITH CARON + 0x0141: 0x009d, # LATIN CAPITAL LETTER L WITH STROKE + 0x0142: 0x0088, # LATIN SMALL LETTER L WITH STROKE + 0x0143: 0x00e3, # LATIN CAPITAL LETTER N WITH ACUTE + 0x0144: 0x00e4, # LATIN SMALL LETTER N WITH ACUTE + 0x0147: 0x00d5, # LATIN CAPITAL LETTER N WITH CARON + 0x0148: 0x00e5, # LATIN SMALL LETTER N WITH CARON + 0x0150: 0x008a, # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE + 0x0151: 0x008b, # LATIN SMALL LETTER O WITH DOUBLE ACUTE + 0x0154: 0x00e8, # LATIN CAPITAL LETTER R WITH ACUTE + 0x0155: 0x00ea, # LATIN SMALL LETTER R WITH ACUTE + 0x0158: 0x00fc, # LATIN CAPITAL LETTER R WITH CARON + 0x0159: 0x00fd, # LATIN SMALL LETTER R WITH CARON + 0x015a: 0x0097, # LATIN CAPITAL LETTER S WITH ACUTE + 0x015b: 0x0098, # LATIN SMALL LETTER S WITH ACUTE + 0x015e: 0x00b8, # LATIN CAPITAL LETTER S WITH CEDILLA + 0x015f: 0x00ad, # LATIN SMALL LETTER S WITH CEDILLA + 0x0160: 0x00e6, # LATIN CAPITAL LETTER S WITH CARON + 0x0161: 0x00e7, # LATIN SMALL LETTER S WITH CARON + 0x0162: 0x00dd, # LATIN CAPITAL LETTER T WITH CEDILLA + 0x0163: 0x00ee, # LATIN SMALL LETTER T WITH CEDILLA + 0x0164: 0x009b, # LATIN CAPITAL LETTER T WITH CARON + 0x0165: 0x009c, # LATIN SMALL LETTER T WITH CARON + 0x016e: 0x00de, # LATIN CAPITAL LETTER U WITH RING ABOVE + 0x016f: 0x0085, # LATIN SMALL LETTER U WITH RING ABOVE + 0x0170: 0x00eb, # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE + 0x0171: 0x00fb, # LATIN SMALL LETTER U WITH DOUBLE ACUTE + 0x0179: 0x008d, # LATIN CAPITAL LETTER Z WITH ACUTE + 0x017a: 0x00ab, # LATIN SMALL LETTER Z WITH ACUTE + 0x017b: 0x00bd, # LATIN CAPITAL LETTER Z WITH DOT ABOVE + 0x017c: 0x00be, # LATIN SMALL LETTER Z WITH DOT ABOVE + 0x017d: 0x00a6, # LATIN CAPITAL LETTER Z WITH CARON + 0x017e: 0x00a7, # LATIN SMALL LETTER Z WITH CARON + 0x02c7: 0x00f3, # CARON + 0x02d8: 0x00f4, # BREVE + 0x02d9: 0x00fa, # DOT ABOVE + 0x02db: 0x00f2, # OGONEK + 0x02dd: 0x00f1, # DOUBLE ACUTE ACCENT + 0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL + 0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL + 0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT + 0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT + 0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT + 0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT + 0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT + 0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT + 0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL + 0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL + 0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL + 0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL + 0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL + 0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT + 0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT + 0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT + 0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT + 0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT + 0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT + 0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL + 0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL + 0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL + 0x2580: 0x00df, # UPPER HALF BLOCK + 0x2584: 0x00dc, # LOWER HALF BLOCK + 0x2588: 0x00db, # FULL BLOCK + 0x2591: 0x00b0, # LIGHT SHADE + 0x2592: 0x00b1, # MEDIUM SHADE + 0x2593: 0x00b2, # DARK SHADE + 0x25a0: 0x00fe, # BLACK SQUARE +} diff --git a/shared/package-files/cc/cc77f7f773108f11529486276be5310e2ffacfbfacc7aab12c2423ee4e31946f/unflatten_compositeimplicitautograd_dispatch.h b/shared/package-files/cc/cc77f7f773108f11529486276be5310e2ffacfbfacc7aab12c2423ee4e31946f/unflatten_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..983504911a84558096fc5ecb3562aa910cb7b6f3 --- /dev/null +++ b/shared/package-files/cc/cc77f7f773108f11529486276be5310e2ffacfbfacc7aab12c2423ee4e31946f/unflatten_compositeimplicitautograd_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor unflatten(const at::Tensor & self, int64_t dim, at::IntArrayRef sizes); +TORCH_API at::Tensor unflatten_symint(const at::Tensor & self, int64_t dim, c10::SymIntArrayRef sizes); +TORCH_API at::Tensor unflatten(const at::Tensor & self, at::Dimname dim, at::IntArrayRef sizes, at::DimnameList names); +TORCH_API at::Tensor unflatten_symint(const at::Tensor & self, at::Dimname dim, c10::SymIntArrayRef sizes, at::DimnameList names); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/cc/cc7e94d56e5f6d77f3fc63948b54dccb481f6970595ee8ab6eda43d868e22261/RECORD b/shared/package-files/cc/cc7e94d56e5f6d77f3fc63948b54dccb481f6970595ee8ab6eda43d868e22261/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..c286b78e9f62032dad997edbf49d95247b6c5e6e --- /dev/null +++ b/shared/package-files/cc/cc7e94d56e5f6d77f3fc63948b54dccb481f6970595ee8ab6eda43d868e22261/RECORD @@ -0,0 +1,9 @@ +cycler-0.12.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +cycler-0.12.1.dist-info/LICENSE,sha256=8SGBQ9dm2j_qZvEzlrfxXfRqgzA_Kb-Wum6Y601C9Ag,1497 +cycler-0.12.1.dist-info/METADATA,sha256=IyieGbdvHgE5Qidpbmryts0c556JcxIJv5GVFIsY7TY,3779 +cycler-0.12.1.dist-info/RECORD,, +cycler-0.12.1.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92 +cycler-0.12.1.dist-info/top_level.txt,sha256=D8BVVDdAAelLb2FOEz7lDpc6-AL21ylKPrMhtG6yzyE,7 +cycler/__init__.py,sha256=1JdRgv5Zzxo-W1ev7B_LWquysWP6LZH6CHk_COtIaXE,16709 +cycler/__pycache__/__init__.cpython-310.pyc,, +cycler/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/shared/package-files/cc/cc7eb30636707cdb579f235833c38d3664ca59eecd40e3ab47e507f4457a881d/Normalization.h b/shared/package-files/cc/cc7eb30636707cdb579f235833c38d3664ca59eecd40e3ab47e507f4457a881d/Normalization.h new file mode 100644 index 0000000000000000000000000000000000000000..6cd4dcde370522874311f43dbcdfca0e16bc5035 --- /dev/null +++ b/shared/package-files/cc/cc7eb30636707cdb579f235833c38d3664ca59eecd40e3ab47e507f4457a881d/Normalization.h @@ -0,0 +1,11 @@ +#pragma once + +#include +#include + +namespace at::native { + +using renorm_scale_factor_fn = void (*) (TensorIteratorBase& iter, double maxnorm); +DECLARE_DISPATCH(renorm_scale_factor_fn, renorm_scale_factor_stub); + +} // namespace at::native diff --git a/shared/package-files/cc/cc81e9c3529d9166d3cdb5dbef784f6c28383761ed8f75cbf0323033bb1e5e9a/foo.f90 b/shared/package-files/cc/cc81e9c3529d9166d3cdb5dbef784f6c28383761ed8f75cbf0323033bb1e5e9a/foo.f90 new file mode 100644 index 0000000000000000000000000000000000000000..d3d15cfb20a15004ed86e45dc91792d1c089033a --- /dev/null +++ b/shared/package-files/cc/cc81e9c3529d9166d3cdb5dbef784f6c28383761ed8f75cbf0323033bb1e5e9a/foo.f90 @@ -0,0 +1,20 @@ + + +subroutine selectedrealkind(p, r, res) + implicit none + + integer, intent(in) :: p, r + !f2py integer :: r=0 + integer, intent(out) :: res + res = selected_real_kind(p, r) + +end subroutine + +subroutine selectedintkind(p, res) + implicit none + + integer, intent(in) :: p + integer, intent(out) :: res + res = selected_int_kind(p) + +end subroutine diff --git a/shared/package-files/cc/cc826c93682ef19d29ab6304657e07802c70cf18b1e5ea99c3480df6d2383983/es_pe.msg b/shared/package-files/cc/cc826c93682ef19d29ab6304657e07802c70cf18b1e5ea99c3480df6d2383983/es_pe.msg new file mode 100644 index 0000000000000000000000000000000000000000..9f90595fce588d0b1e55fd7bf44cf4ebc90c2549 --- /dev/null +++ b/shared/package-files/cc/cc826c93682ef19d29ab6304657e07802c70cf18b1e5ea99c3480df6d2383983/es_pe.msg @@ -0,0 +1,6 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset es_PE DATE_FORMAT "%d/%m/%Y" + ::msgcat::mcset es_PE TIME_FORMAT_12 "%I:%M:%S %P" + ::msgcat::mcset es_PE DATE_TIME_FORMAT "%d/%m/%Y %I:%M:%S %P %z" +} diff --git a/shared/package-files/cc/cc8295c5f24aef4763179bb803bca2adb68fd30daf25d2c40933ce8331b99fc4/op_properties.py b/shared/package-files/cc/cc8295c5f24aef4763179bb803bca2adb68fd30daf25d2c40933ce8331b99fc4/op_properties.py new file mode 100644 index 0000000000000000000000000000000000000000..3760f2cb0ea79c2e4ee802abeb8bc954663553e6 --- /dev/null +++ b/shared/package-files/cc/cc8295c5f24aef4763179bb803bca2adb68fd30daf25d2c40933ce8331b99fc4/op_properties.py @@ -0,0 +1,311 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. +import torch + +# pointwise operators can go through a faster pathway + +tensor_magic_methods = ["add", ""] +pointwise_magic_methods_with_reverse = ( + "add", + "sub", + "mul", + "floordiv", + "div", + "truediv", + "mod", + "pow", + "lshift", + "rshift", + "and", + "or", + "xor", +) +pointwise_magic_methods = ( + *(x for m in pointwise_magic_methods_with_reverse for x in (m, "r" + m)), + "eq", + "gt", + "le", + "lt", + "ge", + "gt", + "ne", + "neg", + "pos", + "abs", + "invert", + "iadd", + "isub", + "imul", + "ifloordiv", + "idiv", + "itruediv", + "imod", + "ipow", + "ilshift", + "irshift", + "iand", + "ior", + "ixor", + "int", + "long", + "float", + "complex", +) + +pointwise_methods = (*(f"__{m}__" for m in pointwise_magic_methods),) + +pointwise = ( + *(getattr(torch.Tensor, m) for m in pointwise_methods), + torch.nn.functional.dropout, + torch.where, + torch.Tensor.abs, + torch.abs, + torch.Tensor.acos, + torch.acos, + torch.Tensor.acosh, + torch.acosh, + torch.Tensor.add, + torch.add, + torch.Tensor.addcdiv, + torch.addcdiv, + torch.Tensor.addcmul, + torch.addcmul, + torch.Tensor.addr, + torch.addr, + torch.Tensor.angle, + torch.angle, + torch.Tensor.asin, + torch.asin, + torch.Tensor.asinh, + torch.asinh, + torch.Tensor.atan, + torch.atan, + torch.Tensor.atan2, + torch.atan2, + torch.Tensor.atanh, + torch.atanh, + torch.Tensor.bitwise_and, + torch.bitwise_and, + torch.Tensor.bitwise_left_shift, + torch.bitwise_left_shift, + torch.Tensor.bitwise_not, + torch.bitwise_not, + torch.Tensor.bitwise_or, + torch.bitwise_or, + torch.Tensor.bitwise_right_shift, + torch.bitwise_right_shift, + torch.Tensor.bitwise_xor, + torch.bitwise_xor, + torch.Tensor.ceil, + torch.ceil, + torch.celu, + torch.nn.functional.celu, + torch.Tensor.clamp, + torch.clamp, + torch.Tensor.clamp_max, + torch.clamp_max, + torch.Tensor.clamp_min, + torch.clamp_min, + torch.Tensor.copysign, + torch.copysign, + torch.Tensor.cos, + torch.cos, + torch.Tensor.cosh, + torch.cosh, + torch.Tensor.deg2rad, + torch.deg2rad, + torch.Tensor.digamma, + torch.digamma, + torch.Tensor.div, + torch.div, + torch.dropout, + torch.nn.functional.dropout, + torch.nn.functional.elu, + torch.Tensor.eq, + torch.eq, + torch.Tensor.erf, + torch.erf, + torch.Tensor.erfc, + torch.erfc, + torch.Tensor.erfinv, + torch.erfinv, + torch.Tensor.exp, + torch.exp, + torch.Tensor.exp2, + torch.exp2, + torch.Tensor.expm1, + torch.expm1, + torch.feature_dropout, + torch.Tensor.float_power, + torch.float_power, + torch.Tensor.floor, + torch.floor, + torch.Tensor.floor_divide, + torch.floor_divide, + torch.Tensor.fmod, + torch.fmod, + torch.Tensor.frac, + torch.frac, + torch.Tensor.frexp, + torch.frexp, + torch.Tensor.gcd, + torch.gcd, + torch.Tensor.ge, + torch.ge, + torch.nn.functional.gelu, + torch.nn.functional.glu, + torch.Tensor.gt, + torch.gt, + torch.Tensor.hardshrink, + torch.hardshrink, + torch.nn.functional.hardshrink, + torch.nn.functional.hardsigmoid, + torch.nn.functional.hardswish, + torch.nn.functional.hardtanh, + torch.Tensor.heaviside, + torch.heaviside, + torch.Tensor.hypot, + torch.hypot, + torch.Tensor.i0, + torch.i0, + torch.Tensor.igamma, + torch.igamma, + torch.Tensor.igammac, + torch.igammac, + torch.Tensor.isclose, + torch.isclose, + torch.Tensor.isfinite, + torch.isfinite, + torch.Tensor.isinf, + torch.isinf, + torch.Tensor.isnan, + torch.isnan, + torch.Tensor.isneginf, + torch.isneginf, + torch.Tensor.isposinf, + torch.isposinf, + torch.Tensor.isreal, + torch.isreal, + torch.Tensor.kron, + torch.kron, + torch.Tensor.lcm, + torch.lcm, + torch.Tensor.ldexp, + torch.ldexp, + torch.Tensor.le, + torch.le, + torch.nn.functional.leaky_relu, + torch.Tensor.lerp, + torch.lerp, + torch.Tensor.lgamma, + torch.lgamma, + torch.Tensor.log, + torch.log, + torch.Tensor.log10, + torch.log10, + torch.Tensor.log1p, + torch.log1p, + torch.Tensor.log2, + torch.log2, + torch.nn.functional.logsigmoid, + torch.Tensor.logical_and, + torch.logical_and, + torch.Tensor.logical_not, + torch.logical_not, + torch.Tensor.logical_or, + torch.logical_or, + torch.Tensor.logical_xor, + torch.logical_xor, + torch.Tensor.logit, + torch.logit, + torch.Tensor.lt, + torch.lt, + torch.Tensor.maximum, + torch.maximum, + torch.Tensor.minimum, + torch.minimum, + torch.nn.functional.mish, + torch.Tensor.mvlgamma, + torch.mvlgamma, + torch.Tensor.nan_to_num, + torch.nan_to_num, + torch.Tensor.ne, + torch.ne, + torch.Tensor.neg, + torch.neg, + torch.Tensor.nextafter, + torch.nextafter, + torch.Tensor.outer, + torch.outer, + torch.polar, + torch.Tensor.polygamma, + torch.polygamma, + torch.Tensor.positive, + torch.positive, + torch.Tensor.pow, + torch.pow, + torch.Tensor.prelu, + torch.prelu, + torch.nn.functional.prelu, + torch.Tensor.rad2deg, + torch.rad2deg, + torch.Tensor.reciprocal, + torch.reciprocal, + torch.Tensor.relu, + torch.relu, + torch.nn.functional.relu, + torch.nn.functional.relu6, + torch.Tensor.remainder, + torch.remainder, + torch.Tensor.round, + torch.round, + torch.rrelu, + torch.nn.functional.rrelu, + torch.Tensor.rsqrt, + torch.rsqrt, + torch.rsub, + torch.selu, + torch.nn.functional.selu, + torch.Tensor.sgn, + torch.sgn, + torch.Tensor.sigmoid, + torch.sigmoid, + torch.nn.functional.sigmoid, + torch.Tensor.sign, + torch.sign, + torch.Tensor.signbit, + torch.signbit, + torch.nn.functional.silu, + torch.Tensor.sin, + torch.sin, + torch.Tensor.sinc, + torch.sinc, + torch.Tensor.sinh, + torch.sinh, + torch.nn.functional.softplus, + torch.nn.functional.softshrink, + torch.Tensor.sqrt, + torch.sqrt, + torch.Tensor.square, + torch.square, + torch.Tensor.sub, + torch.sub, + torch.Tensor.tan, + torch.tan, + torch.Tensor.tanh, + torch.tanh, + torch.nn.functional.tanh, + torch.threshold, + torch.nn.functional.threshold, + torch.trapz, + torch.Tensor.true_divide, + torch.true_divide, + torch.Tensor.trunc, + torch.trunc, + torch.Tensor.xlogy, + torch.xlogy, + torch.rand_like, +) diff --git a/shared/package-files/cc/cc849e42cb2f51b6759094eaac55f4c7c37c416bab88cec5fca3d0bdaa973d0e/wavfile.py b/shared/package-files/cc/cc849e42cb2f51b6759094eaac55f4c7c37c416bab88cec5fca3d0bdaa973d0e/wavfile.py new file mode 100644 index 0000000000000000000000000000000000000000..b6978a1c461c825e35b8a1f0d7de39fceba38bd6 --- /dev/null +++ b/shared/package-files/cc/cc849e42cb2f51b6759094eaac55f4c7c37c416bab88cec5fca3d0bdaa973d0e/wavfile.py @@ -0,0 +1,891 @@ +""" +Module to read / write wav files using NumPy arrays + +Functions +--------- +`read`: Return the sample rate (in samples/sec) and data from a WAV file. + +`write`: Write a NumPy array as a WAV file. + +""" +import io +import sys +import numpy as np +import struct +import warnings +from enum import IntEnum + + +__all__ = [ + 'WavFileWarning', + 'read', + 'write' +] + + +class WavFileWarning(UserWarning): + pass + + +class WAVE_FORMAT(IntEnum): + """ + WAVE form wFormatTag IDs + + Complete list is in mmreg.h in Windows 10 SDK. ALAC and OPUS are the + newest additions, in v10.0.14393 2016-07 + """ + UNKNOWN = 0x0000 + PCM = 0x0001 + ADPCM = 0x0002 + IEEE_FLOAT = 0x0003 + VSELP = 0x0004 + IBM_CVSD = 0x0005 + ALAW = 0x0006 + MULAW = 0x0007 + DTS = 0x0008 + DRM = 0x0009 + WMAVOICE9 = 0x000A + WMAVOICE10 = 0x000B + OKI_ADPCM = 0x0010 + DVI_ADPCM = 0x0011 + IMA_ADPCM = 0x0011 # Duplicate + MEDIASPACE_ADPCM = 0x0012 + SIERRA_ADPCM = 0x0013 + G723_ADPCM = 0x0014 + DIGISTD = 0x0015 + DIGIFIX = 0x0016 + DIALOGIC_OKI_ADPCM = 0x0017 + MEDIAVISION_ADPCM = 0x0018 + CU_CODEC = 0x0019 + HP_DYN_VOICE = 0x001A + YAMAHA_ADPCM = 0x0020 + SONARC = 0x0021 + DSPGROUP_TRUESPEECH = 0x0022 + ECHOSC1 = 0x0023 + AUDIOFILE_AF36 = 0x0024 + APTX = 0x0025 + AUDIOFILE_AF10 = 0x0026 + PROSODY_1612 = 0x0027 + LRC = 0x0028 + DOLBY_AC2 = 0x0030 + GSM610 = 0x0031 + MSNAUDIO = 0x0032 + ANTEX_ADPCME = 0x0033 + CONTROL_RES_VQLPC = 0x0034 + DIGIREAL = 0x0035 + DIGIADPCM = 0x0036 + CONTROL_RES_CR10 = 0x0037 + NMS_VBXADPCM = 0x0038 + CS_IMAADPCM = 0x0039 + ECHOSC3 = 0x003A + ROCKWELL_ADPCM = 0x003B + ROCKWELL_DIGITALK = 0x003C + XEBEC = 0x003D + G721_ADPCM = 0x0040 + G728_CELP = 0x0041 + MSG723 = 0x0042 + INTEL_G723_1 = 0x0043 + INTEL_G729 = 0x0044 + SHARP_G726 = 0x0045 + MPEG = 0x0050 + RT24 = 0x0052 + PAC = 0x0053 + MPEGLAYER3 = 0x0055 + LUCENT_G723 = 0x0059 + CIRRUS = 0x0060 + ESPCM = 0x0061 + VOXWARE = 0x0062 + CANOPUS_ATRAC = 0x0063 + G726_ADPCM = 0x0064 + G722_ADPCM = 0x0065 + DSAT = 0x0066 + DSAT_DISPLAY = 0x0067 + VOXWARE_BYTE_ALIGNED = 0x0069 + VOXWARE_AC8 = 0x0070 + VOXWARE_AC10 = 0x0071 + VOXWARE_AC16 = 0x0072 + VOXWARE_AC20 = 0x0073 + VOXWARE_RT24 = 0x0074 + VOXWARE_RT29 = 0x0075 + VOXWARE_RT29HW = 0x0076 + VOXWARE_VR12 = 0x0077 + VOXWARE_VR18 = 0x0078 + VOXWARE_TQ40 = 0x0079 + VOXWARE_SC3 = 0x007A + VOXWARE_SC3_1 = 0x007B + SOFTSOUND = 0x0080 + VOXWARE_TQ60 = 0x0081 + MSRT24 = 0x0082 + G729A = 0x0083 + MVI_MVI2 = 0x0084 + DF_G726 = 0x0085 + DF_GSM610 = 0x0086 + ISIAUDIO = 0x0088 + ONLIVE = 0x0089 + MULTITUDE_FT_SX20 = 0x008A + INFOCOM_ITS_G721_ADPCM = 0x008B + CONVEDIA_G729 = 0x008C + CONGRUENCY = 0x008D + SBC24 = 0x0091 + DOLBY_AC3_SPDIF = 0x0092 + MEDIASONIC_G723 = 0x0093 + PROSODY_8KBPS = 0x0094 + ZYXEL_ADPCM = 0x0097 + PHILIPS_LPCBB = 0x0098 + PACKED = 0x0099 + MALDEN_PHONYTALK = 0x00A0 + RACAL_RECORDER_GSM = 0x00A1 + RACAL_RECORDER_G720_A = 0x00A2 + RACAL_RECORDER_G723_1 = 0x00A3 + RACAL_RECORDER_TETRA_ACELP = 0x00A4 + NEC_AAC = 0x00B0 + RAW_AAC1 = 0x00FF + RHETOREX_ADPCM = 0x0100 + IRAT = 0x0101 + VIVO_G723 = 0x0111 + VIVO_SIREN = 0x0112 + PHILIPS_CELP = 0x0120 + PHILIPS_GRUNDIG = 0x0121 + DIGITAL_G723 = 0x0123 + SANYO_LD_ADPCM = 0x0125 + SIPROLAB_ACEPLNET = 0x0130 + SIPROLAB_ACELP4800 = 0x0131 + SIPROLAB_ACELP8V3 = 0x0132 + SIPROLAB_G729 = 0x0133 + SIPROLAB_G729A = 0x0134 + SIPROLAB_KELVIN = 0x0135 + VOICEAGE_AMR = 0x0136 + G726ADPCM = 0x0140 + DICTAPHONE_CELP68 = 0x0141 + DICTAPHONE_CELP54 = 0x0142 + QUALCOMM_PUREVOICE = 0x0150 + QUALCOMM_HALFRATE = 0x0151 + TUBGSM = 0x0155 + MSAUDIO1 = 0x0160 + WMAUDIO2 = 0x0161 + WMAUDIO3 = 0x0162 + WMAUDIO_LOSSLESS = 0x0163 + WMASPDIF = 0x0164 + UNISYS_NAP_ADPCM = 0x0170 + UNISYS_NAP_ULAW = 0x0171 + UNISYS_NAP_ALAW = 0x0172 + UNISYS_NAP_16K = 0x0173 + SYCOM_ACM_SYC008 = 0x0174 + SYCOM_ACM_SYC701_G726L = 0x0175 + SYCOM_ACM_SYC701_CELP54 = 0x0176 + SYCOM_ACM_SYC701_CELP68 = 0x0177 + KNOWLEDGE_ADVENTURE_ADPCM = 0x0178 + FRAUNHOFER_IIS_MPEG2_AAC = 0x0180 + DTS_DS = 0x0190 + CREATIVE_ADPCM = 0x0200 + CREATIVE_FASTSPEECH8 = 0x0202 + CREATIVE_FASTSPEECH10 = 0x0203 + UHER_ADPCM = 0x0210 + ULEAD_DV_AUDIO = 0x0215 + ULEAD_DV_AUDIO_1 = 0x0216 + QUARTERDECK = 0x0220 + ILINK_VC = 0x0230 + RAW_SPORT = 0x0240 + ESST_AC3 = 0x0241 + GENERIC_PASSTHRU = 0x0249 + IPI_HSX = 0x0250 + IPI_RPELP = 0x0251 + CS2 = 0x0260 + SONY_SCX = 0x0270 + SONY_SCY = 0x0271 + SONY_ATRAC3 = 0x0272 + SONY_SPC = 0x0273 + TELUM_AUDIO = 0x0280 + TELUM_IA_AUDIO = 0x0281 + NORCOM_VOICE_SYSTEMS_ADPCM = 0x0285 + FM_TOWNS_SND = 0x0300 + MICRONAS = 0x0350 + MICRONAS_CELP833 = 0x0351 + BTV_DIGITAL = 0x0400 + INTEL_MUSIC_CODER = 0x0401 + INDEO_AUDIO = 0x0402 + QDESIGN_MUSIC = 0x0450 + ON2_VP7_AUDIO = 0x0500 + ON2_VP6_AUDIO = 0x0501 + VME_VMPCM = 0x0680 + TPC = 0x0681 + LIGHTWAVE_LOSSLESS = 0x08AE + OLIGSM = 0x1000 + OLIADPCM = 0x1001 + OLICELP = 0x1002 + OLISBC = 0x1003 + OLIOPR = 0x1004 + LH_CODEC = 0x1100 + LH_CODEC_CELP = 0x1101 + LH_CODEC_SBC8 = 0x1102 + LH_CODEC_SBC12 = 0x1103 + LH_CODEC_SBC16 = 0x1104 + NORRIS = 0x1400 + ISIAUDIO_2 = 0x1401 + SOUNDSPACE_MUSICOMPRESS = 0x1500 + MPEG_ADTS_AAC = 0x1600 + MPEG_RAW_AAC = 0x1601 + MPEG_LOAS = 0x1602 + NOKIA_MPEG_ADTS_AAC = 0x1608 + NOKIA_MPEG_RAW_AAC = 0x1609 + VODAFONE_MPEG_ADTS_AAC = 0x160A + VODAFONE_MPEG_RAW_AAC = 0x160B + MPEG_HEAAC = 0x1610 + VOXWARE_RT24_SPEECH = 0x181C + SONICFOUNDRY_LOSSLESS = 0x1971 + INNINGS_TELECOM_ADPCM = 0x1979 + LUCENT_SX8300P = 0x1C07 + LUCENT_SX5363S = 0x1C0C + CUSEEME = 0x1F03 + NTCSOFT_ALF2CM_ACM = 0x1FC4 + DVM = 0x2000 + DTS2 = 0x2001 + MAKEAVIS = 0x3313 + DIVIO_MPEG4_AAC = 0x4143 + NOKIA_ADAPTIVE_MULTIRATE = 0x4201 + DIVIO_G726 = 0x4243 + LEAD_SPEECH = 0x434C + LEAD_VORBIS = 0x564C + WAVPACK_AUDIO = 0x5756 + OGG_VORBIS_MODE_1 = 0x674F + OGG_VORBIS_MODE_2 = 0x6750 + OGG_VORBIS_MODE_3 = 0x6751 + OGG_VORBIS_MODE_1_PLUS = 0x676F + OGG_VORBIS_MODE_2_PLUS = 0x6770 + OGG_VORBIS_MODE_3_PLUS = 0x6771 + ALAC = 0x6C61 + _3COM_NBX = 0x7000 # Can't have leading digit + OPUS = 0x704F + FAAD_AAC = 0x706D + AMR_NB = 0x7361 + AMR_WB = 0x7362 + AMR_WP = 0x7363 + GSM_AMR_CBR = 0x7A21 + GSM_AMR_VBR_SID = 0x7A22 + COMVERSE_INFOSYS_G723_1 = 0xA100 + COMVERSE_INFOSYS_AVQSBC = 0xA101 + COMVERSE_INFOSYS_SBC = 0xA102 + SYMBOL_G729_A = 0xA103 + VOICEAGE_AMR_WB = 0xA104 + INGENIENT_G726 = 0xA105 + MPEG4_AAC = 0xA106 + ENCORE_G726 = 0xA107 + ZOLL_ASAO = 0xA108 + SPEEX_VOICE = 0xA109 + VIANIX_MASC = 0xA10A + WM9_SPECTRUM_ANALYZER = 0xA10B + WMF_SPECTRUM_ANAYZER = 0xA10C + GSM_610 = 0xA10D + GSM_620 = 0xA10E + GSM_660 = 0xA10F + GSM_690 = 0xA110 + GSM_ADAPTIVE_MULTIRATE_WB = 0xA111 + POLYCOM_G722 = 0xA112 + POLYCOM_G728 = 0xA113 + POLYCOM_G729_A = 0xA114 + POLYCOM_SIREN = 0xA115 + GLOBAL_IP_ILBC = 0xA116 + RADIOTIME_TIME_SHIFT_RADIO = 0xA117 + NICE_ACA = 0xA118 + NICE_ADPCM = 0xA119 + VOCORD_G721 = 0xA11A + VOCORD_G726 = 0xA11B + VOCORD_G722_1 = 0xA11C + VOCORD_G728 = 0xA11D + VOCORD_G729 = 0xA11E + VOCORD_G729_A = 0xA11F + VOCORD_G723_1 = 0xA120 + VOCORD_LBC = 0xA121 + NICE_G728 = 0xA122 + FRACE_TELECOM_G729 = 0xA123 + CODIAN = 0xA124 + FLAC = 0xF1AC + EXTENSIBLE = 0xFFFE + DEVELOPMENT = 0xFFFF + + +KNOWN_WAVE_FORMATS = {WAVE_FORMAT.PCM, WAVE_FORMAT.IEEE_FLOAT} + + +def _raise_bad_format(format_tag): + try: + format_name = WAVE_FORMAT(format_tag).name + except ValueError: + format_name = f'{format_tag:#06x}' + raise ValueError(f"Unknown wave file format: {format_name}. Supported " + "formats: " + + ', '.join(x.name for x in KNOWN_WAVE_FORMATS)) + + +def _read_fmt_chunk(fid, is_big_endian): + """ + Returns + ------- + size : int + size of format subchunk in bytes (minus 8 for "fmt " and itself) + format_tag : int + PCM, float, or compressed format + channels : int + number of channels + fs : int + sampling frequency in samples per second + bytes_per_second : int + overall byte rate for the file + block_align : int + bytes per sample, including all channels + bit_depth : int + bits per sample + + Notes + ----- + Assumes file pointer is immediately after the 'fmt ' id + """ + if is_big_endian: + fmt = '>' + else: + fmt = '<' + + size = struct.unpack(fmt+'I', fid.read(4))[0] + + if size < 16: + raise ValueError("Binary structure of wave file is not compliant") + + res = struct.unpack(fmt+'HHIIHH', fid.read(16)) + bytes_read = 16 + + format_tag, channels, fs, bytes_per_second, block_align, bit_depth = res + + if format_tag == WAVE_FORMAT.EXTENSIBLE and size >= (16+2): + ext_chunk_size = struct.unpack(fmt+'H', fid.read(2))[0] + bytes_read += 2 + if ext_chunk_size >= 22: + extensible_chunk_data = fid.read(22) + bytes_read += 22 + raw_guid = extensible_chunk_data[2+4:2+4+16] + # GUID template {XXXXXXXX-0000-0010-8000-00AA00389B71} (RFC-2361) + # MS GUID byte order: first three groups are native byte order, + # rest is Big Endian + if is_big_endian: + tail = b'\x00\x00\x00\x10\x80\x00\x00\xAA\x00\x38\x9B\x71' + else: + tail = b'\x00\x00\x10\x00\x80\x00\x00\xAA\x00\x38\x9B\x71' + if raw_guid.endswith(tail): + format_tag = struct.unpack(fmt+'I', raw_guid[:4])[0] + else: + raise ValueError("Binary structure of wave file is not compliant") + + if format_tag not in KNOWN_WAVE_FORMATS: + _raise_bad_format(format_tag) + + # move file pointer to next chunk + if size > bytes_read: + fid.read(size - bytes_read) + + # fmt should always be 16, 18 or 40, but handle it just in case + _handle_pad_byte(fid, size) + + if format_tag == WAVE_FORMAT.PCM: + if bytes_per_second != fs * block_align: + raise ValueError("WAV header is invalid: nAvgBytesPerSec must" + " equal product of nSamplesPerSec and" + " nBlockAlign, but file has nSamplesPerSec =" + f" {fs}, nBlockAlign = {block_align}, and" + f" nAvgBytesPerSec = {bytes_per_second}") + + return (size, format_tag, channels, fs, bytes_per_second, block_align, + bit_depth) + + +def _read_data_chunk(fid, format_tag, channels, bit_depth, is_big_endian, is_rf64, + block_align, mmap=False): + """ + Notes + ----- + Assumes file pointer is immediately after the 'data' id + + It's possible to not use all available bits in a container, or to store + samples in a container bigger than necessary, so bytes_per_sample uses + the actual reported container size (nBlockAlign / nChannels). Real-world + examples: + + Adobe Audition's "24-bit packed int (type 1, 20-bit)" + + nChannels = 2, nBlockAlign = 6, wBitsPerSample = 20 + + http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Samples/AFsp/M1F1-int12-AFsp.wav + is: + + nChannels = 2, nBlockAlign = 4, wBitsPerSample = 12 + + http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Docs/multichaudP.pdf + gives an example of: + + nChannels = 2, nBlockAlign = 8, wBitsPerSample = 20 + """ + if is_big_endian: + fmt = '>' + else: + fmt = '<' + + # Size of the data subchunk in bytes + if not is_rf64: + size = struct.unpack(fmt+'I', fid.read(4))[0] + else: + pos = fid.tell() + # chunk size is stored in global file header for RF64 + fid.seek(28) + size = struct.unpack(' 1: + data = data.reshape(-1, channels) + return data + + +def _skip_unknown_chunk(fid, is_big_endian): + if is_big_endian: + fmt = '>I' + else: + fmt = '>> from os.path import dirname, join as pjoin + >>> from scipy.io import wavfile + >>> import scipy.io + + Get the filename for an example .wav file from the tests/data directory. + + >>> data_dir = pjoin(dirname(scipy.io.__file__), 'tests', 'data') + >>> wav_fname = pjoin(data_dir, 'test-44100Hz-2ch-32bit-float-be.wav') + + Load the .wav file contents. + + >>> samplerate, data = wavfile.read(wav_fname) + >>> print(f"number of channels = {data.shape[1]}") + number of channels = 2 + >>> length = data.shape[0] / samplerate + >>> print(f"length = {length}s") + length = 0.01s + + Plot the waveform. + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> time = np.linspace(0., length, data.shape[0]) + >>> plt.plot(time, data[:, 0], label="Left channel") + >>> plt.plot(time, data[:, 1], label="Right channel") + >>> plt.legend() + >>> plt.xlabel("Time [s]") + >>> plt.ylabel("Amplitude") + >>> plt.show() + + """ + if hasattr(filename, 'read'): + fid = filename + mmap = False + else: + fid = open(filename, 'rb') + + try: + file_size, is_big_endian, is_rf64 = _read_riff_chunk(fid) + fmt_chunk_received = False + data_chunk_received = False + while fid.tell() < file_size: + # read the next chunk + chunk_id = fid.read(4) + + if not chunk_id: + if data_chunk_received: + # End of file but data successfully read + warnings.warn( + f"Reached EOF prematurely; finished at {fid.tell():d} bytes, " + f"expected {file_size:d} bytes from header.", + WavFileWarning, stacklevel=2) + break + else: + raise ValueError("Unexpected end of file.") + elif len(chunk_id) < 4: + msg = f"Incomplete chunk ID: {repr(chunk_id)}" + # If we have the data, ignore the broken chunk + if fmt_chunk_received and data_chunk_received: + warnings.warn(msg + ", ignoring it.", WavFileWarning, + stacklevel=2) + else: + raise ValueError(msg) + + if chunk_id == b'fmt ': + fmt_chunk_received = True + fmt_chunk = _read_fmt_chunk(fid, is_big_endian) + format_tag, channels, fs = fmt_chunk[1:4] + bit_depth = fmt_chunk[6] + block_align = fmt_chunk[5] + elif chunk_id == b'fact': + _skip_unknown_chunk(fid, is_big_endian) + elif chunk_id == b'data': + data_chunk_received = True + if not fmt_chunk_received: + raise ValueError("No fmt chunk before data") + data = _read_data_chunk(fid, format_tag, channels, bit_depth, + is_big_endian, is_rf64, block_align, mmap) + elif chunk_id == b'LIST': + # Someday this could be handled properly but for now skip it + _skip_unknown_chunk(fid, is_big_endian) + elif chunk_id in {b'JUNK', b'Fake'}: + # Skip alignment chunks without warning + _skip_unknown_chunk(fid, is_big_endian) + else: + warnings.warn("Chunk (non-data) not understood, skipping it.", + WavFileWarning, stacklevel=2) + _skip_unknown_chunk(fid, is_big_endian) + finally: + if not hasattr(filename, 'read'): + fid.close() + else: + fid.seek(0) + + return fs, data + + +def write(filename, rate, data): + """ + Write a NumPy array as a WAV file. + + Parameters + ---------- + filename : string or open file handle + Output wav file. + rate : int + The sample rate (in samples/sec). + data : ndarray + A 1-D or 2-D NumPy array of either integer or float data-type. + + Notes + ----- + * Writes a simple uncompressed WAV file. + * To write multiple-channels, use a 2-D array of shape + (Nsamples, Nchannels). + * The bits-per-sample and PCM/float will be determined by the data-type. + + Common data types: [1]_ + + ===================== =========== =========== ============= + WAV format Min Max NumPy dtype + ===================== =========== =========== ============= + 32-bit floating-point -1.0 +1.0 float32 + 32-bit PCM -2147483648 +2147483647 int32 + 16-bit PCM -32768 +32767 int16 + 8-bit PCM 0 255 uint8 + ===================== =========== =========== ============= + + Note that 8-bit PCM is unsigned. + + References + ---------- + .. [1] IBM Corporation and Microsoft Corporation, "Multimedia Programming + Interface and Data Specifications 1.0", section "Data Format of the + Samples", August 1991 + http://www.tactilemedia.com/info/MCI_Control_Info.html + + Examples + -------- + Create a 100Hz sine wave, sampled at 44100Hz. + Write to 16-bit PCM, Mono. + + >>> from scipy.io.wavfile import write + >>> import numpy as np + >>> samplerate = 44100; fs = 100 + >>> t = np.linspace(0., 1., samplerate) + >>> amplitude = np.iinfo(np.int16).max + >>> data = amplitude * np.sin(2. * np.pi * fs * t) + >>> write("example.wav", samplerate, data.astype(np.int16)) + + """ + if hasattr(filename, 'write'): + fid = filename + else: + fid = open(filename, 'wb') + + fs = rate + + try: + dkind = data.dtype.kind + allowed_dtypes = ['float32', 'float64', + 'uint8', 'int16', 'int32', 'int64'] + if data.dtype.name not in allowed_dtypes: + raise ValueError(f"Unsupported data type '{data.dtype}'") + + header_data = b'' + + header_data += b'RIFF' + header_data += b'\x00\x00\x00\x00' + header_data += b'WAVE' + + # fmt chunk + header_data += b'fmt ' + if dkind == 'f': + format_tag = WAVE_FORMAT.IEEE_FLOAT + else: + format_tag = WAVE_FORMAT.PCM + if data.ndim == 1: + channels = 1 + else: + channels = data.shape[1] + bit_depth = data.dtype.itemsize * 8 + bytes_per_second = fs*(bit_depth // 8)*channels + block_align = channels * (bit_depth // 8) + + fmt_chunk_data = struct.pack(' 0xFFFFFFFF + if is_rf64: + header_data = b'' + header_data += b'RF64' + header_data += b'\xFF\xFF\xFF\xFF' + header_data += b'WAVE' + header_data += b'ds64' + # size of ds64 chunk + header_data += struct.pack('' or (data.dtype.byteorder == '=' and + sys.byteorder == 'big'): + data = data.byteswap() + _array_tofile(fid, data) + + # Determine file size and place it in correct + # position at start of the file or the data chunk. + size = fid.tell() + if not is_rf64: + fid.seek(4) + fid.write(struct.pack(' best_lexer[0]: + best_lexer[:] = (rv, lexer) + if not best_lexer[0] or best_lexer[1] is None: + raise ClassNotFound('no lexer matching the text found') + return best_lexer[1](**options) + + +class _automodule(types.ModuleType): + """Automatically import lexers.""" + + def __getattr__(self, name): + info = LEXERS.get(name) + if info: + _load_lexers(info[0]) + cls = _lexer_cache[info[1]] + setattr(self, name, cls) + return cls + if name in COMPAT: + return getattr(self, COMPAT[name]) + raise AttributeError(name) + + +oldmod = sys.modules[__name__] +newmod = _automodule(__name__) +newmod.__dict__.update(oldmod.__dict__) +sys.modules[__name__] = newmod +del newmod.newmod, newmod.oldmod, newmod.sys, newmod.types diff --git a/shared/package-files/cc/cc8a96937d64183ffe4e007466892afcf2989ad6cd20b67384f32e78e05c933d/thread_constants.h b/shared/package-files/cc/cc8a96937d64183ffe4e007466892afcf2989ad6cd20b67384f32e78e05c933d/thread_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..651053d663e4c204753cdfa4ae31ed60fed34152 --- /dev/null +++ b/shared/package-files/cc/cc8a96937d64183ffe4e007466892afcf2989ad6cd20b67384f32e78e05c933d/thread_constants.h @@ -0,0 +1,22 @@ +#pragma once +#include + +// Marks a lambda as executable on both the host and device. The __host__ +// attribute is important so that we can access static type information from +// the host, even if the function is typically only executed on the device. +#ifndef GPU_LAMBDA +#define GPU_LAMBDA __host__ __device__ +#endif + +#if defined(USE_ROCM) +constexpr int num_threads() { + return 256; +} +#else +constexpr uint32_t num_threads() { + return C10_WARP_SIZE * 4; +} +#endif + +constexpr int thread_work_size() { return 4; } +constexpr int block_work_size() { return thread_work_size() * num_threads(); } diff --git a/shared/package-files/cc/cc8cf64264b82c423e693d39c4ccd74e067a63a6942ca6f1959c566bf47e95be/_helpers.py b/shared/package-files/cc/cc8cf64264b82c423e693d39c4ccd74e067a63a6942ca6f1959c566bf47e95be/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..77175d0d1e97425567f90421e5805c64612c4b4a --- /dev/null +++ b/shared/package-files/cc/cc8cf64264b82c423e693d39c4ccd74e067a63a6942ca6f1959c566bf47e95be/_helpers.py @@ -0,0 +1,1058 @@ +""" +Various helper functions which are not part of the spec. + +Functions which start with an underscore are for internal use only but helpers +that are in __all__ are intended as additional helper functions for use by end +users of the compat library. +""" + +from __future__ import annotations + +import inspect +import math +import sys +import warnings +from collections.abc import Collection, Hashable +from functools import lru_cache +from typing import ( + TYPE_CHECKING, + Any, + Final, + Literal, + SupportsIndex, + TypeAlias, + TypeGuard, + TypeVar, + cast, + overload, +) + +from ._typing import Array, Device, HasShape, Namespace, SupportsArrayNamespace + +if TYPE_CHECKING: + + import dask.array as da + import jax + import ndonnx as ndx + import numpy as np + import numpy.typing as npt + import sparse # pyright: ignore[reportMissingTypeStubs] + import torch + + # TODO: import from typing (requires Python >=3.13) + from typing_extensions import TypeIs, TypeVar + + _SizeT = TypeVar("_SizeT", bound = int | None) + + _ZeroGradientArray: TypeAlias = npt.NDArray[np.void] + _CupyArray: TypeAlias = Any # cupy has no py.typed + + _ArrayApiObj: TypeAlias = ( + npt.NDArray[Any] + | da.Array + | jax.Array + | ndx.Array + | sparse.SparseArray + | torch.Tensor + | SupportsArrayNamespace[Any] + | _CupyArray + ) + +_API_VERSIONS_OLD: Final = frozenset({"2021.12", "2022.12", "2023.12"}) +_API_VERSIONS: Final = _API_VERSIONS_OLD | frozenset({"2024.12"}) + + +@lru_cache(100) +def _issubclass_fast(cls: type, modname: str, clsname: str) -> bool: + try: + mod = sys.modules[modname] + except KeyError: + return False + parent_cls = getattr(mod, clsname) + return issubclass(cls, parent_cls) + + +def _is_jax_zero_gradient_array(x: object) -> TypeGuard[_ZeroGradientArray]: + """Return True if `x` is a zero-gradient array. + + These arrays are a design quirk of Jax that may one day be removed. + See https://github.com/google/jax/issues/20620. + """ + # Fast exit + try: + dtype = x.dtype # type: ignore[attr-defined] + except AttributeError: + return False + cls = cast(Hashable, type(dtype)) + if not _issubclass_fast(cls, "numpy.dtypes", "VoidDType"): + return False + + if "jax" not in sys.modules: + return False + + import jax + # jax.float0 is a np.dtype([('float0', 'V')]) + return dtype == jax.float0 + + +def is_numpy_array(x: object) -> TypeGuard[npt.NDArray[Any]]: + """ + Return True if `x` is a NumPy array. + + This function does not import NumPy if it has not already been imported + and is therefore cheap to use. + + This also returns True for `ndarray` subclasses and NumPy scalar objects. + + See Also + -------- + + array_namespace + is_array_api_obj + is_cupy_array + is_torch_array + is_ndonnx_array + is_dask_array + is_jax_array + is_pydata_sparse_array + """ + # TODO: Should we reject ndarray subclasses? + cls = cast(Hashable, type(x)) + return ( + _issubclass_fast(cls, "numpy", "ndarray") + or _issubclass_fast(cls, "numpy", "generic") + ) and not _is_jax_zero_gradient_array(x) + + +def is_cupy_array(x: object) -> bool: + """ + Return True if `x` is a CuPy array. + + This function does not import CuPy if it has not already been imported + and is therefore cheap to use. + + This also returns True for `cupy.ndarray` subclasses and CuPy scalar objects. + + See Also + -------- + + array_namespace + is_array_api_obj + is_numpy_array + is_torch_array + is_ndonnx_array + is_dask_array + is_jax_array + is_pydata_sparse_array + """ + cls = cast(Hashable, type(x)) + return _issubclass_fast(cls, "cupy", "ndarray") + + +def is_torch_array(x: object) -> TypeIs[torch.Tensor]: + """ + Return True if `x` is a PyTorch tensor. + + This function does not import PyTorch if it has not already been imported + and is therefore cheap to use. + + See Also + -------- + + array_namespace + is_array_api_obj + is_numpy_array + is_cupy_array + is_dask_array + is_jax_array + is_pydata_sparse_array + """ + cls = cast(Hashable, type(x)) + return _issubclass_fast(cls, "torch", "Tensor") + + +def is_ndonnx_array(x: object) -> TypeIs[ndx.Array]: + """ + Return True if `x` is a ndonnx Array. + + This function does not import ndonnx if it has not already been imported + and is therefore cheap to use. + + See Also + -------- + + array_namespace + is_array_api_obj + is_numpy_array + is_cupy_array + is_ndonnx_array + is_dask_array + is_jax_array + is_pydata_sparse_array + """ + cls = cast(Hashable, type(x)) + return _issubclass_fast(cls, "ndonnx", "Array") + + +def is_dask_array(x: object) -> TypeIs[da.Array]: + """ + Return True if `x` is a dask.array Array. + + This function does not import dask if it has not already been imported + and is therefore cheap to use. + + See Also + -------- + + array_namespace + is_array_api_obj + is_numpy_array + is_cupy_array + is_torch_array + is_ndonnx_array + is_jax_array + is_pydata_sparse_array + """ + cls = cast(Hashable, type(x)) + return _issubclass_fast(cls, "dask.array", "Array") + + +def is_jax_array(x: object) -> TypeIs[jax.Array]: + """ + Return True if `x` is a JAX array. + + This function does not import JAX if it has not already been imported + and is therefore cheap to use. + + + See Also + -------- + + array_namespace + is_array_api_obj + is_numpy_array + is_cupy_array + is_torch_array + is_ndonnx_array + is_dask_array + is_pydata_sparse_array + """ + cls = cast(Hashable, type(x)) + return _issubclass_fast(cls, "jax", "Array") or _is_jax_zero_gradient_array(x) + + +def is_pydata_sparse_array(x: object) -> TypeIs[sparse.SparseArray]: + """ + Return True if `x` is an array from the `sparse` package. + + This function does not import `sparse` if it has not already been imported + and is therefore cheap to use. + + + See Also + -------- + + array_namespace + is_array_api_obj + is_numpy_array + is_cupy_array + is_torch_array + is_ndonnx_array + is_dask_array + is_jax_array + """ + # TODO: Account for other backends. + cls = cast(Hashable, type(x)) + return _issubclass_fast(cls, "sparse", "SparseArray") + + +def is_array_api_obj(x: object) -> TypeIs[_ArrayApiObj]: # pyright: ignore[reportUnknownParameterType] + """ + Return True if `x` is an array API compatible array object. + + See Also + -------- + + array_namespace + is_numpy_array + is_cupy_array + is_torch_array + is_ndonnx_array + is_dask_array + is_jax_array + """ + return ( + hasattr(x, '__array_namespace__') + or _is_array_api_cls(cast(Hashable, type(x))) + ) + + +@lru_cache(100) +def _is_array_api_cls(cls: type) -> bool: + return ( + # TODO: drop support for numpy<2 which didn't have __array_namespace__ + _issubclass_fast(cls, "numpy", "ndarray") + or _issubclass_fast(cls, "numpy", "generic") + or _issubclass_fast(cls, "cupy", "ndarray") + or _issubclass_fast(cls, "torch", "Tensor") + or _issubclass_fast(cls, "dask.array", "Array") + or _issubclass_fast(cls, "sparse", "SparseArray") + # TODO: drop support for jax<0.4.32 which didn't have __array_namespace__ + or _issubclass_fast(cls, "jax", "Array") + ) + + +def _compat_module_name() -> str: + assert __name__.endswith(".common._helpers") + return __name__.removesuffix(".common._helpers") + + +@lru_cache(100) +def is_numpy_namespace(xp: Namespace) -> bool: + """ + Returns True if `xp` is a NumPy namespace. + + This includes both NumPy itself and the version wrapped by array-api-compat. + + See Also + -------- + + array_namespace + is_cupy_namespace + is_torch_namespace + is_ndonnx_namespace + is_dask_namespace + is_jax_namespace + is_pydata_sparse_namespace + is_array_api_strict_namespace + """ + return xp.__name__ in {"numpy", _compat_module_name() + ".numpy"} + + +@lru_cache(100) +def is_cupy_namespace(xp: Namespace) -> bool: + """ + Returns True if `xp` is a CuPy namespace. + + This includes both CuPy itself and the version wrapped by array-api-compat. + + See Also + -------- + + array_namespace + is_numpy_namespace + is_torch_namespace + is_ndonnx_namespace + is_dask_namespace + is_jax_namespace + is_pydata_sparse_namespace + is_array_api_strict_namespace + """ + return xp.__name__ in {"cupy", _compat_module_name() + ".cupy"} + + +@lru_cache(100) +def is_torch_namespace(xp: Namespace) -> bool: + """ + Returns True if `xp` is a PyTorch namespace. + + This includes both PyTorch itself and the version wrapped by array-api-compat. + + See Also + -------- + + array_namespace + is_numpy_namespace + is_cupy_namespace + is_ndonnx_namespace + is_dask_namespace + is_jax_namespace + is_pydata_sparse_namespace + is_array_api_strict_namespace + """ + return xp.__name__ in {"torch", _compat_module_name() + ".torch"} + + +def is_ndonnx_namespace(xp: Namespace) -> bool: + """ + Returns True if `xp` is an NDONNX namespace. + + See Also + -------- + + array_namespace + is_numpy_namespace + is_cupy_namespace + is_torch_namespace + is_dask_namespace + is_jax_namespace + is_pydata_sparse_namespace + is_array_api_strict_namespace + """ + return xp.__name__ == "ndonnx" + + +@lru_cache(100) +def is_dask_namespace(xp: Namespace) -> bool: + """ + Returns True if `xp` is a Dask namespace. + + This includes both ``dask.array`` itself and the version wrapped by array-api-compat. + + See Also + -------- + + array_namespace + is_numpy_namespace + is_cupy_namespace + is_torch_namespace + is_ndonnx_namespace + is_jax_namespace + is_pydata_sparse_namespace + is_array_api_strict_namespace + """ + return xp.__name__ in {"dask.array", _compat_module_name() + ".dask.array"} + + +def is_jax_namespace(xp: Namespace) -> bool: + """ + Returns True if `xp` is a JAX namespace. + + This includes ``jax.numpy`` and ``jax.experimental.array_api`` which existed in + older versions of JAX. + + See Also + -------- + + array_namespace + is_numpy_namespace + is_cupy_namespace + is_torch_namespace + is_ndonnx_namespace + is_dask_namespace + is_pydata_sparse_namespace + is_array_api_strict_namespace + """ + return xp.__name__ in {"jax.numpy", "jax.experimental.array_api"} + + +def is_pydata_sparse_namespace(xp: Namespace) -> bool: + """ + Returns True if `xp` is a pydata/sparse namespace. + + See Also + -------- + + array_namespace + is_numpy_namespace + is_cupy_namespace + is_torch_namespace + is_ndonnx_namespace + is_dask_namespace + is_jax_namespace + is_array_api_strict_namespace + """ + return xp.__name__ == "sparse" + + +def is_array_api_strict_namespace(xp: Namespace) -> bool: + """ + Returns True if `xp` is an array-api-strict namespace. + + See Also + -------- + + array_namespace + is_numpy_namespace + is_cupy_namespace + is_torch_namespace + is_ndonnx_namespace + is_dask_namespace + is_jax_namespace + is_pydata_sparse_namespace + """ + return xp.__name__ == "array_api_strict" + + +def _check_api_version(api_version: str | None) -> None: + if api_version in _API_VERSIONS_OLD: + warnings.warn( + f"The {api_version} version of the array API specification was requested but the returned namespace is actually version 2024.12" + ) + elif api_version is not None and api_version not in _API_VERSIONS: + raise ValueError( + "Only the 2024.12 version of the array API specification is currently supported" + ) + + +def array_namespace( + *xs: Array | complex | None, + api_version: str | None = None, + use_compat: bool | None = None, +) -> Namespace: + """ + Get the array API compatible namespace for the arrays `xs`. + + Parameters + ---------- + xs: arrays + one or more arrays. xs can also be Python scalars (bool, int, float, + complex, or None), which are ignored. + + api_version: str + The newest version of the spec that you need support for (currently + the compat library wrapped APIs support v2024.12). + + use_compat: bool or None + If None (the default), the native namespace will be returned if it is + already array API compatible, otherwise a compat wrapper is used. If + True, the compat library wrapped library will be returned. If False, + the native library namespace is returned. + + Returns + ------- + + out: namespace + The array API compatible namespace corresponding to the arrays in `xs`. + + Raises + ------ + TypeError + If `xs` contains arrays from different array libraries or contains a + non-array. + + + Typical usage is to pass the arguments of a function to + `array_namespace()` at the top of a function to get the corresponding + array API namespace: + + .. code:: python + + def your_function(x, y): + xp = array_api_compat.array_namespace(x, y) + # Now use xp as the array library namespace + return xp.mean(x, axis=0) + 2*xp.std(y, axis=0) + + + Wrapped array namespaces can also be imported directly. For example, + `array_namespace(np.array(...))` will return `array_api_compat.numpy`. + This function will also work for any array library not wrapped by + array-api-compat if it explicitly defines `__array_namespace__ + `__ + (the wrapped namespace is always preferred if it exists). + + See Also + -------- + + is_array_api_obj + is_numpy_array + is_cupy_array + is_torch_array + is_dask_array + is_jax_array + is_pydata_sparse_array + + """ + if use_compat not in [None, True, False]: + raise ValueError("use_compat must be None, True, or False") + + _use_compat = use_compat in [None, True] + + namespaces: set[Namespace] = set() + for x in xs: + if is_numpy_array(x): + import numpy as np + + from .. import numpy as numpy_namespace + + if use_compat is True: + _check_api_version(api_version) + namespaces.add(numpy_namespace) + elif use_compat is False: + namespaces.add(np) + else: + # numpy 2.0+ have __array_namespace__, however, they are not yet fully array API + # compatible. + namespaces.add(numpy_namespace) + elif is_cupy_array(x): + if _use_compat: + _check_api_version(api_version) + from .. import cupy as cupy_namespace + + namespaces.add(cupy_namespace) + else: + import cupy as cp # pyright: ignore[reportMissingTypeStubs] + + namespaces.add(cp) + elif is_torch_array(x): + if _use_compat: + _check_api_version(api_version) + from .. import torch as torch_namespace + + namespaces.add(torch_namespace) + else: + import torch + + namespaces.add(torch) + elif is_dask_array(x): + if _use_compat: + _check_api_version(api_version) + from ..dask import array as dask_namespace + + namespaces.add(dask_namespace) + else: + import dask.array as da + + namespaces.add(da) + elif is_jax_array(x): + if use_compat is True: + _check_api_version(api_version) + raise ValueError("JAX does not have an array-api-compat wrapper") + elif use_compat is False: + import jax.numpy as jnp + else: + # JAX v0.4.32 and newer implements the array API directly in jax.numpy. + # For older JAX versions, it is available via jax.experimental.array_api. + import jax.numpy + + if hasattr(jax.numpy, "__array_api_version__"): + jnp = jax.numpy + else: + import jax.experimental.array_api as jnp # pyright: ignore[reportMissingImports] + namespaces.add(jnp) + elif is_pydata_sparse_array(x): + if use_compat is True: + _check_api_version(api_version) + raise ValueError("`sparse` does not have an array-api-compat wrapper") + else: + import sparse # pyright: ignore[reportMissingTypeStubs] + # `sparse` is already an array namespace. We do not have a wrapper + # submodule for it. + namespaces.add(sparse) + elif hasattr(x, "__array_namespace__"): + if use_compat is True: + raise ValueError( + "The given array does not have an array-api-compat wrapper" + ) + x = cast("SupportsArrayNamespace[Any]", x) + namespaces.add(x.__array_namespace__(api_version=api_version)) + elif isinstance(x, (bool, int, float, complex, type(None))): + continue + else: + # TODO: Support Python scalars? + raise TypeError(f"{type(x).__name__} is not a supported array type") + + if not namespaces: + raise TypeError("Unrecognized array input") + + if len(namespaces) != 1: + raise TypeError(f"Multiple namespaces for array inputs: {namespaces}") + + (xp,) = namespaces + + return xp + + +# backwards compatibility alias +get_namespace = array_namespace + + +def _check_device(bare_xp: Namespace, device: Device) -> None: # pyright: ignore[reportUnusedFunction] + """ + Validate dummy device on device-less array backends. + + Notes + ----- + This function is also invoked by CuPy, which does have multiple devices + if there are multiple GPUs available. + However, CuPy multi-device support is currently impossible + without using the global device or a context manager: + + https://github.com/data-apis/array-api-compat/pull/293 + """ + if bare_xp is sys.modules.get("numpy"): + if device not in ("cpu", None): + raise ValueError(f"Unsupported device for NumPy: {device!r}") + + elif bare_xp is sys.modules.get("dask.array"): + if device not in ("cpu", _DASK_DEVICE, None): + raise ValueError(f"Unsupported device for Dask: {device!r}") + + +# Placeholder object to represent the dask device +# when the array backend is not the CPU. +# (since it is not easy to tell which device a dask array is on) +class _dask_device: + def __repr__(self) -> Literal["DASK_DEVICE"]: + return "DASK_DEVICE" + + +_DASK_DEVICE = _dask_device() + + +# device() is not on numpy.ndarray or dask.array and to_device() is not on numpy.ndarray +# or cupy.ndarray. They are not included in array objects of this library +# because this library just reuses the respective ndarray classes without +# wrapping or subclassing them. These helper functions can be used instead of +# the wrapper functions for libraries that need to support both NumPy/CuPy and +# other libraries that use devices. +def device(x: _ArrayApiObj, /) -> Device: + """ + Hardware device the array data resides on. + + This is equivalent to `x.device` according to the `standard + `__. + This helper is included because some array libraries either do not have + the `device` attribute or include it with an incompatible API. + + Parameters + ---------- + x: array + array instance from an array API compatible library. + + Returns + ------- + out: device + a ``device`` object (see the `Device Support `__ + section of the array API specification). + + Notes + ----- + + For NumPy the device is always `"cpu"`. For Dask, the device is always a + special `DASK_DEVICE` object. + + See Also + -------- + + to_device : Move array data to a different device. + + """ + if is_numpy_array(x): + return "cpu" + elif is_dask_array(x): + # Peek at the metadata of the Dask array to determine type + if is_numpy_array(x._meta): # pyright: ignore + # Must be on CPU since backed by numpy + return "cpu" + return _DASK_DEVICE + elif is_jax_array(x): + # FIXME Jitted JAX arrays do not have a device attribute + # https://github.com/jax-ml/jax/issues/26000 + # Return None in this case. Note that this workaround breaks + # the standard and will result in new arrays being created on the + # default device instead of the same device as the input array(s). + x_device = getattr(x, "device", None) + # Older JAX releases had .device() as a method, which has been replaced + # with a property in accordance with the standard. + if inspect.ismethod(x_device): + return x_device() + else: + return x_device + elif is_pydata_sparse_array(x): + # `sparse` will gain `.device`, so check for this first. + x_device = getattr(x, "device", None) + if x_device is not None: + return x_device + # Everything but DOK has this attr. + try: + inner = x.data # pyright: ignore + except AttributeError: + return "cpu" + # Return the device of the constituent array + return device(inner) # pyright: ignore + return x.device # pyright: ignore + + +# Prevent shadowing, used below +_device = device + + +# Based on cupy.array_api.Array.to_device +def _cupy_to_device( + x: _CupyArray, + device: Device, + /, + stream: int | Any | None = None, +) -> _CupyArray: + import cupy as cp + + if device == "cpu": + # allowing us to use `to_device(x, "cpu")` + # is useful for portable test swapping between + # host and device backends + return x.get() + if not isinstance(device, cp.cuda.Device): + raise TypeError(f"Unsupported device type {device!r}") + + if stream is None: + with device: + return cp.asarray(x) + + # stream can be an int as specified in __dlpack__, or a CuPy stream + if isinstance(stream, int): + stream = cp.cuda.ExternalStream(stream) + elif not isinstance(stream, cp.cuda.Stream): + raise TypeError(f"Unsupported stream type {stream!r}") + + with device, stream: + return cp.asarray(x) + + +def _torch_to_device( + x: torch.Tensor, + device: torch.device | str | int, + /, + stream: None = None, +) -> torch.Tensor: + if stream is not None: + raise NotImplementedError + return x.to(device) + + +def to_device(x: Array, device: Device, /, *, stream: int | Any | None = None) -> Array: + """ + Copy the array from the device on which it currently resides to the specified ``device``. + + This is equivalent to `x.to_device(device, stream=stream)` according to + the `standard + `__. + This helper is included because some array libraries do not have the + `to_device` method. + + Parameters + ---------- + + x: array + array instance from an array API compatible library. + + device: device + a ``device`` object (see the `Device Support `__ + section of the array API specification). + + stream: int | Any | None + stream object to use during copy. In addition to the types supported + in ``array.__dlpack__``, implementations may choose to support any + library-specific stream object with the caveat that any code using + such an object would not be portable. + + Returns + ------- + + out: array + an array with the same data and data type as ``x`` and located on the + specified ``device``. + + Notes + ----- + + For NumPy, this function effectively does nothing since the only supported + device is the CPU. For CuPy, this method supports CuPy CUDA + :external+cupy:class:`Device ` and + :external+cupy:class:`Stream ` objects. For PyTorch, + this is the same as :external+torch:meth:`x.to(device) ` + (the ``stream`` argument is not supported in PyTorch). + + See Also + -------- + + device : Hardware device the array data resides on. + + """ + if is_numpy_array(x): + if stream is not None: + raise ValueError("The stream argument to to_device() is not supported") + if device == "cpu": + return x + raise ValueError(f"Unsupported device {device!r}") + elif is_cupy_array(x): + # cupy does not yet have to_device + return _cupy_to_device(x, device, stream=stream) + elif is_torch_array(x): + return _torch_to_device(x, device, stream=stream) # pyright: ignore[reportArgumentType] + elif is_dask_array(x): + if stream is not None: + raise ValueError("The stream argument to to_device() is not supported") + # TODO: What if our array is on the GPU already? + if device == "cpu": + return x + raise ValueError(f"Unsupported device {device!r}") + elif is_jax_array(x): + if not hasattr(x, "__array_namespace__"): + # In JAX v0.4.31 and older, this import adds to_device method to x... + import jax.experimental.array_api # noqa: F401 # pyright: ignore + + # ... but only on eager JAX. It won't work inside jax.jit. + if not hasattr(x, "to_device"): + return x + return x.to_device(device, stream=stream) + elif is_pydata_sparse_array(x) and device == _device(x): + # Perform trivial check to return the same array if + # device is same instead of err-ing. + return x + return x.to_device(device, stream=stream) # pyright: ignore + + +@overload +def size(x: HasShape[Collection[SupportsIndex]]) -> int: ... +@overload +def size(x: HasShape[Collection[None]]) -> None: ... +@overload +def size(x: HasShape[Collection[SupportsIndex | None]]) -> int | None: ... +def size(x: HasShape[Collection[SupportsIndex | None]]) -> int | None: + """ + Return the total number of elements of x. + + This is equivalent to `x.size` according to the `standard + `__. + + This helper is included because PyTorch defines `size` in an + :external+torch:meth:`incompatible way `. + It also fixes dask.array's behaviour which returns nan for unknown sizes, whereas + the standard requires None. + """ + # Lazy API compliant arrays, such as ndonnx, can contain None in their shape + if None in x.shape: + return None + out = math.prod(cast("Collection[SupportsIndex]", x.shape)) + # dask.array.Array.shape can contain NaN + return None if math.isnan(out) else out + + +@lru_cache(100) +def _is_writeable_cls(cls: type) -> bool | None: + if ( + _issubclass_fast(cls, "numpy", "generic") + or _issubclass_fast(cls, "jax", "Array") + or _issubclass_fast(cls, "sparse", "SparseArray") + ): + return False + if _is_array_api_cls(cls): + return True + return None + + +def is_writeable_array(x: object) -> bool: + """ + Return False if ``x.__setitem__`` is expected to raise; True otherwise. + Return False if `x` is not an array API compatible object. + + Warning + ------- + As there is no standard way to check if an array is writeable without actually + writing to it, this function blindly returns True for all unknown array types. + """ + cls = cast(Hashable, type(x)) + if _issubclass_fast(cls, "numpy", "ndarray"): + return cast("npt.NDArray", x).flags.writeable + res = _is_writeable_cls(cls) + if res is not None: + return res + return hasattr(x, '__array_namespace__') + + +@lru_cache(100) +def _is_lazy_cls(cls: type) -> bool | None: + if ( + _issubclass_fast(cls, "numpy", "ndarray") + or _issubclass_fast(cls, "numpy", "generic") + or _issubclass_fast(cls, "cupy", "ndarray") + or _issubclass_fast(cls, "torch", "Tensor") + or _issubclass_fast(cls, "sparse", "SparseArray") + ): + return False + if ( + _issubclass_fast(cls, "jax", "Array") + or _issubclass_fast(cls, "dask.array", "Array") + or _issubclass_fast(cls, "ndonnx", "Array") + ): + return True + return None + + +def is_lazy_array(x: object) -> bool: + """Return True if x is potentially a future or it may be otherwise impossible or + expensive to eagerly read its contents, regardless of their size, e.g. by + calling ``bool(x)`` or ``float(x)``. + + Return False otherwise; e.g. ``bool(x)`` etc. is guaranteed to succeed and to be + cheap as long as the array has the right dtype and size. + + Note + ---- + This function errs on the side of caution for array types that may or may not be + lazy, e.g. JAX arrays, by always returning True for them. + """ + # **JAX note:** while it is possible to determine if you're inside or outside + # jax.jit by testing the subclass of a jax.Array object, as well as testing bool() + # as we do below for unknown arrays, this is not recommended by JAX best practices. + + # **Dask note:** Dask eagerly computes the graph on __bool__, __float__, and so on. + # This behaviour, while impossible to change without breaking backwards + # compatibility, is highly detrimental to performance as the whole graph will end + # up being computed multiple times. + + # Note: skipping reclassification of JAX zero gradient arrays, as one will + # exclusively get them once they leave a jax.grad JIT context. + cls = cast(Hashable, type(x)) + res = _is_lazy_cls(cls) + if res is not None: + return res + + if not hasattr(x, "__array_namespace__"): + return False + + # Unknown Array API compatible object. Note that this test may have dire consequences + # in terms of performance, e.g. for a lazy object that eagerly computes the graph + # on __bool__ (dask is one such example, which however is special-cased above). + + # Select a single point of the array + s = size(cast("HasShape[Collection[SupportsIndex | None]]", x)) + if s is None: + return True + xp = array_namespace(x) + if s > 1: + x = xp.reshape(x, (-1,))[0] + # Cast to dtype=bool and deal with size 0 arrays + x = xp.any(x) + + try: + bool(x) + return False + # The Array API standard dictactes that __bool__ should raise TypeError if the + # output cannot be defined. + # Here we allow for it to raise arbitrary exceptions, e.g. like Dask does. + except Exception: + return True + + +__all__ = [ + "array_namespace", + "device", + "get_namespace", + "is_array_api_obj", + "is_array_api_strict_namespace", + "is_cupy_array", + "is_cupy_namespace", + "is_dask_array", + "is_dask_namespace", + "is_jax_array", + "is_jax_namespace", + "is_numpy_array", + "is_numpy_namespace", + "is_torch_array", + "is_torch_namespace", + "is_ndonnx_array", + "is_ndonnx_namespace", + "is_pydata_sparse_array", + "is_pydata_sparse_namespace", + "is_writeable_array", + "is_lazy_array", + "size", + "to_device", +] + +_all_ignore = ['lru_cache', 'sys', 'math', 'inspect', 'warnings'] + +def __dir__() -> list[str]: + return __all__ diff --git a/shared/package-files/cc/cc8d076755610b08aabd854baaca37c482d550459057792a15e4031f42f02a13/dictobject.c b/shared/package-files/cc/cc8d076755610b08aabd854baaca37c482d550459057792a15e4031f42f02a13/dictobject.c new file mode 100644 index 0000000000000000000000000000000000000000..3557757ba577235d02cbedbf371cf7fedbff4cc4 --- /dev/null +++ b/shared/package-files/cc/cc8d076755610b08aabd854baaca37c482d550459057792a15e4031f42f02a13/dictobject.c @@ -0,0 +1,1265 @@ +/* The following is adapted from CPython3.7. +The exact commit is: + +- https://github.com/python/cpython/blob/44467e8ea4cea390b0718702291b4cfe8ddd67ed/Objects/dictobject.c + + +*/ + +/* Dictionary object implementation using a hash table */ + +/* The distribution includes a separate file, Objects/dictnotes.txt, + describing explorations into dictionary design and optimization. + It covers typical dictionary use patterns, the parameters for + tuning dictionaries, and several ideas for possible optimizations. +*/ + +/* PyDictKeysObject + +This implements the dictionary's hashtable. + +As of Python 3.6, this is compact and ordered. Basic idea is described here: +* https://mail.python.org/pipermail/python-dev/2012-December/123028.html +* https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html + +layout: + ++---------------+ +| dk_refcnt | +| dk_size | +| dk_lookup | +| dk_usable | +| dk_nentries | ++---------------+ +| dk_indices | +| | ++---------------+ +| dk_entries | +| | ++---------------+ + +dk_indices is actual hashtable. It holds index in entries, or DKIX_EMPTY(-1) +or DKIX_DUMMY(-2). +Size of indices is dk_size. Type of each index in indices is vary on dk_size: + +* int8 for dk_size <= 128 +* int16 for 256 <= dk_size <= 2**15 +* int32 for 2**16 <= dk_size <= 2**31 +* int64 for 2**32 <= dk_size + +dk_entries is array of PyDictKeyEntry. It's size is USABLE_FRACTION(dk_size). +DK_ENTRIES(dk) can be used to get pointer to entries. + +NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of +dk_indices entry is signed integer and int16 is used for table which +dk_size == 256. +*/ + + +/* +The DictObject can be in one of two forms. + +Either: + A combined table: + ma_values == NULL, dk_refcnt == 1. + Values are stored in the me_value field of the PyDictKeysObject. +Or: + + (Numba dev notes: split table logic is removed) + + A split table: + ma_values != NULL, dk_refcnt >= 1 + Values are stored in the ma_values array. + Only string (unicode) keys are allowed. + All dicts sharing same key must have same insertion order. + +There are four kinds of slots in the table (slot is index, and +DK_ENTRIES(keys)[index] if index >= 0): + +1. Unused. index == DKIX_EMPTY + Does not hold an active (key, value) pair now and never did. Unused can + transition to Active upon key insertion. This is each slot's initial state. + +2. Active. index >= 0, me_key != NULL and me_value != NULL + Holds an active (key, value) pair. Active can transition to Dummy or + Pending upon key deletion (for combined and split tables respectively). + This is the only case in which me_value != NULL. + +3. Dummy. index == DKIX_DUMMY (combined only) + Previously held an active (key, value) pair, but that was deleted and an + active pair has not yet overwritten the slot. Dummy can transition to + Active upon key insertion. Dummy slots cannot be made Unused again + else the probe sequence in case of collision would have no way to know + they were once active. + +4. Pending. index >= 0, key != NULL, and value == NULL (split only) + Not yet inserted in split-table. +*/ + +/* +Preserving insertion order + +It's simple for combined table. Since dk_entries is mostly append only, we can +get insertion order by just iterating dk_entries. + +One exception is .popitem(). It removes last item in dk_entries and decrement +dk_nentries to achieve amortized O(1). Since there are DKIX_DUMMY remains in +dk_indices, we can't increment dk_usable even though dk_nentries is +decremented. + +In split table, inserting into pending entry is allowed only for dk_entries[ix] +where ix == mp->ma_used. Inserting into other index and deleting item cause +converting the dict to the combined table. +*/ + + +/* D_MINSIZE (adapted from PyDict_MINSIZE) + * is the starting size for any new dict. + * 8 allows dicts with no more than 5 active entries; experiments suggested + * this suffices for the majority of dicts (consisting mostly of usually-small + * dicts created to pass keyword arguments). + * Making this 8, rather than 4 reduces the number of resizes for most + * dictionaries, without any significant extra memory use. + */ +#define D_MINSIZE 8 + +#include "dictobject.h" + + +#if defined(_MSC_VER) +# if _MSC_VER <= 1900 /* Visual Studio 2014 */ + typedef __int8 int8_t; + typedef __int16 int16_t; + typedef __int32 int32_t; + typedef __int64 int64_t; +# endif + /* Use _alloca() to dynamically allocate on the stack on MSVC */ + #define STACK_ALLOC(Type, Name, Size) Type * const Name = _alloca(Size); +#else + #define STACK_ALLOC(Type, Name, Size) Type Name[Size]; +#endif + + +/*[clinic input] +class dict "PyDictObject *" "&PyDict_Type" +[clinic start generated code]*/ +/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f157a5a0ce9589d6]*/ + + +/* +To ensure the lookup algorithm terminates, there must be at least one Unused +slot (NULL key) in the table. +To avoid slowing down lookups on a near-full table, we resize the table when +it's USABLE_FRACTION (currently two-thirds) full. +*/ + +#define PERTURB_SHIFT 5 + +/* +Major subtleties ahead: Most hash schemes depend on having a "good" hash +function, in the sense of simulating randomness. Python doesn't: its most +important hash functions (for ints) are very regular in common +cases: + + >>>[hash(i) for i in range(4)] + [0, 1, 2, 3] + +This isn't necessarily bad! To the contrary, in a table of size 2**i, taking +the low-order i bits as the initial table index is extremely fast, and there +are no collisions at all for dicts indexed by a contiguous range of ints. So +this gives better-than-random behavior in common cases, and that's very +desirable. + +OTOH, when collisions occur, the tendency to fill contiguous slices of the +hash table makes a good collision resolution strategy crucial. Taking only +the last i bits of the hash code is also vulnerable: for example, consider +the list [i << 16 for i in range(20000)] as a set of keys. Since ints are +their own hash codes, and this fits in a dict of size 2**15, the last 15 bits + of every hash code are all 0: they *all* map to the same table index. + +But catering to unusual cases should not slow the usual ones, so we just take +the last i bits anyway. It's up to collision resolution to do the rest. If +we *usually* find the key we're looking for on the first try (and, it turns +out, we usually do -- the table load factor is kept under 2/3, so the odds +are solidly in our favor), then it makes best sense to keep the initial index +computation dirt cheap. + +The first half of collision resolution is to visit table indices via this +recurrence: + + j = ((5*j) + 1) mod 2**i + +For any initial j in range(2**i), repeating that 2**i times generates each +int in range(2**i) exactly once (see any text on random-number generation for +proof). By itself, this doesn't help much: like linear probing (setting +j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed +order. This would be bad, except that's not the only thing we do, and it's +actually *good* in the common cases where hash keys are consecutive. In an +example that's really too small to make this entirely clear, for a table of +size 2**3 the order of indices is: + + 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating] + +If two things come in at index 5, the first place we look after is index 2, +not 6, so if another comes in at index 6 the collision at 5 didn't hurt it. +Linear probing is deadly in this case because there the fixed probe order +is the *same* as the order consecutive keys are likely to arrive. But it's +extremely unlikely hash codes will follow a 5*j+1 recurrence by accident, +and certain that consecutive hash codes do not. + +The other half of the strategy is to get the other bits of the hash code +into play. This is done by initializing a (unsigned) vrbl "perturb" to the +full hash code, and changing the recurrence to: + + perturb >>= PERTURB_SHIFT; + j = (5*j) + 1 + perturb; + use j % 2**i as the next table index; + +Now the probe sequence depends (eventually) on every bit in the hash code, +and the pseudo-scrambling property of recurring on 5*j+1 is more valuable, +because it quickly magnifies small differences in the bits that didn't affect +the initial index. Note that because perturb is unsigned, if the recurrence +is executed often enough perturb eventually becomes and remains 0. At that +point (very rarely reached) the recurrence is on (just) 5*j+1 again, and +that's certain to find an empty slot eventually (since it generates every int +in range(2**i), and we make sure there's always at least one empty slot). + +Selecting a good value for PERTURB_SHIFT is a balancing act. You want it +small so that the high bits of the hash code continue to affect the probe +sequence across iterations; but you want it large so that in really bad cases +the high-order hash bits have an effect on early iterations. 5 was "the +best" in minimizing total collisions across experiments Tim Peters ran (on +both normal and pathological cases), but 4 and 6 weren't significantly worse. + +Historical: Reimer Behrends contributed the idea of using a polynomial-based +approach, using repeated multiplication by x in GF(2**n) where an irreducible +polynomial for each table size was chosen such that x was a primitive root. +Christian Tismer later extended that to use division by x instead, as an +efficient way to get the high bits of the hash code into play. This scheme +also gave excellent collision statistics, but was more expensive: two +if-tests were required inside the loop; computing "the next" index took about +the same number of operations but without as much potential parallelism +(e.g., computing 5*j can go on at the same time as computing 1+perturb in the +above, and then shifting perturb can be done while the table index is being +masked); and the PyDictObject struct required a member to hold the table's +polynomial. In Tim's experiments the current scheme ran faster, produced +equally good collision statistics, needed less code & used less memory. + +*/ + +#define DKIX_EMPTY (-1) +#define DKIX_DUMMY (-2) /* Used internally */ +#define DKIX_ERROR (-3) + +typedef enum { + OK = 0, + OK_REPLACED = 1, + ERR_NO_MEMORY = -1, + ERR_DICT_MUTATED = -2, + ERR_ITER_EXHAUSTED = -3, + ERR_DICT_EMPTY = -4, + ERR_CMP_FAILED = -5, +} Status; + + +#ifndef NDEBUG +static +int mem_cmp_zeros(void *obj, size_t n){ + int diff = 0; + char *mem = obj; + char *it; + for (it = mem; it < mem + n; ++it) { + if (*it != 0) diff += 1; + } + return diff; +} +#endif + +#define D_MASK(dk) ((dk)->size-1) +#define D_GROWTH_RATE(d) ((d)->used*3) + +static int +ix_size(Py_ssize_t size) { + if ( size < 0xff ) return 1; + if ( size < 0xffff ) return 2; + if ( size < 0xffffffff ) return 4; + return sizeof(int64_t); +} + +#ifndef NDEBUG +/* NOTE: This function is only used in assert()s */ +/* Align pointer *ptr* to pointer size */ +static void* +aligned_pointer(void *ptr) { + return (void*)aligned_size((size_t)ptr); +} +#endif + +/* lookup indices. returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */ +static Py_ssize_t +get_index(NB_DictKeys *dk, Py_ssize_t i) +{ + Py_ssize_t s = dk->size; + Py_ssize_t ix; + + if (s <= 0xff) { + int8_t *indices = (int8_t*)(dk->indices); + assert (i < dk->size); + ix = indices[i]; + } + else if (s <= 0xffff) { + int16_t *indices = (int16_t*)(dk->indices); + ix = indices[i]; + } +#if SIZEOF_VOID_P > 4 + else if (s > 0xffffffff) { + int64_t *indices = (int64_t*)(dk->indices); + ix = indices[i]; + } +#endif + else { + int32_t *indices = (int32_t*)(dk->indices); + ix = indices[i]; + } + assert(ix >= DKIX_DUMMY); + return ix; +} + +/* write to indices. */ +static void +set_index(NB_DictKeys *dk, Py_ssize_t i, Py_ssize_t ix) +{ + Py_ssize_t s = dk->size; + + assert(ix >= DKIX_DUMMY); + + if (s <= 0xff) { + int8_t *indices = (int8_t*)(dk->indices); + assert(ix <= 0x7f); + indices[i] = (char)ix; + } + else if (s <= 0xffff) { + int16_t *indices = (int16_t*)(dk->indices); + assert(ix <= 0x7fff); + indices[i] = (int16_t)ix; + } +#if SIZEOF_VOID_P > 4 + else if (s > 0xffffffff) { + int64_t *indices = (int64_t*)(dk->indices); + indices[i] = ix; + } +#endif + else { + int32_t *indices = (int32_t*)(dk->indices); + assert(ix <= 0x7fffffff); + indices[i] = (int32_t)ix; + } +} + + +/* USABLE_FRACTION is the maximum dictionary load. + * Increasing this ratio makes dictionaries more dense resulting in more + * collisions. Decreasing it improves sparseness at the expense of spreading + * indices over more cache lines and at the cost of total memory consumed. + * + * USABLE_FRACTION must obey the following: + * (0 < USABLE_FRACTION(n) < n) for all n >= 2 + * + * USABLE_FRACTION should be quick to calculate. + * Fractions around 1/2 to 2/3 seem to work well in practice. + */ + +#define USABLE_FRACTION(n) (((n) << 1)/3) // ratio: 2/3 + +/* Alternative fraction that is otherwise close enough to 2n/3 to make + * little difference. 8 * 2/3 == 8 * 5/8 == 5. 16 * 2/3 == 16 * 5/8 == 10. + * 32 * 2/3 = 21, 32 * 5/8 = 20. + * Its advantage is that it is faster to compute on machines with slow division. + * #define USABLE_FRACTION(n) (((n) >> 1) + ((n) >> 2) - ((n) >> 3)) // ratio: 5/8 + */ + + +/* INV_USABLE_FRACTION gives the inverse of USABLE_FRACTION. + * Used for sizing a new dictionary to a specified number of keys. + * + * NOTE: If the denominator of the USABLE_FRACTION ratio is not a power + * of 2, must add 1 to the result of the inverse for correct sizing. + * + * For example, when USABLE_FRACTION ratio = 5/8 (8 is a power of 2): + * #define INV_USABLE_FRACTION(n) (((n) << 3)/5) // inv_ratio: 8/5 + * + * When USABLE_FRACTION ratio = 5/7 (7 is not a power of 2): + * #define INV_USABLE_FRACTION(n) ((7*(n))/5 + 1) // inv_ratio: 7/5 + */ + +#define INV_USABLE_FRACTION(n) ((n) + ((n) >> 1) + 1) // inv_ratio: 3/2 + + +/* GROWTH_RATE. Growth rate upon hitting maximum load. + * Currently set to used*3. + * This means that dicts double in size when growing without deletions, + * but have more head room when the number of deletions is on a par with the + * number of insertions. See also bpo-17563 and bpo-33205. + * + * GROWTH_RATE was set to used*4 up to version 3.2. + * GROWTH_RATE was set to used*2 in version 3.3.0 + * GROWTH_RATE was set to used*2 + capacity/2 in 3.4.0-3.6.0. + */ +#define GROWTH_RATE(d) ((d)->ma_used*3) + + +static NB_DictEntry* +get_entry(NB_DictKeys *dk, Py_ssize_t idx) { + Py_ssize_t offset; + char *ptr; + + assert (idx < dk->size); + offset = idx * dk->entry_size; + ptr = dk->indices + dk->entry_offset + offset; + return (NB_DictEntry*)ptr; +} + +static void +zero_key(NB_DictKeys *dk, char *data){ + memset(data, 0, dk->key_size); +} + +static void +zero_val(NB_DictKeys *dk, char *data){ + memset(data, 0, dk->val_size); +} + +static void +copy_key(NB_DictKeys *dk, char *dst, const char *src){ + memcpy(dst, src, dk->key_size); +} + +static void +copy_val(NB_DictKeys *dk, char *dst, const char *src){ + memcpy(dst, src, dk->val_size); +} + +/* Returns -1 for error; 0 for not equal; 1 for equal */ +static int +key_equal(NB_DictKeys *dk, const char *lhs, const char *rhs) { + if ( dk->methods.key_equal ) { + return dk->methods.key_equal(lhs, rhs); + } else { + return memcmp(lhs, rhs, dk->key_size) == 0; + } +} + +static char * +entry_get_key(NB_DictKeys *dk, NB_DictEntry* entry) { + char * out = entry->keyvalue; + assert (out == aligned_pointer(out)); + return out; +} + +static char * +entry_get_val(NB_DictKeys *dk, NB_DictEntry* entry) { + char * out = entry_get_key(dk, entry) + aligned_size(dk->key_size); + assert (out == aligned_pointer(out)); + return out; +} + +static void +dk_incref_key(NB_DictKeys *dk, const char *key) { + if ( dk->methods.key_incref ) { + dk->methods.key_incref(key); + } +} + +static void +dk_decref_key(NB_DictKeys *dk, const char *key) { + if ( dk->methods.key_decref ) { + dk->methods.key_decref(key); + } +} + +static void +dk_incref_val(NB_DictKeys *dk, const char *val) { + if ( dk->methods.value_incref ) { + dk->methods.value_incref(val); + } +} + +static void +dk_decref_val(NB_DictKeys *dk, const char *val) { + if ( dk->methods.value_decref ) { + dk->methods.value_decref(val); + } +} + + +void +numba_dictkeys_free(NB_DictKeys *dk) { + /* Clear all references from the entries */ + Py_ssize_t i; + NB_DictEntry *ep; + + for (i = 0; i < dk->nentries; i++) { + ep = get_entry(dk, i); + if (ep->hash != DKIX_EMPTY) { + dk_decref_key(dk, entry_get_key(dk, ep)); + dk_decref_val(dk, entry_get_val(dk, ep)); + } + } + /* Deallocate */ + free(dk); +} + +void +numba_dict_free(NB_Dict *d) { + numba_dictkeys_free(d->keys); + free(d); +} + +Py_ssize_t +numba_dict_length(NB_Dict *d) { + return d->used; +} + +/* Allocate new dictionary keys + +Adapted from CPython's new_keys_object(). +*/ +int +numba_dictkeys_new(NB_DictKeys **out, Py_ssize_t size, Py_ssize_t key_size, Py_ssize_t val_size) { + Py_ssize_t usable = USABLE_FRACTION(size); + Py_ssize_t index_size = ix_size(size); + Py_ssize_t entry_size = aligned_size(sizeof(NB_DictEntry) + aligned_size(key_size) + aligned_size(val_size)); + Py_ssize_t entry_offset = aligned_size(index_size * size); + Py_ssize_t alloc_size = sizeof(NB_DictKeys) + entry_offset + entry_size * usable; + + NB_DictKeys *dk = malloc(aligned_size(alloc_size)); + if (!dk) return ERR_NO_MEMORY; + + assert ( size >= D_MINSIZE ); + + dk->size = size; + dk->usable = usable; + dk->nentries = 0; + dk->key_size = key_size; + dk->val_size = val_size; + dk->entry_offset = entry_offset; + dk->entry_size = entry_size; + + assert (aligned_pointer(dk->indices) == dk->indices ); + /* Ensure that the method table is all nulls */ + memset(&dk->methods, 0x00, sizeof(type_based_methods_table)); + /* Ensure hash is (-1) for empty entry */ + memset(dk->indices, 0xff, entry_offset + entry_size * usable); + + *out = dk; + return OK; +} + + +/* Allocate new dictionary */ +int +numba_dict_new(NB_Dict **out, Py_ssize_t size, Py_ssize_t key_size, Py_ssize_t val_size) { + NB_DictKeys *dk; + NB_Dict *d; + int status = numba_dictkeys_new(&dk, size, key_size, val_size); + if (status != OK) return status; + + d = malloc(sizeof(NB_Dict)); + if (!d) { + numba_dictkeys_free(dk); + return ERR_NO_MEMORY; + } + + d->used = 0; + d->keys = dk; + *out = d; + return OK; +} + + +/* +Adapted from CPython lookdict_index(). + +Search index of hash table from offset of entry table +*/ +static Py_ssize_t +lookdict_index(NB_DictKeys *dk, Py_hash_t hash, Py_ssize_t index) +{ + size_t mask = D_MASK(dk); + size_t perturb = (size_t)hash; + size_t i = (size_t)hash & mask; + + for (;;) { + Py_ssize_t ix = get_index(dk, i); + if (ix == index) { + return i; + } + if (ix == DKIX_EMPTY) { + return DKIX_EMPTY; + } + perturb >>= PERTURB_SHIFT; + i = mask & (i*5 + perturb + 1); + } + assert(0 && "unreachable"); +} + +/* + +Adapted from the CPython3.7 lookdict(). + +The basic lookup function used by all operations. +This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4. +Open addressing is preferred over chaining since the link overhead for +chaining would be substantial (100% with typical malloc overhead). + +The initial probe index is computed as hash mod the table size. Subsequent +probe indices are computed as explained earlier. + +All arithmetic on hash should ignore overflow. + +The details in this version are due to Tim Peters, building on many past +contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and +Christian Tismer. + +lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a +comparison raises an exception. +lookdict_unicode() below is specialized to string keys, comparison of which can +never raise an exception; that function can never return DKIX_ERROR when key +is string. Otherwise, it falls back to lookdict(). +lookdict_unicode_nodummy is further specialized for string keys that cannot be +the value. +For both, when the key isn't found a DKIX_EMPTY is returned. +*/ +Py_ssize_t +numba_dict_lookup(NB_Dict *d, const char *key_bytes, Py_hash_t hash, char *oldval_bytes) +{ + NB_DictKeys *dk = d->keys; + size_t mask = D_MASK(dk); + size_t perturb = hash; + size_t i = (size_t)hash & mask; + + for (;;) { + Py_ssize_t ix = get_index(dk, i); + if (ix == DKIX_EMPTY) { + zero_val(dk, oldval_bytes); + return ix; + } + if (ix >= 0) { + NB_DictEntry *ep = get_entry(dk, ix); + const char *startkey = NULL; + if (ep->hash == hash) { + int cmp; + + startkey = entry_get_key(dk, ep); + cmp = key_equal(dk, startkey, key_bytes); + if (cmp < 0) { + // error'ed in comparison + memset(oldval_bytes, 0, dk->val_size); + return DKIX_ERROR; + } + if (cmp > 0) { + // key is equal; retrieve the value. + copy_val(dk, oldval_bytes, entry_get_val(dk, ep)); + return ix; + } + } + } + perturb >>= PERTURB_SHIFT; + i = (i*5 + perturb + 1) & mask; + } + assert(0 && "unreachable"); +} + + +/* Internal function to find slot for an item from its hash + when it is known that the key is not present in the dict. + + The dict must be combined. */ +static Py_ssize_t +find_empty_slot(NB_DictKeys *dk, Py_hash_t hash){ + size_t mask; + size_t i; + Py_ssize_t ix; + size_t perturb; + + assert(dk != NULL); + + mask = D_MASK(dk); + i = hash & mask; + ix = get_index(dk, i); + for (perturb = hash; ix >= 0;) { + perturb >>= PERTURB_SHIFT; + i = (i*5 + perturb + 1) & mask; + ix = get_index(dk, i); + } + return i; +} + +static int +insertion_resize(NB_Dict *d) +{ + return numba_dict_resize(d, D_GROWTH_RATE(d)); +} + +int +numba_dict_insert( + NB_Dict *d, + const char *key_bytes, + Py_hash_t hash, + const char *val_bytes, + char *oldval_bytes + ) +{ + + NB_DictKeys *dk = d->keys; + + Py_ssize_t ix = numba_dict_lookup(d, key_bytes, hash, oldval_bytes); + if (ix == DKIX_ERROR) { + // exception in key comparison in lookup. + return ERR_CMP_FAILED; + } + + if (ix == DKIX_EMPTY) { + /* Insert into new slot */ + Py_ssize_t hashpos; + NB_DictEntry *ep; + + if (dk->usable <= 0) { + /* Need to resize */ + if (insertion_resize(d) != OK) + return ERR_NO_MEMORY; + else + dk = d->keys; // reload + } + hashpos = find_empty_slot(dk, hash); + ep = get_entry(dk, dk->nentries); + set_index(dk, hashpos, dk->nentries); + copy_key(dk, entry_get_key(dk, ep), key_bytes); + assert ( hash != -1 ); + ep->hash = hash; + copy_val(dk, entry_get_val(dk, ep), val_bytes); + + /* incref */ + dk_incref_key(dk, key_bytes); + dk_incref_val(dk, val_bytes); + + d->used += 1; + dk->usable -= 1; + dk->nentries += 1; + assert (dk->usable >= 0); + return OK; + } else { + /* Replace existing value in the slot at ix */ + /* decref old value */ + dk_decref_val(dk, oldval_bytes); + // Replace the previous value + copy_val(dk, entry_get_val(dk, get_entry(dk, ix)), val_bytes); + + /* incref */ + dk_incref_val(dk, val_bytes); + return OK_REPLACED; + } +} + +/* +Adapted from build_indices(). +Internal routine used by dictresize() to build a hashtable of entries. +*/ +void +build_indices(NB_DictKeys *keys, Py_ssize_t n) { + size_t mask = (size_t)D_MASK(keys); + Py_ssize_t ix; + for (ix = 0; ix != n; ix++) { + size_t perturb; + Py_hash_t hash = get_entry(keys, ix)->hash; + size_t i = hash & mask; + for (perturb = hash; get_index(keys, i) != DKIX_EMPTY;) { + perturb >>= PERTURB_SHIFT; + i = mask & (i*5 + perturb + 1); + } + set_index(keys, i, ix); + } +} + +/* + +Adapted from CPython dictresize(). + +Restructure the table by allocating a new table and reinserting all +items again. When entries have been deleted, the new table may +actually be smaller than the old one. +If a table is split (its keys and hashes are shared, its values are not), +then the values are temporarily copied into the table, it is resized as +a combined table, then the me_value slots in the old table are NULLed out. +After resizing a table is always combined, +but can be resplit by make_keys_shared(). +*/ +int +numba_dict_resize(NB_Dict *d, Py_ssize_t minsize) { + Py_ssize_t newsize, numentries; + NB_DictKeys *oldkeys; + int status; + + /* Find the smallest table size > minused. */ + for (newsize = D_MINSIZE; + newsize < minsize && newsize > 0; + newsize <<= 1) + ; + if (newsize <= 0) { + return ERR_NO_MEMORY; + } + oldkeys = d->keys; + + /* NOTE: Current odict checks mp->ma_keys to detect resize happen. + * So we can't reuse oldkeys even if oldkeys->dk_size == newsize. + * TODO: Try reusing oldkeys when reimplement odict. + */ + + /* Allocate a new table. */ + status = numba_dictkeys_new( + &d->keys, newsize, oldkeys->key_size, oldkeys->val_size + ); + if (status != OK) { + d->keys = oldkeys; + return status; + } + // New table must be large enough. + assert(d->keys->usable >= d->used); + // Copy method table + memcpy(&d->keys->methods, &oldkeys->methods, sizeof(type_based_methods_table)); + + numentries = d->used; + + if (oldkeys->nentries == numentries) { + NB_DictEntry *oldentries, *newentries; + + oldentries = get_entry(oldkeys, 0); + newentries = get_entry(d->keys, 0); + memcpy(newentries, oldentries, numentries * oldkeys->entry_size); + // to avoid decref + memset(oldentries, 0xff, numentries * oldkeys->entry_size); + } + else { + Py_ssize_t i; + size_t epi = 0; + for (i=0; ihash == (-1) hash means it is empty + + Here, we skip until a non empty entry is encountered. + */ + while( get_entry(oldkeys, epi)->hash == DKIX_EMPTY ) { + assert( mem_cmp_zeros(entry_get_val(oldkeys, get_entry(oldkeys, epi)), oldkeys->val_size) == 0 ); + epi += 1; + } + memcpy( + get_entry(d->keys, i), + get_entry(oldkeys, epi), + oldkeys->entry_size + ); + get_entry(oldkeys, epi)->hash = DKIX_EMPTY; // to avoid decref + epi += 1; + + } + + } + numba_dictkeys_free(oldkeys); + + build_indices(d->keys, numentries); + d->keys->usable -= numentries; + d->keys->nentries = numentries; + return OK; +} + +/* + Adapted from CPython delitem_common + */ +int +numba_dict_delitem(NB_Dict *d, Py_hash_t hash, Py_ssize_t ix) +{ + Py_ssize_t hashpos; + NB_DictEntry *ep; + NB_DictKeys *dk = d->keys; + + hashpos = lookdict_index(dk, hash, ix); + assert(hashpos >= 0); + + d->used -= 1; + ep = get_entry(dk, ix); + set_index(dk, hashpos, DKIX_DUMMY); + + /* decref */ + dk_decref_key(dk, entry_get_key(dk, ep)); + dk_decref_val(dk, entry_get_val(dk, ep)); + + /* zero the entries */ + zero_key(dk, entry_get_key(dk, ep)); + zero_val(dk, entry_get_val(dk, ep)); + ep->hash = DKIX_EMPTY; // to mark it as empty; + + return OK; +} + + +/** + * Adapted from dict_popitem + * + */ +int +numba_dict_popitem(NB_Dict *d, char *key_bytes, char *val_bytes) +{ + Py_ssize_t i, j; + char *key_ptr, *val_ptr; + NB_DictEntry *ep = NULL; + + if (d->used == 0) { + return ERR_DICT_EMPTY; + } + + /* Pop last item */ + i = d->keys->nentries - 1; + while (i >= 0 && (ep = get_entry(d->keys, i))->hash == DKIX_EMPTY ) { + i--; + } + assert(i >= 0); + + j = lookdict_index(d->keys, ep->hash, i); + assert(j >= 0); + assert(get_index(d->keys, j) == i); + set_index(d->keys, j, DKIX_DUMMY); + + key_ptr = entry_get_key(d->keys, ep); + val_ptr = entry_get_val(d->keys, ep); + + copy_key(d->keys, key_bytes, key_ptr); + copy_val(d->keys, val_bytes, val_ptr); + + zero_key(d->keys, key_ptr); + zero_val(d->keys, val_ptr); + + /* We can't dk_usable++ since there is DKIX_DUMMY in indices */ + d->keys->nentries = i; + d->used--; + + return OK; +} + +void +numba_dict_dump(NB_Dict *d) { + long long i, j, k; + long long size, n; + char *cp; + NB_DictEntry *ep; + NB_DictKeys *dk = d->keys; + + n = d->used; + size = dk->nentries; + + printf("Dict dump\n"); + printf(" key_size = %lld\n", (long long)d->keys->key_size); + printf(" val_size = %lld\n", (long long)d->keys->val_size); + + for (i = 0, j = 0; i < size; i++) { + ep = get_entry(dk, i); + if (ep->hash != DKIX_EMPTY) { + long long hash = ep->hash; + printf(" key="); + for (cp=entry_get_key(dk, ep), k=0; k < d->keys->key_size; ++k, ++cp){ + printf("%02x ", ((int)*cp) & 0xff); + } + printf(" hash=%llu value=", hash); + for (cp=entry_get_val(dk, ep), k=0; k < d->keys->val_size; ++k, ++cp){ + printf("%02x ", ((int)*cp) & 0xff); + } + printf("\n"); + j++; + } + } + printf("j = %lld; n = %lld\n", j, n); + assert(j == n); +} + +size_t +numba_dict_iter_sizeof() { + return sizeof(NB_DictIter); +} + +void +numba_dict_iter(NB_DictIter *it, NB_Dict *d) { + it->parent = d; + it->parent_keys = d->keys; + it->size = d->used; + it->pos = 0; +} + +int +numba_dict_iter_next(NB_DictIter *it, const char **key_ptr, const char **val_ptr) { + /* Detect dictionary mutation during iteration */ + NB_DictKeys *dk; + if (it->parent->keys != it->parent_keys || + it->parent->used != it->size) { + return ERR_DICT_MUTATED; + } + dk = it->parent_keys; + while ( it->pos < dk->nentries ) { + NB_DictEntry *ep = get_entry(dk, it->pos++); + if ( ep->hash != DKIX_EMPTY ) { + *key_ptr = entry_get_key(dk, ep); + *val_ptr = entry_get_val(dk, ep); + return OK; + } + } + return ERR_ITER_EXHAUSTED; +} + +int +numba_dict_insert_ez( + NB_Dict *d, + const char *key_bytes, + Py_hash_t hash, + const char *val_bytes + ) +{ + STACK_ALLOC(char, old, d->keys->val_size); + return numba_dict_insert(d, key_bytes, hash, val_bytes, old); +} + + +/* Allocate a new dictionary with enough space to hold n_keys without resizes */ +int +numba_dict_new_sized(NB_Dict **out, Py_ssize_t n_keys, Py_ssize_t key_size, Py_ssize_t val_size) { + + /* Respect D_MINSIZE */ + if (n_keys <= USABLE_FRACTION(D_MINSIZE)) { + return numba_dict_new(out, D_MINSIZE, key_size, val_size); + } + + /* Adjust for load factor */ + Py_ssize_t size = INV_USABLE_FRACTION(n_keys) - 1; + + /* Round up size to the nearest power of 2. */ + for (unsigned int shift = 1; shift < sizeof(Py_ssize_t) * CHAR_BIT; shift <<= 1) { + size |= (size >> shift); + } + size++; + + /* Handle overflows */ + if (size <= 0) { + return ERR_NO_MEMORY; + } + + return numba_dict_new(out, size, key_size, val_size); +} + + +void +numba_dict_set_method_table(NB_Dict *d, type_based_methods_table *methods) +{ + memcpy(&d->keys->methods, methods, sizeof(type_based_methods_table)); +} + + +#define CHECK(CASE) { \ + if ( !(CASE) ) { \ + printf("'%s' failed file %s:%d\n", #CASE, __FILE__, __LINE__); \ + return 1; \ + } \ +} + +int +numba_test_dict(void) { + NB_Dict *d; + int status; + Py_ssize_t ix; + Py_ssize_t usable; + Py_ssize_t it_count; + const char *it_key, *it_val; + NB_DictIter iter; + +#if defined(_MSC_VER) + /* So that VS2008 compiler is happy */ + char *got_key, *got_value; + got_key = _alloca(4); + got_value = _alloca(8); +#else + char got_key[4]; + char got_value[8]; +#endif + puts("test_dict"); + + status = numba_dict_new(&d, D_MINSIZE, 4, 8); + CHECK(status == OK); + CHECK(d->keys->size == D_MINSIZE); + CHECK(d->keys->key_size == 4); + CHECK(d->keys->val_size == 8); + CHECK(ix_size(d->keys->size) == 1); + printf("aligned_size(index_size * size) = %d\n", (int)(aligned_size(ix_size(d->keys->size) * d->keys->size))); + + printf("d %p\n", d); + printf("d->usable = %u\n", (int)d->keys->usable); + usable = d->keys->usable; + printf("d[0] %d\n", (int)((char*)get_entry(d->keys, 0) - (char*)d->keys)); + CHECK ((char*)get_entry(d->keys, 0) - (char*)d->keys->indices == d->keys->entry_offset); + printf("d[1] %d\n", (int)((char*)get_entry(d->keys, 1) - (char*)d->keys)); + CHECK ((char*)get_entry(d->keys, 1) - (char*)d->keys->indices == d->keys->entry_offset + d->keys->entry_size); + + ix = numba_dict_lookup(d, "bef", 0xbeef, got_value); + printf("ix = %d\n", (int)ix); + CHECK (ix == DKIX_EMPTY); + + // insert 1st key + status = numba_dict_insert(d, "bef", 0xbeef, "1234567", got_value); + CHECK (status == OK); + CHECK (d->used == 1); + CHECK (d->keys->usable == usable - d->used); + + // insert same key + status = numba_dict_insert(d, "bef", 0xbeef, "1234567", got_value); + CHECK (status == OK_REPLACED); + printf("got_value %s\n", got_value); + CHECK (d->used == 1); + CHECK (d->keys->usable == usable - d->used); + + // insert 2nd key + status = numba_dict_insert(d, "beg", 0xbeef, "1234568", got_value); + CHECK (status == OK); + CHECK (d->used == 2); + CHECK (d->keys->usable == usable - d->used); + + // insert 3rd key + status = numba_dict_insert(d, "beh", 0xcafe, "1234569", got_value); + CHECK (status == OK); + CHECK (d->used == 3); + CHECK (d->keys->usable == usable - d->used); + + // replace key "bef"'s value + status = numba_dict_insert(d, "bef", 0xbeef, "7654321", got_value); + CHECK (status == OK_REPLACED); + CHECK (d->used == 3); + CHECK (d->keys->usable == usable - d->used); + + // insert 4th key + status = numba_dict_insert(d, "bei", 0xcafe, "0_0_0_1", got_value); + CHECK (status == OK); + CHECK (d->used == 4); + CHECK (d->keys->usable == usable - d->used); + + // insert 5th key + status = numba_dict_insert(d, "bej", 0xcafe, "0_0_0_2", got_value); + CHECK (status == OK); + CHECK (d->used == 5); + CHECK (d->keys->usable == usable - d->used); + + // insert 6th key & triggers resize + status = numba_dict_insert(d, "bek", 0xcafe, "0_0_0_3", got_value); + CHECK (status == OK); + CHECK (d->used == 6); + CHECK (d->keys->usable == USABLE_FRACTION(d->keys->size) - d->used); + + // Dump + numba_dict_dump(d); + + // Make sure everything are still in there + ix = numba_dict_lookup(d, "bef", 0xbeef, got_value); + CHECK (ix >= 0); + CHECK (memcpy(got_value, "7654321", d->keys->val_size)); + + ix = numba_dict_lookup(d, "beg", 0xbeef, got_value); + CHECK (ix >= 0); + CHECK (memcpy(got_value, "1234567", d->keys->val_size)); + + ix = numba_dict_lookup(d, "beh", 0xcafe, got_value); + printf("ix = %d\n", (int)ix); + CHECK (ix >= 0); + CHECK (memcpy(got_value, "1234569", d->keys->val_size)); + + ix = numba_dict_lookup(d, "bei", 0xcafe, got_value); + CHECK (ix >= 0); + CHECK (memcpy(got_value, "0_0_0_1", d->keys->val_size)); + + ix = numba_dict_lookup(d, "bej", 0xcafe, got_value); + CHECK (ix >= 0); + CHECK (memcpy(got_value, "0_0_0_2", d->keys->val_size)); + + ix = numba_dict_lookup(d, "bek", 0xcafe, got_value); + CHECK (ix >= 0); + CHECK (memcpy(got_value, "0_0_0_3", d->keys->val_size)); + + // Test delete + ix = numba_dict_lookup(d, "beg", 0xbeef, got_value); + status = numba_dict_delitem(d, 0xbeef, ix); + CHECK (status == OK); + + ix = numba_dict_lookup(d, "beg", 0xbeef, got_value); + CHECK (ix == DKIX_EMPTY); // not found + + ix = numba_dict_lookup(d, "bef", 0xbeef, got_value); + CHECK (ix >= 0); + ix = numba_dict_lookup(d, "beh", 0xcafe, got_value); + CHECK (ix >= 0); + + + // Test popitem + // They are always the last item + status = numba_dict_popitem(d, got_key, got_value); + CHECK(status == OK); + CHECK(memcmp("bek", got_key, d->keys->key_size) == 0); + CHECK(memcmp("0_0_0_3", got_value, d->keys->val_size) == 0); + + status = numba_dict_popitem(d, got_key, got_value); + CHECK(status == OK); + CHECK(memcmp("bej", got_key, d->keys->key_size) == 0); + CHECK(memcmp("0_0_0_2", got_value, d->keys->val_size) == 0); + + // Test iterator + CHECK( d->used > 0 ); + numba_dict_iter(&iter, d); + it_count = 0; + while ( (status = numba_dict_iter_next(&iter, &it_key, &it_val)) == OK) { + it_count += 1; // valid items + CHECK(it_key != NULL); + CHECK(it_val != NULL); + } + + CHECK(status == ERR_ITER_EXHAUSTED); + CHECK(d->used == it_count); + + numba_dict_free(d); + + /* numba_dict_new_sized() */ + + Py_ssize_t target_size; + Py_ssize_t n_keys; + + // Test if minsize dict returned with n_keys=0 + target_size = D_MINSIZE; + n_keys = 0; + + numba_dict_new_sized(&d, n_keys, 1, 1); + CHECK(d->keys->size == target_size); + CHECK(d->keys->usable == USABLE_FRACTION(target_size)); + numba_dict_free(d); + + // Test sizing at power of 2 boundary + target_size = D_MINSIZE * 2; + n_keys = USABLE_FRACTION(target_size); + + numba_dict_new_sized(&d, n_keys, 1, 1); + CHECK(d->keys->size == target_size); + CHECK(d->keys->usable == n_keys); + numba_dict_free(d); + + target_size *= 2; + n_keys++; + + numba_dict_new_sized(&d, n_keys, 1, 1); + CHECK(d->keys->size == target_size); + CHECK(d->keys->usable > n_keys); + CHECK(d->keys->usable == USABLE_FRACTION(target_size)); + numba_dict_free(d); + + return 0; + +} + +#undef CHECK diff --git a/shared/package-files/cc/cc90fe7eb065b841363eb65c72c1ebf538e44ee59c0902cf7bd1681b462928c2/_sqltypes.pyi b/shared/package-files/cc/cc90fe7eb065b841363eb65c72c1ebf538e44ee59c0902cf7bd1681b462928c2/_sqltypes.pyi new file mode 100644 index 0000000000000000000000000000000000000000..88abb977af0741f72d88955501ee95076f478e67 --- /dev/null +++ b/shared/package-files/cc/cc90fe7eb065b841363eb65c72c1ebf538e44ee59c0902cf7bd1681b462928c2/_sqltypes.pyi @@ -0,0 +1,75 @@ +import duckdb +import typing as pytyping + +__all__: list[str] = [ + "BIGINT", + "BIT", + "BLOB", + "BOOLEAN", + "DATE", + "DOUBLE", + "FLOAT", + "HUGEINT", + "INTEGER", + "INTERVAL", + "SMALLINT", + "SQLNULL", + "TIME", + "TIMESTAMP", + "TIMESTAMP_MS", + "TIMESTAMP_NS", + "TIMESTAMP_S", + "TIMESTAMP_TZ", + "TIME_TZ", + "TINYINT", + "UBIGINT", + "UHUGEINT", + "UINTEGER", + "USMALLINT", + "UTINYINT", + "UUID", + "VARCHAR", + "DuckDBPyType", +] + +class DuckDBPyType: + def __eq__(self, other: object) -> bool: ... + def __getattr__(self, name: str) -> DuckDBPyType: ... + def __getitem__(self, name: str) -> DuckDBPyType: ... + def __hash__(self) -> int: ... + @pytyping.overload + def __init__(self, type_str: str, connection: duckdb.DuckDBPyConnection) -> None: ... + @pytyping.overload + def __init__(self, obj: object) -> None: ... + @property + def children(self) -> list[tuple[str, object]]: ... + @property + def id(self) -> str: ... + +BIGINT: DuckDBPyType # value = BIGINT +BIT: DuckDBPyType # value = BIT +BLOB: DuckDBPyType # value = BLOB +BOOLEAN: DuckDBPyType # value = BOOLEAN +DATE: DuckDBPyType # value = DATE +DOUBLE: DuckDBPyType # value = DOUBLE +FLOAT: DuckDBPyType # value = FLOAT +HUGEINT: DuckDBPyType # value = HUGEINT +INTEGER: DuckDBPyType # value = INTEGER +INTERVAL: DuckDBPyType # value = INTERVAL +SMALLINT: DuckDBPyType # value = SMALLINT +SQLNULL: DuckDBPyType # value = "NULL" +TIME: DuckDBPyType # value = TIME +TIMESTAMP: DuckDBPyType # value = TIMESTAMP +TIMESTAMP_MS: DuckDBPyType # value = TIMESTAMP_MS +TIMESTAMP_NS: DuckDBPyType # value = TIMESTAMP_NS +TIMESTAMP_S: DuckDBPyType # value = TIMESTAMP_S +TIMESTAMP_TZ: DuckDBPyType # value = TIMESTAMP WITH TIME ZONE +TIME_TZ: DuckDBPyType # value = TIME WITH TIME ZONE +TINYINT: DuckDBPyType # value = TINYINT +UBIGINT: DuckDBPyType # value = UBIGINT +UHUGEINT: DuckDBPyType # value = UHUGEINT +UINTEGER: DuckDBPyType # value = UINTEGER +USMALLINT: DuckDBPyType # value = USMALLINT +UTINYINT: DuckDBPyType # value = UTINYINT +UUID: DuckDBPyType # value = UUID +VARCHAR: DuckDBPyType # value = VARCHAR diff --git a/shared/package-files/cc/cc929246dde512f77a42f83d6f8f500323b87132725674cac8f61ccae7691f19/Samarkand b/shared/package-files/cc/cc929246dde512f77a42f83d6f8f500323b87132725674cac8f61ccae7691f19/Samarkand new file mode 100644 index 0000000000000000000000000000000000000000..8a93767bfef2cecbeee15db413a0a7c277e761a1 Binary files /dev/null and b/shared/package-files/cc/cc929246dde512f77a42f83d6f8f500323b87132725674cac8f61ccae7691f19/Samarkand differ diff --git a/shared/package-files/cc/cc94e137716fa1fd3d876e3cd38a4d0cf77688dfa5087577c8f959ca549e7e04/_distributor_init.py b/shared/package-files/cc/cc94e137716fa1fd3d876e3cd38a4d0cf77688dfa5087577c8f959ca549e7e04/_distributor_init.py new file mode 100644 index 0000000000000000000000000000000000000000..5df134975aa27d31beaff74c3cbfd2d3fb0a55dd --- /dev/null +++ b/shared/package-files/cc/cc94e137716fa1fd3d876e3cd38a4d0cf77688dfa5087577c8f959ca549e7e04/_distributor_init.py @@ -0,0 +1,18 @@ +""" Distributor init file + +Distributors: you can replace the contents of this file with your own custom +code to support particular distributions of SciPy. + +For example, this is a good place to put any checks for hardware requirements +or BLAS/LAPACK library initialization. + +The SciPy standard source distribution will not put code in this file beyond +the try-except import of `_distributor_init_local` (which is not part of a +standard source distribution), so you can safely replace this file with your +own version. +""" + +try: + from . import _distributor_init_local # noqa: F401 +except ImportError: + pass diff --git a/shared/package-files/cc/cc97742d269c82324693bd9d357294c9a6eec90096ace9ea11e5f92ace8d9168/_histogramdd_bin_edges_native.h b/shared/package-files/cc/cc97742d269c82324693bd9d357294c9a6eec90096ace9ea11e5f92ace8d9168/_histogramdd_bin_edges_native.h new file mode 100644 index 0000000000000000000000000000000000000000..0a03f50ccf20b2fefcc7f3b6172a1b477240fc67 --- /dev/null +++ b/shared/package-files/cc/cc97742d269c82324693bd9d357294c9a6eec90096ace9ea11e5f92ace8d9168/_histogramdd_bin_edges_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API void _histogramdd_bin_edges_out(const at::Tensor & self, at::IntArrayRef bins, c10::optional> range, const c10::optional & weight, bool density, at::TensorList out); +TORCH_API ::std::vector histogramdd_bin_edges(const at::Tensor & self, at::IntArrayRef bins, c10::optional> range=c10::nullopt, const c10::optional & weight={}, bool density=false); +} // namespace native +} // namespace at diff --git a/shared/package-files/cc/cc9cb4a516b99fefe9d9d9b8e4fc44081ffe07a49567234a7e3c450e93ea4f7f/ec.pyi b/shared/package-files/cc/cc9cb4a516b99fefe9d9d9b8e4fc44081ffe07a49567234a7e3c450e93ea4f7f/ec.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5c3b7bf6e4a9bafac1423bd3936ebc347885a950 --- /dev/null +++ b/shared/package-files/cc/cc9cb4a516b99fefe9d9d9b8e4fc44081ffe07a49567234a7e3c450e93ea4f7f/ec.pyi @@ -0,0 +1,52 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives.asymmetric import ec + +class ECPrivateKey: ... +class ECPublicKey: ... + +class EllipticCurvePrivateNumbers: + def __init__( + self, private_value: int, public_numbers: EllipticCurvePublicNumbers + ) -> None: ... + def private_key( + self, backend: typing.Any = None + ) -> ec.EllipticCurvePrivateKey: ... + @property + def private_value(self) -> int: ... + @property + def public_numbers(self) -> EllipticCurvePublicNumbers: ... + +class EllipticCurvePublicNumbers: + def __init__(self, x: int, y: int, curve: ec.EllipticCurve) -> None: ... + def public_key( + self, backend: typing.Any = None + ) -> ec.EllipticCurvePublicKey: ... + @property + def x(self) -> int: ... + @property + def y(self) -> int: ... + @property + def curve(self) -> ec.EllipticCurve: ... + def __eq__(self, other: object) -> bool: ... + +def curve_supported(curve: ec.EllipticCurve) -> bool: ... +def generate_private_key( + curve: ec.EllipticCurve, backend: typing.Any = None +) -> ec.EllipticCurvePrivateKey: ... +def from_private_numbers( + numbers: ec.EllipticCurvePrivateNumbers, +) -> ec.EllipticCurvePrivateKey: ... +def from_public_numbers( + numbers: ec.EllipticCurvePublicNumbers, +) -> ec.EllipticCurvePublicKey: ... +def from_public_bytes( + curve: ec.EllipticCurve, data: bytes +) -> ec.EllipticCurvePublicKey: ... +def derive_private_key( + private_value: int, curve: ec.EllipticCurve +) -> ec.EllipticCurvePrivateKey: ... diff --git a/shared/package-files/cc/cca331fb1aa4ae6cf89f8f62ccf943f501f77718c3222e73c7f7502494af77b8/menubutton.tcl b/shared/package-files/cc/cca331fb1aa4ae6cf89f8f62ccf943f501f77718c3222e73c7f7502494af77b8/menubutton.tcl new file mode 100644 index 0000000000000000000000000000000000000000..a0f70c99d017857038df17471cfdc0623515e617 --- /dev/null +++ b/shared/package-files/cc/cca331fb1aa4ae6cf89f8f62ccf943f501f77718c3222e73c7f7502494af77b8/menubutton.tcl @@ -0,0 +1,241 @@ +# +# Bindings for Menubuttons. +# +# Menubuttons have three interaction modes: +# +# Pulldown: Press menubutton, drag over menu, release to activate menu entry +# Popdown: Click menubutton to post menu +# Keyboard: or accelerator key to post menu +# +# (In addition, when menu system is active, "dropdown" -- menu posts +# on mouse-over. Ttk menubuttons don't implement this). +# +# For keyboard and popdown mode, we hand off to tk_popup and let +# the built-in Tk bindings handle the rest of the interaction. +# +# ON X11: +# +# Standard Tk menubuttons use a global grab on the menubutton. +# This won't work for Ttk menubuttons in pulldown mode, +# since we need to process the final event, +# and this might be delivered to the menu. So instead we +# rely on the passive grab that occurs on